A library to send and receive packets over serial, uses MODSERIAL

Dependents:   SimpleSerialProtocolExample SerialFileReceiver

Revision:
0:1639507580d5
Child:
1:98ad30934a71
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Packet.h	Thu Jun 28 21:19:58 2012 +0000
@@ -0,0 +1,62 @@
+#ifndef SIMPLE_SERIAL_PROTOCOL_PACKET
+#define SIMPLE_SERIAL_PROTOCOL_PACKET
+
+namespace SimpleSerialProtocol {
+
+class Packet {
+public:
+    Packet() {
+        _type = 0;
+        _size = 0;
+        _checksum = 0;
+        _valid = false;
+        memset(_data, 0, sizeof(_data));
+    }
+    virtual ~Packet() {}
+
+    void reset() {
+        _type = 0;
+        _size = 0;
+        _checksum = 0;
+        _valid = false;
+    }
+
+    template <class T> void buildData (T* message) {
+        uint8_t* payload_array = reinterpret_cast<uint8_t *>(message);
+        memcpy(_data, payload_array, sizeof(T));
+        _type = _data[0];
+        _size = sizeof(T);
+    }
+
+    template <class T> T* interpretData () {
+        if (_size == sizeof(T)) {
+            return reinterpret_cast<T*>(_data);
+        }
+        return 0;
+    }
+    
+    static void swapEndian(void *pv, size_t n) {
+        uint8_t *p = reinterpret_cast<uint8_t *>(pv);
+        size_t lo, hi;
+        for (lo=0, hi=n-1; hi>lo; lo++, hi--) {
+            uint8_t tmp=p[lo];
+            p[lo] = p[hi];
+            p[hi] = tmp;
+        }
+    }
+    
+    template <class T> static T swapEndian(T pv) {
+        swapEndian(reinterpret_cast<void*>(&pv), sizeof(T));
+        return pv;
+    }
+
+    uint8_t _type;
+    uint8_t _data[512];
+    uint16_t _size;
+    uint16_t _checksum;
+    bool _valid;
+};
+
+};
+
+#endif
\ No newline at end of file