]> mj.ucw.cz Git - home-hw.git/blob - ssr/host/test.c
SSR: Adjusting to STM32F1
[home-hw.git] / ssr / host / test.c
1 #include <ucw/lib.h>
2 #include <ucw/unaligned.h>
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <stdint.h>
7 #include <unistd.h>
8 #include <time.h>
9 #include <libusb-1.0/libusb.h>
10
11 struct libusb_context *usb_ctxt;
12 struct libusb_device_handle *devh;
13
14 static libusb_device *find_device(void)
15 {
16   libusb_device **devlist;
17   ssize_t devn = libusb_get_device_list(usb_ctxt, &devlist);
18   if (devn < 0)
19     {
20       fprintf(stderr, "Cannot enumerate USB devices: error %d\n", (int) devn);
21       exit(1);
22     }
23
24   for (ssize_t i=0; i<devn; i++)
25     {
26       struct libusb_device_descriptor desc;
27       libusb_device *dev = devlist[i];
28       if (!libusb_get_device_descriptor(dev, &desc))
29         {
30           if (desc.idVendor == 0x4242 && desc.idProduct == 0x0002)
31             {
32               printf("Found device at usb%d.%d\n", libusb_get_bus_number(dev), libusb_get_device_address(dev));
33               // FIXME: Free device list
34               return dev;
35             }
36         }
37     }
38
39   libusb_free_device_list(devlist, 1);
40   fprintf(stderr, "Device not found\n");
41   exit(1);
42 }
43
44 int main(void)
45 {
46   int err;
47   if (err = libusb_init(&usb_ctxt))
48     {
49       fprintf(stderr, "Cannot initialize libusb: error %d\n", err);
50       exit(1);
51     }
52   libusb_set_debug(usb_ctxt, 3);
53
54   libusb_device *dev = find_device();
55
56   if (err = libusb_open(dev, &devh))
57     {
58       fprintf(stderr, "Cannot open device: error %d\n", err);
59       exit(1);
60     }
61   libusb_reset_device(devh);
62   if (err = libusb_claim_interface(devh, 0))
63     {
64       fprintf(stderr, "Cannot claim interface: error %d\n", err);
65       exit(1);
66     }
67
68   uint tst = 0;
69
70   for (;;)
71     {
72       byte req[8];
73       put_u32_be(req, 1);
74       put_u32_be(req+4, (1 << tst));
75       tst = (tst+1) % 4;
76
77       int transferred;
78       if (err = libusb_bulk_transfer(devh, 0x01, req, 8, &transferred, 2000))
79         die("Transfer failed: error %d\n", err);
80       // printf("Transferred %d bytes\n", transferred);
81
82       unsigned char resp[64];
83       int received;
84       if (err = libusb_bulk_transfer(devh, 0x82, resp, 64, &received, 2000))
85         die("Receive failed: error %d\n", err);
86       // printf("Received %d bytes\n", received);
87
88       if (received >= 4)
89         {
90           int status = get_u32_be(resp);
91           if (status)
92             msg(L_ERROR, "Received error status %08x", status);
93         }
94       else
95         msg(L_ERROR, "Received short packet");
96
97       sleep(1);
98     }
99
100   return 0;
101 }