d12ed7af5288c90c49fc7253126790184501e1ff
[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 #include <aversive.h>
29 #include <aversive/queue.h>
30 #include <aversive/endian.h>
31 #include <aversive/wait.h>
32 #include <aversive/error.h>
33
34 #include <uart.h>
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <stdint.h>
39 #include <inttypes.h>
40 #include <stdlib.h>
41 #include <stdarg.h>
42 #include <errno.h>
43 #include <ctype.h>
44
45 #include <scheduler.h>
46 #include <clock_time.h>
47 #include <parse.h>
48 #include <rdline.h>
49 #include <timer.h>
50
51 #include "xbee_neighbor.h"
52 #include "xbee_atcmd.h"
53 #include "xbee_stats.h"
54 #include "xbee_buf.h"
55 #include "xbee_proto.h"
56 #include "xbee.h"
57 #include "cmdline.h"
58 #include "callout.h"
59 #include "rc_proto.h"
60 #include "spi_servo.h"
61 #include "main.h"
62
63 struct xbeeboard xbeeboard;
64 volatile uint16_t global_ms;
65 struct callout_manager cm;
66
67 #define TIMEOUT_MS 1000
68
69 /* global xbee device */
70 struct xbee_dev *xbee_dev;
71
72 /* events */
73 //static struct event stdin_read_event, xbee_read_event;
74
75 /* parameters */
76 int xbee_raw = 0;
77 int xbee_hexdump = 0;
78 int xbee_debug = 0;
79
80 int xbee_cmdline_input_enabled = 1;
81
82 static struct xbee_ctx xbee_ctx[XBEE_MAX_CHANNEL];
83
84 static void hexdump(const char *title, const void *buf, unsigned int len)
85 {
86         unsigned int i, out, ofs;
87         const unsigned char *data = buf;
88 #define LINE_LEN 80
89         char line[LINE_LEN];    /* space needed 8+16*3+3+16 == 75 */
90
91         printf_P(PSTR("%s at [%p], len=%d\r\n"), title, data, len);
92         ofs = 0;
93         while (ofs < len) {
94                 /* format 1 line in the buffer, then use printk to print them */
95                 out = snprintf_P(line, LINE_LEN, PSTR("%08X"), ofs);
96                 for (i=0; ofs+i < len && i<16; i++)
97                         out += snprintf_P(line+out, LINE_LEN - out,
98                                           PSTR(" %02X"),
99                                           data[ofs+i]&0xff);
100                 for (;i<=16;i++)
101                         out += snprintf(line+out, LINE_LEN - out, "   ");
102                 for (i=0; ofs < len && i<16; i++, ofs++) {
103                         unsigned char c = data[ofs];
104                         if (!isascii(c) || !isprint(c))
105                                 c = '.';
106                         out += snprintf_P(line+out,
107                                           LINE_LEN - out,
108                                           PSTR("%c"), c);
109                 }
110                 printf_P(PSTR("%s\r\n"), line);
111         }
112 }
113
114 static int parse_xmit_status(struct xbee_ctx *ctx,
115                              struct xbee_xmit_status_hdr *frame, unsigned len)
116 {
117         if (ctx == NULL) {
118                 printf_P(PSTR("no context\r\n"));
119                 return -1;
120         }
121
122         /* see if it matches a xmit query (atcmd_query must be NULL) */
123         if (ctx->atcmd_query[0] != '\0') {
124                 printf_P(PSTR("invalid response 2\r\n"));
125                 return -1;
126         }
127
128         /* XXX use defines for these values */
129         if (frame->delivery_status == 0x00)
130                 printf_P(PSTR("Success\r\n"));
131         else if (frame->delivery_status == 0x01)
132                 printf_P(PSTR("MAC ACK Failure\r\n"));
133         else if (frame->delivery_status == 0x15)
134                 printf_P(PSTR("Invalid destination endpoint\r\n"));
135         else if (frame->delivery_status == 0x21)
136                 printf_P(PSTR("Network ACK Failure\r\n"));
137         else if (frame->delivery_status == 0x25)
138                 printf_P(PSTR("Route Not Found\r\n"));
139
140         return 0;
141 }
142
143 static int dump_atcmd(struct xbee_ctx *ctx, struct xbee_atresp_hdr *frame,
144                unsigned len)
145 {
146         char atcmd_str[3];
147         struct xbee_atcmd_pgm *cmd_pgm;
148         struct xbee_atcmd cmd;
149         union {
150                 uint8_t u8;
151                 uint16_t u16;
152                 uint32_t u32;
153                 int16_t s16;
154         } __attribute__((packed)) *result;
155
156         if (ctx == NULL) {
157                 printf_P(PSTR("no context\r\n"));
158                 return -1;
159         }
160
161         /* get AT command from frame */
162         memcpy(atcmd_str, &frame->cmd, 2);
163         atcmd_str[2] = '\0';
164
165         /* see if it matches query */
166         if (memcmp(atcmd_str, ctx->atcmd_query, 2)) {
167                 printf_P(PSTR("invalid response <%c%c><%s><%s>\r\n"),
168                          frame->cmd & 0xFF,
169                          (frame->cmd >> 8) & 0xFF,
170                          atcmd_str, ctx->atcmd_query);
171                 return -1;
172         }
173
174         /* see if it exists */
175         cmd_pgm = xbee_atcmd_lookup_name(atcmd_str);
176         if (cmd_pgm == NULL) {
177                 printf_P(PSTR("unknown response\r\n"));
178                 return -1;
179         }
180         memcpy_P(&cmd, cmd_pgm, sizeof(cmd));
181
182         /* bad status */
183         if (frame->status == 1) {
184                 printf_P(PSTR("Status is error\r\n"));
185                 return -1;
186         }
187         else if (frame->status == 2) {
188                 printf_P(PSTR("Invalid command\r\n"));
189                 return -1;
190         }
191         else if (frame->status == 3) {
192                 printf_P(PSTR("Invalid parameter\r\n"));
193                 return -1;
194         }
195         else if (frame->status != 0) {
196                 printf_P(PSTR("Unknown status error %d\r\n"), frame->status);
197                 return -1;
198         }
199
200         /* callback */
201         if (ctx->func != NULL)
202                 ctx->func(frame, len, ctx->arg);
203
204         /* dump frame */
205         result = (void *)frame->data;
206         len -= offsetof(struct xbee_atresp_hdr, data);
207         if (cmd.flags & XBEE_ATCMD_F_PARAM_U8 && len == sizeof(uint8_t))
208                 printf_P(PSTR("<%s> is 0x%x\r\n"), atcmd_str, result->u8);
209         else if (cmd.flags & XBEE_ATCMD_F_PARAM_U16 && len == sizeof(uint16_t))
210                 printf_P(PSTR("<%s> is 0x%x\r\n"),
211                          atcmd_str,
212                          ntohs(result->u16));
213         else if (cmd.flags & XBEE_ATCMD_F_PARAM_U32 && len == sizeof(uint32_t))
214                 printf_P(PSTR("<%s> is 0x%"PRIx32"\r\n"),
215                          atcmd_str,
216                          ntohl(result->u32));
217         else if (cmd.flags & XBEE_ATCMD_F_PARAM_S16 && len == sizeof(int16_t))
218                 printf_P(PSTR("<%s> is %d\r\n"), atcmd_str, ntohs(result->s16));
219         else if (len == 0)
220                 printf_P(PSTR("no data, status ok\r\n"));
221         else
222                 hexdump("atcmd answer", frame->data, len);
223
224
225         return 0;
226 }
227
228
229 int xbee_recv_data(struct xbee_recv_hdr *recvframe, unsigned len)
230 {
231         int datalen = len - sizeof(*recvframe);
232         struct rc_proto_hdr *rch = (struct rc_proto_hdr *) &recvframe->data;
233
234         if (datalen < sizeof(struct rc_proto_hdr))
235                 return -1;
236
237         switch (rch->type) {
238                 case RC_PROTO_TYPE_CHANNEL:
239                         if (datalen != sizeof(struct rc_proto_channel))
240                                 return -1;
241                         break;
242                 case RC_PROTO_TYPE_RANGE: {
243                         struct rc_proto_range *rcr =
244                                 (struct rc_proto_range *) recvframe->data;
245
246                         if (datalen != sizeof(struct rc_proto_range))
247                                 return -1;
248
249                         if (rcr->power_level >= MAX_POWER_LEVEL)
250                                 return -1;
251
252                         rc_proto_rx_range(rcr->power_level);
253
254                         break;
255                 }
256                 default:
257                         return -1;
258         }
259
260         return 0;
261 }
262
263 /* socat /dev/ttyUSB0,raw,echo=0,b115200 /dev/ttyACM1,raw,echo=0,b115200 */
264 void xbee_rx(struct xbee_dev *dev, int channel, int type,
265              void *frame, unsigned len, void *opaque)
266 {
267         struct xbee_ctx *ctx = opaque;
268         int do_hexdump = xbee_hexdump;
269
270         if (xbee_debug)
271                 printf_P(PSTR("type=0x%x, channel=%d, ctx=%p\r\n"),
272                          type, channel, ctx);
273
274         /* if ctx is !NULL, it is an answer to a query */
275         if (ctx != NULL) {
276                 /* XXX only delete timeout if answer matched */
277                 xbee_unload_timeout(ctx);
278                 if (xbee_debug && ctx->atcmd_query)
279                         printf_P(PSTR("Received answer to query <%c%c>\r\n"),
280                                  ctx->atcmd_query[0], ctx->atcmd_query[1]);
281         }
282
283         /* some additional checks before sending */
284         switch (type) {
285                 case XBEE_TYPE_MODEM_STATUS: {
286                         printf_P(PSTR("Received Modem Status frame\r\n"));
287                         break;
288                 }
289
290                 case XBEE_TYPE_RMT_ATRESP: {
291                         union {
292                                 uint64_t u64;
293                                 struct {
294 #if BYTE_ORDER == LITTLE_ENDIAN
295                                         uint32_t low;
296                                         uint32_t high;
297 #else
298                                         uint32_t high;
299                                         uint32_t low;
300 #endif
301                                 } u32;
302                         } addr;
303                         memcpy(&addr, frame, sizeof(addr));
304                         addr.u64 = ntohll(addr.u64);
305                         printf_P(PSTR("from remote address %"PRIx32"%"PRIx32"\r\n"),
306                                  addr.u32.high, addr.u32.low);
307
308                         /* this answer contains an atcmd answer at offset 10 */
309                         if (dump_atcmd(ctx, frame + 10, len - 10) < 0)
310                                 do_hexdump = 1;
311                         break;
312                 }
313                 case XBEE_TYPE_ATRESP: {
314                         if (dump_atcmd(ctx, frame, len) < 0)
315                                 do_hexdump = 1;
316                         break;
317                 }
318
319                 case XBEE_TYPE_XMIT_STATUS: {
320                         if (parse_xmit_status(ctx, frame, len) < 0)
321                                 do_hexdump = 1;
322                         break;
323                 }
324
325                 case XBEE_TYPE_RECV: {
326                         if (xbee_recv_data(frame, len) < 0)
327                                 do_hexdump = 1;
328                         break;
329                 }
330
331                 case XBEE_TYPE_ATCMD:
332                 case XBEE_TYPE_ATCMD_Q:
333                 case XBEE_TYPE_XMIT:
334                 case XBEE_TYPE_EXPL_XMIT:
335                 case XBEE_TYPE_RMT_ATCMD:
336                 case XBEE_TYPE_EXPL_RECV:
337                 case XBEE_TYPE_NODE_ID:
338                 default:
339                         printf_P(PSTR("Invalid frame\r\n"));
340                         do_hexdump = 1;
341                         break;
342         }
343
344         if (do_hexdump)
345                 hexdump("undecoded rx frame", frame, len);
346
347         /* restart command line if it was a blocking query */
348         if (ctx != NULL) {
349                 xbee_unregister_channel(dev, channel);
350                 if (ctx->foreground) {
351                         xbee_stdin_enable();
352                         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
353                 }
354         }
355 }
356
357 static int xbeeapp_send(struct xbee_ctx *ctx, int type, void *buf, unsigned len,
358                         int foreground)
359 {
360         int ret;
361         int channel;
362
363         if (len > XBEE_MAX_FRAME_LEN) {
364                 printf_P(PSTR("frame too large\r\n"));
365                 return -1;
366         }
367
368         /* register a channel */
369         channel = xbee_register_channel(xbee_dev, XBEE_CHANNEL_ANY,
370                                         xbee_rx, NULL);
371         if (channel < 0) {
372                 printf_P(PSTR("cannot send: no free channel\r\n"));
373                 return -1;
374         }
375
376         /* copy context in the static struct table (avoiding a malloc) */
377         memcpy(&xbee_ctx[channel], ctx, sizeof(*ctx));
378         ctx = &xbee_ctx[channel];
379         xbee_set_opaque(xbee_dev, channel, ctx);
380
381         if (xbee_debug)
382                 printf_P(PSTR("send frame channel=%d type=0x%x len=%d\r\n"),
383                          channel, type, len);
384         if (xbee_hexdump)
385                 hexdump("xmit frame", buf, len);
386
387         /* transmit the frame on this channel */
388         ret = xbee_proto_xmit(xbee_dev, channel, type, buf,
389                               len);
390         if (ret < 0) {
391                 printf_P(PSTR("cannot send\r\n"));
392                 xbee_unregister_channel(xbee_dev, channel);
393                 return -1;
394         }
395
396         ctx->channel = channel;
397         xbee_load_timeout(ctx);   /* load a timeout event */
398
399         /* suspend command line until we have answer or timeout */
400         if (foreground) {
401                 ctx->foreground = 1;
402                 rdline_stop(&xbeeboard.rdl); /* don't display prompt when return */
403                 xbee_stdin_disable();  /* unload file descriptor polling */
404         }
405
406         return 0;
407 }
408
409 /* send an AT command with parameters filled by caller. Disable
410  * command line until we get the answer or until a timeout occurs */
411 int xbeeapp_send_atcmd(const char *atcmd_str,
412                        void *param, unsigned param_len, int foreground,
413                        int (*func)(void *frame, unsigned len, void *arg), void *arg)
414 {
415         struct xbee_ctx ctx;
416         struct {
417                 struct xbee_atcmd_hdr atcmd;
418                 char buf[XBEE_MAX_FRAME_LEN];
419         } __attribute__((packed)) frame;
420
421         memset(&ctx, 0, sizeof(ctx));
422         ctx.atcmd_query[0] = atcmd_str[0];
423         ctx.atcmd_query[1] = atcmd_str[1];
424         ctx.func = func;
425         ctx.arg = arg;
426
427         memcpy(&frame.atcmd.cmd, atcmd_str, 2);
428         memcpy(&frame.buf, param, param_len);
429
430         if (xbeeapp_send(&ctx, XBEE_TYPE_ATCMD, &frame,
431                          sizeof(struct xbee_atcmd_hdr) +
432                          param_len, foreground) < 0) {
433                 return -1;
434         }
435
436         return 0;
437 }
438
439 int xbeeapp_send_msg(uint64_t addr, void *data,
440                      unsigned data_len, int foreground)
441 {
442         struct xbee_ctx ctx;
443         struct {
444                 struct xbee_xmit_hdr xmit;
445                 char buf[XBEE_MAX_FRAME_LEN];
446         } __attribute__((packed)) frame;
447
448         memset(&ctx, 0, sizeof(ctx));
449         ctx.atcmd_query[0] = '\0';
450
451         frame.xmit.dstaddr = htonll(addr);
452         frame.xmit.reserved = htons(0xFFFE);
453         frame.xmit.bcast_radius = 0;
454         frame.xmit.opts = 0;
455         memcpy(&frame.buf, data, data_len);
456
457         if (xbeeapp_send(&ctx, XBEE_TYPE_XMIT, &frame,
458                          sizeof(struct xbee_xmit_hdr) +
459                          data_len, foreground) < 0) {
460                 return -1;
461         }
462
463         return 0;
464 }
465
466 void xbee_stdin_enable(void)
467 {
468         xbee_cmdline_input_enabled = 1;
469 }
470
471 void xbee_stdin_disable(void)
472 {
473         xbee_cmdline_input_enabled = 0;
474 }
475
476 static void evt_timeout(struct callout_manager *cm, struct callout *clt,
477                         void *arg)
478 {
479         struct xbee_ctx *ctx = arg;
480
481         printf_P(PSTR("Timeout\r\n"));
482
483         /* restart command line */
484         xbee_stdin_enable();
485         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
486
487         /* free event */
488         xbee_unregister_channel(xbee_dev, ctx->channel);
489 }
490
491 void xbee_load_timeout(struct xbee_ctx *ctx)
492 {
493         callout_reset(&cm, &ctx->timeout, TIMEOUT_MS, SINGLE, evt_timeout, ctx);
494 }
495
496 void xbee_unload_timeout(struct xbee_ctx *ctx)
497 {
498         callout_stop(&cm, &ctx->timeout);
499 }
500
501 void bootloader(void)
502 {
503 #ifndef USE_USB
504 #define BOOTLOADER_ADDR 0x3f000
505         if (pgm_read_byte_far(BOOTLOADER_ADDR) == 0xff) {
506                 printf_P(PSTR("Bootloader is not present\r\n"));
507                 return;
508         }
509         cli();
510         /* ... very specific :( */
511         TIMSK0 = 0;
512         TIMSK1 = 0;
513         TIMSK2 = 0;
514         TIMSK3 = 0;
515         TIMSK4 = 0;
516         TIMSK5 = 0;
517         EIMSK = 0;
518         UCSR0B = 0;
519         UCSR1B = 0;
520         UCSR2B = 0;
521         UCSR3B = 0;
522         SPCR = 0;
523         TWCR = 0;
524         ACSR = 0;
525         ADCSRA = 0;
526
527         EIND = 1;
528         __asm__ __volatile__ ("ldi r31,0xf8\n");
529         __asm__ __volatile__ ("ldi r30,0x00\n");
530         __asm__ __volatile__ ("eijmp\n");
531 #endif
532 }
533
534 void xbee_mainloop(void)
535 {
536         while (1) {
537                 callout_manage(&cm);
538
539                 if (xbee_raw) {
540                         int16_t c;
541
542                         /* from xbee to cmdline */
543                         c = xbee_dev_recv(NULL);
544                         if (c >= 0)
545                                 cmdline_dev_send((uint8_t)c, NULL);
546
547                         /* from cmdline to xbee */
548                         c = cmdline_dev_recv(NULL);
549                         if (c == 4) { /* CTRL-d */
550                                 xbee_raw = 0;
551                                 rdline_newline(&xbeeboard.rdl,
552                                                xbeeboard.prompt);
553                         }
554                         else if (c >= 0) {
555                                 /* send to xbee */
556                                 xbee_dev_send((uint8_t)c, NULL);
557
558                                 /* echo on cmdline */
559                                 cmdline_dev_send((uint8_t)c, NULL);
560                         }
561                 }
562                 else {
563                         if (xbee_cmdline_input_enabled)
564                                 cmdline_poll();
565                         xbee_proto_rx(xbee_dev);
566                 }
567
568 #ifdef USE_USB
569                 CDC_Device_USBTask(&VirtualSerial1_CDC_Interface);
570                 CDC_Device_USBTask(&VirtualSerial2_CDC_Interface);
571                 USB_USBTask();
572 #endif
573         }
574 }
575
576 /* return time in milliseconds on unsigned 16 bits */
577 static uint16_t get_time_ms(void)
578 {
579         return global_ms;
580 }
581
582 static void do_led_blink(struct callout_manager *cm,
583                          struct callout *clt, void *dummy)
584 {
585         static uint8_t a = 0;
586
587 #ifdef USE_USB
588         if (a & 1)
589                 LEDs_SetAllLEDs(0);
590         else
591                 LEDs_SetAllLEDs(0xff);
592 #else
593         /* XXX */
594 #endif
595         a++;
596 }
597
598 static void increment_ms(void *dummy)
599 {
600         global_ms++;
601 }
602
603 static void main_timer_interrupt(void)
604 {
605         static uint8_t cpt = 0;
606         cpt++;
607         sei();
608         if ((cpt & 0x3) == 0)
609                 scheduler_interrupt();
610 }
611
612 /** Main program entry point. This routine contains the overall program flow, including initial
613  *  setup of all components and the main program loop.
614  */
615 int main(void)
616 {
617         struct callout t1;
618         FILE *xbee_file;
619         int8_t err;
620         struct xbee_dev dev;
621
622         spi_servo_init();
623 #ifdef USE_USB
624         SetupHardware();
625
626         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
627 #else
628         uart_init();
629 #endif
630
631         fdevopen(cmdline_dev_send, cmdline_dev_recv);
632         xbee_file = fdevopen(xbee_dev_send, xbee_dev_recv);
633         scheduler_init();
634         timer_init();
635         timer0_register_OV_intr(main_timer_interrupt);
636
637         scheduler_add_periodical_event_priority(increment_ms, NULL,
638                                                 1000L / SCHEDULER_UNIT,
639                                                 LED_PRIO);
640         cmdline_init();
641 #ifndef USE_USB
642         /* in usb mode, it's done in usb callback */
643         printf_P(PSTR("\r\n"));
644         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
645 #endif
646         callout_manager_init(&cm, get_time_ms);
647         callout_reset(&cm, &t1, 500, PERIODICAL, do_led_blink, NULL);
648
649         /* initialize libxbee */
650         err = xbee_init();
651         if (err < 0)
652                 return -1;
653
654         xbee_dev = &dev;
655
656         /* open xbee device */
657         if (xbee_open(xbee_dev, xbee_file) < 0)
658                 return -1;
659
660         /* register default channel with a callback */
661         if (xbee_register_channel(xbee_dev, XBEE_DEFAULT_CHANNEL,
662                                   xbee_rx, NULL) < 0) {
663                 fprintf(stderr, "cannot register default channel\n");
664                 return -1;
665         }
666
667         sei();
668         xbee_mainloop();
669         return 0;
670 }