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.

87 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
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(size_t buflen = 128) : _buffer_size(buflen) {
  10. _buffer = new char[buflen];
  11. }
  12. ~StreamInjector() {
  13. delete[] _buffer;
  14. }
  15. // ---------------------------------------------------------------------
  16. virtual uint8_t inject(char ch) {
  17. _buffer[_buffer_write] = ch;
  18. _buffer_write = (_buffer_write + 1) % _buffer_size;
  19. return 1;
  20. }
  21. virtual uint8_t inject(char *data, size_t len) {
  22. for (int i=0; i<len; i++) {
  23. inject(data[i]);
  24. }
  25. return len;
  26. }
  27. // ---------------------------------------------------------------------
  28. virtual void callback(writeCallback c) {
  29. _callback = c;
  30. }
  31. virtual size_t write(uint8_t ch) {
  32. if (_callback) _callback(ch);
  33. }
  34. virtual int read() {
  35. int ch = -1;
  36. if (_buffer_read != _buffer_write) {
  37. ch = _buffer[_buffer_read];
  38. _buffer_read = (_buffer_read + 1) % _buffer_size;
  39. }
  40. return ch;
  41. }
  42. virtual int available() {
  43. unsigned int bytes = 0;
  44. if (_buffer_read > _buffer_write) {
  45. bytes += (_buffer_write - _buffer_read + _buffer_size);
  46. } else if (_buffer_read < _buffer_write) {
  47. bytes += (_buffer_write - _buffer_read);
  48. }
  49. return bytes;
  50. }
  51. virtual int peek() {
  52. int ch = -1;
  53. if (_buffer_read != _buffer_write) {
  54. ch = _buffer[_buffer_read];
  55. }
  56. return ch;
  57. }
  58. virtual void flush() {
  59. _buffer_read = _buffer_write;
  60. }
  61. private:
  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. };