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.

104 lines
2.8 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
7 years ago
  1. /*
  2. StreamInjector
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #pragma once
  16. #include <Stream.h>
  17. class StreamInjector : public Stream {
  18. public:
  19. typedef std::function<void(uint8_t ch)> writeCallback;
  20. StreamInjector(size_t buflen = 128) : _buffer_size(buflen) {
  21. _buffer = new char[buflen];
  22. }
  23. ~StreamInjector() {
  24. delete[] _buffer;
  25. }
  26. // ---------------------------------------------------------------------
  27. virtual uint8_t inject(char ch) {
  28. _buffer[_buffer_write] = ch;
  29. _buffer_write = (_buffer_write + 1) % _buffer_size;
  30. return 1;
  31. }
  32. virtual uint8_t inject(char *data, size_t len) {
  33. for (int i=0; i<len; i++) {
  34. inject(data[i]);
  35. }
  36. return len;
  37. }
  38. virtual void callback(writeCallback c) {
  39. _callback = c;
  40. }
  41. // ---------------------------------------------------------------------
  42. virtual size_t write(uint8_t ch) {
  43. if (_callback) _callback(ch);
  44. }
  45. virtual int read() {
  46. int ch = -1;
  47. if (_buffer_read != _buffer_write) {
  48. ch = _buffer[_buffer_read];
  49. _buffer_read = (_buffer_read + 1) % _buffer_size;
  50. }
  51. return ch;
  52. }
  53. virtual int available() {
  54. unsigned int bytes = 0;
  55. if (_buffer_read > _buffer_write) {
  56. bytes += (_buffer_write - _buffer_read + _buffer_size);
  57. } else if (_buffer_read < _buffer_write) {
  58. bytes += (_buffer_write - _buffer_read);
  59. }
  60. return bytes;
  61. }
  62. virtual int peek() {
  63. int ch = -1;
  64. if (_buffer_read != _buffer_write) {
  65. ch = _buffer[_buffer_read];
  66. }
  67. return ch;
  68. }
  69. virtual void flush() {
  70. _buffer_read = _buffer_write;
  71. }
  72. private:
  73. char * _buffer;
  74. unsigned char _buffer_size;
  75. unsigned char _buffer_write = 0;
  76. unsigned char _buffer_read = 0;
  77. writeCallback _callback = NULL;
  78. };