xnecas il y a 1 semaine
commit
50d756b16f
2 fichiers modifiés avec 122 ajouts et 0 suppressions
  1. 89 0
      nbus_app_driver.cpp
  2. 33 0
      nbus_app_driver.h

+ 89 - 0
nbus_app_driver.cpp

@@ -0,0 +1,89 @@
+#include "nbus_app_driver.h"
+
+NbusAppDriver::NbusAppDriver(Stream *stream_obj, uint8_t *data, int16_t size, int32_t timeout)
+: _stream_obj{stream_obj}, _data{data}, _size{size}, _timeout{timeout}
+{
+
+}
+
+void NbusAppDriver::setData(uint8_t *data, int16_t size)
+{
+    _data = data;
+    _size = size;
+}
+
+int16_t NbusAppDriver::receiveFromMaster()
+{     
+    // check if timeout elapsed
+    if (_checkTimeout() == 1)
+    {
+        _resetRxState();
+        return 0;
+    }
+
+    // get incoming bytes
+    int32_t in_bytes = _stream_obj->available();
+
+    // check if empty
+    if (in_bytes == 0)
+    {
+        return 0;
+    }
+
+    // read length
+    if (_rx_size == 0)
+    {
+        _rx_size = _stream_obj->read();
+
+        // check length size
+        if (_rx_size < NBUS_APP_DRIVER_PAYLOAD_MIN || _rx_size > NBUS_APP_DRIVER_PAYLOAD_MAX)
+        {
+            _resetRxState();
+            return 0;
+        }
+
+        _time0 = millis();
+        in_bytes--;
+    }
+    
+    // read payload
+    if (in_bytes > 0 && _rx_index < _rx_size)
+    {
+        // handle overflow
+        if (in_bytes + _rx_index > _size)
+        {
+            _resetRxState(); 
+            return 0;
+        }
+
+        _rx_index += _stream_obj->readBytes(_data + _rx_index, in_bytes);
+    }
+
+    if (_rx_index >= _rx_size)
+    { 
+        int16_t length = _rx_index;
+        _resetRxState();
+        return length;
+    }
+    else
+    {
+        return 0;
+    }
+}
+
+bool NbusAppDriver::_checkTimeout()
+{
+    if (_time0 == INT64_MAX)
+    {
+        return 0;
+    }
+    
+    return millis() - _time0 > _timeout;
+}
+
+void NbusAppDriver::_resetRxState()
+{
+    _rx_index = 0;
+    _rx_size = 0;
+    _time0 = INT64_MAX;
+}

+ 33 - 0
nbus_app_driver.h

@@ -0,0 +1,33 @@
+#ifndef _NBUS_APP_DRIVER_H_
+#define _NBUS_APP_DRIVER_H_
+
+#include <cinttypes>
+#include <Stream.h>
+#include <esp32-hal.h>
+
+#define NBUS_APP_DRIVER_PAYLOAD_MIN 4
+#define NBUS_APP_DRIVER_PAYLOAD_MAX 127
+
+class NbusAppDriver
+{
+public:
+    NbusAppDriver(Stream *stream_obj, uint8_t *data, int16_t size, int32_t timeout);
+    void setData(uint8_t *data, int16_t size);
+    int16_t receiveFromMaster();
+    
+    
+private:
+    bool _checkTimeout();
+    void _resetRxState();
+
+    Stream  *_stream_obj;
+    uint8_t *_data{nullptr};
+    int16_t _size{0};
+    int32_t _timeout{0};
+
+    int64_t _time0{INT64_MAX};
+    int16_t _rx_index{0};
+    int16_t _rx_size{0};
+};
+
+#endif // _NBUS_APP_DRIVER_H_