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