add code to control the audio buzzer
[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 "beep.h"
56 #include "main.h"
57
58 struct xbeeboard xbeeboard;
59 volatile uint16_t global_ms;
60 struct callout_manager cm;
61
62 #define TIMEOUT_MS 1000
63
64 /* global xbee device */
65 struct xbee_dev *xbee_dev;
66
67 /* events */
68 //static struct event stdin_read_event, xbee_read_event;
69
70 /* parameters */
71 int xbee_raw = 0;
72 int xbee_hexdump = 0;
73 int xbee_debug = 0;
74
75 int xbee_cmdline_input_enabled = 1;
76
77 static struct xbee_ctx xbee_ctx[XBEE_MAX_CHANNEL];
78
79 static void hexdump(const char *title, const void *buf, unsigned int len)
80 {
81         unsigned int i, out, ofs;
82         const unsigned char *data = buf;
83 #define LINE_LEN 80
84         char line[LINE_LEN];    /* space needed 8+16*3+3+16 == 75 */
85
86         printf_P(PSTR("%s at [%p], len=%d\r\n"), title, data, len);
87         ofs = 0;
88         while (ofs < len) {
89                 /* format 1 line in the buffer, then use printk to print them */
90                 out = snprintf_P(line, LINE_LEN, PSTR("%08X"), ofs);
91                 for (i=0; ofs+i < len && i<16; i++)
92                         out += snprintf_P(line+out, LINE_LEN - out,
93                                           PSTR(" %02X"),
94                                           data[ofs+i]&0xff);
95                 for (;i<=16;i++)
96                         out += snprintf(line+out, LINE_LEN - out, "   ");
97                 for (i=0; ofs < len && i<16; i++, ofs++) {
98                         unsigned char c = data[ofs];
99                         if (!isascii(c) || !isprint(c))
100                                 c = '.';
101                         out += snprintf_P(line+out,
102                                           LINE_LEN - out,
103                                           PSTR("%c"), c);
104                 }
105                 printf_P(PSTR("%s\r\n"), line);
106         }
107 }
108
109 static int parse_xmit_status(struct xbee_ctx *ctx,
110                              struct xbee_xmit_status_hdr *frame, unsigned len)
111 {
112         (void)len;
113
114         if (ctx == NULL) {
115                 printf_P(PSTR("no context\r\n"));
116                 return -1;
117         }
118
119         /* see if it matches a xmit query (atcmd_query must be NULL) */
120         if (ctx->atcmd_query[0] != '\0') {
121                 printf_P(PSTR("invalid response 2\r\n"));
122                 return -1;
123         }
124
125         /* XXX use defines for these values */
126         if (frame->delivery_status == 0x00)
127                 printf_P(PSTR("Success\r\n"));
128         else if (frame->delivery_status == 0x01)
129                 printf_P(PSTR("MAC ACK Failure\r\n"));
130         else if (frame->delivery_status == 0x15)
131                 printf_P(PSTR("Invalid destination endpoint\r\n"));
132         else if (frame->delivery_status == 0x21)
133                 printf_P(PSTR("Network ACK Failure\r\n"));
134         else if (frame->delivery_status == 0x25)
135                 printf_P(PSTR("Route Not Found\r\n"));
136
137         return 0;
138 }
139
140 static int dump_atcmd(struct xbee_ctx *ctx, struct xbee_atresp_hdr *frame,
141                unsigned len)
142 {
143         char atcmd_str[3];
144         const struct xbee_atcmd *cmd_pgm;
145         struct xbee_atcmd cmd;
146         union {
147                 uint8_t u8;
148                 uint16_t u16;
149                 uint32_t u32;
150                 int16_t s16;
151         } __attribute__((packed)) *result;
152
153         if (ctx == NULL) {
154                 printf_P(PSTR("no context\r\n"));
155                 return -1;
156         }
157
158         /* get AT command from frame */
159         memcpy(atcmd_str, &frame->cmd, 2);
160         atcmd_str[2] = '\0';
161
162         /* see if it matches query */
163         if (memcmp(atcmd_str, ctx->atcmd_query, 2)) {
164                 printf_P(PSTR("invalid response <%c%c><%s><%s>\r\n"),
165                          frame->cmd & 0xFF,
166                          (frame->cmd >> 8) & 0xFF,
167                          atcmd_str, ctx->atcmd_query);
168                 return -1;
169         }
170
171         /* see if it exists */
172         cmd_pgm = xbee_atcmd_lookup_name(atcmd_str);
173         if (cmd_pgm == NULL) {
174                 printf_P(PSTR("unknown response\r\n"));
175                 return -1;
176         }
177         memcpy_P(&cmd, cmd_pgm, sizeof(cmd));
178
179         /* bad status */
180         if (frame->status == 1) {
181                 printf_P(PSTR("Status is error\r\n"));
182                 return -1;
183         }
184         else if (frame->status == 2) {
185                 printf_P(PSTR("Invalid command\r\n"));
186                 return -1;
187         }
188         else if (frame->status == 3) {
189                 printf_P(PSTR("Invalid parameter\r\n"));
190                 return -1;
191         }
192         else if (frame->status != 0) {
193                 printf_P(PSTR("Unknown status error %d\r\n"), frame->status);
194                 return -1;
195         }
196
197         /* callback */
198         if (ctx->func != NULL)
199                 ctx->func(frame, len, ctx->arg);
200
201         /* dump frame */
202         result = (void *)frame->data;
203         len -= offsetof(struct xbee_atresp_hdr, data);
204         if (cmd.flags & XBEE_ATCMD_F_PARAM_U8 && len == sizeof(uint8_t))
205                 printf_P(PSTR("<%s> is 0x%x\r\n"), atcmd_str, result->u8);
206         else if (cmd.flags & XBEE_ATCMD_F_PARAM_U16 && len == sizeof(uint16_t))
207                 printf_P(PSTR("<%s> is 0x%x\r\n"),
208                          atcmd_str,
209                          ntohs(result->u16));
210         else if (cmd.flags & XBEE_ATCMD_F_PARAM_U32 && len == sizeof(uint32_t))
211                 printf_P(PSTR("<%s> is 0x%"PRIx32"\r\n"),
212                          atcmd_str,
213                          ntohl(result->u32));
214         else if (cmd.flags & XBEE_ATCMD_F_PARAM_S16 && len == sizeof(int16_t))
215                 printf_P(PSTR("<%s> is %d\r\n"), atcmd_str, ntohs(result->s16));
216         else if (len == 0)
217                 printf_P(PSTR("no data, status ok\r\n"));
218         else
219                 hexdump("atcmd answer", frame->data, len);
220
221
222         return 0;
223 }
224
225
226 int xbee_recv_data(struct xbee_recv_hdr *recvframe, unsigned len)
227 {
228         unsigned int datalen;
229         struct rc_proto_hdr *rch = (struct rc_proto_hdr *) &recvframe->data;
230
231         if (len <  sizeof(*recvframe))
232                 return -1;
233
234         datalen = len - sizeof(*recvframe);
235         if (datalen < sizeof(struct rc_proto_hdr))
236                 return -1;
237
238         switch (rch->type) {
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                 default:
266                         return -1;
267         }
268
269         return 0;
270 }
271
272 /* socat /dev/ttyUSB0,raw,echo=0,b115200 /dev/ttyACM1,raw,echo=0,b115200 */
273 void xbee_rx(struct xbee_dev *dev, int channel, int type,
274              void *frame, unsigned len, void *opaque)
275 {
276         struct xbee_ctx *ctx = opaque;
277         int do_hexdump = xbee_hexdump;
278
279         if (xbee_debug)
280                 printf_P(PSTR("type=0x%x, channel=%d, ctx=%p\r\n"),
281                          type, channel, ctx);
282
283         /* if ctx is !NULL, it is an answer to a query */
284         if (ctx != NULL) {
285                 /* XXX only delete timeout if answer matched */
286                 xbee_unload_timeout(ctx);
287                 if (xbee_debug && ctx->atcmd_query)
288                         printf_P(PSTR("Received answer to query <%c%c>\r\n"),
289                                  ctx->atcmd_query[0], ctx->atcmd_query[1]);
290         }
291
292         /* some additional checks before sending */
293         switch (type) {
294                 case XBEE_TYPE_MODEM_STATUS: {
295                         printf_P(PSTR("Received Modem Status frame\r\n"));
296                         break;
297                 }
298
299                 case XBEE_TYPE_RMT_ATRESP: {
300                         union {
301                                 uint64_t u64;
302                                 struct {
303 #if BYTE_ORDER == LITTLE_ENDIAN
304                                         uint32_t low;
305                                         uint32_t high;
306 #else
307                                         uint32_t high;
308                                         uint32_t low;
309 #endif
310                                 } u32;
311                         } addr;
312                         memcpy(&addr, frame, sizeof(addr));
313                         addr.u64 = ntohll(addr.u64);
314                         printf_P(PSTR("from remote address %"PRIx32"%"PRIx32"\r\n"),
315                                  addr.u32.high, addr.u32.low);
316
317                         /* this answer contains an atcmd answer at offset 10 */
318                         if (dump_atcmd(ctx, frame + 10, len - 10) < 0)
319                                 do_hexdump = 1;
320                         break;
321                 }
322                 case XBEE_TYPE_ATRESP: {
323                         if (dump_atcmd(ctx, frame, len) < 0)
324                                 do_hexdump = 1;
325                         break;
326                 }
327
328                 case XBEE_TYPE_XMIT_STATUS: {
329                         if (parse_xmit_status(ctx, frame, len) < 0)
330                                 do_hexdump = 1;
331                         break;
332                 }
333
334                 case XBEE_TYPE_RECV: {
335                         if (xbee_recv_data(frame, len) < 0)
336                                 do_hexdump = 1;
337                         break;
338                 }
339
340                 case XBEE_TYPE_ATCMD:
341                 case XBEE_TYPE_ATCMD_Q:
342                 case XBEE_TYPE_XMIT:
343                 case XBEE_TYPE_EXPL_XMIT:
344                 case XBEE_TYPE_RMT_ATCMD:
345                 case XBEE_TYPE_EXPL_RECV:
346                 case XBEE_TYPE_NODE_ID:
347                 default:
348                         printf_P(PSTR("Invalid frame\r\n"));
349                         do_hexdump = 1;
350                         break;
351         }
352
353         if (do_hexdump)
354                 hexdump("undecoded rx frame", frame, len);
355
356         /* restart command line if it was a blocking query */
357         if (ctx != NULL) {
358                 xbee_unregister_channel(dev, channel);
359                 if (ctx->foreground) {
360                         xbee_stdin_enable();
361                         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
362                 }
363         }
364 }
365
366 static int xbeeapp_send(struct xbee_ctx *ctx, int type, void *buf, unsigned len,
367                         int foreground)
368 {
369         int ret;
370         int channel;
371
372         if (len > XBEE_MAX_FRAME_LEN) {
373                 printf_P(PSTR("frame too large\r\n"));
374                 return -1;
375         }
376
377         /* register a channel */
378         channel = xbee_register_channel(xbee_dev, XBEE_CHANNEL_ANY,
379                                         xbee_rx, NULL);
380         if (channel < 0) {
381                 printf_P(PSTR("cannot send: no free channel\r\n"));
382                 return -1;
383         }
384
385         /* copy context in the static struct table (avoiding a malloc) */
386         memcpy(&xbee_ctx[channel], ctx, sizeof(*ctx));
387         ctx = &xbee_ctx[channel];
388         xbee_set_opaque(xbee_dev, channel, ctx);
389
390         if (xbee_debug)
391                 printf_P(PSTR("send frame channel=%d type=0x%x len=%d\r\n"),
392                          channel, type, len);
393         if (xbee_hexdump)
394                 hexdump("xmit frame", buf, len);
395
396         /* transmit the frame on this channel */
397         ret = xbee_proto_xmit(xbee_dev, channel, type, buf,
398                               len);
399         if (ret < 0) {
400                 printf_P(PSTR("cannot send\r\n"));
401                 xbee_unregister_channel(xbee_dev, channel);
402                 return -1;
403         }
404
405         ctx->channel = channel;
406         xbee_load_timeout(ctx);   /* load a timeout event */
407
408         /* suspend command line until we have answer or timeout */
409         if (foreground) {
410                 ctx->foreground = 1;
411                 rdline_stop(&xbeeboard.rdl); /* don't display prompt when return */
412                 xbee_stdin_disable();  /* unload file descriptor polling */
413         }
414
415         return 0;
416 }
417
418 /* send an AT command with parameters filled by caller. Disable
419  * command line until we get the answer or until a timeout occurs */
420 int xbeeapp_send_atcmd(const char *atcmd_str,
421                        void *param, unsigned param_len, int foreground,
422                        int (*func)(void *frame, unsigned len, void *arg), void *arg)
423 {
424         struct xbee_ctx ctx;
425         struct {
426                 struct xbee_atcmd_hdr atcmd;
427                 char buf[XBEE_MAX_FRAME_LEN];
428         } __attribute__((packed)) frame;
429
430         memset(&ctx, 0, sizeof(ctx));
431         ctx.atcmd_query[0] = atcmd_str[0];
432         ctx.atcmd_query[1] = atcmd_str[1];
433         ctx.func = func;
434         ctx.arg = arg;
435
436         memcpy(&frame.atcmd.cmd, atcmd_str, 2);
437         memcpy(&frame.buf, param, param_len);
438
439         if (xbeeapp_send(&ctx, XBEE_TYPE_ATCMD, &frame,
440                          sizeof(struct xbee_atcmd_hdr) +
441                          param_len, foreground) < 0) {
442                 return -1;
443         }
444
445         return 0;
446 }
447
448 int xbeeapp_send_msg(uint64_t addr, void *data,
449                      unsigned data_len, int foreground)
450 {
451         struct xbee_ctx ctx;
452         struct {
453                 struct xbee_xmit_hdr xmit;
454                 char buf[XBEE_MAX_FRAME_LEN];
455         } __attribute__((packed)) frame;
456
457         memset(&ctx, 0, sizeof(ctx));
458         ctx.atcmd_query[0] = '\0';
459
460         frame.xmit.dstaddr = htonll(addr);
461         frame.xmit.reserved = htons(0xFFFE);
462         frame.xmit.bcast_radius = 0;
463         frame.xmit.opts = 0;
464         memcpy(&frame.buf, data, data_len);
465
466         if (xbeeapp_send(&ctx, XBEE_TYPE_XMIT, &frame,
467                          sizeof(struct xbee_xmit_hdr) +
468                          data_len, foreground) < 0) {
469                 return -1;
470         }
471
472         return 0;
473 }
474
475 void xbee_stdin_enable(void)
476 {
477         xbee_cmdline_input_enabled = 1;
478 }
479
480 void xbee_stdin_disable(void)
481 {
482         xbee_cmdline_input_enabled = 0;
483 }
484
485 static void evt_timeout(struct callout_manager *cm, struct callout *clt,
486                         void *arg)
487 {
488         struct xbee_ctx *ctx = arg;
489
490         (void)cm;
491         (void)clt;
492
493         printf_P(PSTR("Timeout\r\n"));
494
495         /* restart command line */
496         xbee_stdin_enable();
497         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
498
499         /* free event */
500         xbee_unregister_channel(xbee_dev, ctx->channel);
501 }
502
503 void xbee_load_timeout(struct xbee_ctx *ctx)
504 {
505         callout_reset(&cm, &ctx->timeout, TIMEOUT_MS, SINGLE, evt_timeout, ctx);
506 }
507
508 void xbee_unload_timeout(struct xbee_ctx *ctx)
509 {
510         callout_stop(&cm, &ctx->timeout);
511 }
512
513 void bootloader(void)
514 {
515 #define BOOTLOADER_ADDR 0x3f000
516         if (pgm_read_byte_far(BOOTLOADER_ADDR) == 0xff) {
517                 printf_P(PSTR("Bootloader is not present\r\n"));
518                 return;
519         }
520         cli();
521         /* ... very specific :( */
522         TIMSK0 = 0;
523         TIMSK1 = 0;
524         TIMSK2 = 0;
525         TIMSK3 = 0;
526         EIMSK = 0;
527         UCSR0B = 0;
528         UCSR1B = 0;
529         SPCR = 0;
530         TWCR = 0;
531         ACSR = 0;
532         ADCSRA = 0;
533
534         /* XXX */
535         /* __asm__ __volatile__ ("ldi r31,0xf8\n"); */
536         /* __asm__ __volatile__ ("ldi r30,0x00\n"); */
537         /* __asm__ __volatile__ ("eijmp\n"); */
538 }
539
540 void xbee_mainloop(void)
541 {
542         while (1) {
543                 callout_manage(&cm);
544
545                 if (xbee_raw) {
546                         int16_t c;
547
548                         /* from xbee to cmdline */
549                         c = xbee_dev_recv(NULL);
550                         if (c >= 0)
551                                 cmdline_dev_send((uint8_t)c, NULL);
552
553                         /* from cmdline to xbee */
554                         c = cmdline_dev_recv(NULL);
555                         if (c == 4) { /* CTRL-d */
556                                 xbee_dev_send('A', NULL);
557                                 xbee_dev_send('T', NULL);
558                                 xbee_dev_send('C', NULL);
559                                 xbee_dev_send('N', NULL);
560                                 xbee_dev_send('\n', NULL);
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 main_timer_interrupt(void)
588 {
589         static uint16_t cycles;
590         static uint8_t cpt;
591
592         cpt++;
593
594         /* interrupt every 2048 cycles */
595         cycles += 2048;
596         if (cycles >= 12000) {
597                 cycles -= 12000;
598                 global_ms ++;
599         }
600
601         /* LED blink */
602         if (global_ms & 0x80)
603                 LED1_ON();
604         else
605                 LED1_OFF();
606
607         if (cpt & beep_mask)
608                 BUZZER_ON();
609         else
610                 BUZZER_OFF();
611
612         /* call scheduler every 682us with interrupt unlocked */
613         sei();
614         if ((cpt & 0x3) == 0)
615                 scheduler_interrupt();
616 }
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         DDRA = 0x07 /* LEDs */ | 0x10 /* buzzer */;
626
627         uart_init();
628         uart_register_rx_event(CMDLINE_UART, emergency);
629
630         fdevopen(cmdline_dev_send, cmdline_dev_recv);
631         xbee_file = fdevopen(xbee_dev_send, xbee_dev_recv);
632         scheduler_init();
633         timer_init();
634         timer0_register_OV_intr(main_timer_interrupt);
635
636         cmdline_init();
637         spi_servo_init();
638         beep_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
666         xbee_mainloop();
667         return 0;
668 }