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