parse rx hello frames
[protos/xbee-avr.git] / main.c
1 /*
2  * Copyright (c) 2011, Olivier MATZ <zer0@droids-corp.org>
3  * All rights reserved.
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  *     * Redistributions of source code must retain the above copyright
8  *       notice, this list of conditions and the following disclaimer.
9  *     * Redistributions in binary form must reproduce the above copyright
10  *       notice, this list of conditions and the following disclaimer in the
11  *       documentation and/or other materials provided with the distribution.
12  *     * Neither the name of the University of California, Berkeley nor the
13  *       names of its contributors may be used to endorse or promote products
14  *       derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 /* fuses:
29  * avrdude -p atmega1284p -P usb -c avrispmkii -U lfuse:w:0xff:m -U hfuse:w:0x91:m -U efuse:w:0xff:m
30  */
31
32 #include <aversive.h>
33 #include <aversive/queue.h>
34 #include <aversive/endian.h>
35 #include <aversive/wait.h>
36 #include <aversive/error.h>
37
38 #include <uart.h>
39
40 #include <stdio.h>
41 #include <string.h>
42 #include <stdint.h>
43 #include <inttypes.h>
44 #include <stdlib.h>
45 #include <stdarg.h>
46 #include <errno.h>
47 #include <ctype.h>
48
49 #include <scheduler.h>
50 #include <clock_time.h>
51 #include <parse.h>
52 #include <rdline.h>
53 #include <timer.h>
54
55 #include "eeprom_config.h"
56 #include "beep.h"
57 #include "main.h"
58
59 struct xbeeboard xbeeboard;
60 volatile uint16_t global_ms;
61 struct callout_manager cm;
62
63 #define TIMEOUT_MS 1000
64
65 /* global xbee device */
66 struct xbee_dev *xbee_dev;
67
68 /* events */
69 //static struct event stdin_read_event, xbee_read_event;
70
71 /* parameters */
72 int xbee_raw = 0;
73 int xbee_hexdump = 0;
74 int xbee_debug = 0;
75
76 int xbee_cmdline_input_enabled = 1;
77
78 static struct xbee_ctx xbee_ctx[XBEE_MAX_CHANNEL];
79
80 static void hexdump(const char *title, const void *buf, unsigned int len)
81 {
82         unsigned int i, out, ofs;
83         const unsigned char *data = buf;
84 #define LINE_LEN 80
85         char line[LINE_LEN];    /* space needed 8+16*3+3+16 == 75 */
86
87         printf_P(PSTR("%s at [%p], len=%d\r\n"), title, data, len);
88         ofs = 0;
89         while (ofs < len) {
90                 /* format 1 line in the buffer, then use printk to print them */
91                 out = snprintf_P(line, LINE_LEN, PSTR("%08X"), ofs);
92                 for (i=0; ofs+i < len && i<16; i++)
93                         out += snprintf_P(line+out, LINE_LEN - out,
94                                           PSTR(" %02X"),
95                                           data[ofs+i]&0xff);
96                 for (;i<=16;i++)
97                         out += snprintf(line+out, LINE_LEN - out, "   ");
98                 for (i=0; ofs < len && i<16; i++, ofs++) {
99                         unsigned char c = data[ofs];
100                         if (!isascii(c) || !isprint(c))
101                                 c = '.';
102                         out += snprintf_P(line+out,
103                                           LINE_LEN - out,
104                                           PSTR("%c"), c);
105                 }
106                 printf_P(PSTR("%s\r\n"), line);
107         }
108 }
109
110 static int parse_xmit_status(struct xbee_ctx *ctx,
111                              struct xbee_xmit_status_hdr *frame, unsigned len)
112 {
113         (void)len;
114
115         if (ctx == NULL) {
116                 printf_P(PSTR("no context\r\n"));
117                 return -1;
118         }
119
120         /* see if it matches a xmit query (atcmd_query must be NULL) */
121         if (ctx->atcmd_query[0] != '\0') {
122                 printf_P(PSTR("invalid response 2\r\n"));
123                 return -1;
124         }
125
126         /* XXX use defines for these values */
127         if (frame->delivery_status == 0x00)
128                 printf_P(PSTR("Success\r\n"));
129         else if (frame->delivery_status == 0x01)
130                 printf_P(PSTR("MAC ACK Failure\r\n"));
131         else if (frame->delivery_status == 0x15)
132                 printf_P(PSTR("Invalid destination endpoint\r\n"));
133         else if (frame->delivery_status == 0x21)
134                 printf_P(PSTR("Network ACK Failure\r\n"));
135         else if (frame->delivery_status == 0x25)
136                 printf_P(PSTR("Route Not Found\r\n"));
137
138         return 0;
139 }
140
141 static int dump_atcmd(struct xbee_ctx *ctx, struct xbee_atresp_hdr *frame,
142                unsigned len)
143 {
144         char atcmd_str[3];
145         const struct xbee_atcmd *cmd_pgm;
146         struct xbee_atcmd cmd;
147         union {
148                 uint8_t u8;
149                 uint16_t u16;
150                 uint32_t u32;
151                 int16_t s16;
152         } __attribute__((packed)) *result;
153
154         if (ctx == NULL) {
155                 printf_P(PSTR("no context\r\n"));
156                 return -1;
157         }
158
159         /* get AT command from frame */
160         memcpy(atcmd_str, &frame->cmd, 2);
161         atcmd_str[2] = '\0';
162
163         /* see if it matches query */
164         if (memcmp(atcmd_str, ctx->atcmd_query, 2)) {
165                 printf_P(PSTR("invalid response <%c%c><%s><%s>\r\n"),
166                          frame->cmd & 0xFF,
167                          (frame->cmd >> 8) & 0xFF,
168                          atcmd_str, ctx->atcmd_query);
169                 return -1;
170         }
171
172         /* see if it exists */
173         cmd_pgm = xbee_atcmd_lookup_name(atcmd_str);
174         if (cmd_pgm == NULL) {
175                 printf_P(PSTR("unknown response\r\n"));
176                 return -1;
177         }
178         memcpy_P(&cmd, cmd_pgm, sizeof(cmd));
179
180         /* bad status */
181         if (frame->status == 1) {
182                 printf_P(PSTR("Status is error\r\n"));
183                 return -1;
184         }
185         else if (frame->status == 2) {
186                 printf_P(PSTR("Invalid command\r\n"));
187                 return -1;
188         }
189         else if (frame->status == 3) {
190                 printf_P(PSTR("Invalid parameter\r\n"));
191                 return -1;
192         }
193         else if (frame->status != 0) {
194                 printf_P(PSTR("Unknown status error %d\r\n"), frame->status);
195                 return -1;
196         }
197
198         /* callback */
199         if (ctx->func != NULL)
200                 ctx->func(frame, len, ctx->arg);
201
202         /* dump frame */
203         result = (void *)frame->data;
204         len -= offsetof(struct xbee_atresp_hdr, data);
205         if (cmd.flags & XBEE_ATCMD_F_PARAM_U8 && len == sizeof(uint8_t))
206                 printf_P(PSTR("<%s> is 0x%x (%d)\r\n"), atcmd_str, result->u8,
207                          result->u8);
208         else if (cmd.flags & XBEE_ATCMD_F_PARAM_U16 && len == sizeof(uint16_t))
209                 printf_P(PSTR("<%s> is 0x%x (%d)\r\n"),
210                          atcmd_str,
211                          ntohs(result->u16), ntohs(result->u16));
212         else if (cmd.flags & XBEE_ATCMD_F_PARAM_U32 && len == sizeof(uint32_t))
213                 printf_P(PSTR("<%s> is 0x%"PRIx32" (%"PRIu32")\r\n"),
214                          atcmd_str,
215                          ntohl(result->u32), ntohs(result->u32));
216         else if (cmd.flags & XBEE_ATCMD_F_PARAM_S16 && len == sizeof(int16_t))
217                 printf_P(PSTR("<%s> is %d\r\n"), atcmd_str, ntohs(result->s16));
218         else if (len == 0)
219                 printf_P(PSTR("no data, status ok\r\n"));
220         else
221                 hexdump("atcmd answer", frame->data, len);
222
223
224         return 0;
225 }
226
227
228 int xbee_recv_data(struct xbee_recv_hdr *recvframe, unsigned len)
229 {
230         unsigned int datalen;
231         struct rc_proto_hdr *rch = (struct rc_proto_hdr *) &recvframe->data;
232
233         if (len <  sizeof(*recvframe))
234                 return -1;
235
236         datalen = len - sizeof(*recvframe);
237         if (datalen < sizeof(struct rc_proto_hdr))
238                 return -1;
239
240         switch (rch->type) {
241 #if 0
242                 case RC_PROTO_TYPE_CHANNEL: {
243                         struct rc_proto_channel *rcc =
244                                 (struct rc_proto_channel *) recvframe->data;
245                         int16_t val;
246                         if (datalen != sizeof(struct rc_proto_channel))
247                                 return -1;
248                         val = ntohs(rcc->axis[0]);
249                         val >>= 6;
250                         val += 512;
251                         spi_servo_set(0, val);
252                         break;
253                 }
254                 case RC_PROTO_TYPE_RANGE: {
255                         struct rc_proto_range *rcr =
256                                 (struct rc_proto_range *) recvframe->data;
257
258                         if (datalen != sizeof(struct rc_proto_range))
259                                 return -1;
260
261                         if (rcr->power_level >= MAX_POWER_LEVEL)
262                                 return -1;
263
264                         rc_proto_rx_range(rcr->power_level);
265
266                         break;
267                 }
268 #endif
269                 case RC_PROTO_HELLO: {
270                         struct rc_proto_hello *rch =
271                                 (struct rc_proto_hello *) recvframe->data;
272
273                         if (xbee_debug)
274                                 printf_P(PSTR("recv hello len=%d\r\n"),
275                                          rch->datalen);
276
277                         break;
278                 }
279                 default:
280                         return -1;
281         }
282
283         return 0;
284 }
285
286 /* socat /dev/ttyUSB0,raw,echo=0,b115200 /dev/ttyACM1,raw,echo=0,b115200 */
287 int8_t xbeeapp_rx(struct xbee_dev *dev, int channel, int type,
288              void *frame, unsigned len, void *opaque)
289 {
290         struct xbee_ctx *ctx = opaque;
291         int8_t ret = 0;
292
293         if (xbee_debug)
294                 printf_P(PSTR("type=0x%x, channel=%d, ctx=%p\r\n"),
295                          type, channel, ctx);
296
297         /* if ctx is !NULL, it is an answer to a query */
298         if (ctx != NULL) {
299                 /* XXX only delete timeout if answer matched */
300                 xbee_unload_timeout(ctx);
301                 if (xbee_debug && ctx->atcmd_query)
302                         printf_P(PSTR("Received answer to query <%c%c>\r\n"),
303                                  ctx->atcmd_query[0], ctx->atcmd_query[1]);
304         }
305
306         /* some additional checks before sending */
307         switch (type) {
308                 case XBEE_TYPE_MODEM_STATUS: {
309                         printf_P(PSTR("Received Modem Status frame\r\n"));
310                         break;
311                 }
312
313                 case XBEE_TYPE_RMT_ATRESP: {
314                         union {
315                                 uint64_t u64;
316                                 struct {
317 #if BYTE_ORDER == LITTLE_ENDIAN
318                                         uint32_t low;
319                                         uint32_t high;
320 #else
321                                         uint32_t high;
322                                         uint32_t low;
323 #endif
324                                 } u32;
325                         } addr;
326                         memcpy(&addr, frame, sizeof(addr));
327                         addr.u64 = ntohll(addr.u64);
328                         printf_P(PSTR("from remote address %"PRIx32"%"PRIx32"\r\n"),
329                                  addr.u32.high, addr.u32.low);
330
331                         /* this answer contains an atcmd answer at offset 10 */
332                         if (dump_atcmd(ctx, frame + 10, len - 10) < 0)
333                                 ret = -1;
334
335                         break;
336                 }
337                 case XBEE_TYPE_ATRESP: {
338                         if (dump_atcmd(ctx, frame, len) < 0)
339                                 ret = -1;
340
341                         break;
342                 }
343
344                 case XBEE_TYPE_XMIT_STATUS: {
345                         if (parse_xmit_status(ctx, frame, len) < 0)
346                                 ret = -1;
347
348                         break;
349                 }
350
351                 case XBEE_TYPE_RECV: {
352                         if (xbee_recv_data(frame, len) < 0)
353                                 ret = -1;
354
355                         break;
356                 }
357
358                 case XBEE_TYPE_ATCMD:
359                 case XBEE_TYPE_ATCMD_Q:
360                 case XBEE_TYPE_XMIT:
361                 case XBEE_TYPE_EXPL_XMIT:
362                 case XBEE_TYPE_RMT_ATCMD:
363                 case XBEE_TYPE_EXPL_RECV:
364                 case XBEE_TYPE_NODE_ID:
365                 default:
366                         printf_P(PSTR("Invalid frame\r\n"));
367                         ret = -1;
368                         break;
369         }
370
371         if (ret < 0)
372                 hexdump("undecoded rx frame", frame, len);
373         else if (xbee_hexdump)
374                 hexdump("undecoded rx frame", frame, len);
375
376         /* restart command line if it was a blocking query */
377         if (ctx != NULL) {
378                 xbee_unregister_channel(dev, channel);
379                 if (ctx->foreground) {
380                         xbee_stdin_enable();
381                         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
382                 }
383         }
384 }
385
386 static int xbeeapp_send(struct xbee_ctx *ctx, int type, void *buf, unsigned len,
387                         int foreground)
388 {
389         int ret;
390         int channel;
391
392         if (len > XBEE_MAX_FRAME_LEN) {
393                 printf_P(PSTR("frame too large\r\n"));
394                 return -1;
395         }
396
397         /* register a channel */
398         channel = xbee_register_channel(xbee_dev, XBEE_CHANNEL_ANY,
399                                         xbeeapp_rx, NULL);
400         if (channel < 0) {
401                 printf_P(PSTR("cannot send: no free channel\r\n"));
402                 return -1;
403         }
404
405         /* copy context in the static struct table (avoiding a malloc) */
406         memcpy(&xbee_ctx[channel], ctx, sizeof(*ctx));
407         ctx = &xbee_ctx[channel];
408         xbee_set_opaque(xbee_dev, channel, ctx);
409
410         if (xbee_debug)
411                 printf_P(PSTR("send frame channel=%d type=0x%x len=%d\r\n"),
412                          channel, type, len);
413         if (xbee_hexdump)
414                 hexdump("xmit frame", buf, len);
415
416         /* transmit the frame on this channel */
417         ret = xbee_tx(xbee_dev, channel, type, buf, len);
418         if (ret < 0) {
419                 printf_P(PSTR("cannot send\r\n"));
420                 xbee_unregister_channel(xbee_dev, channel);
421                 return -1;
422         }
423
424         ctx->channel = channel;
425         xbee_load_timeout(ctx);   /* load a timeout event */
426
427         /* suspend command line until we have answer or timeout */
428         if (foreground) {
429                 ctx->foreground = 1;
430                 rdline_stop(&xbeeboard.rdl); /* don't display prompt when return */
431                 xbee_stdin_disable();  /* unload file descriptor polling */
432         }
433
434         return 0;
435 }
436
437 /* send an AT command with parameters filled by caller. Disable
438  * command line until we get the answer or until a timeout occurs */
439 int xbeeapp_send_atcmd(const char *atcmd_str,
440                        void *param, unsigned param_len, int foreground,
441                        int (*func)(void *frame, unsigned len, void *arg), void *arg)
442 {
443         struct xbee_ctx ctx;
444         struct {
445                 struct xbee_atcmd_hdr atcmd;
446                 char buf[XBEE_MAX_FRAME_LEN];
447         } __attribute__((packed)) frame;
448
449         memset(&ctx, 0, sizeof(ctx));
450         ctx.atcmd_query[0] = atcmd_str[0];
451         ctx.atcmd_query[1] = atcmd_str[1];
452         ctx.func = func;
453         ctx.arg = arg;
454
455         memcpy(&frame.atcmd.cmd, atcmd_str, 2);
456         memcpy(&frame.buf, param, param_len);
457
458         if (xbeeapp_send(&ctx, XBEE_TYPE_ATCMD, &frame,
459                          sizeof(struct xbee_atcmd_hdr) +
460                          param_len, foreground) < 0) {
461                 return -1;
462         }
463
464         return 0;
465 }
466
467 int xbeeapp_send_msg(uint64_t addr, void *data,
468                      unsigned data_len, int foreground)
469 {
470         struct xbee_ctx ctx;
471         struct {
472                 struct xbee_xmit_hdr xmit;
473                 char buf[XBEE_MAX_FRAME_LEN];
474         } __attribute__((packed)) frame;
475
476         memset(&ctx, 0, sizeof(ctx));
477         ctx.atcmd_query[0] = '\0';
478
479         frame.xmit.dstaddr = htonll(addr);
480         frame.xmit.reserved = htons(0xFFFE);
481         frame.xmit.bcast_radius = 0;
482         frame.xmit.opts = 0;
483         memcpy(&frame.buf, data, data_len);
484
485         if (xbeeapp_send(&ctx, XBEE_TYPE_XMIT, &frame,
486                          sizeof(struct xbee_xmit_hdr) +
487                          data_len, foreground) < 0) {
488                 return -1;
489         }
490
491         return 0;
492 }
493
494 void xbee_stdin_enable(void)
495 {
496         xbee_cmdline_input_enabled = 1;
497 }
498
499 void xbee_stdin_disable(void)
500 {
501         xbee_cmdline_input_enabled = 0;
502 }
503
504 static void evt_timeout(struct callout_manager *cm, struct callout *clt,
505                         void *arg)
506 {
507         struct xbee_ctx *ctx = arg;
508
509         (void)cm;
510         (void)clt;
511
512         printf_P(PSTR("Timeout\r\n"));
513
514         /* restart command line */
515         xbee_stdin_enable();
516         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
517
518         /* free event */
519         xbee_unregister_channel(xbee_dev, ctx->channel);
520 }
521
522 void xbee_load_timeout(struct xbee_ctx *ctx)
523 {
524         callout_reset(&cm, &ctx->timeout, TIMEOUT_MS, SINGLE, evt_timeout, ctx);
525 }
526
527 void xbee_unload_timeout(struct xbee_ctx *ctx)
528 {
529         callout_stop(&cm, &ctx->timeout);
530 }
531
532 void bootloader(void)
533 {
534 #define BOOTLOADER_ADDR 0x3f000
535         if (pgm_read_byte_far(BOOTLOADER_ADDR) == 0xff) {
536                 printf_P(PSTR("Bootloader is not present\r\n"));
537                 return;
538         }
539         cli();
540         /* ... very specific :( */
541         TIMSK0 = 0;
542         TIMSK1 = 0;
543         TIMSK2 = 0;
544         TIMSK3 = 0;
545         EIMSK = 0;
546         UCSR0B = 0;
547         UCSR1B = 0;
548         SPCR = 0;
549         TWCR = 0;
550         ACSR = 0;
551         ADCSRA = 0;
552
553         /* XXX */
554         /* __asm__ __volatile__ ("ldi r31,0xf8\n"); */
555         /* __asm__ __volatile__ ("ldi r30,0x00\n"); */
556         /* __asm__ __volatile__ ("eijmp\n"); */
557 }
558
559 void xbee_mainloop(void)
560 {
561         while (1) {
562                 callout_manage(&cm);
563
564                 if (xbee_raw) {
565                         int16_t c;
566
567                         /* from xbee to cmdline */
568                         c = xbee_dev_recv(NULL);
569                         if (c >= 0)
570                                 cmdline_dev_send((uint8_t)c, NULL);
571
572                         /* from cmdline to xbee */
573                         c = cmdline_dev_recv(NULL);
574                         if (c == 4) { /* CTRL-d */
575                                 xbee_dev_send('A', NULL);
576                                 xbee_dev_send('T', NULL);
577                                 xbee_dev_send('C', NULL);
578                                 xbee_dev_send('N', NULL);
579                                 xbee_dev_send('\n', NULL);
580                                 xbee_raw = 0;
581                                 rdline_newline(&xbeeboard.rdl,
582                                                xbeeboard.prompt);
583                         }
584                         else if (c >= 0) {
585                                 /* send to xbee */
586                                 xbee_dev_send((uint8_t)c, NULL);
587
588                                 /* echo on cmdline */
589                                 cmdline_dev_send((uint8_t)c, NULL);
590                         }
591                 }
592                 else {
593                         if (xbee_cmdline_input_enabled)
594                                 cmdline_poll();
595                         xbee_rx(xbee_dev);
596                 }
597         }
598 }
599
600 /* return time in milliseconds on unsigned 16 bits */
601 static uint16_t get_time_ms(void)
602 {
603         return global_ms;
604 }
605
606 static void main_timer_interrupt(void)
607 {
608         static uint16_t cycles;
609         static uint8_t cpt;
610
611         cpt++;
612
613         /* interrupt every 2048 cycles */
614         cycles += 2048;
615         if (cycles >= 12000) {
616                 cycles -= 12000;
617                 global_ms ++;
618         }
619
620         /* LED blink */
621         if (global_ms & 0x80)
622                 LED1_ON();
623         else
624                 LED1_OFF();
625
626         if (cpt & beep_mask)
627                 BUZZER_ON();
628         else
629                 BUZZER_OFF();
630
631         /* call scheduler every 682us with interrupt unlocked */
632         sei();
633         if ((cpt & 0x3) == 0)
634                 scheduler_interrupt();
635 }
636
637 int main(void)
638 {
639         //struct callout t1;
640         FILE *xbee_file;
641         int8_t err;
642         struct xbee_dev dev;
643
644         DDRA = 0x07 /* LEDs */ | 0x10 /* buzzer */;
645
646         uart_init();
647         uart_register_rx_event(CMDLINE_UART, emergency);
648
649         fdevopen(cmdline_dev_send, cmdline_dev_recv);
650         xbee_file = fdevopen(xbee_dev_send, xbee_dev_recv);
651         scheduler_init();
652         timer_init();
653         timer0_register_OV_intr(main_timer_interrupt);
654
655         cmdline_init();
656         spi_servo_init();
657         beep_init();
658
659         callout_manager_init(&cm, get_time_ms);
660         //callout_reset(&cm, &t1, 500, PERIODICAL, do_led_blink, NULL);
661
662         /* initialize libxbee */
663         err = xbee_init();
664         if (err < 0)
665                 return -1;
666
667         xbee_dev = &dev;
668
669         /* open xbee device */
670         if (xbee_open(xbee_dev, xbee_file) < 0)
671                 return -1;
672
673         /* register default channel with a callback */
674         if (xbee_register_channel(xbee_dev, XBEE_DEFAULT_CHANNEL,
675                                   xbeeapp_rx, NULL) < 0) {
676                 fprintf(stderr, "cannot register default channel\n");
677                 return -1;
678         }
679         sei();
680
681         eeprom_load_config();
682
683         printf_P(PSTR("\r\n"));
684         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
685
686         xbee_mainloop();
687         return 0;
688 }