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