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