fix bootloader for atm2560
[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\r\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 #ifndef USE_USB
503 #define BOOTLOADER_ADDR 0x3f000
504         if (pgm_read_byte_far(BOOTLOADER_ADDR) == 0xff) {
505                 printf_P(PSTR("Bootloader is not present\r\n"));
506                 return;
507         }
508         cli();
509         /* ... very specific :( */
510         TIMSK0 = 0;
511         TIMSK1 = 0;
512         TIMSK2 = 0;
513         TIMSK3 = 0;
514         TIMSK4 = 0;
515         TIMSK5 = 0;
516         EIMSK = 0;
517         UCSR0B = 0;
518         UCSR1B = 0;
519         UCSR2B = 0;
520         UCSR3B = 0;
521         SPCR = 0;
522         TWCR = 0;
523         ACSR = 0;
524         ADCSRA = 0;
525
526         EIND = 1;
527         __asm__ __volatile__ ("ldi r31,0xf8\n");
528         __asm__ __volatile__ ("ldi r30,0x00\n");
529         __asm__ __volatile__ ("eijmp\n");
530 #endif
531 }
532
533 void xbee_mainloop(void)
534 {
535         while (1) {
536                 callout_manage(&cm);
537
538                 if (xbee_raw) {
539                         int16_t c;
540
541                         /* from xbee to cmdline */
542                         c = xbee_dev_recv(NULL);
543                         if (c >= 0)
544                                 cmdline_dev_send((uint8_t)c, NULL);
545
546                         /* from cmdline to xbee */
547                         c = cmdline_dev_recv(NULL);
548                         if (c == 4) { /* CTRL-d */
549                                 xbee_raw = 0;
550                                 rdline_newline(&xbeeboard.rdl,
551                                                xbeeboard.prompt);
552                         }
553                         else if (c >= 0) {
554                                 /* send to xbee */
555                                 xbee_dev_send((uint8_t)c, NULL);
556
557                                 /* echo on cmdline */
558                                 cmdline_dev_send((uint8_t)c, NULL);
559                         }
560                 }
561                 else {
562                         if (xbee_cmdline_input_enabled)
563                                 cmdline_poll();
564                         xbee_proto_rx(xbee_dev);
565                 }
566
567 #ifdef USE_USB
568                 CDC_Device_USBTask(&VirtualSerial1_CDC_Interface);
569                 CDC_Device_USBTask(&VirtualSerial2_CDC_Interface);
570                 USB_USBTask();
571 #endif
572         }
573 }
574
575 /* return time in milliseconds on unsigned 16 bits */
576 static uint16_t get_time_ms(void)
577 {
578         return global_ms;
579 }
580
581 static void do_led_blink(struct callout_manager *cm,
582                          struct callout *clt, void *dummy)
583 {
584         static uint8_t a = 0;
585
586 #ifdef USE_USB
587         if (a & 1)
588                 LEDs_SetAllLEDs(0);
589         else
590                 LEDs_SetAllLEDs(0xff);
591 #else
592         /* XXX */
593 #endif
594         a++;
595 }
596
597 static void increment_ms(void *dummy)
598 {
599         global_ms++;
600 }
601
602 static void main_timer_interrupt(void)
603 {
604         static uint8_t cpt = 0;
605         cpt++;
606         sei();
607         if ((cpt & 0x3) == 0)
608                 scheduler_interrupt();
609 }
610
611 /** Main program entry point. This routine contains the overall program flow, including initial
612  *  setup of all components and the main program loop.
613  */
614 int main(void)
615 {
616         struct callout t1;
617         FILE *xbee_file;
618         int8_t err;
619         struct xbee_dev dev;
620
621 #ifdef USE_USB
622         SetupHardware();
623
624         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
625 #else
626         uart_init();
627 #endif
628
629         fdevopen(cmdline_dev_send, cmdline_dev_recv);
630         xbee_file = fdevopen(xbee_dev_send, xbee_dev_recv);
631         scheduler_init();
632         timer_init();
633         timer0_register_OV_intr(main_timer_interrupt);
634
635         scheduler_add_periodical_event_priority(increment_ms, NULL,
636                                                 1000L / SCHEDULER_UNIT,
637                                                 LED_PRIO);
638         cmdline_init();
639 #ifndef USE_USB
640         /* in usb mode, it's done in usb callback */
641         printf_P(PSTR("\r\n"));
642         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
643 #endif
644         callout_manager_init(&cm, get_time_ms);
645         callout_reset(&cm, &t1, 500, PERIODICAL, do_led_blink, NULL);
646
647         /* initialize libxbee */
648         err = xbee_init();
649         if (err < 0)
650                 return -1;
651
652         xbee_dev = &dev;
653
654         /* open xbee device */
655         if (xbee_open(xbee_dev, xbee_file) < 0)
656                 return -1;
657
658         /* register default channel with a callback */
659         if (xbee_register_channel(xbee_dev, XBEE_DEFAULT_CHANNEL,
660                                   xbee_rx, NULL) < 0) {
661                 fprintf(stderr, "cannot register default channel\n");
662                 return -1;
663         }
664
665         sei();
666         xbee_mainloop();
667         return 0;
668 }