chiark / gitweb /
hostside: hidrawconv: break out dispatch()
[trains.git] / hostside / hidrawconv.c
index 762133ec9670bf515a9e41b9e97b2a5f5a991165..6151b0ade984162544fadf9c1200625d1a379be5 100644 (file)
@@ -17,8 +17,7 @@
 void die_vprintf_hook(const char *fmt, va_list al) { }
 void die_hook(void) { }
 
-typedef struct { int len; uint8_t *msg; } Last;
-static Last lasts[MAXREPORTS];
+static LastReports lasts;
 
 void reportbits(const uint8_t msg[], const uint8_t last[],
                int len, const KeyBit *bit) {
@@ -45,30 +44,38 @@ void reportlocs(const uint8_t msg[], const uint8_t last[],
     printf("%s %.5f\n", loc->str, loc->sign * val);
   }
 }
-  
+
+void dispatch(LastReports *lasts, const char *message_prefix,
+             ProcessReport *const report_processors[MAXREPORTS],
+             const uint8_t *msg, int l) {
+  ProcessReport *pr= report_processors[msg[0]];
+  Last *last= &lasts->lasts[msg[0]];
+  if (!pr) {
+    if (!last->len)
+      fprintf(stderr,"%s:%s unexpected report 0x%02x\n",
+             progname, message_prefix, msg[0]);
+    last->len= l;
+    return;
+  }
+  if (last->len < l) {
+    last->msg= mrealloc(last->msg, l);
+    memset(last->msg + last->len, 0, l - last->len);
+    last->len= l;
+  }
+  pr(msg, l, last->msg);
+  memcpy(last->msg, msg, l);
+}  
+
 static void events(void) {
   uint8_t msg[MAXREPORTLEN];
+
   for (;;) {
     int l= read(0, msg, sizeof(msg));
     if (!l) break;
     if (l<0) { perror("hidrawconv: read"); exit(-1); }
-    ProcessReport *pr= report_processors[msg[0]];
-    Last *last= &lasts[msg[0]];
-    if (!pr) {
-      if (!last->len)
-       fprintf(stderr,"%s: unexpected report 0x%02x\n", progname, msg[0]);
-      last->len= l;
-      continue;
-    }
-    if (last->len < l) {
-      last->msg= mrealloc(last->msg, l);
-      memset(last->msg + last->len, 0, l - last->len);
-      last->len= l;
-    }
-    pr(msg, l, last->msg);
+    dispatch(&lasts,"",report_processors, msg,l);
     if (ferror(stdout) || fflush(stdout))
       diee("failed flushing event to stdout");
-    memcpy(last->msg, msg, l);
   }
 }