parse_monitor: replace printf printf_P
[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_P(PSTR("%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_P(line, LINE_LEN, PSTR("%08X"), ofs);
93                 for (i=0; ofs+i < len && i<16; i++)
94                         out += snprintf_P(line+out, LINE_LEN - out,
95                                           PSTR(" %02X"),
96                                           data[ofs+i]&0xff);
97                 for (;i<=16;i++)
98                         out += snprintf(line+out, LINE_LEN - out, "   ");
99                 for (i=0; ofs < len && i<16; i++, ofs++) {
100                         unsigned char c = data[ofs];
101                         if (!isascii(c) || !isprint(c))
102                                 c = '.';
103                         out += snprintf_P(line+out,
104                                           LINE_LEN - out,
105                                           PSTR("%c"), c);
106                 }
107                 printf_P(PSTR("%s\r\n"), line);
108         }
109 }
110
111 static int parse_xmit_status(struct xbee_ctx *ctx,
112                              struct xbee_xmit_status_hdr *frame, unsigned 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         struct xbee_atcmd_pgm *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         int datalen = len - sizeof(*recvframe);
229         struct rc_proto_hdr *rch = (struct rc_proto_hdr *) &recvframe->data;
230
231         if (datalen < sizeof(struct rc_proto_hdr))
232                 return -1;
233
234         switch (rch->type) {
235                 case RC_PROTO_TYPE_CHANNEL:
236                         if (datalen != sizeof(struct rc_proto_channel))
237                                 return -1;
238                         break;
239                 case RC_PROTO_TYPE_RANGE: {
240                         struct rc_proto_range *rcr =
241                                 (struct rc_proto_range *) recvframe->data;
242
243                         if (datalen != sizeof(struct rc_proto_range))
244                                 return -1;
245
246                         if (rcr->power_level >= MAX_POWER_LEVEL)
247                                 return -1;
248
249                         rc_proto_rx_range(rcr->power_level);
250
251                         break;
252                 }
253                 default:
254                         return -1;
255         }
256
257         return 0;
258 }
259
260 /* socat /dev/ttyUSB0,raw,echo=0,b115200 /dev/ttyACM1,raw,echo=0,b115200 */
261 void xbee_rx(struct xbee_dev *dev, int channel, int type,
262              void *frame, unsigned len, void *opaque)
263 {
264         struct xbee_ctx *ctx = opaque;
265         int do_hexdump = xbee_hexdump;
266
267         if (xbee_debug)
268                 printf_P(PSTR("type=0x%x, channel=%d, ctx=%p\r\n"),
269                          type, channel, ctx);
270
271         /* if ctx is !NULL, it is an answer to a query */
272         if (ctx != NULL) {
273                 /* XXX only delete timeout if answer matched */
274                 xbee_unload_timeout(ctx);
275                 if (xbee_debug && ctx->atcmd_query)
276                         printf_P(PSTR("Received answer to query <%c%c>\r\n"),
277                                  ctx->atcmd_query[0], ctx->atcmd_query[1]);
278         }
279
280         /* some additional checks before sending */
281         switch (type) {
282                 case XBEE_TYPE_MODEM_STATUS: {
283                         printf_P(PSTR("Received Modem Status frame\r\n"));
284                         break;
285                 }
286
287                 case XBEE_TYPE_RMT_ATRESP: {
288                         union {
289                                 uint64_t u64;
290                                 struct {
291 #if BYTE_ORDER == LITTLE_ENDIAN
292                                         uint32_t low;
293                                         uint32_t high;
294 #else
295                                         uint32_t high;
296                                         uint32_t low;
297 #endif
298                                 } u32;
299                         } addr;
300                         memcpy(&addr, frame, sizeof(addr));
301                         addr.u64 = ntohll(addr.u64);
302                         printf_P(PSTR("from remote address %"PRIx32"%"PRIx32"\r\n"),
303                                  addr.u32.high, addr.u32.low);
304
305                         /* this answer contains an atcmd answer at offset 10 */
306                         if (dump_atcmd(ctx, frame + 10, len - 10) < 0)
307                                 do_hexdump = 1;
308                         break;
309                 }
310                 case XBEE_TYPE_ATRESP: {
311                         if (dump_atcmd(ctx, frame, len) < 0)
312                                 do_hexdump = 1;
313                         break;
314                 }
315
316                 case XBEE_TYPE_XMIT_STATUS: {
317                         if (parse_xmit_status(ctx, frame, len) < 0)
318                                 do_hexdump = 1;
319                         break;
320                 }
321
322                 case XBEE_TYPE_RECV: {
323                         if (xbee_recv_data(frame, len) < 0)
324                                 do_hexdump = 1;
325                         break;
326                 }
327
328                 case XBEE_TYPE_ATCMD:
329                 case XBEE_TYPE_ATCMD_Q:
330                 case XBEE_TYPE_XMIT:
331                 case XBEE_TYPE_EXPL_XMIT:
332                 case XBEE_TYPE_RMT_ATCMD:
333                 case XBEE_TYPE_EXPL_RECV:
334                 case XBEE_TYPE_NODE_ID:
335                 default:
336                         printf_P(PSTR("Invalid frame\r\n"));
337                         do_hexdump = 1;
338                         break;
339         }
340
341         if (do_hexdump)
342                 hexdump("undecoded rx frame", frame, len);
343
344         /* restart command line if it was a blocking query */
345         if (ctx != NULL) {
346                 xbee_unregister_channel(dev, channel);
347                 if (ctx->foreground) {
348                         xbee_stdin_enable();
349                         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
350                 }
351         }
352 }
353
354 static int xbeeapp_send(struct xbee_ctx *ctx, int type, void *buf, unsigned len,
355                         int foreground)
356 {
357         int ret;
358         int channel;
359
360         if (len > XBEE_MAX_FRAME_LEN) {
361                 printf_P(PSTR("frame too large\r\n"));
362                 return -1;
363         }
364
365         /* register a channel */
366         channel = xbee_register_channel(xbee_dev, XBEE_CHANNEL_ANY,
367                                         xbee_rx, NULL);
368         if (channel < 0) {
369                 printf_P(PSTR("cannot send: no free channel\r\n"));
370                 return -1;
371         }
372
373         /* copy context in the static struct table (avoiding a malloc) */
374         memcpy(&xbee_ctx[channel], ctx, sizeof(*ctx));
375         ctx = &xbee_ctx[channel];
376         xbee_set_opaque(xbee_dev, channel, ctx);
377
378         if (xbee_debug)
379                 printf_P(PSTR("send frame channel=%d type=0x%x len=%d\r\n"),
380                          channel, type, len);
381         if (xbee_hexdump)
382                 hexdump("xmit frame", buf, len);
383
384         /* transmit the frame on this channel */
385         ret = xbee_proto_xmit(xbee_dev, channel, type, buf,
386                               len);
387         if (ret < 0) {
388                 printf_P(PSTR("cannot send\r\n"));
389                 xbee_unregister_channel(xbee_dev, channel);
390                 return -1;
391         }
392
393         ctx->channel = channel;
394         xbee_load_timeout(ctx);   /* load a timeout event */
395
396         /* suspend command line until we have answer or timeout */
397         if (foreground) {
398                 ctx->foreground = 1;
399                 rdline_stop(&xbeeboard.rdl); /* don't display prompt when return */
400                 xbee_stdin_disable();  /* unload file descriptor polling */
401         }
402
403         return 0;
404 }
405
406 /* send an AT command with parameters filled by caller. Disable
407  * command line until we get the answer or until a timeout occurs */
408 int xbeeapp_send_atcmd(const char *atcmd_str,
409                        void *param, unsigned param_len, int foreground,
410                        int (*func)(void *frame, unsigned len, void *arg), void *arg)
411 {
412         struct xbee_ctx ctx;
413         struct {
414                 struct xbee_atcmd_hdr atcmd;
415                 char buf[XBEE_MAX_FRAME_LEN];
416         } __attribute__((packed)) frame;
417
418         memset(&ctx, 0, sizeof(ctx));
419         ctx.atcmd_query[0] = atcmd_str[0];
420         ctx.atcmd_query[1] = atcmd_str[1];
421         ctx.func = func;
422         ctx.arg = arg;
423
424         memcpy(&frame.atcmd.cmd, atcmd_str, 2);
425         memcpy(&frame.buf, param, param_len);
426
427         if (xbeeapp_send(&ctx, XBEE_TYPE_ATCMD, &frame,
428                          sizeof(struct xbee_atcmd_hdr) +
429                          param_len, foreground) < 0) {
430                 return -1;
431         }
432
433         return 0;
434 }
435
436 int xbeeapp_send_msg(uint64_t addr, void *data,
437                      unsigned data_len, int foreground)
438 {
439         struct xbee_ctx ctx;
440         struct {
441                 struct xbee_xmit_hdr xmit;
442                 char buf[XBEE_MAX_FRAME_LEN];
443         } __attribute__((packed)) frame;
444
445         memset(&ctx, 0, sizeof(ctx));
446         ctx.atcmd_query[0] = '\0';
447
448         frame.xmit.dstaddr = htonll(addr);
449         frame.xmit.reserved = htons(0xFFFE);
450         frame.xmit.bcast_radius = 0;
451         frame.xmit.opts = 0;
452         memcpy(&frame.buf, data, data_len);
453
454         if (xbeeapp_send(&ctx, XBEE_TYPE_XMIT, &frame,
455                          sizeof(struct xbee_xmit_hdr) +
456                          data_len, foreground) < 0) {
457                 return -1;
458         }
459
460         return 0;
461 }
462
463 void xbee_stdin_enable(void)
464 {
465         xbee_cmdline_input_enabled = 1;
466 }
467
468 void xbee_stdin_disable(void)
469 {
470         xbee_cmdline_input_enabled = 0;
471 }
472
473 static void evt_timeout(struct callout_manager *cm, struct callout *clt,
474                         void *arg)
475 {
476         struct xbee_ctx *ctx = arg;
477
478         printf_P(PSTR("Timeout\r\n"));
479
480         /* restart command line */
481         xbee_stdin_enable();
482         rdline_newline(&xbeeboard.rdl, xbeeboard.prompt);
483
484         /* free event */
485         xbee_unregister_channel(xbee_dev, ctx->channel);
486 }
487
488 void xbee_load_timeout(struct xbee_ctx *ctx)
489 {
490         callout_reset(&cm, &ctx->timeout, TIMEOUT_MS, SINGLE, evt_timeout, ctx);
491 }
492
493 void xbee_unload_timeout(struct xbee_ctx *ctx)
494 {
495         callout_stop(&cm, &ctx->timeout);
496 }
497
498 void bootloader(void)
499 {
500 #define BOOTLOADER_ADDR 0x1e000
501         if (pgm_read_byte_far(BOOTLOADER_ADDR) == 0xff) {
502                 printf_P(PSTR("Bootloader is not present\r\n"));
503                 return;
504         }
505         cli();
506         /* ... very specific :( */
507         EIMSK = 0;
508         SPCR = 0;
509         TWCR = 0;
510         ACSR = 0;
511         ADCSRA = 0;
512
513         __asm__ __volatile__ ("ldi r31,0xf0\n");
514         __asm__ __volatile__ ("ldi r30,0x00\n");
515         __asm__ __volatile__ ("ijmp\n");
516
517         /* never returns */
518 }
519
520 void xbee_mainloop(void)
521 {
522         while (1) {
523                 callout_manage(&cm);
524
525                 if (xbee_raw) {
526                         int16_t c;
527
528                         /* from xbee to cmdline */
529                         c = CDC_Device_ReceiveByte(&VirtualSerial2_CDC_Interface);
530                         if (c >= 0)
531                                 CDC_Device_SendByte(&VirtualSerial1_CDC_Interface,
532                                                     (uint8_t)c);
533
534                         /* from cmdline to xbee */
535                         c = CDC_Device_ReceiveByte(&VirtualSerial1_CDC_Interface);
536                         if (c == 4) { /* CTRL-d */
537                                 xbee_raw = 0;
538                                 rdline_newline(&xbeeboard.rdl,
539                                                xbeeboard.prompt);
540                         }
541                         else if (c >= 0) {
542                                 /* send to xbee */
543                                 CDC_Device_SendByte(&VirtualSerial2_CDC_Interface,
544                                                     (uint8_t)c);
545                                 /* echo on cmdline */
546                                 CDC_Device_SendByte(&VirtualSerial1_CDC_Interface,
547                                                     (uint8_t)c);
548                         }
549                 }
550                 else {
551                         if (xbee_cmdline_input_enabled)
552                                 cmdline_poll();
553                         xbee_proto_rx(xbee_dev);
554                 }
555
556                 CDC_Device_USBTask(&VirtualSerial1_CDC_Interface);
557                 CDC_Device_USBTask(&VirtualSerial2_CDC_Interface);
558                 USB_USBTask();
559         }
560 }