]>
Commit | Line | Data |
---|---|---|
1 | #include <stdio.h> | |
2 | #include <sys/types.h> | |
3 | #include <sys/stat.h> | |
4 | #include <fcntl.h> | |
5 | #include <stdlib.h> | |
6 | #include <poll.h> | |
7 | ||
8 | void dowrite(char *s, int len) | |
9 | { | |
10 | int i = 0; | |
11 | while (i < len) | |
12 | { | |
13 | int cs = ((len-i) > 1) ? 1 : (len-i); | |
14 | ||
15 | write(1, s+i, cs); | |
16 | i += cs; | |
17 | } | |
18 | } | |
19 | ||
20 | int waitchar(int timeout) | |
21 | { | |
22 | struct pollfd pfd; | |
23 | ||
24 | pfd.fd = 0; | |
25 | pfd.events = POLLIN; | |
26 | return poll(&pfd, 1, timeout) == 1; | |
27 | } | |
28 | ||
29 | int expect(char *s, int len) | |
30 | { | |
31 | int i; | |
32 | char c; | |
33 | for (i=0; i < len; i++) | |
34 | { | |
35 | if (waitchar(1000) == 0) | |
36 | { | |
37 | fprintf(stderr, "Timeout reached in expect (expected %c)\n", s[i]); | |
38 | return 1; | |
39 | } | |
40 | while (read(0, &c, 1) == 0) | |
41 | fprintf(stderr, "Short read...\n"); | |
42 | if (c != s[i]) | |
43 | { | |
44 | fprintf(stderr, "Expect failed: expected %d, got %d (pos %d)\n", s[i], c, i); | |
45 | return 1; | |
46 | } | |
47 | } | |
48 | return 0; | |
49 | } | |
50 | ||
51 | void expect_no_chars() | |
52 | { | |
53 | int cs = 0; | |
54 | ||
55 | while (waitchar(100) == 1) | |
56 | { | |
57 | char c; | |
58 | if (read(0, &c, 1) == 0) | |
59 | fprintf(stderr, "enc Short read...\n"); | |
60 | cs++; | |
61 | fprintf(stderr, "Warning: expected no chars, got %d\n", c); | |
62 | } | |
63 | if (cs) | |
64 | fprintf(stderr, "Expect no chars failed: got %d chars\n", cs); | |
65 | } | |
66 | ||
67 | void main(int argc, char **argv) | |
68 | { | |
69 | unsigned char buf[259]; | |
70 | int sz; | |
71 | int rfd; | |
72 | int tc = 0; | |
73 | ||
74 | if (argc < 2) | |
75 | { | |
76 | fprintf(stderr, "Usage: %s [filename]\n", argv[0]); | |
77 | exit(1); | |
78 | } | |
79 | rfd = open(argv[1], O_RDONLY); | |
80 | if (rfd < 0) | |
81 | { | |
82 | perror("open"); | |
83 | exit(1); | |
84 | } | |
85 | ||
86 | dowrite("\x1B" "A\x00\x00\x00", 5); | |
87 | fprintf(stderr, "Address sent\n"); | |
88 | expect("A", 1); | |
89 | expect_no_chars(); | |
90 | while ((sz = read(rfd, buf+3, 255)) > 0) | |
91 | { | |
92 | int rv; | |
93 | char abuf[5]; | |
94 | buf[0] = 0x1B; | |
95 | buf[1] = 'D'; | |
96 | buf[2] = sz+1; | |
97 | abuf[0] = 0x1B; | |
98 | abuf[1] = 'A'; | |
99 | abuf[2] = (tc >> 16) & 0xFF; | |
100 | abuf[3] = (tc >> 8) & 0xFF; | |
101 | abuf[4] = tc & 0xFF; | |
102 | tc += sz; | |
103 | retry: | |
104 | dowrite(abuf, 5); | |
105 | rv = expect("A", 1); | |
106 | dowrite(buf, sz + 3); | |
107 | fprintf(stderr, "Data sent (%d)\n", tc); | |
108 | rv |= expect("D", 1); | |
109 | expect_no_chars(); | |
110 | if (rv) | |
111 | { | |
112 | printf("Failure to ack... retrying\n"); | |
113 | dowrite("...", 3); | |
114 | rv = expect("...", 3); | |
115 | expect_no_chars(); | |
116 | goto retry; | |
117 | } | |
118 | } | |
119 | exit(0); | |
120 | } |