]> Pileus Git - ~andy/csm213a-hw/blob - hw2/control.c
Make slave mode configurable
[~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_CTL_VALID_SYNC : 0;
34         int   opt_relay  = opt_device == 2;
35
36         // Lookup current wall-clock time
37         struct timespec ts;
38         clock_gettime(CLOCK_REALTIME, &ts);
39
40         // Message buffers
41         header_t   head = {};
42         init_msg_t body = {};
43
44         // Set message header
45         head.header  = MSG_HEADER;
46         head.msgid   = MSG_ID_INIT;
47         head.length  = sizeof(init_msg_t);
48         head.cksum   = 0; // todo
49
50         // Set valid flags
51         body.control = MSG_CTL_VALID_DEVICE
52                      | MSG_CTL_VALID_START
53                      | MSG_CTL_VALID_PERIOD
54                      | MSG_CTL_VALID_WORLD
55                      | opt_relay
56                      | opt_sync;
57
58         // Set message body
59         body.device         = opt_device;
60         body.world.seconds  = ts.tv_sec;
61         body.world.nanosec  = ts.tv_nsec;
62         body.start.seconds  = ts.tv_sec;
63         body.start.nanosec  = 0; //ts.tv_nsec;
64         body.period.seconds = 0;
65         body.period.nanosec =  100000000;
66         //                  [s][m][u][n]
67
68         // Transmit message
69         FILE *fd = fopen(opt_tty, "a+");
70         if (!fd) error("opening device");
71         int len = 0;
72         len += fwrite(&head, 1, sizeof(head), fd);
73         len += fwrite(&body, 1, sizeof(body), fd);
74         fclose(fd);
75
76         // Debug output
77         dump("head", (uint8_t*)&head, sizeof(head));
78         dump("body", (uint8_t*)&body, sizeof(body));
79
80         printf("wrote %d bytes\n", len);
81
82         return 0;
83 }