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