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