ev3duder  0.3.0
EV3 Downloader/Uploader
tunnel.c
Go to the documentation of this file.
1 
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <ctype.h>
14 
15 #include "ev3_io.h"
16 
17 #include "defs.h"
18 #include "packets.h"
19 #include "error.h"
20 #include "funcs.h"
21 
22 #ifdef _WIN32
23 #define isatty _isatty
24 #endif
25 
26 static int hex2nib(char hex);
27 
35 int tunnel()
36 {
37  int res;
38  (void)res;
39  u8 binbuf[1280];
40  binbuf[0] = 0x00;
41 #if 0
42  struct termios new, old;
43  tcgetattr(0, &old);
44  new = old;
45  new.c_lflag &= ~ICANON; /* disable buffered i/o */
46  new.c_lf lag &= ~ECHO; /* disable echoing input */
47  tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
48 #endif
49  if (isatty(STDIN_FILENO) || 1)
50  {
51  char hexbuf[2560];
52  while (fgets(hexbuf, sizeof hexbuf, stdin))
53  {
54  int prefix_len = 0;
55  const char *hp; u8 *bp;
56  int tmp;
57  for (hp = hexbuf, bp = binbuf+1; *hp != '\0'; hp++)
58  {
59  if ((tmp = hex2nib(*hp)) == -1) continue;
60  if (tmp == 0 && *hp != '0')
61  {
62  prefix_len++;
63  if (prefix_len == 4)
64  break;
65  }else break;
66  }
67 
68  u8 byte = 0; int nibble = 0;
69  for (hp = hexbuf, bp = binbuf+1; *hp != '\0'; hp++)
70  {
71  if ((tmp = hex2nib(*hp)) == -1) continue;
72  //printf("hp=[%c],tmp=%d\n", *hp, tmp);
73  if (nibble == 1)
74  {
75  *bp++ = byte + tmp;
76  nibble = 0;
77  }else
78  {
79  byte = (u8)tmp << 4;
80  nibble = 1;
81  }
82  }
83 
84  int len = bp - binbuf+1; //FIXME: size_t
85  if(prefix_len == 4)
86  memcpy(binbuf+1, (u16[]){len - 2}, 2);
87  printf("prefix_len=%d, len=%i\n", prefix_len, len);
88 
89  // ev3_write then read
90  print_bytes(binbuf, len - 1);
91  ev3_write(handle, binbuf, len -1);
92  }
93  }
94  else{
95  /* FIXME: switch to binary setmode */
96  printf("%zu\n", fread(binbuf+1, 1, 2, stdin));
97  size_t len = (binbuf[1] | (binbuf[2] << 4));
98  printf("len%zu\n", len);
99  fread(binbuf+3, 1, len, stdin);
100  print_bytes(binbuf, (int)len+3);
101 
102  }
103 
104 
105  return ERR_UNK;
106 }
107 static int hex2nib(char hex)
108 {
109  if ('a' <= hex && hex <= 'f')
110  return hex - 'a' + 0x0a;
111  else if ('A' <= hex && hex <= 'F')
112  return hex - 'A' + 0x0a;
113  else if ('0' <= hex && hex <= '9')
114  return hex - '0';
115  else if (isspace(hex) || !isgraph(hex))
116  return -1;
117  else
118  return 0;
119 }
120 
EXTERN void * handle
Definition: ev3_io.h:17
int tunnel()
tunnels from stdio to ev3
Definition: tunnel.c:35
Error enumerations and decriptions.
#define print_bytes(buf, len)
Definition: defs.h:34
uint16_t u16
Definition: defs.h:10
packed structs for the packets.
uint8_t u8
Definition: defs.h:9
Definition: error.h:20
contains declarations for ev3 commands
EXTERN int(* ev3_write)(void *, const u8 *, size_t)
Definition: ev3_io.h:13