]> Pileus Git - ~andy/csm213a-hw/blob - hw2/messages.h
Factor out message parser
[~andy/csm213a-hw] / hw2 / messages.h
1 #ifndef MESSAGES_H
2 #define MESSAGES_H
3
4 #include <stdint.h>
5
6 #ifdef __cplusplus
7 extern "C" {
8 #endif
9
10 /***********************
11  * Message Definitions *
12  ***********************/
13
14 #define MSG_HEADER       0x1234
15
16 #define MSG_VALID_DEVICE 0x0001  // device id is valid
17 #define MSG_VALID_WORLD  0x0002  // world time is valid
18 #define MSG_VALID_START  0x0004  // start time is valid
19 #define MSG_VALID_PERIOD 0x0008  // period is valid
20 #define MSG_VALID_SYNC   0x8000  // begin time sync
21
22 #pragma pack(1)
23
24 typedef enum {
25         MSG_ID_INIT,       // Device initialization
26         MSG_ID_SYNC,       // Time synchronization
27         MSG_ID_EVENT,      // Event occurred
28         MSG_MAX_ID,        // Maximum message ID
29 } msgid_t;
30
31 typedef struct {
32         uint32_t seconds;  // Seconds since 1970
33         uint32_t nanosec;  // Nanoseconds since 'seconds'
34 } ntime_t;
35
36 typedef struct {
37         uint16_t header;   // Message Header
38         uint16_t msgid;    // Message ID
39         uint16_t length;   // Body length
40         uint16_t cksum;    // Body checksum
41 } header_t;
42
43 typedef struct {
44         uint16_t valid;    // Message valid bits
45         uint16_t device;   // Device ID to use
46         ntime_t  world;    // World time (since 1970)
47         ntime_t  start;    // Transmit start time 
48         ntime_t  period;   // Transmit period
49 } init_msg_t;
50
51 typedef struct {
52         ntime_t  time;     // Time of previous message
53 } sync_msg_t;
54
55 typedef struct {
56         uint16_t device;   // Device ID
57         uint16_t event;    // Event ID
58         ntime_t  world;    // UTC Time of event
59         ntime_t  local;    // Time since turn-on
60 } event_msg_t;
61
62 #pragma pack()
63
64 /******************
65  * Message Parser *
66  ******************/
67
68 typedef void (*handler_t)(int msgid, void *msg);
69
70 typedef struct {
71         int       index;
72         int       state;
73         uint8_t   buffer[256];
74         handler_t handler[MSG_MAX_ID];
75 } parser_t;
76
77 void msg_register(parser_t *parser, int msgid, handler_t handler);
78
79 void msg_receive(parser_t *parser, int byte);
80
81 #ifdef __cplusplus
82 }
83 #endif
84
85 #endif