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