]> git.kernelconcepts.de Git - metawatch.git/blob - metawatch.c
Add CRC16 with reverse bit order
[metawatch.git] / metawatch.c
1 /*
2  * (c) 2011 Siegen, Germany by Nils Faerber
3  *
4  * license GPL
5  */
6 #include <stdio.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include <string.h>
11 #include <time.h>
12
13 #include "metawatch_protocol.h"
14 #include "crc16ccitt.h"
15
16
17 void dump_frame(unsigned char *frame, int len)
18 {
19   int i;
20   for (i=0; i<len; i++)
21     fprintf(stderr, "0x%02x ", frame[i]);
22   fprintf(stderr, "\n");
23 }
24
25
26 void mw_send_packet(int mw_fd, unsigned char msg_type, unsigned char options, unsigned char *data, unsigned char len)
27 {
28   unsigned short crc;
29   unsigned char frame[64];
30
31   memset(frame, 0, 64);
32   frame[0] = MW_SOF;
33   frame[1] = len + 6;
34   frame[2] = msg_type;
35   frame[3] = options;
36   memcpy(frame+4, data, len);
37   
38   crc = crc16ccitt(frame, len+4);
39   *(unsigned short *)(frame+len+4) = crc;
40
41   dump_frame(frame, len+6);
42
43   write(mw_fd, frame, len+6);
44 }
45
46 void mw_set_rtc(int mw_fd, unsigned char clk1224, unsigned char date_fmt)
47 {
48   time_t mtime;
49   struct tm mtm;
50   unsigned short year;
51   unsigned char data[32];
52   
53   mtime = time(NULL);
54   localtime_r(&mtime, &mtm);
55
56   year = mtm.tm_year + 1900;  
57   data[0] = (year & 0x0f00) >> 8;
58   data[1] = (year & 0x00ff);
59   data[2] = mtm.tm_mon + 1;
60   data[3] = mtm.tm_mday;
61   data[4] = mtm.tm_wday;
62   data[5] = mtm.tm_hour;
63   data[6] = mtm.tm_min;
64   data[7] = mtm.tm_sec;
65   data[8] = clk1224;
66   data[9] = date_fmt;
67
68   mw_send_packet(mw_fd, MW_SET_REAL_TIME_CLOCK, 0, data, 10);
69 }
70
71
72 int main(int argc, char **argv)
73 {
74   int mw_fd;
75
76   if (argc != 2) {
77     fprintf(stderr, "Usage:\n\t%s <devicename>\n", argv[0]);
78     return 1;
79   };
80   
81   crc16ccitt_init();
82
83   mw_fd = open(argv[1], O_RDWR);
84   if (mw_fd < 0) {
85     perror("open");
86     return 1;
87   };
88
89   mw_set_rtc(mw_fd, MW_RTC_CLOCK_24HR, MW_RTC_DATE_DDMM);
90
91   fsync(mw_fd);
92
93   close(mw_fd);
94
95   return 0;
96 };