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