w.i.p C client, connects and sends a ping

master
Ondřej Hruška 7 years ago
parent d4bd31c964
commit 5dec30d19c
Signed by: MightyPork
GPG Key ID: 2C5FD5035250423D
  1. 3
      .gitignore
  2. 31
      CMakeLists.txt
  3. 29
      gex/TF_Integration.c
  4. 102
      gex/gex_client.c
  5. 49
      gex/gex_client.h
  6. 61
      gex/hexdump.c
  7. 19
      gex/hexdump.h
  8. 72
      gex/protocol/TF_Config.h
  9. 872
      gex/protocol/TinyFrame.c
  10. 280
      gex/protocol/TinyFrame.h
  11. 100
      gex/protocol/payload_builder.c
  12. 110
      gex/protocol/payload_builder.h
  13. 121
      gex/protocol/payload_parser.c
  14. 143
      gex/protocol/payload_parser.h
  15. 32
      gex/protocol/type_coerce.h
  16. 77
      gex/serial/serial.c
  17. 17
      gex/serial/serial.h
  18. 17
      main.c

3
.gitignore vendored

@ -50,3 +50,6 @@ modules.order
Module.symvers
Mkfile.old
dkms.conf
.idea/
cmake-build-debug/

@ -0,0 +1,31 @@
cmake_minimum_required(VERSION 3.10)
project(gex_client)
set(CMAKE_C_STANDARD 99)
set(SOURCE_FILES
main.c
gex/serial/serial.c
gex/serial/serial.h
gex/gex_client.c
gex/gex_client.h
gex/hexdump.c
gex/hexdump.h
gex/TF_Integration.c
gex/protocol/payload_builder.c
gex/protocol/payload_builder.h
gex/protocol/payload_parser.c
gex/protocol/payload_parser.h
gex/protocol/TF_Config.h
gex/protocol/TinyFrame.c
gex/protocol/TinyFrame.h
gex/protocol/type_coerce.h
)
include_directories(
gex
gex/protocol
gex/serial
)
add_executable(gex_client ${SOURCE_FILES})

@ -0,0 +1,29 @@
#include "TinyFrame.h"
#include "gex_client.h"
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
void TF_WriteImpl(const uint8_t *buff, size_t len)
{
assert(gex_serial_fd != 0);
ssize_t rv = write(gex_serial_fd, buff, len);
if (rv != len) {
fprintf(stderr, "ERROR %d in TF write: %s\n", errno, strerror(errno));
}
}
/** Claim the TX interface before composing and sending a frame */
void TF_ClaimTx(void)
{
//
}
/** Free the TX interface after composing and sending a frame */
void TF_ReleaseTx(void)
{
//
}

@ -0,0 +1,102 @@
//
// Created by MightyPork on 2017/12/12.
//
#include <malloc.h>
#include <assert.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <protocol/TinyFrame.h>
#include <string.h>
#include <errno.h>
#include "gex_client.h"
#include "serial.h"
#include "hexdump.h"
int gex_serial_fd = -1;
static void sigintHandler(int sig)
{
if (gex_serial_fd != -1) {
close(gex_serial_fd);
}
exit(0);
}
TF_Result connectivityCheckCb(TF_Msg *msg)
{
GexClient *gc = msg->userdata;
gc->connected = true;
fprintf(stderr, "GEX connected! Version string: %.*s\n", msg->len, msg->data);
msg->userdata = NULL;
return TF_CLOSE;
}
GexClient *GEX_Init(const char *device, int timeout_ms)
{
assert(device != NULL);
GexClient *gc = calloc(1, sizeof(GexClient));
assert(gc != NULL);
// Bind ^C handler for safe shutdown
signal(SIGINT, sigintHandler);
// Open the device
gc->acm_device = device;
gc->acm_fd = serial_open(device, false, (timeout_ms+50)/100);
if (gc->acm_fd == -1) {
free(gc);
return NULL;
}
gex_serial_fd = gc->acm_fd;
// Test connectivity
TF_Msg msg;
TF_ClearMsg(&msg);
msg.type = 0x01; // TODO use constant
msg.userdata = gc;
TF_Query(&msg, connectivityCheckCb, 0);
GEX_Poll(gc);
if (!gc->connected) {
fprintf(stderr, "GEX doesn't respond to ping!\n");
GEX_DeInit(gc);
return NULL;
}
// TODO load and store unit callsigns + names
return gc;
}
void GEX_Poll(GexClient *gc)
{
static uint8_t pollbuffer[4096];
assert(gc != NULL);
ssize_t len = read(gc->acm_fd, pollbuffer, 4096);
if (len < 0) {
fprintf(stderr, "ERROR %d in GEX Poll: %s\n", errno, strerror(errno));
} else {
// hexDump("Received", pollbuffer, (uint32_t) len);
TF_Accept(pollbuffer, (size_t) len);
}
}
void GEX_DeInit(GexClient *gc)
{
if (gc == NULL) return;
close(gc->acm_fd);
gex_serial_fd = -1;
free(gc);
}

@ -0,0 +1,49 @@
//
// Created by MightyPork on 2017/12/12.
//
#ifndef GEX_CLIENT_GEX_CLIENT_H
#define GEX_CLIENT_GEX_CLIENT_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
struct gex_client_ {
const char *acm_device;
int acm_fd;
bool connected;
};
typedef struct gex_client_ GexClient;
/**
* Initialize the GEX client
*
* @param device - device, e.g. /dev/ttyACM0
* @param timeout_ms - read timeout in ms (allowed only multiples of 100 ms, others are rounded)
* @return an allocated client instance
*/
GexClient *GEX_Init(const char *device, int timeout_ms);
/**
* Poll for new messages
* @param gc - client
*/
void GEX_Poll(GexClient *gc);
/**
* Safely release all resources used up by GEX_Init()
*
* @param gc - the allocated client structure
*/
void GEX_DeInit(GexClient *gc);
// --- Internal ---
/**
* This is accessed by TF_WriteImpl().
* To be removed once TF supports multiple instances, i.e. without globals
*/
extern int gex_serial_fd;
#endif //GEX_CLIENT_GEX_CLIENT_H

@ -0,0 +1,61 @@
//
// Created by MightyPork on 2017/12/04.
//
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <inttypes.h>
#include <stdio.h>
#include "hexdump.h"
void hexDump(const char *restrict desc, const void *restrict addr, uint32_t len)
{
uint32_t i;
uint8_t buff[17];
uint8_t *pc = (unsigned char*)addr;
// Output description if given.
if (desc != NULL)
fprintf(stderr, "%s:\r\n", desc);
if (len == 0) {
fprintf(stderr, " ZERO LENGTH\r\n");
return;
}
// Process every byte in the data.
for (i = 0; i < len; i++) {
// Multiple of 16 means new line (with line offset).
if ((i % 16) == 0) {
// Just don't print ASCII for the zeroth line.
if (i != 0)
fprintf(stderr, " %s\r\n", buff);
// Output the offset.
fprintf(stderr, " %04"PRIx32" ", i);
}
// Now the hex code for the specific character.
fprintf(stderr, " %02x", pc[i]);
// And store a printable ASCII character for later.
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
buff[i % 16] = '.';
else
buff[i % 16] = pc[i];
buff[(i % 16) + 1] = '\0';
}
// Pad out last line if not exactly 16 characters.
while ((i % 16) != 0) {
fprintf(stderr, " ");
i++;
}
// And print the final ASCII bit.
fprintf(stderr, " %s\r\n", buff);
(void)buff;
}

@ -0,0 +1,19 @@
//
// Created by MightyPork on 2017/12/04.
//
#ifndef GEX_HEXDUMP_H
#define GEX_HEXDUMP_H
#include <stdint.h>
/**
* HEXDUMP https://stackoverflow.com/a/7776146/2180189
*
* @param desc - description printed above the dump
* @param addr - address to dump
* @param len - number of bytes
*/
void hexDump(const char *restrict desc, const void *restrict addr, uint32_t len);
#endif //GEX_HEXDUMP_H

@ -0,0 +1,72 @@
//
// Rename to TF_Config.h
//
#ifndef TF_CONFIG_H
#define TF_CONFIG_H
#include <stdint.h>
//#include <esp8266.h> // when using with esphttpd
//----------------------------- FRAME FORMAT ---------------------------------
// The format can be adjusted to fit your particular application needs
// If the connection is reliable, you can disable the SOF byte and checksums.
// That can save up to 9 bytes of overhead.
// ,-----+----+-----+------+------------+- - - -+------------,
// | SOF | ID | LEN | TYPE | HEAD_CKSUM | DATA | PLD_CKSUM |
// | 1 | ? | ? | ? | ? | ... | ? | <- size (bytes)
// '-----+----+-----+------+------------+- - - -+------------'
// !!! BOTH SIDES MUST USE THE SAME SETTINGS !!!
// Adjust sizes as desired (1,2,4)
#define TF_ID_BYTES 2
#define TF_LEN_BYTES 2
#define TF_TYPE_BYTES 1
// Checksum type
//#define TF_CKSUM_TYPE TF_CKSUM_NONE
#define TF_CKSUM_TYPE TF_CKSUM_XOR
//#define TF_CKSUM_TYPE TF_CKSUM_CRC16
//#define TF_CKSUM_TYPE TF_CKSUM_CRC32
// Use a SOF byte to mark the start of a frame
#define TF_USE_SOF_BYTE 1
// Value of the SOF byte (if TF_USE_SOF_BYTE == 1)
#define TF_SOF_BYTE 0x01
//----------------------- PLATFORM COMPATIBILITY ----------------------------
// used for timeout tick counters - should be large enough for all used timeouts
typedef uint16_t TF_TICKS;
// used in loops iterating over listeners
typedef uint8_t TF_COUNT;
//----------------------------- PARAMETERS ----------------------------------
// Maximum received payload size (static buffer)
// Larger payloads will be rejected.
#define TF_MAX_PAYLOAD_RX 4096
// Size of the sending buffer. Larger payloads will be split to pieces and sent
// in multiple calls to the write function. This can be lowered to reduce RAM usage.
#define TF_SENDBUF_LEN 1024
// --- Listener counts - determine sizes of the static slot tables ---
// Frame ID listeners (wait for response / multi-part message)
#define TF_MAX_ID_LST 10
// Frame Type listeners (wait for frame with a specific first payload byte)
#define TF_MAX_TYPE_LST 10
// Generic listeners (fallback if no other listener catches it)
#define TF_MAX_GEN_LST 1
// Timeout for receiving & parsing a frame
// ticks = number of calls to TF_Tick()
#define TF_PARSER_TIMEOUT_TICKS 10
//------------------------- End of user config ------------------------------
#endif //TF_CONFIG_H

@ -0,0 +1,872 @@
//---------------------------------------------------------------------------
#include "TinyFrame.h"
#include <string.h>
//---------------------------------------------------------------------------
// Compatibility with ESP8266 SDK
#ifdef ICACHE_FLASH_ATTR
#define _TF_FN ICACHE_FLASH_ATTR
#else
#define _TF_FN
#endif
// Helper macros
#define TF_MAX(a, b) ((a)>(b)?(a):(b))
#define TF_MIN(a, b) ((a)<(b)?(a):(b))
enum TFState {
TFState_SOF = 0, //!< Wait for SOF
TFState_LEN, //!< Wait for Number Of Bytes
TFState_HEAD_CKSUM, //!< Wait for header Checksum
TFState_ID, //!< Wait for ID
TFState_TYPE, //!< Wait for message type
TFState_DATA, //!< Receive payload
TFState_DATA_CKSUM //!< Wait for Checksum
};
typedef struct _IdListener_struct_ {
TF_ID id;
TF_Listener fn;
TF_TICKS timeout; // nr of ticks remaining to disable this listener
TF_TICKS timeout_max; // the original timeout is stored here
void *userdata;
void *userdata2;
} IdListener;
typedef struct _TypeListener_struct_ {
TF_TYPE type;
TF_Listener fn;
} TypeListener;
typedef struct _GenericListener_struct_ {
TF_Listener fn;
} GenericListener;
/**
* Frame parser internal state
*/
static struct TinyFrameStruct {
/* Own state */
TF_Peer peer_bit; //!< Own peer bit (unqiue to avoid msg ID clash)
TF_ID next_id; //!< Next frame / frame chain ID
/* Parser state */
enum TFState state;
TF_TICKS parser_timeout_ticks;
TF_ID id; //!< Incoming packet ID
TF_LEN len; //!< Payload length
uint8_t data[TF_MAX_PAYLOAD_RX]; //!< Data byte buffer
TF_LEN rxi; //!< Field size byte counter
TF_CKSUM cksum; //!< Checksum calculated of the data stream
TF_CKSUM ref_cksum; //!< Reference checksum read from the message
TF_TYPE type; //!< Collected message type number
bool discard_data; //!< Set if (len > TF_MAX_PAYLOAD) to read the frame, but ignore the data.
/* --- Callbacks --- */
/* Transaction callbacks */
IdListener id_listeners[TF_MAX_ID_LST];
TypeListener type_listeners[TF_MAX_TYPE_LST];
GenericListener generic_listeners[TF_MAX_GEN_LST];
// Those counters are used to optimize look-up times.
// They point to the highest used slot number,
// or close to it, depending on the removal order.
TF_COUNT count_id_lst;
TF_COUNT count_type_lst;
TF_COUNT count_generic_lst;
// Buffer for building frames
uint8_t sendbuf[TF_SENDBUF_LEN];
} tf;
//region Checksums
#if TF_CKSUM_TYPE == TF_CKSUM_NONE
// NONE
#define CKSUM_RESET(cksum)
#define CKSUM_ADD(cksum, byte)
#define CKSUM_FINALIZE(cksum)
#elif TF_CKSUM_TYPE == TF_CKSUM_XOR
// ~XOR
#define CKSUM_RESET(cksum) do { (cksum) = 0; } while (0)
#define CKSUM_ADD(cksum, byte) do { (cksum) ^= (byte); } while(0)
#define CKSUM_FINALIZE(cksum) do { (cksum) = (TF_CKSUM)~cksum; } while(0)
#elif TF_CKSUM_TYPE == TF_CKSUM_CRC16
/** CRC table for the CRC-16. The poly is 0x8005 (x^16 + x^15 + x^2 + 1) */
static const uint16_t crc16_table[256] = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};
static inline uint16_t crc16_byte(uint16_t cksum, const uint8_t byte)
{
return (cksum >> 8) ^ crc16_table[(cksum ^ byte) & 0xff];
}
#define CKSUM_RESET(cksum) do { (cksum) = 0; } while (0)
#define CKSUM_ADD(cksum, byte) do { (cksum) = crc16_byte((cksum), (byte)); } while(0)
#define CKSUM_FINALIZE(cksum)
#elif TF_CKSUM_TYPE == TF_CKSUM_CRC32
static const uint32_t crc32_table[] = { /* CRC polynomial 0xedb88320 */
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
static inline uint32_t crc32_byte(uint32_t cksum, const uint8_t byte)
{
return (crc32_table[((cksum) ^ ((uint8_t)byte)) & 0xff] ^ ((cksum) >> 8));
}
#define CKSUM_RESET(cksum) do { (cksum) = (TF_CKSUM)0xFFFFFFFF; } while (0)
#define CKSUM_ADD(cksum, byte) do { (cksum) = crc32_byte(cksum, byte); } while(0)
#define CKSUM_FINALIZE(cksum) do { (cksum) = (TF_CKSUM)~(cksum); } while(0)
#endif
//endregion
void _TF_FN TF_Init(TF_Peer peer_bit)
{
// Zero it out
memset(&tf, 0, sizeof(struct TinyFrameStruct));
tf.peer_bit = peer_bit;
}
//region Listeners
static void _TF_FN renew_id_listener(IdListener *lst)
{
lst->timeout = lst->timeout_max;
}
/**
* Notify callback about ID listener demise & clean it
*
* @param lst - listener to clean
*/
static void _TF_FN cleanup_id_listener(TF_COUNT i, IdListener *lst)
{
TF_Msg msg;
if (lst->fn == NULL) return;
// Make user clean up their data - only if not NULL
if (lst->userdata != NULL) {
msg.userdata = lst->userdata;
msg.userdata2 = lst->userdata2;
msg.data = NULL; // this is a signal that the listener should clean up
lst->fn(&msg); // return value is ignored here - use TF_STAY or TF_CLOSE
}
lst->fn = NULL; // Discard listener
if (i == tf.count_id_lst - 1) {
tf.count_id_lst--;
}
}
/**
* Clean up Type listener
*
* @param lst - listener to clean
*/
static inline void _TF_FN cleanup_type_listener(TF_COUNT i, TypeListener *lst)
{
lst->fn = NULL; // Discard listener
if (i == tf.count_type_lst - 1) {
tf.count_type_lst--;
}
}
/**
* Clean up Generic listener
*
* @param lst - listener to clean
*/
static inline void _TF_FN cleanup_generic_listener(TF_COUNT i, GenericListener *lst)
{
lst->fn = NULL; // Discard listener
if (i == tf.count_generic_lst - 1) {
tf.count_generic_lst--;
}
}
bool _TF_FN TF_AddIdListener(TF_Msg *msg, TF_Listener cb, TF_TICKS timeout)
{
TF_COUNT i;
IdListener *lst;
for (i = 0; i < TF_MAX_ID_LST; i++) {
lst = &tf.id_listeners[i];
// test for empty slot
if (lst->fn == NULL) {
lst->fn = cb;
lst->id = msg->frame_id;
lst->userdata = msg->userdata;
lst->userdata2 = msg->userdata2;
lst->timeout_max = lst->timeout = timeout;
if (i >= tf.count_id_lst) {
tf.count_id_lst = (TF_COUNT) (i + 1);
}
return true;
}
}
return false;
}
bool _TF_FN TF_AddTypeListener(TF_TYPE frame_type, TF_Listener cb)
{
TF_COUNT i;
TypeListener *lst;
for (i = 0; i < TF_MAX_TYPE_LST; i++) {
lst = &tf.type_listeners[i];
// test for empty slot
if (lst->fn == NULL) {
lst->fn = cb;
lst->type = frame_type;
if (i >= tf.count_type_lst) {
tf.count_type_lst = (TF_COUNT) (i + 1);
}
return true;
}
}
return false;
}
bool _TF_FN TF_AddGenericListener(TF_Listener cb)
{
TF_COUNT i;
GenericListener *lst;
for (i = 0; i < TF_MAX_GEN_LST; i++) {
lst = &tf.generic_listeners[i];
// test for empty slot
if (lst->fn == NULL) {
lst->fn = cb;
if (i >= tf.count_generic_lst) {
tf.count_generic_lst = (TF_COUNT) (i + 1);
}
return true;
}
}
return false;
}
bool _TF_FN TF_RemoveIdListener(TF_ID frame_id)
{
TF_COUNT i;
IdListener *lst;
for (i = 0; i < tf.count_id_lst; i++) {
lst = &tf.id_listeners[i];
// test if live & matching
if (lst->fn != NULL && lst->id == frame_id) {
cleanup_id_listener(i, lst);
return true;
}
}
return false;
}
bool _TF_FN TF_RemoveTypeListener(TF_TYPE type)
{
TF_COUNT i;
TypeListener *lst;
for (i = 0; i < tf.count_type_lst; i++) {
lst = &tf.type_listeners[i];
// test if live & matching
if (lst->fn != NULL && lst->type == type) {
cleanup_type_listener(i, lst);
return true;
}
}
return false;
}
bool _TF_FN TF_RemoveGenericListener(TF_Listener cb)
{
TF_COUNT i;
GenericListener *lst;
for (i = 0; i < tf.count_generic_lst; i++) {
lst = &tf.generic_listeners[i];
// test if live & matching
if (lst->fn == cb) {
cleanup_generic_listener(i, lst);
return true;
}
}
return false;
}
/** Handle a message that was just collected & verified by the parser */
static void _TF_FN TF_HandleReceivedMessage(void)
{
TF_COUNT i;
IdListener *ilst;
TypeListener *tlst;
GenericListener *glst;
TF_Result res;
// Prepare message object
TF_Msg msg;
msg.frame_id = tf.id;
msg.is_response = false;
msg.type = tf.type;
msg.data = tf.data;
msg.len = tf.len;
//dumpFrameInfo(&msg);
// Any listener can consume the message (return true),
// or let someone else handle it.
// The loop upper bounds are the highest currently used slot index
// (or close to it, depending on the order of listener removals)
// ID listeners first
for (i = 0; i < tf.count_id_lst; i++) {
ilst = &tf.id_listeners[i];
if (ilst->fn && ilst->id == msg.frame_id) {
msg.userdata = ilst->userdata; // pass userdata pointer to the callback
msg.userdata2 = ilst->userdata2;
res = ilst->fn(&msg);
ilst->userdata = msg.userdata; // put it back (may have changed the pointer or set to NULL)
ilst->userdata2 = msg.userdata2; // put it back (may have changed the pointer or set to NULL)
if (res != TF_NEXT) {
if (res == TF_CLOSE) {
cleanup_id_listener(i, ilst);
}
else if (res == TF_RENEW) {
renew_id_listener(ilst);
}
return;
}
}
}
msg.userdata = NULL;
msg.userdata2 = NULL;
// clean up for the following listeners that don't use userdata
// Type listeners
for (i = 0; i < tf.count_type_lst; i++) {
tlst = &tf.type_listeners[i];
if (tlst->fn && tlst->type == msg.type) {
res = tlst->fn(&msg);
if (res != TF_NEXT) {
if (res == TF_CLOSE) {
cleanup_type_listener(i, tlst);
}
return;
}
}
}
// Generic listeners
for (i = 0; i < tf.count_generic_lst; i++) {
glst = &tf.generic_listeners[i];
if (glst->fn) {
res = glst->fn(&msg);
if (res != TF_NEXT) {
if (res == TF_CLOSE) {
cleanup_generic_listener(i, glst);
}
return;
}
}
}
}
//endregion Listeners
void _TF_FN TF_Accept(const uint8_t *buffer, size_t count)
{
size_t i;
for (i = 0; i < count; i++) {
TF_AcceptChar(buffer[i]);
}
}
void _TF_FN TF_ResetParser(void)
{
tf.state = TFState_SOF;
}
/** SOF was received */
static void _TF_FN TF_ParsBeginFrame(void) {
// Reset state vars
CKSUM_RESET(tf.cksum);
#if TF_USE_SOF_BYTE
CKSUM_ADD(tf.cksum, TF_SOF_BYTE);
#endif
tf.discard_data = false;
// Enter ID state
tf.state = TFState_ID;
tf.rxi = 0;
}
void _TF_FN TF_AcceptChar(unsigned char c)
{
// Parser timeout - clear
if (tf.parser_timeout_ticks >= TF_PARSER_TIMEOUT_TICKS) {
TF_ResetParser();
}
tf.parser_timeout_ticks = 0;
// DRY snippet - collect multi-byte number from the input stream
#define COLLECT_NUMBER(dest, type) dest = (type)(((dest) << 8) | c); \
if (++tf.rxi == sizeof(type))
#if !TF_USE_SOF_BYTE
if (tf.state == TFState_SOF) {
TF_ParsBeginFrame();
}
#endif
switch (tf.state) {
case TFState_SOF:
if (c == TF_SOF_BYTE) {
TF_ParsBeginFrame();
}
break;
case TFState_ID:
CKSUM_ADD(tf.cksum, c);
COLLECT_NUMBER(tf.id, TF_ID) {
// Enter LEN state
tf.state = TFState_LEN;
tf.rxi = 0;
}
break;
case TFState_LEN:
CKSUM_ADD(tf.cksum, c);
COLLECT_NUMBER(tf.len, TF_LEN) {
// Enter TYPE state
tf.state = TFState_TYPE;
tf.rxi = 0;
}
break;
case TFState_TYPE:
CKSUM_ADD(tf.cksum, c);
COLLECT_NUMBER(tf.type, TF_TYPE) {
#if TF_CKSUM_TYPE == TF_CKSUM_NONE
tf.state = TFState_DATA;
tf.rxi = 0;
#else
// enter HEAD_CKSUM state
tf.state = TFState_HEAD_CKSUM;
tf.rxi = 0;
tf.ref_cksum = 0;
#endif
}
break;
case TFState_HEAD_CKSUM:
COLLECT_NUMBER(tf.ref_cksum, TF_CKSUM) {
// Check the header checksum against the computed value
CKSUM_FINALIZE(tf.cksum);
if (tf.cksum != tf.ref_cksum) {
TF_ResetParser();
break;
}
if (tf.len == 0) {
TF_HandleReceivedMessage();
TF_ResetParser();
break;
}
// Enter DATA state
tf.state = TFState_DATA;
tf.rxi = 0;
CKSUM_RESET(tf.cksum); // Start collecting the payload
if (tf.len >= TF_MAX_PAYLOAD_RX) {
// ERROR - frame too long. Consume, but do not store.
tf.discard_data = true;
}
}
break;
case TFState_DATA:
if (tf.discard_data) {
tf.rxi++;
} else {
CKSUM_ADD(tf.cksum, c);
tf.data[tf.rxi++] = c;
}
if (tf.rxi == tf.len) {
#if TF_CKSUM_TYPE == TF_CKSUM_NONE
// All done
TF_HandleReceivedMessage();
TF_ResetParser();
#else
// Enter DATA_CKSUM state
tf.state = TFState_DATA_CKSUM;
tf.rxi = 0;
tf.ref_cksum = 0;
#endif
}
break;
case TFState_DATA_CKSUM:
COLLECT_NUMBER(tf.ref_cksum, TF_CKSUM) {
// Check the header checksum against the computed value
CKSUM_FINALIZE(tf.cksum);
if (!tf.discard_data && tf.cksum == tf.ref_cksum) {
TF_HandleReceivedMessage();
}
TF_ResetParser();
}
break;
}
// we get here after finishing HEAD, if no data are to be received - handle and clear
if (tf.len == 0 && tf.state == TFState_DATA) {
TF_HandleReceivedMessage();
TF_ResetParser();
}
}
// Helper macros for the Compose functions
// use variables: si - signed int, b - byte, outbuf - target buffer, pos - count of bytes in buffer
#define WRITENUM_BASE(type, num, xtra) \
for (si = sizeof(type)-1; si>=0; si--) { \
b = (uint8_t)((num) >> (si*8) & 0xFF); \
outbuff[pos++] = b; \
xtra; \
}
#define _NOOP()
#define WRITENUM(type, num) WRITENUM_BASE(type, num, _NOOP())
#define WRITENUM_CKSUM(type, num) WRITENUM_BASE(type, num, CKSUM_ADD(cksum, b))
/**
* Compose a frame (used internally by TF_Send and TF_Respond).
* The frame can be sent using TF_WriteImpl(), or received by TF_Accept()
*
* @param outbuff - buffer to store the result in
* @param msgid - message ID is stored here, if not NULL
* @param type - message type
* @param len - payload size in bytes
* @param explicit_id - ID to use in the frame (8-bit)
* @param use_expl_id - whether to use the previous param
* @return nr of bytes in outbuff used by the frame, 0 on failure
*/
static inline size_t _TF_FN TF_ComposeHead(uint8_t *outbuff, TF_ID *id_ptr,
TF_TYPE type, TF_LEN data_len,
TF_ID explicit_id, bool use_expl_id)
{
int8_t si = 0; // signed small int
uint8_t b = 0;
TF_ID id = 0;
TF_CKSUM cksum = 0;
size_t pos = 0; // can be needed to grow larger than TF_LEN
(void)cksum;
CKSUM_RESET(cksum);
// Gen ID
if (use_expl_id) {
id = explicit_id;
}
else {
id = (TF_ID) (tf.next_id++ & TF_ID_MASK);
if (tf.peer_bit) {
id |= TF_ID_PEERBIT;
}
}
if (id_ptr != NULL) *id_ptr = id;
// --- Start ---
CKSUM_RESET(cksum);
#if TF_USE_SOF_BYTE
outbuff[pos++] = TF_SOF_BYTE;
CKSUM_ADD(cksum, TF_SOF_BYTE);
#endif
WRITENUM_CKSUM(TF_ID, id);
WRITENUM_CKSUM(TF_LEN, data_len);
WRITENUM_CKSUM(TF_TYPE, type);
#if TF_CKSUM_TYPE != TF_CKSUM_NONE
CKSUM_FINALIZE(cksum);
WRITENUM(TF_CKSUM, cksum);
#endif
return pos;
}
/**
* Compose a frame (used internally by TF_Send and TF_Respond).
* The frame can be sent using TF_WriteImpl(), or received by TF_Accept()
*
* @param outbuff - buffer to store the result in
* @param data - data buffer
* @param data_len - data buffer len
* @param cksum - checksum variable, used for all calls to TF_ComposeBody. Must be reset before first use! (CKSUM_RESET(cksum);)
* @return nr of bytes in outbuff used
*/
static size_t _TF_FN TF_ComposeBody(uint8_t *outbuff, const uint8_t *data, TF_LEN data_len, TF_CKSUM *cksum)
{
TF_LEN i = 0;
uint8_t b = 0;
size_t pos = 0;
for (i = 0; i < data_len; i++) {
b = data[i];
outbuff[pos++] = b;
CKSUM_ADD(*cksum, b);
}
return pos;
}
/**
* Finalize a frame
*
* @param outbuff - buffer to store the result in
* @param cksum - checksum variable used for the body
* @return nr of bytes in outbuff used
*/
static size_t _TF_FN TF_ComposeTail(uint8_t *outbuff, TF_CKSUM *cksum)
{
int8_t si = 0; // signed small int
uint8_t b = 0;
size_t pos = 0;
#if TF_CKSUM_TYPE != TF_CKSUM_NONE
CKSUM_FINALIZE(*cksum);
WRITENUM(TF_CKSUM, *cksum);
#endif
return pos;
}
// send with listener
static bool _TF_FN TF_SendFrame(TF_Msg *msg, TF_Listener listener, TF_TICKS timeout)
{
size_t len = 0;
size_t remain = 0;
size_t sent = 0;
TF_CKSUM cksum = 0;
TF_ClaimTx();
len = TF_ComposeHead(tf.sendbuf,
&msg->frame_id,
msg->type,
msg->len,
msg->frame_id,
msg->is_response);
if (listener) TF_AddIdListener(msg, listener, timeout);
CKSUM_RESET(cksum);
remain = msg->len;
while (remain > 0) {
size_t chunk = TF_MIN(TF_SENDBUF_LEN - len, remain);
len += TF_ComposeBody(tf.sendbuf+len, msg->data+sent, (TF_LEN) chunk, &cksum);
remain -= chunk;
sent += chunk;
// Flush if the buffer is full and we have more to send
if (remain > 0 && len == TF_SENDBUF_LEN) {
TF_WriteImpl((const uint8_t *) tf.sendbuf, len);
len = 0;
}
}
// Flush if checksum wouldn't fit in the buffer
if (TF_SENDBUF_LEN - len < sizeof(TF_CKSUM)) {
TF_WriteImpl((const uint8_t *) tf.sendbuf, len);
len = 0;
}
// Add checksum, flush what remains to be sent
len += TF_ComposeTail(tf.sendbuf+len, &cksum);
TF_WriteImpl((const uint8_t *) tf.sendbuf, len);
TF_ReleaseTx();
return true;
}
// send without listener
bool _TF_FN TF_Send(TF_Msg *msg)
{
return TF_SendFrame(msg, NULL, 0);
}
// send without listener and struct
bool _TF_FN TF_SendSimple(TF_TYPE type, const uint8_t *data, TF_LEN len)
{
TF_Msg msg;
TF_ClearMsg(&msg);
msg.type = type;
msg.data = data;
msg.len = len;
return TF_Send(&msg);
}
// send without listener and struct
bool _TF_FN TF_QuerySimple(TF_TYPE type, const uint8_t *data, TF_LEN len, TF_Listener listener, TF_TICKS timeout, void *userdata)
{
TF_Msg msg;
TF_ClearMsg(&msg);
msg.type = type;
msg.data = data;
msg.len = len;
msg.userdata = userdata;
return TF_SendFrame(&msg, listener, timeout);
}
// send with listener
bool _TF_FN TF_Query(TF_Msg *msg, TF_Listener listener, TF_TICKS timeout)
{
return TF_SendFrame(msg, listener, timeout);
}
// Like TF_Send, but with explicit frame ID
bool _TF_FN TF_Respond(TF_Msg *msg)
{
msg->is_response = true;
return TF_Send(msg);
}
bool _TF_FN TF_RenewIdListener(TF_ID id)
{
TF_COUNT i;
IdListener *lst;
for (i = 0; i < tf.count_id_lst; i++) {
lst = &tf.id_listeners[i];
// test if live & matching
if (lst->fn != NULL && lst->id == id) {
renew_id_listener(lst);
return true;
}
}
return false;
}
/** Timebase hook - for timeouts */
void _TF_FN TF_Tick(void)
{
TF_COUNT i = 0;
IdListener *lst;
// increment parser timeout (timeout is handled when receiving next byte)
if (tf.parser_timeout_ticks < TF_PARSER_TIMEOUT_TICKS) {
tf.parser_timeout_ticks++;
}
// decrement and expire ID listeners
for (i = 0; i < tf.count_id_lst; i++) {
lst = &tf.id_listeners[i];
if (!lst->fn || lst->timeout == 0) continue;
// count down...
if (--lst->timeout == 0) {
// Listener has expired
cleanup_id_listener(i, lst);
}
}
}
void __attribute__((weak)) TF_ClaimTx(void)
{
// do nothing
}
void __attribute__((weak)) TF_ReleaseTx(void)
{
// do nothing
}

@ -0,0 +1,280 @@
#ifndef TinyFrameH
#define TinyFrameH
/**
* TinyFrame protocol library
*
* (c) Ondřej Hruška 2017, MIT License
* no liability/warranty, free for any use, must retain this notice & license
*
* Upstream URL: https://github.com/MightyPork/TinyFrame
*/
#define TF_VERSION "1.2.0"
//---------------------------------------------------------------------------
#include <stdint.h> // for uint8_t etc
#include <stdbool.h> // for bool
#include <stdlib.h> // for NULL
//---------------------------------------------------------------------------
// Select checksum type (0 = none, 8 = ~XOR, 16 = CRC16 0x8005, 32 = CRC32)
#define TF_CKSUM_NONE 0
#define TF_CKSUM_XOR 8
#define TF_CKSUM_CRC16 16
#define TF_CKSUM_CRC32 32
#include <TF_Config.h>
//region Resolve data types
#if TF_LEN_BYTES == 1
typedef uint8_t TF_LEN;
#elif TF_LEN_BYTES == 2
typedef uint16_t TF_LEN;
#elif TF_LEN_BYTES == 4
typedef uint32_t TF_LEN;
#else
#error Bad value of TF_LEN_BYTES, must be 1, 2 or 4
#endif
#if TF_TYPE_BYTES == 1
typedef uint8_t TF_TYPE;
#elif TF_TYPE_BYTES == 2
typedef uint16_t TF_TYPE;
#elif TF_TYPE_BYTES == 4
typedef uint32_t TF_TYPE;
#else
#error Bad value of TF_TYPE_BYTES, must be 1, 2 or 4
#endif
#if TF_ID_BYTES == 1
typedef uint8_t TF_ID;
#elif TF_ID_BYTES == 2
typedef uint16_t TF_ID;
#elif TF_ID_BYTES == 4
typedef uint32_t TF_ID;
#else
#error Bad value of TF_ID_BYTES, must be 1, 2 or 4
#endif
#if TF_CKSUM_TYPE == TF_CKSUM_XOR || TF_CKSUM_TYPE == TF_CKSUM_NONE
// ~XOR (if 0, still use 1 byte - it won't be used)
typedef uint8_t TF_CKSUM;
#elif TF_CKSUM_TYPE == TF_CKSUM_CRC16
// CRC16
typedef uint16_t TF_CKSUM;
#elif TF_CKSUM_TYPE == TF_CKSUM_CRC32
// CRC32
typedef uint32_t TF_CKSUM;
#else
#error Bad value for TF_CKSUM_TYPE, must be 8, 16 or 32
#endif
//endregion
//---------------------------------------------------------------------------
// Type-dependent masks for bit manipulation in the ID field
#define TF_ID_MASK (TF_ID)(((TF_ID)1 << (sizeof(TF_ID)*8 - 1)) - 1)
#define TF_ID_PEERBIT (TF_ID)((TF_ID)1 << ((sizeof(TF_ID)*8) - 1))
//---------------------------------------------------------------------------
/** Peer bit enum (used for init) */
typedef enum {
TF_SLAVE = 0,
TF_MASTER,
} TF_Peer;
typedef enum {
TF_NEXT = 0, //!< Not handled, let other listeners handle it
TF_STAY = 1, //!< Handled, stay
TF_RENEW = 2, //!< Handled, stay, renew - useful only with listener timeout
TF_CLOSE = 3, //!< Handled, remove self
} TF_Result;
/** Data structure for sending / receiving messages */
typedef struct _TF_MSG_STRUCT_ {
TF_ID frame_id; //!< message ID
bool is_response; //!< internal flag, set when using the Respond function. frame_id is then kept unchanged.
TF_TYPE type; //!< received or sent message type
const uint8_t *data; //!< buffer of received data or data to send. NULL = listener timed out, free userdata!
TF_LEN len; //!< length of the buffer
void *userdata; //!< here's a place for custom data; this data will be stored with the listener
void *userdata2;
} TF_Msg;
/**
* Clear message struct
*/
static inline void TF_ClearMsg(TF_Msg *msg)
{
msg->frame_id = 0;
msg->is_response = false;
msg->type = 0;
msg->data = NULL;
msg->len = 0;
msg->userdata = NULL;
msg->userdata2 = NULL;
}
/**
* TinyFrame Type Listener callback
*
* @param frame_id - ID of the received frame
* @param type - type field from the message
* @param data - byte buffer with the application data
* @param len - number of bytes in the buffer
* @return listener result
*/
typedef TF_Result (*TF_Listener)(TF_Msg *msg);
/**
* Initialize the TinyFrame engine.
* This can also be used to completely reset it (removing all listeners etc)
*
* @param peer_bit - peer bit to use for self
*/
void TF_Init(TF_Peer peer_bit);
/**
* Reset the frame parser state machine.
* This does not affect registered listeners.
*/
void TF_ResetParser(void);
/**
* Register a frame type listener.
*
* @param msg - message (contains frame_id and userdata)
* @param cb - callback
* @param timeout - timeout in ticks to auto-remove the listener (0 = keep forever)
* @return slot index (for removing), or TF_ERROR (-1)
*/
bool TF_AddIdListener(TF_Msg *msg, TF_Listener cb, TF_TICKS timeout);
/**
* Remove a listener by the message ID it's registered for
*
* @param frame_id - the frame we're listening for
*/
bool TF_RemoveIdListener(TF_ID frame_id);
/**
* Register a frame type listener.
*
* @param frame_type - frame type to listen for
* @param cb - callback
* @return slot index (for removing), or TF_ERROR (-1)
*/
bool TF_AddTypeListener(TF_TYPE frame_type, TF_Listener cb);
/**
* Remove a listener by type.
*
* @param type - the type it's registered for
*/
bool TF_RemoveTypeListener(TF_TYPE type);
/**
* Register a generic listener.
*
* @param cb - callback
* @return slot index (for removing), or TF_ERROR (-1)
*/
bool TF_AddGenericListener(TF_Listener cb);
/**
* Remove a generic listener by function pointer
*
* @param cb - callback function to remove
*/
bool TF_RemoveGenericListener(TF_Listener cb);
/**
* Send a frame, no listener
*
* @param msg - message struct. ID is stored in the frame_id field
* @return success
*/
bool TF_Send(TF_Msg *msg);
/**
* Like TF_Send, but without the struct
*/
bool TF_SendSimple(TF_TYPE type, const uint8_t *data, TF_LEN len);
/**
* Like TF_Query, but without the struct
*/
bool TF_QuerySimple(TF_TYPE type, const uint8_t *data, TF_LEN len, TF_Listener listener, TF_TICKS timeout, void *userdata);
/**
* Send a frame, and optionally attach an ID listener.
*
* @param msg - message struct. ID is stored in the frame_id field
* @param listener - listener waiting for the response (can be NULL)
* @param timeout - listener expiry time in ticks
* @return success
*/
bool TF_Query(TF_Msg *msg, TF_Listener listener, TF_TICKS timeout);
/**
* Send a response to a received message.
*
* @param msg - message struct. ID is read from frame_id. set ->renew to reset listener timeout
* @return success
*/
bool TF_Respond(TF_Msg *msg);
/**
* Renew ID listener timeout
*
* @param id - listener ID to renew
* @return true if listener was found and renewed
*/
bool TF_RenewIdListener(TF_ID id);
/**
* Accept incoming bytes & parse frames
*
* @param buffer - byte buffer to process
* @param count - nr of bytes in the buffer
*/
void TF_Accept(const uint8_t *buffer, size_t count);
/**
* Accept a single incoming byte
*
* @param c - a received char
*/
void TF_AcceptChar(uint8_t c);
/**
* 'Write bytes' function that sends data to UART
*
* ! Implement this in your application code !
*/
extern void TF_WriteImpl(const uint8_t *buff, size_t len);
/**
* This function should be called periodically.
*
* The time base is used to time-out partial frames in the parser and
* automatically reset it.
*
* (suggestion - call this in a SysTick handler)
*/
void TF_Tick(void);
/** Claim the TX interface before composing and sending a frame */
extern void TF_ClaimTx(void);
/** Free the TX interface after composing and sending a frame */
extern void TF_ReleaseTx(void);
#endif

@ -0,0 +1,100 @@
#include <string.h>
#include "payload_builder.h"
#define pb_check_capacity(pb, needed) \
if ((pb)->current + (needed) > (pb)->end) { \
if ((pb)->full_handler == NULL || !(pb)->full_handler(pb, needed)) (pb)->ok = 0; \
}
/** Write from a buffer */
bool pb_buf(PayloadBuilder *pb, const uint8_t *buf, uint32_t len)
{
pb_check_capacity(pb, len);
if (!pb->ok) return false;
memcpy(pb->current, buf, len);
pb->current += len;
return true;
}
/** Write s zero terminated string */
bool pb_string(PayloadBuilder *pb, const char *str)
{
uint32_t len = (uint32_t) strlen(str);
pb_check_capacity(pb, len+1);
if (!pb->ok) return false;
memcpy(pb->current, str, len+1);
pb->current += len+1;
return true;
}
/** Write uint8_t to the buffer */
bool pb_u8(PayloadBuilder *pb, uint8_t byte)
{
pb_check_capacity(pb, 1);
if (!pb->ok) return false;
*pb->current++ = byte;
return true;
}
/** Write uint16_t to the buffer. */
bool pb_u16(PayloadBuilder *pb, uint16_t word)
{
pb_check_capacity(pb, 2);
if (!pb->ok) return false;
if (pb->bigendian) {
*pb->current++ = (uint8_t) ((word >> 8) & 0xFF);
*pb->current++ = (uint8_t) (word & 0xFF);
} else {
*pb->current++ = (uint8_t) (word & 0xFF);
*pb->current++ = (uint8_t) ((word >> 8) & 0xFF);
}
return true;
}
/** Write uint32_t to the buffer. */
bool pb_u32(PayloadBuilder *pb, uint32_t word)
{
pb_check_capacity(pb, 4);
if (!pb->ok) return false;
if (pb->bigendian) {
*pb->current++ = (uint8_t) ((word >> 24) & 0xFF);
*pb->current++ = (uint8_t) ((word >> 16) & 0xFF);
*pb->current++ = (uint8_t) ((word >> 8) & 0xFF);
*pb->current++ = (uint8_t) (word & 0xFF);
} else {
*pb->current++ = (uint8_t) (word & 0xFF);
*pb->current++ = (uint8_t) ((word >> 8) & 0xFF);
*pb->current++ = (uint8_t) ((word >> 16) & 0xFF);
*pb->current++ = (uint8_t) ((word >> 24) & 0xFF);
}
return true;
}
/** Write int8_t to the buffer. */
bool pb_i8(PayloadBuilder *pb, int8_t byte)
{
return pb_u8(pb, ((union conv8){.i8 = byte}).u8);
}
/** Write int16_t to the buffer. */
bool pb_i16(PayloadBuilder *pb, int16_t word)
{
return pb_u16(pb, ((union conv16){.i16 = word}).u16);
}
/** Write int32_t to the buffer. */
bool pb_i32(PayloadBuilder *pb, int32_t word)
{
return pb_u32(pb, ((union conv32){.i32 = word}).u32);
}
/** Write 4-byte float to the buffer. */
bool pb_float(PayloadBuilder *pb, float f)
{
return pb_u32(pb, ((union conv32){.f32 = f}).u32);
}

@ -0,0 +1,110 @@
#ifndef PAYLOAD_BUILDER_H
#define PAYLOAD_BUILDER_H
/**
* PayloadBuilder, part of the TinyFrame utilities collection
*
* (c) Ondřej Hruška, 2014-2017. MIT license.
*
* The builder supports big and little endian which is selected when
* initializing it or by accessing the bigendian struct field.
*
* This module helps you with building payloads (not only for TinyFrame)
*
* The builder performs bounds checking and calls the provided handler when
* the requested write wouldn't fit. Use the handler to realloc / flush the buffer
* or report an error.
*/
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "type_coerce.h"
typedef struct PayloadBuilder_ PayloadBuilder;
/**
* Full buffer handler.
*
* 'needed' more bytes should be written but the end of the buffer was reached.
*
* Return true if the problem was solved (e.g. buffer was flushed and the
* 'current' pointer moved to the beginning).
*
* If false is returned, the 'ok' flag on the struct is set to false
* and all following writes are discarded.
*/
typedef bool (*pb_full_handler)(PayloadBuilder *pb, uint32_t needed);
struct PayloadBuilder_ {
uint8_t *start; //!< Pointer to the beginning of the buffer
uint8_t *current; //!< Pointer to the next byte to be read
uint8_t *end; //!< Pointer to the end of the buffer (start + length)
pb_full_handler full_handler; //!< Callback for buffer overrun
bool bigendian; //!< Flag to use big-endian parsing
bool ok; //!< Indicates that all reads were successful
};
// --- initializer helper macros ---
/** Start the builder. */
#define pb_start_e(buf, capacity, bigendian, full_handler) ((PayloadBuilder){buf, buf, (buf)+(capacity), full_handler, bigendian, 1})
/** Start the builder in big-endian mode */
#define pb_start_be(buf, capacity, full_handler) pb_start_e(buf, capacity, 1, full_handler)
/** Start the builder in little-endian mode */
#define pb_start_le(buf, capacity, full_handler) pb_start_e(buf, capacity, 0, full_handler)
/** Start the parser in little-endian mode (default) */
#define pb_start(buf, capacity, full_handler) pb_start_le(buf, capacity, full_handler)
// --- utilities ---
/** Get already used bytes count */
#define pb_length(pb) ((pb)->current - (pb)->start)
/** Reset the current pointer to start */
#define pb_rewind(pb) do { pb->current = pb->start; } while (0)
/** Write from a buffer */
bool pb_buf(PayloadBuilder *pb, const uint8_t *buf, uint32_t len);
/** Write a zero terminated string */
bool pb_string(PayloadBuilder *pb, const char *str);
/** Write uint8_t to the buffer */
bool pb_u8(PayloadBuilder *pb, uint8_t byte);
/** Write boolean to the buffer. */
static inline bool pb_bool(PayloadBuilder *pb, bool b)
{
return pb_u8(pb, (uint8_t) b);
}
/** Write uint16_t to the buffer. */
bool pb_u16(PayloadBuilder *pb, uint16_t word);
/** Write uint32_t to the buffer. */
bool pb_u32(PayloadBuilder *pb, uint32_t word);
/** Write int8_t to the buffer. */
bool pb_i8(PayloadBuilder *pb, int8_t byte);
/** Write char (int8_t) to the buffer. */
static inline bool pb_char(PayloadBuilder *pb, char c)
{
return pb_i8(pb, c);
}
/** Write int16_t to the buffer. */
bool pb_i16(PayloadBuilder *pb, int16_t word);
/** Write int32_t to the buffer. */
bool pb_i32(PayloadBuilder *pb, int32_t word);
/** Write 4-byte float to the buffer. */
bool pb_float(PayloadBuilder *pb, float f);
#endif // PAYLOAD_BUILDER_H

@ -0,0 +1,121 @@
#include "payload_parser.h"
#define pp_check_capacity(pp, needed) \
if ((pp)->current + (needed) > (pp)->end) { \
if ((pp)->empty_handler == NULL || !(pp)->empty_handler(pp, needed)) {(pp)->ok = 0;} ; \
}
void pp_skip(PayloadParser *pp, uint32_t num)
{
pp->current += num;
}
uint8_t pp_u8(PayloadParser *pp)
{
pp_check_capacity(pp, 1);
if (!pp->ok) return 0;
return *pp->current++;
}
uint16_t pp_u16(PayloadParser *pp)
{
pp_check_capacity(pp, 2);
if (!pp->ok) return 0;
uint16_t x = 0;
if (pp->bigendian) {
x |= *pp->current++ << 8;
x |= *pp->current++;
} else {
x |= *pp->current++;
x |= *pp->current++ << 8;
}
return x;
}
uint32_t pp_u32(PayloadParser *pp)
{
pp_check_capacity(pp, 4);
if (!pp->ok) return 0;
uint32_t x = 0;
if (pp->bigendian) {
x |= (uint32_t) (*pp->current++ << 24);
x |= (uint32_t) (*pp->current++ << 16);
x |= (uint32_t) (*pp->current++ << 8);
x |= *pp->current++;
} else {
x |= *pp->current++;
x |= (uint32_t) (*pp->current++ << 8);
x |= (uint32_t) (*pp->current++ << 16);
x |= (uint32_t) (*pp->current++ << 24);
}
return x;
}
const uint8_t *pp_tail(PayloadParser *pp, uint32_t *length)
{
int32_t len = (int) (pp->end - pp->current);
if (!pp->ok || len <= 0) {
if (length != NULL) *length = 0;
return NULL;
}
if (length != NULL) {
*length = (uint32_t) len;
}
return pp->current;
}
/** Read int8_t from the payload. */
int8_t pp_i8(PayloadParser *pp)
{
return ((union conv8) {.u8 = pp_u8(pp)}).i8;
}
/** Read int16_t from the payload. */
int16_t pp_i16(PayloadParser *pp)
{
return ((union conv16) {.u16 = pp_u16(pp)}).i16;
}
/** Read int32_t from the payload. */
int32_t pp_i32(PayloadParser *pp)
{
return ((union conv32) {.u32 = pp_u32(pp)}).i32;
}
/** Read 4-byte float from the payload. */
float pp_float(PayloadParser *pp)
{
return ((union conv32) {.u32 = pp_u32(pp)}).f32;
}
/** Read a zstring */
uint32_t pp_string(PayloadParser *pp, char *buffer, uint32_t maxlen)
{
pp_check_capacity(pp, 1);
uint32_t len = 0;
while (len < maxlen-1 && pp->current != pp->end) {
char c = *buffer++ = *pp->current++;
if (c == 0) break;
len++;
}
*buffer = 0;
return len;
}
/** Read a buffer */
uint32_t pp_buf(PayloadParser *pp, uint8_t *buffer, uint32_t maxlen)
{
uint32_t len = 0;
while (len < maxlen && pp->current != pp->end) {
*buffer++ = *pp->current++;
len++;
}
return len;
}

@ -0,0 +1,143 @@
#ifndef PAYLOAD_PARSER_H
#define PAYLOAD_PARSER_H
/**
* PayloadParser, part of the TinyFrame utilities collection
*
* (c) Ondřej Hruška, 2016-2017. MIT license.
*
* This module helps you with parsing payloads (not only from TinyFrame).
*
* The parser supports big and little-endian which is selected when
* initializing it or by accessing the bigendian struct field.
*
* The parser performs bounds checking and calls the provided handler when
* the requested read doesn't have enough data. Use the callback to take
* appropriate action, e.g. report an error.
*
* If the handler function is not defined, the pb->ok flag is set to false
* (use this to check for success), and further reads won't have any effect
* and always result in 0 or empty array.
*/
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "type_coerce.h"
typedef struct PayloadParser_ PayloadParser;
/**
* Empty buffer handler.
*
* 'needed' more bytes should be read but the end was reached.
*
* Return true if the problem was solved (e.g. new data loaded into
* the buffer and the 'current' pointer moved to the beginning).
*
* If false is returned, the 'ok' flag on the struct is set to false
* and all following reads will fail / return 0.
*/
typedef bool (*pp_empty_handler)(PayloadParser *pp, uint32_t needed);
struct PayloadParser_ {
uint8_t *start; //!< Pointer to the beginning of the buffer
uint8_t *current; //!< Pointer to the next byte to be read
uint8_t *end; //!< Pointer to the end of the buffer (start + length)
pp_empty_handler empty_handler; //!< Callback for buffer underrun
bool bigendian; //!< Flag to use big-endian parsing
bool ok; //!< Indicates that all reads were successful
};
// --- initializer helper macros ---
/** Start the parser. */
#define pp_start_e(buf, length, bigendian, empty_handler) ((PayloadParser){buf, buf, (buf)+(length), empty_handler, bigendian, 1})
/** Start the parser in big-endian mode */
#define pp_start_be(buf, length, empty_handler) pp_start_e(buf, length, 1, empty_handler)
/** Start the parser in little-endian mode */
#define pp_start_le(buf, length, empty_handler) pp_start_e(buf, length, 0, empty_handler)
/** Start the parser in little-endian mode (default) */
#define pp_start(buf, length, empty_handler) pp_start_le(buf, length, empty_handler)
// --- utilities ---
/** Get remaining length */
#define pp_length(pp) ((pp)->end - (pp)->current)
/** Reset the current pointer to start */
#define pp_rewind(pp) do { pp->current = pp->start; } while (0)
/**
* @brief Get the remainder of the buffer.
*
* Returns NULL and sets 'length' to 0 if there are no bytes left.
*
* @param pp
* @param length : here the buffer length will be stored. NULL to do not store.
* @return the remaining portion of the input buffer
*/
const uint8_t *pp_tail(PayloadParser *pp, uint32_t *length);
/** Read uint8_t from the payload. */
uint8_t pp_u8(PayloadParser *pp);
/** Read bool from the payload. */
static inline int8_t pp_bool(PayloadParser *pp)
{
return pp_u8(pp) != 0;
}
/** Skip bytes */
void pp_skip(PayloadParser *pp, uint32_t num);
/** Read uint16_t from the payload. */
uint16_t pp_u16(PayloadParser *pp);
/** Read uint32_t from the payload. */
uint32_t pp_u32(PayloadParser *pp);
/** Read int8_t from the payload. */
int8_t pp_i8(PayloadParser *pp);
/** Read char (int8_t) from the payload. */
static inline int8_t pp_char(PayloadParser *pp)
{
return pp_i8(pp);
}
/** Read int16_t from the payload. */
int16_t pp_i16(PayloadParser *pp);
/** Read int32_t from the payload. */
int32_t pp_i32(PayloadParser *pp);
/** Read 4-byte float from the payload. */
float pp_float(PayloadParser *pp);
/**
* Parse a zero-terminated string
*
* @param pp - parser
* @param buffer - target buffer
* @param maxlen - buffer size
* @return actual number of bytes, excluding terminator
*/
uint32_t pp_string(PayloadParser *pp, char *buffer, uint32_t maxlen);
/**
* Parse a buffer
*
* @param pp - parser
* @param buffer - target buffer
* @param maxlen - buffer size
* @return actual number of bytes, excluding terminator
*/
uint32_t pp_buf(PayloadParser *pp, uint8_t *buffer, uint32_t maxlen);
#endif // PAYLOAD_PARSER_H

@ -0,0 +1,32 @@
#ifndef TYPE_COERCE_H
#define TYPE_COERCE_H
/**
* Structs for conversion between types,
* part of the TinyFrame utilities collection
*
* (c) Ondřej Hruška, 2016-2017. MIT license.
*
* This is a support header file for PayloadParser and PayloadBuilder.
*/
#include <stdint.h>
#include <stddef.h>
union conv8 {
uint8_t u8;
int8_t i8;
};
union conv16 {
uint16_t u16;
int16_t i16;
};
union conv32 {
uint32_t u32;
int32_t i32;
float f32;
};
#endif // TYPE_COERCE_H

@ -0,0 +1,77 @@
#include "serial.h"
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
static int set_interface_attribs(int fd, int speed, int parity)
{
struct termios tty;
memset(&tty, 0, sizeof tty);
if (tcgetattr(fd, &tty) != 0) {
printf("error %d from tcgetattr\n", errno);
return -1;
}
cfsetospeed(&tty, (speed_t) speed);
cfsetispeed(&tty, (speed_t) speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
printf("error %d from tcsetattr\n", errno);
return -1;
}
return 0;
}
static void set_blocking(int fd, bool should_block, int read_timeout_0s1)
{
struct termios tty;
memset(&tty, 0, sizeof tty);
if (tcgetattr(fd, &tty) != 0) {
fprintf(stderr, "error %d from tggetattr\n", errno);
return;
}
tty.c_cc[VMIN] = (cc_t) (should_block ? 1 : 0);
tty.c_cc[VTIME] = (cc_t) read_timeout_0s1;
if (tcsetattr(fd, TCSANOW, &tty) != 0)
fprintf(stderr, "error %d setting term attributes\n", errno);
}
int serial_open(const char *device, bool blocking, int timeout_0s1)
{
int fd = open (device, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
fprintf (stderr, "FAILED TO OPEN SERIAL! Error %d opening %s: %s\n", errno, device, strerror (errno));
return -1;
}
set_interface_attribs(fd, B115200, 0);
set_blocking (fd, blocking, timeout_0s1);
return fd;
}

@ -0,0 +1,17 @@
#ifndef SERIAL_H
#define SERIAL_H
#include <stdbool.h>
#include <stdint.h>
/**
* Open a serial port
*
* @param device - device to open, e.g. /dev/ttyACM0
* @param blocking - true for `read()` to block until at least 1 byte is read
* @param timeout_0s1 - timeout for `read()` - if blocking, starts after the first character
* @return file descriptor
*/
int serial_open(const char *device, bool blocking, int timeout_0s1);
#endif

@ -0,0 +1,17 @@
#include <stdio.h>
#include <stdlib.h>
#include "gex_client.h"
int main()
{
GexClient *gex = GEX_Init("/dev/ttyACM0", 200);
if (!gex) {
fprintf(stderr, "FAILED TO CONNECT, ABORTING!\n");
exit(1);
}
printf("Hello, World!\n");
GEX_DeInit(gex);
return 0;
}
Loading…
Cancel
Save