2 * Copyright (c) 2011, Olivier MATZ <zer0@droids-corp.org>
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
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.
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.
28 #define _BSD_SOURCE /* for be64toh, endian.h */
42 #include <netinet/in.h>
43 #include <sys/queue.h>
44 #include <linux/joystick.h>
48 #include <cmdline_rdline.h>
49 #include <cmdline_parse.h>
50 #include <cmdline_socket.h>
55 #include "xbee_neighbor.h"
56 #include "xbee_atcmd.h"
57 #include "xbee_stats.h"
59 #include "xbee_proto.h"
64 #define TIMEOUT_US 1000000
66 /* XXX qd on deconnecte, prend 100% du cpu */
68 /* XXX neighbor discovery */
69 /* XXX dump et restauration de la config */
71 /* global xbee device */
72 static int xbeeapp_dump_conf_continue(struct xbee_ctx *ctx,
73 struct xbee_atresp_hdr *frame,
76 struct xbee_dev *xbee_dev;
79 static struct event stdin_read_event, xbee_read_event;
80 static struct event joystick_read_event;
82 static struct cmdline *xbee_cl;
85 static char *xbee_devname = NULL;
86 static int xbee_baud = 9600;
91 static char *joystick_devname = NULL;
92 struct joystick_info joyinfo;
94 void xbeeapp_log(int always_on_stdout, const char *fmt, ...)
100 if (xbee_logfile != NULL)
101 vfprintf(xbee_logfile, fmt, ap);
102 if (always_on_stdout || xbee_debug)
108 static void hexdump(int always_on_stdout, const char *title, const void *buf,
111 unsigned int i, out, ofs;
112 const unsigned char *data = buf;
114 char line[LINE_LEN]; /* space needed 8+16*3+3+16 == 75 */
117 gettimeofday(&tv, NULL);
119 xbeeapp_log(always_on_stdout, "%"PRIi64".%.6d %s at [%p], len=%d\n",
120 (uint64_t)tv.tv_sec, (int)tv.tv_usec, title, data, len);
123 /* format 1 line in the buffer, then use printk to print them */
124 out = snprintf(line, LINE_LEN, "%08X", ofs);
125 for (i=0; ofs+i < len && i<16; i++)
126 out += snprintf(line+out, LINE_LEN - out, " %02X",
129 out += snprintf(line+out, LINE_LEN - out, " ");
130 for (i=0; ofs < len && i<16; i++, ofs++) {
131 unsigned char c = data[ofs];
132 if (!isascii(c) || !isprint(c))
134 out += snprintf(line+out, LINE_LEN - out, "%c", c);
136 xbeeapp_log(always_on_stdout, "%s\n", line);
140 static int parse_xmit_status(struct xbee_ctx *ctx,
141 struct xbee_xmit_status_hdr *frame, unsigned len)
144 xbeeapp_log(1, "no context\n");
148 /* see if it matches a xmit query */
149 if (ctx->type != SEND_MSG) {
150 xbeeapp_log(ctx->foreground, "invalid response\n");
154 /* XXX use defines for these values */
155 if (frame->delivery_status == 0x00)
156 xbeeapp_log(ctx->foreground, "Success\n");
157 else if (frame->delivery_status == 0x01)
158 xbeeapp_log(ctx->foreground, "MAC ACK Failure\n");
159 else if (frame->delivery_status == 0x15)
160 xbeeapp_log(ctx->foreground, "Invalid destination endpoint\n");
161 else if (frame->delivery_status == 0x21)
162 xbeeapp_log(ctx->foreground, "Network ACK Failure\n");
163 else if (frame->delivery_status == 0x25)
164 xbeeapp_log(ctx->foreground, "Route Not Found\n");
169 static int atcmd_frame_status(struct xbee_atresp_hdr *frame, unsigned len)
173 /* get AT command from frame */
174 memcpy(atcmd_str, &frame->cmd, 2);
177 if (frame->status == 1)
178 xbeeapp_log(1, "<%s>: Status is error\n", atcmd_str);
179 else if (frame->status == 2)
180 xbeeapp_log(1, "<%s>: Invalid command\n", atcmd_str);
181 else if (frame->status == 3)
182 xbeeapp_log(1, "<%s>: Invalid parameter\n", atcmd_str);
183 else if (frame->status != 0)
184 xbeeapp_log(1, "<%s>: Unknown status error %d\n", atcmd_str,
186 return frame->status;
189 /* assume frame->status is 0 */
190 static int atcmd_frame_to_string(struct xbee_atresp_hdr *frame, unsigned len,
191 char *dstbuf, unsigned dstlen)
198 } __attribute__((packed)) *result;
200 struct xbee_atcmd *cmd;
202 /* get AT command from frame */
203 memcpy(atcmd_str, &frame->cmd, 2);
206 /* see if it exists */
207 cmd = xbee_atcmd_lookup_name(atcmd_str);
209 xbeeapp_log(1, "unknown response\n");
214 result = (void *)frame->data;
215 len -= offsetof(struct xbee_atresp_hdr, data);
216 if (cmd->flags & XBEE_ATCMD_F_PARAM_NONE && len == 0)
217 snprintf(dstbuf, dstlen, "ok");
218 if (cmd->flags & XBEE_ATCMD_F_PARAM_U8 && len == sizeof(uint8_t))
219 snprintf(dstbuf, dstlen, "0x%x", result->u8);
220 else if (cmd->flags & XBEE_ATCMD_F_PARAM_U16 && len == sizeof(uint16_t))
221 snprintf(dstbuf, dstlen, "0x%x", ntohs(result->u16));
222 else if (cmd->flags & XBEE_ATCMD_F_PARAM_U32 && len == sizeof(uint32_t))
223 snprintf(dstbuf, dstlen, "0x%x", ntohl(result->u32));
224 else if (cmd->flags & XBEE_ATCMD_F_PARAM_S16 && len == sizeof(int16_t))
225 snprintf(dstbuf, dstlen, "%d\n", ntohs(result->s16));
232 static int dump_atcmd(struct xbee_ctx *ctx, struct xbee_atresp_hdr *frame,
237 /* see if it matches query */
238 if (memcmp(&frame->cmd, ctx->atcmd_query->name, 2)) {
239 printf("invalid response\n");
244 if (atcmd_frame_status(frame, len) == 0) {
246 if (len == sizeof(struct xbee_atresp_hdr))
247 xbeeapp_log(ctx->foreground, "<%s>: ok\n",
248 ctx->atcmd_query->name);
249 else if (atcmd_frame_to_string(frame, len, buf,
251 xbeeapp_log(ctx->foreground, "<%s> is %s\n",
252 ctx->atcmd_query->name, buf);
254 hexdump(ctx->foreground, "atcmd answer", frame, len);
259 void xbee_rx(struct xbee_dev *dev, int channel, int type,
260 void *frame, unsigned len, void *opaque)
262 struct xbee_ctx *ctx = opaque;
263 int do_hexdump = xbee_hexdump;
265 xbeeapp_log(0, "type=0x%x, channel=%d, ctx=%p\n", type, channel, ctx);
266 hexdump(0, "rx", frame, len);
268 /* if ctx is !NULL, it is an answer to a query */
270 /* XXX only delete timeout if answer matched */
271 xbee_unload_timeout(ctx);
272 if (xbee_debug && ctx->atcmd_query != NULL)
273 printf("Received answer to query <%s>\n",
274 ctx->atcmd_query->name);
275 xbee_unregister_channel(dev, channel);
278 /* some additional checks before sending */
280 case XBEE_TYPE_MODEM_STATUS: {
281 printf("Received Modem Status frame\n");
285 case XBEE_TYPE_RMT_ATRESP: {
287 memcpy(&addr, frame, sizeof(addr));
288 addr = be64toh(addr);
289 printf("from remote address %"PRIx64"\n", addr);
291 /* this answer contains an atcmd answer at offset 10 */
292 if (ctx != NULL && ctx->type == ATCMD_RMT) {
293 if (dump_atcmd(ctx, frame + 10, len - 10) < 0)
297 printf("invalid response\n");
302 case XBEE_TYPE_ATRESP: {
303 /* we are currently dumping config, continue */
304 if (ctx != NULL && ctx->type == DUMP_CONF) {
305 xbeeapp_dump_conf_continue(ctx, frame, len);
307 else if (ctx != NULL && ctx->type == ATCMD) {
308 if (dump_atcmd(ctx, frame, len) < 0)
312 printf("invalid response\n");
318 case XBEE_TYPE_XMIT_STATUS: {
319 if (parse_xmit_status(ctx, frame, len) < 0)
324 case XBEE_TYPE_RECV: {
325 struct xbee_recv_hdr *recvframe = frame;
326 int recvlen = len - sizeof(*recvframe);
329 /* if we receive a range-test frame, ask for RSSI now */
330 if (recvlen >= strlen("range") &&
331 !strncmp((char *)recvframe->data,
332 "range", strlen("range"))) {
333 xbeeapp_send_atcmd("DB", NULL, 0, 0);
336 hexdump(on_stdout, "rx data", recvframe->data,
341 case XBEE_TYPE_ATCMD:
342 case XBEE_TYPE_ATCMD_Q:
344 case XBEE_TYPE_EXPL_XMIT:
345 case XBEE_TYPE_RMT_ATCMD:
346 case XBEE_TYPE_EXPL_RECV:
347 case XBEE_TYPE_NODE_ID:
349 xbeeapp_log(0, "Invalid frame\n");
355 xbeeapp_log(1, "rx frame type=0x%x, channel=%d, ctx=%p\n",
357 hexdump(1, "undecoded rx frame", frame, len);
360 /* restart command line if it was a blocking query */
362 if (ctx->foreground && !ctx->have_more_command) {
364 rdline_newline(&xbee_cl->rdl, xbee_cl->prompt);
366 if (!ctx->have_more_command)
371 static int xbeeapp_send(struct xbee_ctx *ctx, int type, void *buf, unsigned len,
377 if (len > XBEE_MAX_FRAME_LEN) {
378 printf("frame too large\n");
382 /* register a channel */
383 channel = xbee_register_channel(xbee_dev, XBEE_CHANNEL_ANY,
386 printf("cannot send: no free channel\n");
390 xbeeapp_log(0, "send frame ctx=%p channel=%d type=0x%x len=%d\n",
391 ctx, channel, type, len);
392 hexdump(0, "xmit frame", buf, len);
394 /* transmit the frame on this channel */
395 ret = xbee_proto_xmit(xbee_dev, channel, type, buf,
398 printf("cannot send: %s\n", strerror(errno));
399 xbee_unregister_channel(xbee_dev, channel);
403 ctx->channel = channel;
404 xbee_load_timeout(ctx); /* load a timeout event */
406 /* suspend command line until we have answer or timeout */
409 rdline_stop(&xbee_cl->rdl); /* don't display prompt when return */
410 xbee_stdin_disable(); /* unload file descriptor polling */
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, void *param, unsigned param_len,
421 struct xbee_ctx *ctx;
422 struct xbee_atcmd *cmd;
424 struct xbee_atcmd_hdr atcmd;
425 char buf[XBEE_MAX_FRAME_LEN];
426 } __attribute__((packed)) frame;
428 cmd = xbee_atcmd_lookup_name(atcmd_str);
430 printf("no such at command\n");
434 /* allocate memory to store the context for async cb */
435 ctx = malloc(sizeof(*ctx));
437 printf("not enough memory\n");
441 memset(ctx, 0, sizeof(*ctx));
443 ctx->atcmd_query = cmd;
445 memcpy(&frame.atcmd.cmd, atcmd_str, 2);
446 memcpy(&frame.buf, param, param_len);
448 if (xbeeapp_send(ctx, XBEE_TYPE_ATCMD, &frame,
449 sizeof(struct xbee_atcmd_hdr) +
450 param_len, foreground) < 0) {
459 static int __xbeeapp_dump_config(struct xbee_ctx *ctx, struct xbee_atcmd *cmd)
461 struct xbee_atcmd_hdr atcmd;
463 /* find the first command that is readable and writable */
464 for (; cmd->name != NULL; cmd++) {
465 if ((cmd->flags & (XBEE_ATCMD_F_READ|XBEE_ATCMD_F_WRITE)) ==
466 (XBEE_ATCMD_F_READ|XBEE_ATCMD_F_WRITE))
469 if (cmd->name == NULL) {
470 printf("no register to dump\n");
474 ctx->atcmd_query = cmd;
475 ctx->have_more_command = 1;
476 memcpy(&atcmd.cmd, cmd->name, 2);
478 if (xbeeapp_send(ctx, XBEE_TYPE_ATCMD, &atcmd,
479 sizeof(struct xbee_atcmd_hdr), 1) < 0) {
487 int xbeeapp_dump_config(const char *filename)
489 struct xbee_ctx *ctx;
490 struct xbee_atcmd *cmd;
493 /* find the first command that is readable and writable */
494 cmd = &xbee_atcmd_list[0];
496 /* allocate memory to store the context for async cb */
497 ctx = malloc(sizeof(*ctx));
499 printf("not enough memory\n");
503 memset(ctx, 0, sizeof(*ctx));
504 ctx->type = DUMP_CONF;
505 ret = __xbeeapp_dump_config(ctx, cmd);
512 /* continue a dump conf */
513 static int xbeeapp_dump_conf_continue(struct xbee_ctx *ctx,
514 struct xbee_atresp_hdr *frame,
517 struct xbee_atcmd *cmd;
520 /* see if it matches query */
521 if (memcmp(&frame->cmd, ctx->atcmd_query->name, 2)) {
522 printf("invalid response\n");
523 ctx->have_more_command = 0;
527 /* dump register content in buf, skip on error */
528 if (atcmd_frame_status(frame, len) == 0 &&
529 atcmd_frame_to_string(frame, len, buf, sizeof(buf)) == 0)
530 printf("write %s %s\n", ctx->atcmd_query->desc, buf);
532 cmd = ctx->atcmd_query + 1;
533 if (__xbeeapp_dump_config(ctx, cmd) < 0) {
534 ctx->have_more_command = 0;
535 //close(xbee_config_file);
536 printf("END\n"); /* XXX */
541 /* send data message */
542 int xbeeapp_send_msg(uint64_t addr, void *data, unsigned data_len,
545 struct xbee_ctx *ctx;
547 struct xbee_xmit_hdr xmit;
548 char buf[XBEE_MAX_FRAME_LEN];
549 } __attribute__((packed)) frame;
551 /* allocate memory to store the context for async cb */
552 ctx = malloc(sizeof(*ctx));
554 printf("not enough memory\n");
558 memset(ctx, 0, sizeof(*ctx));
559 ctx->type = SEND_MSG;
560 ctx->atcmd_query = NULL;
562 frame.xmit.dstaddr = htobe64(addr);
563 frame.xmit.reserved = htons(0xFFFE);
564 frame.xmit.bcast_radius = 0;
566 memcpy(&frame.buf, data, data_len);
568 if (xbeeapp_send(ctx, XBEE_TYPE_XMIT, &frame,
569 sizeof(struct xbee_xmit_hdr) +
570 data_len, foreground) < 0) {
578 void xbee_stdin_enable(void)
580 event_add(&stdin_read_event, NULL);
583 void xbee_stdin_disable(void)
585 event_del(&stdin_read_event);
588 static void evt_timeout(int s, short event, void *arg)
590 struct xbee_ctx *ctx = arg;
592 xbeeapp_log(0, "Timeout\n");
594 /* restart command line */
595 if (ctx->foreground) {
599 rdline_newline(&xbee_cl->rdl, xbee_cl->prompt);
602 xbee_unregister_channel(xbee_dev, ctx->channel);
606 void xbee_load_timeout(struct xbee_ctx *ctx)
611 tv.tv_usec = TIMEOUT_US;
612 evtimer_set(&ctx->timeout, evt_timeout, ctx);
613 evtimer_add(&ctx->timeout, &tv);
616 void xbee_unload_timeout(struct xbee_ctx *ctx)
618 evtimer_del(&ctx->timeout);
622 evt_stdin_input(int s, short event, void *arg)
627 n = read(s, buf, sizeof(buf));
635 for (i = 0; i < n; i++) {
636 /* ctrl-d is pressed, back in cmdline mode XXX */
640 rdline_newline(&xbee_cl->rdl, xbee_cl->prompt);
646 write(xbee_dev->fd, "\r\n", 2);
648 write(xbee_dev->fd, buf, n);
653 if (cmdline_in(xbee_cl, buf, n) < 0) {
661 evt_xbee_input(int s, short event, void *arg)
667 n = read(s, buf, sizeof(buf));
675 xbee_process_queue(xbee_dev);
680 usage(const char *prgname)
682 printf("%s [-s BAUD] -d DEVNAME\n"
683 " -s BAUD: set baud rate of xbee device\n"
684 " -d DEVNAME: xbee char device\n"
685 " -r: start in raw mode\n"
690 /* Parse the argument given in the command line of the application */
692 parse_args(int argc, char **argv)
697 char *prgname = argv[0];
698 static struct option lgopts[] = {
704 while ((opt = getopt_long(argc, argvopt, "hd:s:j:",
705 lgopts, &option_index)) != EOF) {
715 xbee_devname = strdup(optarg);
719 xbee_baud = atoi(optarg);
727 joystick_devname = optarg;
732 /* if (!strcmp(lgopts[option_index].name, "option")) */
741 if (xbee_devname == NULL) {
742 fprintf(stderr, "xbee device argument missing\n");
747 if (argc != optind) {
748 printf("Invalid argument\n");
758 int main(int argc, char **argv)
760 struct termios oldterm, term;
763 char xbeerc_path[256];
765 if (parse_args(argc, argv) < 0)
768 /* initializa libevent */
771 /* initialize libxbee */
777 if (joystick_devname != NULL) {
778 if (joystick_init(joystick_devname, &joyinfo) < 0) {
779 fprintf(stderr, "error in joystick init\n");
782 event_set(&joystick_read_event, joyinfo.fd, EV_READ | EV_PERSIST,
783 joystick_input, &joyinfo);
784 event_add(&joystick_read_event, NULL);
787 /* open xbee device */
788 xbee_dev = xbee_open(xbee_devname, xbee_baud);
789 if (xbee_dev == NULL)
792 /* register default channel with a callback */
793 if (xbee_register_channel(xbee_dev, XBEE_DEFAULT_CHANNEL,
794 xbee_rx, NULL) < 0) {
795 fprintf(stderr, "cannot register default channel\n");
799 /* add read event on xbee device */
800 event_set(&xbee_read_event, xbee_dev->fd, EV_READ | EV_PERSIST,
801 evt_xbee_input, xbee_dev);
802 event_add(&xbee_read_event, NULL);
804 /* set terminal in raw mode */
805 tcgetattr(0, &oldterm);
806 memcpy(&term, &oldterm, sizeof(term));
807 term.c_lflag &= ~(ICANON | ECHO | ISIG);
808 tcsetattr(0, TCSANOW, &term);
811 /* parse the config file */
812 homedir = getenv("HOME");
813 if (homedir != NULL) {
814 snprintf(xbeerc_path, sizeof(xbeerc_path), "%s/.xbeerc",
816 if (access(xbeerc_path, R_OK) == 0) {
818 xbee_cl = cmdline_file_new(&main_ctx, "xbeerc> ",
819 "/home/zer0/.xbeerc", 1);
820 if (xbee_cl != NULL) {
821 cmdline_interact(xbee_cl);
822 cmdline_free(xbee_cl);
823 printf("\nconfig file parsed\n");
828 /* create a new cmdline instance */
829 xbee_cl = cmdline_stdin_new(&main_ctx, "xbee> ");
830 if (xbee_cl == NULL) {
835 /* load read event on stdin */
836 event_set(&stdin_read_event, 0, EV_READ | EV_PERSIST,
837 evt_stdin_input, xbee_cl);
838 event_add(&stdin_read_event, NULL);
840 /* libevent main loop */
843 tcsetattr(0, TCSANOW, &oldterm);
847 tcsetattr(0, TCSANOW, &oldterm);