simple serial protocol

Dependents:   AwsomeStation LoRaBaseStation LoRaTerminal

SerialInterfaceProtocol.h

Committer:
rba90
Date:
2016-09-02
Revision:
11:390476907bfc
Parent:
7:100865963801

File content as of revision 11:390476907bfc:

// SerialInterfaceProtocol (SIP) is a protocol which help to exchange
// information between host and slave devices
#ifndef SERIALINTERFACEPROTOCOL_H_
#define SERIALINTERFACEPROTOCOL_H_

#include "mbed.h"
#include "stdint.h"
#include "RingBuffer.h"
#include "CommandPacket2.h"

#define SIP_CMD_VECTOR_TABLE_SZ 256
#define SIP_MAX_RESP_LEN 256
#define SIP_MAX_PAYLOAD_LEN 256

typedef int (*callback_func)(uint8_t *payload, uint8_t payload_length, uint8_t *response, uint8_t *response_length); 
typedef CircularBuffer<uint8_t> SerialBuffer_t;

uint8_t hexchar_to_uint8(uint8_t ch);

class SerialInterfaceProtocol
{
public:
    // namespace
    typedef enum
    {
        NONE = 0,
        SFLAG,
        COMMAND_H,
        COMMAND_L,
        LENGTH_H,
        LENGTH_L,
        PAYLOAD_H,
        PAYLOAD_L,
        CHECKSUM_H,
        CHECKSUM_L,
        EFLAG
    } State_t;

    typedef enum
    {
        NO_ERROR = 0,
        INVALID_SFLAG_ERROR,
        INVALID_EFLAG_ERROR,
        INVALID_CMD_ERROR,
        INVALID_CS_ERROR,
        INVALID_EXEC_ERROR
    } Error_t;
    
protected:
    // internal variable
    callback_func CommandVectorTable[SIP_CMD_VECTOR_TABLE_SZ];
    
    // buffered interface
    SerialBuffer_t *SerialInputBuffer;
    SerialBuffer_t *SerialOutputBuffer;
    
    // internal packet buffer (the SIP could issue one command at a time)
    CommandPacket2 PacketBuffer;
    
    // state machine
    State_t state;
    
    // error code
    Error_t errno;
    
    // internal state
    bool isChecksumEnabled;
    
protected:
    // internal methods
    int execute(uint8_t *response, uint8_t *response_length);
    
    int assemble(uint8_t *response, uint8_t response_length);
    
    
public:
    // public methods
    int respond(uint8_t command, uint8_t *response, uint8_t response_length);
    
    // constructor
    SerialInterfaceProtocol(SerialBuffer_t *in, SerialBuffer_t *out);
    ~SerialInterfaceProtocol();
    
    // member function
    void poll();
    void registerCommand(uint8_t command, callback_func f);
    void deRegisterCommand(uint8_t command);
    
    void disableChecksum();
    void enableChecksum();
    
};
        
        
        
        
#endif