support servo control through SPI
[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:0x99: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 <scheduler.h>
50 #include <clock_time.h>
51 #include <parse.h>
52 #include <rdline.h>
53 #include <timer.h>
54
55 #include "main.h"
56
57 struct xbeeboard xbeeboard;
58 volatile uint16_t global_ms;
59 struct callout_manager cm;
60
61 #define TIMEOUT_MS 1000
62
63 /* global xbee device */
64 struct xbee_dev *xbee_dev;
65
66 /* events */
67 //static struct event stdin_read_event, xbee_read_event;
68
69 /* parameters */
70 int xbee_raw = 0;
71 int xbee_hexdump = 0;
72 int xbee_debug = 0;
73
74 int xbee_cmdline_input_enabled = 1;
75
76 static struct xbee_ctx xbee_ctx[XBEE_MAX_CHANNEL];
77
78 static void hexdump(const char *title, const void *buf, unsigned int len)
79 {
80         unsigned int i, out, ofs;
81         const unsigned char *data = buf;
82 #define LINE_LEN 80
83         char line[LINE_LEN];    /* space needed 8+16*3+3+16 == 75 */
84
85         printf_P(PSTR("%s at [%p], len=%d\r\n"), title, data, len);
86         ofs = 0;
87         while (ofs < len) {
88                 /* format 1 line in the buffer, then use printk to print them */
89                 out = snprintf_P(line, LINE_LEN, PSTR("%08X"), ofs);
90                 for (i=0; ofs+i < len && i<16; i++)
91                         out += snprintf_P(line+out, LINE_LEN - out,
92                                           PSTR(" %02X"),
93                                           data[ofs+i]&0xff);
94                 for (;i<=16;i++)
95                         out += snprintf(line+out, LINE_LEN - out, "   ");
96                 for (i=0; ofs < len && i<16; i++, ofs++) {
97                         unsigned char c = data[ofs];
98                         if (!isascii(c) || !isprint(c))
99                                 c = '.';
100                         out += snprintf_P(line+out,
101                                           LINE_LEN - out,
102                                           PSTR("%c"), c);
103                 }
104                 printf_P(PSTR("%s\r\n"), line);
105         }
106 }
107
108 static int parse_xmit_status(struct xbee_ctx *ctx,
109                              struct xbee_xmit_status_hdr *frame, unsigned len)
110 {
111         (void)len;
112
113         if (ctx == NULL) {
114                 printf_P(PSTR("no context\r\n"));
115                 return -1;
116         }
117
118         /* see if it matches a xmit query (atcmd_query must be NULL) */
119         if (ctx->atcmd_query[0] != '\0') {
120                 printf_P(PSTR("invalid response 2\r\n"));
121                 return -1;
122         }
123
124         /* XXX use defines for these values */
125         if (frame->delivery_status == 0x00)
126                 printf_P(PSTR("Success\r\n"));
127         else if (frame->delivery_status == 0x01)
128                 printf_P(PSTR("MAC ACK Failure\r\n"));
129         else if (frame->delivery_status == 0x15)
130                 printf_P(PSTR("Invalid destination endpoint\r\n"));
131         else if (frame->delivery_status == 0x21)
132                 printf_P(PSTR("Network ACK Failure\r\n"));
133         else if (frame->delivery_status == 0x25)
134                 printf_P(PSTR("Route Not Found\r\n"));
135
136         return 0;
137 }
138
139 static int dump_atcmd(struct xbee_ctx *ctx, struct xbee_atresp_hdr *frame,
140                unsigned len)
141 {
142         char atcmd_str[3];
143         const struct xbee_atcmd *cmd_pgm;
144         struct xbee_atcmd cmd;
145         union {
146                 uint8_t u8;
147                 uint16_t u16;
148                 uint32_t u32;
149                 int16_t s16;
150         } __attribute__((packed)) *result;
151
152         if (ctx == NULL) {
153                 printf_P(PSTR("no context\r\n"));
154                 return -1;
155         }
156
157         /* get AT command from frame */
158         memcpy(atcmd_str, &frame->cmd, 2);
159         atcmd_str[2] = '\0';
160
161         /* see if it matches query */
162         if (memcmp(atcmd_str, ctx->atcmd_query, 2)) {
163                 printf_P(PSTR("invalid response <%c%c><%s><%s>\r\n"),
164                          frame->cmd & 0xFF,
165                          (frame->cmd >> 8) & 0xFF,
166                          atcmd_str, ctx->atcmd_query);
167                 return -1;
168         }
169
170         /* see if it exists */
171         cmd_pgm = xbee_atcmd_lookup_name(atcmd_str);
172         if (cmd_pgm == NULL) {
173                 printf_P(PSTR("unknown response\r\n"));
174                 return -1;
175         }
176         memcpy_P(&cmd, cmd_pgm, sizeof(cmd));
177
178         /* bad status */
179         if (frame->status == 1) {
180                 printf_P(PSTR("Status is error\r\n"));
181                 return -1;
182         }
183         else if (frame->status == 2) {
184                 printf_P(PSTR("Invalid command\r\n"));
185                 return -1;
186         }
187         else if (frame->status == 3) {
188                 printf_P(PSTR("Invalid parameter\r\n"));
189                 return -1;
190         }
191         else if (frame->status != 0) {
192                 printf_P(PSTR("Unknown status error %d\r\n"), frame->status);
193                 return -1;
194         }
195
196         /* callback */
197         if (ctx->func != NULL)
198                 ctx->func(frame, len, ctx->arg);
199
200         /* dump frame */
201         result = (void *)frame->data;
202         len -= offsetof(struct xbee_atresp_hdr, data);
203         if (cmd.flags & XBEE_ATCMD_F_PARAM_U8 && len == sizeof(uint8_t))
204                 printf_P(PSTR("<%s> is 0x%x\r\n"), atcmd_str, result->u8);
205         else if (cmd.flags & XBEE_ATCMD_F_PARAM_U16 && len == sizeof(uint16_t))
206                 printf_P(PSTR("<%s> is 0x%x\r\n"),
207                          atcmd_str,
208                          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"\r\n"),
211                          atcmd_str,
212                          ntohl(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                 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         (void)cm;
490         (void)clt;
491
492         printf_P(PSTR("Timeout\r\n"));
493
494         /* restart command line */
495         xbee_stdin_enable();
496         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
497
498         /* free event */
499         xbee_unregister_channel(xbee_dev, ctx->channel);
500 }
501
502 void xbee_load_timeout(struct xbee_ctx *ctx)
503 {
504         callout_reset(&cm, &ctx->timeout, TIMEOUT_MS, SINGLE, evt_timeout, ctx);
505 }
506
507 void xbee_unload_timeout(struct xbee_ctx *ctx)
508 {
509         callout_stop(&cm, &ctx->timeout);
510 }
511
512 void bootloader(void)
513 {
514 #define BOOTLOADER_ADDR 0x3f000
515         if (pgm_read_byte_far(BOOTLOADER_ADDR) == 0xff) {
516                 printf_P(PSTR("Bootloader is not present\r\n"));
517                 return;
518         }
519         cli();
520         /* ... very specific :( */
521         TIMSK0 = 0;
522         TIMSK1 = 0;
523         TIMSK2 = 0;
524         TIMSK3 = 0;
525         EIMSK = 0;
526         UCSR0B = 0;
527         UCSR1B = 0;
528         SPCR = 0;
529         TWCR = 0;
530         ACSR = 0;
531         ADCSRA = 0;
532
533         /* XXX */
534         /* __asm__ __volatile__ ("ldi r31,0xf8\n"); */
535         /* __asm__ __volatile__ ("ldi r30,0x00\n"); */
536         /* __asm__ __volatile__ ("eijmp\n"); */
537 }
538
539 void xbee_mainloop(void)
540 {
541         while (1) {
542                 callout_manage(&cm);
543
544                 if (xbee_raw) {
545                         int16_t c;
546
547                         /* from xbee to cmdline */
548                         c = xbee_dev_recv(NULL);
549                         if (c >= 0)
550                                 cmdline_dev_send((uint8_t)c, NULL);
551
552                         /* from cmdline to xbee */
553                         c = cmdline_dev_recv(NULL);
554                         if (c == 4) { /* CTRL-d */
555                                 xbee_raw = 0;
556                                 rdline_newline(&xbeeboard.rdl,
557                                                xbeeboard.prompt);
558                         }
559                         else if (c >= 0) {
560                                 /* send to xbee */
561                                 xbee_dev_send((uint8_t)c, NULL);
562
563                                 /* echo on cmdline */
564                                 cmdline_dev_send((uint8_t)c, NULL);
565                         }
566                 }
567                 else {
568                         if (xbee_cmdline_input_enabled)
569                                 cmdline_poll();
570                         xbee_proto_rx(xbee_dev);
571                 }
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 main_timer_interrupt(void)
582 {
583         static uint16_t cycles;
584         static uint8_t cpt;
585
586         /* interrupt every 2048 cycles */
587         cycles += 2048;
588         if (cycles >= 12000) {
589                 cycles -= 12000;
590                 global_ms ++;
591         }
592
593         /* LED blink */
594         if (global_ms & 0x80)
595                 LED1_ON();
596         else
597                 LED1_OFF();
598
599         /* call scheduler every 682us with interrupt unlocked */
600         sei();
601         if ((cpt & 0x3) == 0)
602                 scheduler_interrupt();
603 }
604
605 int main(void)
606 {
607         //struct callout t1;
608         FILE *xbee_file;
609         int8_t err;
610         struct xbee_dev dev;
611
612         DDRA = 0x07; /* LEDs */
613
614         uart_init();
615         uart_register_rx_event(CMDLINE_UART, emergency);
616
617         fdevopen(cmdline_dev_send, cmdline_dev_recv);
618         xbee_file = fdevopen(xbee_dev_send, xbee_dev_recv);
619         scheduler_init();
620         timer_init();
621         timer0_register_OV_intr(main_timer_interrupt);
622
623         cmdline_init();
624         spi_servo_init();
625
626         printf_P(PSTR("\r\n"));
627         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
628
629         callout_manager_init(&cm, get_time_ms);
630         //callout_reset(&cm, &t1, 500, PERIODICAL, do_led_blink, NULL);
631
632         /* initialize libxbee */
633         err = xbee_init();
634         if (err < 0)
635                 return -1;
636
637         xbee_dev = &dev;
638
639         /* open xbee device */
640         if (xbee_open(xbee_dev, xbee_file) < 0)
641                 return -1;
642
643         /* register default channel with a callback */
644         if (xbee_register_channel(xbee_dev, XBEE_DEFAULT_CHANNEL,
645                                   xbee_rx, NULL) < 0) {
646                 fprintf(stderr, "cannot register default channel\n");
647                 return -1;
648         }
649
650         sei();
651
652         xbee_mainloop();
653         return 0;
654 }