add code for converting messages
authorFelix Fietkau <nbd@openwrt.org>
Thu, 30 May 2013 14:24:19 +0000 (16:24 +0200)
committerFelix Fietkau <nbd@openwrt.org>
Thu, 30 May 2013 17:05:33 +0000 (19:05 +0200)
main.c
switch.c

diff --git a/main.c b/main.c
index c00b5b9..5f5c4ff 100644 (file)
--- a/main.c
+++ b/main.c
@@ -1,6 +1,7 @@
 #include <stdio.h>
 #include <getopt.h>
 #include <stdbool.h>
+#include <ctype.h>
 
 #include <libubox/blobmsg_json.h>
 #include <libubox/avl.h>
@@ -27,6 +28,67 @@ static struct libusb_context *usb;
 static struct libusb_device **usbdevs;
 static int n_usbdevs;
 
+static int hex2num(char c)
+{
+       if (c >= '0' && c <= '9')
+               return c - '0';
+
+       c = toupper(c);
+       if (c >= 'A' && c <= 'F')
+               return c - 'A' + 10;
+
+       return -1;
+}
+
+static int hex2byte(const char *hex)
+{
+       int a, b;
+
+       a = hex2num(*hex++);
+       if (a < 0)
+               return -1;
+
+       b = hex2num(*hex++);
+       if (b < 0)
+               return -1;
+
+       return (a << 4) | b;
+}
+
+static int hexstr2bin(const char *hex, char *buffer, int len)
+{
+       const char *ipos = hex;
+       char *opos = buffer;
+       int i, a;
+
+       for (i = 0; i < len; i++) {
+               a = hex2byte(ipos);
+               if (a < 0)
+                       return -1;
+
+               *opos++ = a;
+               ipos += 2;
+       }
+
+       return 0;
+}
+
+static bool convert_message(struct blob_attr *attr)
+{
+       char *data;
+       int len;
+
+       if (!attr)
+               return true;
+
+       data = blobmsg_data(attr);
+       len = strlen(data);
+       if (len % 2)
+               return false;
+
+       return !hexstr2bin(data, data, len / 2);
+}
+
 static int parse_config(void)
 {
        enum {
@@ -54,8 +116,13 @@ static int parse_config(void)
 
        messages = calloc(n_messages, sizeof(*messages));
        n_messages = 0;
-       blobmsg_for_each_attr(cur, tb[CONF_MESSAGES], rem)
+       blobmsg_for_each_attr(cur, tb[CONF_MESSAGES], rem) {
+               if (!convert_message(cur)) {
+                       fprintf(stderr, "Invalid data in message %d\n", n_messages);
+                       return -1;
+               }
                messages[n_messages++] = cur;
+       }
 
        blobmsg_for_each_attr(cur, tb[CONF_DEVICES], rem) {
            dev = calloc(1, sizeof(*dev));
index 8061322..3f1e3f3 100644 (file)
--- a/switch.c
+++ b/switch.c
@@ -109,5 +109,3 @@ void handle_switch(struct usbdev_data *data)
 
        modeswitch_cb[mode].cb(data, tb);
 }
-
-