]> Pileus Git - ~andy/csm213a-hw/blob - hw2/control.c
Update message definitions
[~andy/csm213a-hw] / hw2 / control.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #include <time.h>
6
7 #include "messages.h"
8
9 void error(char *msg)
10 {
11         printf("Error: %s\n", msg);
12         exit(0);
13 }
14
15 void dump(const char *label, uint8_t *data, int len)
16 {
17         int i;
18         printf("%s: ", label);
19         for (i = 0; i < len; i++)
20                 printf("%02hhx ", data[i]);
21         printf("\n");
22 }
23
24 int main(int argc, char **argv)
25 {
26         if (argc < 3)
27                 error("usage: control /dev/ttyACM0 0 sync");
28
29         // Parse args
30         char *opt_tty    = argv[1];
31         int   opt_device = atoi(argv[2]);
32         int   opt_sync   = argv[3] && !strcmp(argv[3], "sync") ?
33                            MSG_VALID_SYNC : 0;
34
35         // Lookup current wall-clock time
36         struct timespec ts;
37         clock_gettime(CLOCK_REALTIME, &ts);
38
39         // Message buffers
40         header_t   head = {};
41         init_msg_t body = {};
42
43         // Set message header
44         head.header = MSG_HEADER;
45         head.msgid  = MSG_ID_INIT;
46         head.length = sizeof(init_msg_t);
47         head.cksum  = 0; // todo
48
49         // Set valid flags
50         body.valid  = MSG_VALID_DEVICE
51                     | MSG_VALID_START
52                     | MSG_VALID_PERIOD
53                     | MSG_VALID_WORLD
54                     | opt_sync;
55
56         // Set message body
57         body.device         = opt_device;
58         body.world.seconds  = ts.tv_sec;
59         body.world.nanosec  = ts.tv_nsec;
60         body.start.seconds  = ts.tv_sec;
61         body.start.nanosec  = 0; //ts.tv_nsec;
62         body.period.seconds = 0;
63         body.period.nanosec =  100000000;
64         //                  [s][m][u][n]
65
66         // Transmit message
67         FILE *fd = fopen(opt_tty, "a+");
68         if (!fd) error("opening device");
69         int len = 0;
70         len += fwrite(&head, 1, sizeof(head), fd);
71         len += fwrite(&body, 1, sizeof(body), fd);
72         fclose(fd);
73
74         // Debug output
75         dump("head", (uint8_t*)&head, sizeof(head));
76         dump("body", (uint8_t*)&body, sizeof(body));
77
78         printf("wrote %d bytes\n", len);
79
80         return 0;
81 }