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

Dependents:   SimpleSerialProtocolExample SerialFileReceiver

Packet.h

Committer:
p3p
Date:
2014-09-19
Revision:
3:5caff50e14a7
Parent:
1:98ad30934a71

File content as of revision 3:5caff50e14a7:

#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[256];
    uint16_t _size;
    uint16_t _checksum;
    bool _valid;
};

};

#endif