create 'packet' interface and 'read' from raw uint8_t[]
This commit is contained in:
parent
a6a2b53ca8
commit
33f343caf6
|
@ -0,0 +1,65 @@
|
|||
#include "packet.h"
|
||||
|
||||
|
||||
/* PUBLIC
|
||||
----------------------------------------*/
|
||||
// builds a packet from raw data and returns the error code
|
||||
uint8_t Packet::read(uint8_t buf[], uint8_t size){
|
||||
// 1. fail on invalid size
|
||||
if( size < 1 ) return PKTREAD_EMPTY;
|
||||
if( size > PROTO_SIZE ) return PKTREAD_OVERFLOW;
|
||||
|
||||
// 2. extract packet type
|
||||
type = buf[0] == 0;
|
||||
|
||||
// 3. extract depending on type
|
||||
return type ? read_discover(buf, size) : read_message(buf, size);
|
||||
|
||||
};
|
||||
|
||||
// writes the binary representation of the packet
|
||||
uint8_t Packet::write(uint8_t buf[], uint8_t size){
|
||||
/* TODO */
|
||||
return 0;
|
||||
};
|
||||
|
||||
|
||||
/* PRIVATE
|
||||
----------------------------------------*/
|
||||
uint8_t Packet::read_discover(uint8_t buf[], uint8_t size){
|
||||
// 1. fail on invalid size
|
||||
if( size != DISCOVER_SIZE )
|
||||
return PKTREAD_INVALID_DISCOVER_FORMAT;
|
||||
|
||||
// 2. extract fixed
|
||||
dsc.opcode = buf[0];
|
||||
dsc.wave = buf[1];
|
||||
dsc.dist = buf[2];
|
||||
|
||||
return PKTREAD_OK;
|
||||
};
|
||||
|
||||
uint8_t Packet::read_message(uint8_t buf[], uint8_t size){
|
||||
// 1. fail on invalid size
|
||||
if( size < MESSAGE_MIN_SIZE || size > MESSAGE_MAX_SIZE )
|
||||
return PKTREAD_INVALID_MESSAGE_FORMAT;
|
||||
|
||||
// 2. extract fixed
|
||||
msg.opcode = buf[0];
|
||||
msg.dist = buf[1];
|
||||
msg.ttl = buf[2];
|
||||
msg.size = buf[3];
|
||||
|
||||
// 3. check message size
|
||||
if( size - 4 - 1 != msg.size )
|
||||
return PKTREAD_INVALID_MESSAGE_FORMAT;
|
||||
|
||||
// 4. extract message
|
||||
strncpy(
|
||||
(char*) msg.data,
|
||||
(char*)buf+4,
|
||||
msg.size
|
||||
);
|
||||
|
||||
return PKTREAD_OK;
|
||||
};
|
|
@ -0,0 +1,37 @@
|
|||
#ifndef _PACKET_H_
|
||||
#define _PACKET_H_
|
||||
|
||||
#include "protocol.h"
|
||||
#include <Wire.h>
|
||||
|
||||
#define PKTREAD_OK 0
|
||||
#define PKTREAD_EMPTY 1
|
||||
#define PKTREAD_OVERFLOW 2
|
||||
#define PKTREAD_INVALID_DISCOVER_FORMAT 3
|
||||
#define PKTREAD_INVALID_MESSAGE_FORMAT 4
|
||||
|
||||
class Packet {
|
||||
private:
|
||||
// 1. common
|
||||
uint8_t buf[];
|
||||
uint8_t bufsize;
|
||||
bool type; // true = discover ; false = message
|
||||
|
||||
// 2. wrappers
|
||||
struct discover dsc;
|
||||
struct message msg;
|
||||
|
||||
// 3. helpers
|
||||
uint8_t read_discover(uint8_t buf[], uint8_t size);
|
||||
uint8_t read_message(uint8_t buf[], uint8_t size);
|
||||
|
||||
public:
|
||||
// builds a packet from raw data and returns the status code
|
||||
uint8_t read(uint8_t buf[], uint8_t size);
|
||||
|
||||
// writes the binary representation of the packet
|
||||
uint8_t write(uint8_t buf[], uint8_t size);
|
||||
|
||||
};
|
||||
|
||||
#endif
|
Loading…
Reference in New Issue