added butans
[fpgaboy.git] / binwire.c
CommitLineData
2bcaaabf 1#include <stdio.h>
bf3f2c5f
JW
2#include <sys/types.h>
3#include <sys/stat.h>
4#include <fcntl.h>
5#include <stdlib.h>
6#include <poll.h>
2bcaaabf
JW
7
8void 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
bf3f2c5f 17int waitchar(int timeout)
2bcaaabf 18{
bf3f2c5f
JW
19 struct pollfd pfd;
20
21 pfd.fd = 0;
22 pfd.events = POLLIN;
23 return poll(&pfd, 1, timeout) == 1;
24}
25
6d070aee 26int expect(char *s, int len)
bf3f2c5f
JW
27{
28 int i;
29 char c;
30 for (i=0; i < len; i++)
31 {
6d070aee 32 if (waitchar(1000) == 0)
bf3f2c5f
JW
33 {
34 fprintf(stderr, "Timeout reached in expect (expected %c)\n", s[i]);
6d070aee 35 return 1;
bf3f2c5f
JW
36 }
37 while (read(0, &c, 1) == 0)
38 fprintf(stderr, "Short read...\n");
39 if (c != s[i])
6d070aee 40 {
bf3f2c5f 41 fprintf(stderr, "Expect failed: expected %d, got %d (pos %d)\n", s[i], c, i);
6d070aee
JW
42 return 1;
43 }
bf3f2c5f 44 }
6d070aee 45 return 0;
bf3f2c5f
JW
46}
47
48void expect_no_chars()
49{
50 int cs = 0;
51
3db3fc27 52 while (waitchar(100) == 1)
bf3f2c5f
JW
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);
bf3f2c5f
JW
62}
63
64void main(int argc, char **argv)
65{
66 unsigned char buf[259];
2bcaaabf 67 int sz;
bf3f2c5f 68 int rfd;
6d070aee 69 int tc = 0;
bf3f2c5f
JW
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
3db3fc27 83 dowrite("\x1B" "A\x00\x00\x00", 5);
2bcaaabf 84 fprintf(stderr, "Address sent\n");
3db3fc27
JW
85 expect("A", 1);
86 expect_no_chars();
87 while ((sz = read(rfd, buf+3, 255)) > 0)
2bcaaabf 88 {
6d070aee 89 int rv;
c3cb12e8 90 char abuf[5];
2bcaaabf
JW
91 buf[0] = 0x1B;
92 buf[1] = 'D';
bf3f2c5f 93 buf[2] = sz+1;
c3cb12e8
JW
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;
6d070aee
JW
99 tc += sz;
100 retry:
c3cb12e8
JW
101 dowrite(abuf, 5);
102 rv = expect("A", 1);
2bcaaabf 103 dowrite(buf, sz + 3);
6d070aee 104 fprintf(stderr, "Data sent (%d)\n", tc);
c3cb12e8 105 rv |= expect("D", 1);
bf3f2c5f 106 expect_no_chars();
6d070aee
JW
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 }
2bcaaabf 115 }
bf3f2c5f 116 exit(0);
2bcaaabf 117}
This page took 0.083981 seconds and 4 git commands to generate.