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