TinyRobotics
Loading...
Searching...
No Matches
SynchronizedStream.h
1#pragma once
2#include "TinyRobotics/utils/Buffers.h"
3#include "LockGuard.h"
4#include "Mutex.h"
5#include "Stream.h"
6
7namespace tinyrobotics {
8
9
10/**
11 * @class SynchronizedStream
12 * @ingroup concurrency
13 * @brief Wrapper class that can turn any Stream into a thread save
14 * implementation. This is done by adding a Mutex to the Stream. The
15 * read and write operations are buffered and the access to the stream is
16 * protected by the Mutex.
17 * @author Phil Schatzmann
18 */
19
20class SynchronizedStream : public Stream {
21 public:
22 SynchronizedStream(Stream &stream, MutexBase &mutex) {
23 p_stream = &stream;
24 p_mutex = &mutex;
25 }
26
27 // reads a single value
28 int read() override {
29 if (read_buffer.isEmpty()) {
30 LockGuard guard(p_mutex);
31 p_stream->readBytes(read_buffer.address(), read_buffer.size());
32 }
33 uint8_t data;
34 bool result = read_buffer.read(data);
35 return result ? data : -1;
36 }
37
38 // peeks the actual entry from the buffer
39 int peek() override {
40 LockGuard guard(p_mutex);
41 return p_stream->peek();
42 }
43
44 // write add an entry to the buffer
45 size_t write(uint8_t data) override {
46 write_buffer.write(data);
47 if (write_buffer.isFull()) {
48 LockGuard guard(p_mutex);
49 size_t written = p_stream->write((const uint8_t *)write_buffer.data(),
50 write_buffer.size());
51 assert(written == write_buffer.size());
52 write_buffer.reset();
53 }
54 return 1;
55 }
56
57 // provides the number of entries that are available to read
58 int available() override {
59 LockGuard guard(p_mutex);
60 return p_stream->available();
61 }
62
63 // provides the number of entries that are available to write
64 int availableForWrite() override {
65 LockGuard guard(p_mutex);
66 return p_stream->availableForWrite();
67 }
68
69 /// Defines the size of the internal buffers
70 void setBufferSize(int size) {
71 read_buffer.resize(size);
72 write_buffer.resize(size);
73 }
74
75 protected:
76 Stream *p_stream = nullptr;
77 MutexBase *p_mutex = nullptr;
78 SingleBuffer<uint8_t> read_buffer;
79 SingleBuffer<uint8_t> write_buffer;
80};
81
82} // namespace audio_tools
RAII implementaion using a Mutex: Only a few microcontrollers provide lock guards,...
Definition: LockGuard.h:18
Empty Mutex implementation which does nothing.
Definition: Mutex.h:18
A simple Buffer implementation which just uses a (dynamically sized) array.
Definition: Buffers.h:136
Wrapper class that can turn any Stream into a thread save implementation. This is done by adding a Mu...
Definition: SynchronizedStream.h:20
void setBufferSize(int size)
Defines the size of the internal buffers.
Definition: SynchronizedStream.h:70