Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.3 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. // -----------------------------------------------------------------------------
  2. // Stream Injector
  3. // -----------------------------------------------------------------------------
  4. #pragma once
  5. #include <Stream.h>
  6. class StreamInjector : public Stream {
  7. public:
  8. typedef std::function<void(uint8_t ch)> writeCallback;
  9. StreamInjector(Stream& serial, size_t buflen = 128) : _stream(serial), _buffer_size(buflen) {
  10. _buffer = new char[buflen];
  11. }
  12. ~StreamInjector() {
  13. delete[] _buffer;
  14. }
  15. virtual void callback(writeCallback c) {
  16. _callback = c;
  17. }
  18. virtual size_t write(uint8_t ch) {
  19. if (_callback) _callback(ch);
  20. return _stream.write(ch);
  21. }
  22. virtual int read() {
  23. int ch = _stream.read();
  24. if (ch == -1) {
  25. if (_buffer_read != _buffer_write) {
  26. ch = _buffer[_buffer_read];
  27. _buffer_read = (_buffer_read + 1) % _buffer_size;
  28. }
  29. }
  30. return ch;
  31. }
  32. virtual int available() {
  33. unsigned int bytes = _stream.available();
  34. if (_buffer_read > _buffer_write) {
  35. bytes += (_buffer_write - _buffer_read + _buffer_size);
  36. } else if (_buffer_read < _buffer_write) {
  37. bytes += (_buffer_write - _buffer_read);
  38. }
  39. return bytes;
  40. }
  41. virtual int peek() {
  42. int ch = _stream.peek();
  43. if (ch == -1) {
  44. if (_buffer_read != _buffer_write) {
  45. ch = _buffer[_buffer_read];
  46. }
  47. }
  48. return ch;
  49. }
  50. virtual void flush() {
  51. _stream.flush();
  52. _buffer_read = _buffer_write;
  53. }
  54. virtual void inject(char *data, size_t len) {
  55. for (int i=0; i<len; i++) {
  56. _buffer[_buffer_write] = data[i];
  57. _buffer_write = (_buffer_write + 1) % _buffer_size;
  58. }
  59. }
  60. private:
  61. Stream& _stream;
  62. char * _buffer;
  63. unsigned char _buffer_size;
  64. unsigned char _buffer_write = 0;
  65. unsigned char _buffer_read = 0;
  66. writeCallback _callback = NULL;
  67. };