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