]> mj.ucw.cz Git - home-hw.git/blob - test-sinclair/main.c
test-sinclair: RC again, this time with the correct checksum
[home-hw.git] / test-sinclair / main.c
1 /*
2  *      Testing Communication with Sinclair Air Conditioner
3  *
4  *      (c) 2023 Martin Mareš <mj@ucw.cz>
5  */
6
7 #include "util.h"
8
9 #include <libopencm3/cm3/cortex.h>
10 #include <libopencm3/cm3/nvic.h>
11 #include <libopencm3/cm3/systick.h>
12 #include <libopencm3/cm3/scb.h>
13 #include <libopencm3/stm32/rcc.h>
14 #include <libopencm3/stm32/desig.h>
15 #include <libopencm3/stm32/gpio.h>
16 #include <libopencm3/stm32/usart.h>
17 #include <libopencm3/stm32/spi.h>
18 #include <libopencm3/stm32/timer.h>
19 #include <libopencm3/usb/dfu.h>
20 #include <libopencm3/usb/usbd.h>
21
22 #include <string.h>
23
24 /*** Hardware init ***/
25
26 static void clock_init(void)
27 {
28         rcc_clock_setup_pll(&rcc_hse_configs[RCC_CLOCK_HSE8_72MHZ]);
29
30         rcc_periph_clock_enable(RCC_GPIOA);
31         rcc_periph_clock_enable(RCC_GPIOB);
32         rcc_periph_clock_enable(RCC_GPIOC);
33         rcc_periph_clock_enable(RCC_SPI2);
34         rcc_periph_clock_enable(RCC_USART1);
35         rcc_periph_clock_enable(RCC_USB);
36         rcc_periph_clock_enable(RCC_TIM3);
37         rcc_periph_clock_enable(RCC_TIM4);
38
39         rcc_periph_reset_pulse(RST_GPIOA);
40         rcc_periph_reset_pulse(RST_GPIOB);
41         rcc_periph_reset_pulse(RST_GPIOC);
42         rcc_periph_reset_pulse(RST_SPI2);
43         rcc_periph_reset_pulse(RST_USART1);
44         rcc_periph_reset_pulse(RST_USB);
45         rcc_periph_reset_pulse(RST_TIM3);
46         rcc_periph_reset_pulse(RST_TIM4);
47 }
48
49 static void gpio_init(void)
50 {
51         // PA9 = TXD1 for debugging console
52         // PA10 = RXD1 for debugging console
53         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
54         gpio_set_mode(GPIOA, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO10);
55
56         // PC13 = BluePill LED
57         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
58         gpio_clear(GPIOC, GPIO13);
59
60         // PB13 = SCK2
61         // PB15 = MOSI2
62         gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO13);
63         gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO15);
64
65         // PA8 = IR remote control
66         gpio_clear(GPIOA, GPIO8);
67         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO8);
68 }
69
70 static void usart_init(void)
71 {
72         usart_set_baudrate(USART1, 115200);
73         usart_set_databits(USART1, 8);
74         usart_set_stopbits(USART1, USART_STOPBITS_1);
75         usart_set_mode(USART1, USART_MODE_TX_RX);
76         usart_set_parity(USART1, USART_PARITY_NONE);
77         usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
78
79         usart_enable(USART1);
80 }
81
82 /*** System ticks ***/
83
84 static volatile u32 ms_ticks;
85
86 void sys_tick_handler(void)
87 {
88         ms_ticks++;
89 }
90
91 static void tick_init(void)
92 {
93         systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
94         systick_counter_enable();
95         systick_interrupt_enable();
96 }
97
98 static void delay_ms(uint ms)
99 {
100         u32 start_ticks = ms_ticks;
101         while (ms_ticks - start_ticks < ms)
102                 ;
103 }
104
105 /*** Emulated TM1618 LED Driver ***/
106
107 /*
108  *  Theory of operation:
109  *
110  *  TM1618 communicates using a bi-directional SPI-like protocol.
111  *  The AC unit is sending a stream of commands like this once per ca. 4 ms:
112  *
113  *      00 - set mode: 4 grids, 8 segments
114  *      44 - will write to display memory, no auto-increment
115  *      Cx - set memory address to x
116  *      yy - data to write, two most-significant bits are always zero
117  *      8B - display ON, duty cycle 10/16
118  *
119  *  No read commands are issued, so we can simulate TM1618 using a pure SPI slave.
120  *
121  *  Commands are delimited using the STB* (strobe) pin, but since our opto-couplers
122  *  are negating, we cannot route this pin to SS (slave select) of our SPI.
123  *  We tried triggering an external interrupt by this pin, but it turned out
124  *  that the latency is too high.
125  *
126  *  Instead, we ignore STB* completely and implement a self-synchronizing receiver:
127  *
128  *    - The only byte which can have top 2 bits both set is the Cx command,
129  *      so we can use this to find memory addresses and data in the stream.
130  *      We can ignore all other commands.
131  *
132  *    - Whenever 1 ms passes since the last byte was received, we reset the SPI.
133  *      This allows us to recover from misaligned bytes.
134  */
135
136 static void tm_init(void)
137 {
138         // Configure SPI2 to receive
139         spi_set_receive_only_mode(SPI2);
140         spi_enable_software_slave_management(SPI2);
141         spi_set_nss_low(SPI2);
142         spi_send_lsb_first(SPI2);
143         spi_set_clock_polarity_0(SPI2);
144         spi_set_clock_phase_1(SPI2);
145         spi_enable_rx_buffer_not_empty_interrupt(SPI2);
146         nvic_enable_irq(NVIC_SPI2_IRQ);
147         spi_enable(SPI2);
148
149         // TIM3 will handle receive timeout
150         timer_set_prescaler(TIM3, CPU_CLOCK_MHZ-1);     // 1 tick = 1 μs
151         timer_set_mode(TIM3, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_DOWN);
152         timer_update_on_overflow(TIM3);
153         timer_disable_preload(TIM3);
154         timer_one_shot_mode(TIM3);
155         timer_enable_irq(TIM3, TIM_DIER_UIE);
156         nvic_enable_irq(NVIC_TIM3_IRQ);
157 }
158
159 /*
160  *  Data memory of TM1618:
161  *
162  *  [0]    .    .    .    -    -    -    -    -
163  *  [1]    .    .    -    -    HEAT .    .    .
164  *  [2]    .    .    .    DRY  -    SLP  MED  LOW
165  *  [3]    .    .    HIGH AUTO COOL .    .    .
166  *  [4]    .    .    .    B2   -    G2   D2   C2
167  *  [5]    .    .    E2   F2   A2   .    .    .
168  *  [6]    .    .    .    B1   -    G1   D1   C1
169  *  [7]    .    .    E1   F1   A1   .    .    .
170  *
171  *  "." is an always-zero bit not defined by TM1618, "-" is defined, but not used by AC.
172  */
173 static volatile byte tm_data[8];
174 static volatile uint tm_overruns;
175
176 static volatile byte tm_buffer[256];
177 static volatile uint tm_len;
178
179 /*
180  *
181  *  Display segments:
182  *
183  *      +--A--+
184  *      |     |
185  *      F     B
186  *      |     |
187  *      +--G--+
188  *      |     |
189  *      E     C
190  *      |     |
191  *      +--D--+
192  */
193
194 enum tm_seg {
195         SEGa = 0x0800,
196         SEGb = 0x0010,
197         SEGc = 0x0001,
198         SEGd = 0x0002,
199         SEGe = 0x2000,
200         SEGf = 0x1000,
201         SEGg = 0x0004,
202 };
203
204 static const u16 tm_digits[10] = {
205         [0] = SEGa | SEGb | SEGc | SEGd | SEGe | SEGf,
206         [1] = SEGb | SEGc,
207         [2] = SEGa | SEGb | SEGd | SEGe | SEGg,
208         [3] = SEGa | SEGb | SEGc | SEGd | SEGg,
209         [4] = SEGb | SEGc | SEGf | SEGg,
210         [5] = SEGa | SEGc | SEGd | SEGf | SEGg,
211         [6] = SEGa | SEGc | SEGd | SEGe | SEGf | SEGg,
212         [7] = SEGa | SEGb | SEGc,
213         [8] = SEGa | SEGb | SEGc | SEGd | SEGe | SEGf | SEGg,
214         [9] = SEGa | SEGb | SEGc | SEGd | SEGf | SEGg,
215 };
216
217 static volatile uint tm_timeouts;
218
219 void spi2_isr(void)
220 {
221         if (SPI_SR(SPI2) & SPI_SR_OVR)
222                 tm_overruns++;
223         if (SPI_SR(SPI2) & SPI_SR_RXNE) {
224                 byte x = SPI_DR(SPI2) ^ 0xff;
225 #if 0
226                 if (tm_len < ARRAY_SIZE(tm_buffer))
227                         tm_buffer[tm_len++] = x;
228 #endif
229                 static byte tm_address;
230                 if (tm_address) {
231                         tm_data[tm_address & 7] = x;
232                         tm_address = 0;
233                 } else if ((x & 0xc0) == 0xc0) {
234                         tm_address = x;
235                 }
236                 timer_set_period(TIM3, 999);
237                 timer_generate_event(TIM3, TIM_EGR_UG);
238                 timer_enable_counter(TIM3);
239         }
240 }
241
242 void tim3_isr(void)
243 {
244         if (TIM_SR(TIM3) & TIM_SR_UIF) {
245                 TIM_SR(TIM3) &= ~TIM_SR_UIF;
246                 tm_timeouts++;
247                 spi_set_nss_high(SPI2);
248                 spi_set_nss_low(SPI2);
249         }
250 }
251
252 static void tm_show(void)
253 {
254         debug_printf("TM:");
255         for (uint i=0; i<8; i++)
256                 debug_printf(" %02x", tm_data[i]);
257         debug_printf(" o=%d t=%d", tm_overruns, tm_timeouts);
258
259         debug_printf(" =>");
260         if (tm_data[1] & 0x08)
261                 debug_printf(" HEAT");
262         if (tm_data[2] & 0x10)
263                 debug_printf(" DRY");
264         if (tm_data[2] & 0x04)
265                 debug_printf(" SLEEP");
266         if (tm_data[2] & 0x02)
267                 debug_printf(" MED");
268         if (tm_data[2] & 0x01)
269                 debug_printf(" LOW");
270         if (tm_data[3] & 0x20)
271                 debug_printf(" HIGH");
272         if (tm_data[3] & 0x10)
273                 debug_printf(" AUTO");
274         if (tm_data[3] & 0x08)
275                 debug_printf(" COOL");
276
277         debug_putc(' ');
278         for (int i=0; i<2; i++) {
279                 uint x = (tm_data[7-2*i] << 8) | tm_data[6-2*i];
280                 uint j = 0;
281                 while (j < 10 && tm_digits[j] != x)
282                         j++;
283                 if (j == 10)
284                         debug_putc('?');
285                 else
286                         debug_putc('0' + j);
287         }
288
289         debug_putc('\n');
290
291 #if 0
292         static byte tm_dumped;
293         if (!tm_dumped && tm_len == ARRAY_SIZE(tm_buffer)) {
294                 for (uint i=0; i < tm_len; i++)
295                         debug_printf("%02x ", tm_buffer[i]);
296                 debug_putc('\n');
297                 // tm_dumped = 1;
298                 tm_len = 0;
299         }
300 #endif
301 }
302
303 /*** Infra-red remote control simulator ***/
304
305 /*
306  *  The AC unit expects demodulated IR signal. The RC sends 52-bit messages
307  *  (plus leader and trailer). The last 4 bits are a complement of checksum
308  *  of 4-bit nibbles.
309  */
310
311 #define RC_POWER_OFF_HI         0b00000000000000000000
312 #define RC_POWER_OFF_LO         0b00000000000000010000000010100100
313
314 #define RC_DEFAULT_HI           0b00000011000000000000
315
316 // Combines with a temperature setting (17-30)
317 #define RC_COOL_AUTO            0b00000000000000010000000000000000
318 #define RC_COOL_HI              0b00000000000000010000100000000000
319 #define RC_COOL_MED             0b00000000000000010001000100000000
320 #define RC_COOL_LO              0b00000000000000010010001000000000
321
322 static const u32 rc_cool_fan[4] = {
323         RC_COOL_AUTO,
324         RC_COOL_LO,
325         RC_COOL_MED,
326         RC_COOL_HI,
327 };
328
329 // Combines with a temperature setting (15-25)
330 #define RC_WARM                 0b00000000000000010000001100000000
331
332 // This is sent with temperature=17
333 #define RC_DEHUMIDIFY           0b00000000000000010010010000000000
334
335 // This can be added to any command to enable sleep mode, but we do not issue these yet
336 #define RC_SLEEP                0b00000000000010000000000000000000
337
338 enum rc_mode {
339         MODE_OFF,
340         MODE_COOL,
341         MODE_WARM,
342         MODE_DEHUMIDIFY,
343 };
344
345 static byte rc_mode = MODE_COOL;        // MODE_xxx
346 static byte rc_fan;                     // 0-3
347 static byte rc_temp = 17;               // 15-30
348
349 static void rc_init(void)
350 {
351         // TIM4 runs at 1 MHz and it is used for timing of RC pulses
352         timer_set_prescaler(TIM4, CPU_CLOCK_MHZ - 1);
353         timer_set_mode(TIM4, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
354         timer_update_on_overflow(TIM4);
355         timer_disable_preload(TIM4);
356         timer_one_shot_mode(TIM4);
357         timer_enable_irq(TIM4, TIM_DIER_UIE);
358         nvic_enable_irq(NVIC_TIM4_IRQ);
359 }
360
361 static u32 rc_pattern[2];
362 static uint rc_tick;
363
364 static void rc_encode(void)
365 {
366         if (rc_mode == MODE_OFF) {
367                 rc_pattern[0] = RC_POWER_OFF_HI;
368                 rc_pattern[1] = RC_POWER_OFF_LO;
369                 return;
370         }
371
372         rc_pattern[0] = RC_DEFAULT_HI;
373         uint t = rc_temp;
374
375         if (rc_mode == MODE_COOL) {
376                 rc_pattern[1] = rc_cool_fan[rc_fan];
377                 if (t < 17)
378                         t = 17;
379                 if (t > 30)
380                         t = 30;
381         } else if (rc_mode == MODE_WARM) {
382                 rc_pattern[1] = RC_WARM;
383                 if (t < 15)
384                         t = 15;
385                 if (t > 25)
386                         t = 25;
387         } else {
388                 rc_pattern[1] = RC_DEHUMIDIFY;
389                 t = 17;
390         }
391
392         // Encode temperature
393         rc_pattern[1] |= (t - 15) << 4;
394
395         // Compute checksum
396         uint sum = 0;
397         for (uint i=0; i<2; i++)
398                 for (uint j=0; j<32; j+=4)
399                         sum += (rc_pattern[i] >> j) & 0x0f;
400         rc_pattern[1] |= (sum & 0x0f) ^ 0x0f;
401 }
402
403 void tim4_isr(void)
404 {
405         if (TIM_SR(TIM4) & TIM_SR_UIF) {
406                 TIM_SR(TIM4) &= ~TIM_SR_UIF;
407
408                 bool val;       // 1=pulse, 0=break
409                 uint duration;  // in μs
410
411                 switch (rc_tick) {
412                         case 0:
413                                 // Better be safe
414                                 return;
415                         case 2:
416                         case 108:
417                                 // Initial / final marker
418                                 val = 0;
419                                 duration = 3600;
420                                 // debug_putc('#');
421                                 break;
422                         case 110:
423                                 // Inter-packet gap
424                                 val = 0;
425                                 duration = 10000;
426                                 // debug_putc('$');
427                                 break;
428                         case 111:
429                                 // End of message
430                                 rc_tick = 0;
431                                 return;
432                         default:
433                                 if (rc_tick % 2) {
434                                         val = 1;
435                                         duration = 565;
436                                         // debug_putc('*');
437                                 } else {
438                                         // Even ticks 4 to 106 transmit 52 bits of data
439                                         uint i = 12 + (rc_tick - 4) / 2;
440                                         val = 0;
441                                         if (rc_pattern[i>>5] & (0x80000000 >> (i & 31))) {
442                                                 duration = 1471;
443                                                 // debug_putc('B');
444                                         } else {
445                                                 duration = 480;
446                                                 // debug_putc('A');
447                                         }
448                                 }
449                 }
450
451                 rc_tick++;
452
453                 if (val)
454                         gpio_set(GPIOA, GPIO8);
455                 else
456                         gpio_clear(GPIOA, GPIO8);
457
458                 timer_set_period(TIM4, duration - 1);
459                 timer_generate_event(TIM4, TIM_EGR_UG);
460                 timer_enable_counter(TIM4);
461         }
462 }
463
464 static void rc_send(void)
465 {
466         if (rc_tick)
467                 return;
468
469         rc_encode();
470         debug_printf("RC sending: %05x %08x (mode=%d, fan=%d, temp=%d)\n",
471                 (uint) rc_pattern[0], (uint) rc_pattern[1],
472                 rc_mode, rc_fan, rc_temp);
473         rc_tick = 1;
474
475         timer_set_period(TIM4, 1);
476         timer_generate_event(TIM4, TIM_EGR_UG);
477         timer_enable_counter(TIM4);
478 }
479
480 static bool rc_key(char key)
481 {
482         if (key == 'o') {
483                 rc_mode = MODE_OFF;
484                 rc_send();
485                 return true;
486         } else if (key == 'c') {
487                 rc_mode = MODE_COOL;
488                 rc_send();
489                 return true;
490         } else if (key == 'w') {
491                 rc_mode = MODE_WARM;
492                 rc_send();
493                 return true;
494         } else if (key == 'd') {
495                 rc_mode = MODE_DEHUMIDIFY;
496                 rc_send();
497                 return true;
498         } else if (key == 'a') {
499                 rc_fan = 0;
500                 rc_send();
501                 return true;
502         } else if (key == 'l') {
503                 rc_fan = 1;
504                 rc_send();
505                 return true;
506         } else if (key == 'm') {
507                 rc_fan = 2;
508                 rc_send();
509                 return true;
510         } else if (key == 'h') {
511                 rc_fan = 3;
512                 rc_send();
513                 return true;
514         } else if (key >= '7' && key <= '9') {
515                 rc_temp = key - '0' + 10;
516                 rc_send();
517                 return true;
518         } else if (key >= '0' && key <= '6') {
519                 rc_temp = key - '0' + 20;
520                 rc_send();
521                 return true;
522         } else if (key == '&') {
523                 rc_temp = 27;
524                 rc_send();
525                 return true;
526         } else if (key == '*') {
527                 rc_temp = 28;
528                 rc_send();
529                 return true;
530         } else if (key == '(') {
531                 rc_temp = 29;
532                 rc_send();
533                 return true;
534         } else if (key == ')') {
535                 rc_temp = 30;
536                 rc_send();
537                 return true;
538         }
539         return false;
540 }
541
542 /*** USB ***/
543
544 static usbd_device *usbd_dev;
545
546 enum usb_string {
547         STR_MANUFACTURER = 1,
548         STR_PRODUCT,
549         STR_SERIAL,
550 };
551
552 static char usb_serial_number[13];
553
554 static const char *usb_strings[] = {
555         "United Computer Wizards",
556         "Sinclair Air Conditioner",
557         usb_serial_number,
558 };
559
560 static const struct usb_device_descriptor device = {
561         .bLength = USB_DT_DEVICE_SIZE,
562         .bDescriptorType = USB_DT_DEVICE,
563         .bcdUSB = 0x0200,
564         .bDeviceClass = 0xFF,
565         .bDeviceSubClass = 0,
566         .bDeviceProtocol = 0,
567         .bMaxPacketSize0 = 64,
568         .idVendor = 0x4242,
569         .idProduct = 0x0007,
570         .bcdDevice = 0x0000,
571         .iManufacturer = STR_MANUFACTURER,
572         .iProduct = STR_PRODUCT,
573         .iSerialNumber = STR_SERIAL,
574         .bNumConfigurations = 1,
575 };
576
577 static const struct usb_endpoint_descriptor endpoints[] = {{
578         // Bulk end-point for sending values to the display
579         .bLength = USB_DT_ENDPOINT_SIZE,
580         .bDescriptorType = USB_DT_ENDPOINT,
581         .bEndpointAddress = 0x01,
582         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
583         .wMaxPacketSize = 64,
584         .bInterval = 1,
585 }};
586
587 static const struct usb_interface_descriptor iface = {
588         .bLength = USB_DT_INTERFACE_SIZE,
589         .bDescriptorType = USB_DT_INTERFACE,
590         .bInterfaceNumber = 0,
591         .bAlternateSetting = 0,
592         .bNumEndpoints = 1,
593         .bInterfaceClass = 0xFF,
594         .bInterfaceSubClass = 0,
595         .bInterfaceProtocol = 0,
596         .iInterface = 0,
597         .endpoint = endpoints,
598 };
599
600 static const struct usb_dfu_descriptor dfu_function = {
601         .bLength = sizeof(struct usb_dfu_descriptor),
602         .bDescriptorType = DFU_FUNCTIONAL,
603         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
604         .wDetachTimeout = 255,
605         .wTransferSize = 1024,
606         .bcdDFUVersion = 0x0100,
607 };
608
609 static const struct usb_interface_descriptor dfu_iface = {
610         .bLength = USB_DT_INTERFACE_SIZE,
611         .bDescriptorType = USB_DT_INTERFACE,
612         .bInterfaceNumber = 1,
613         .bAlternateSetting = 0,
614         .bNumEndpoints = 0,
615         .bInterfaceClass = 0xFE,
616         .bInterfaceSubClass = 1,
617         .bInterfaceProtocol = 1,
618         .iInterface = 0,
619
620         .extra = &dfu_function,
621         .extralen = sizeof(dfu_function),
622 };
623
624 static const struct usb_interface ifaces[] = {{
625         .num_altsetting = 1,
626         .altsetting = &iface,
627 }, {
628         .num_altsetting = 1,
629         .altsetting = &dfu_iface,
630 }};
631
632 static const struct usb_config_descriptor config = {
633         .bLength = USB_DT_CONFIGURATION_SIZE,
634         .bDescriptorType = USB_DT_CONFIGURATION,
635         .wTotalLength = 0,
636         .bNumInterfaces = 2,
637         .bConfigurationValue = 1,
638         .iConfiguration = 0,
639         .bmAttributes = 0x80,
640         .bMaxPower = 50,        // multiplied by 2 mA
641         .interface = ifaces,
642 };
643
644 static byte usb_configured;
645 static uint8_t usbd_control_buffer[64];
646
647 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
648 {
649         // Reset to bootloader, which implements the rest of DFU
650         debug_printf("Switching to DFU\n");
651         debug_flush();
652         scb_reset_core();
653 }
654
655 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
656         struct usb_setup_data *req,
657         uint8_t **buf UNUSED,
658         uint16_t *len UNUSED,
659         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
660 {
661         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
662                 return USBD_REQ_NOTSUPP;
663
664         *complete = dfu_detach_complete;
665         return USBD_REQ_HANDLED;
666 }
667
668 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
669 {
670         // We received a frame from the USB host
671         byte buf[8];
672         uint len = usbd_ep_read_packet(dev, 0x01, buf, 8);
673         debug_printf("USB: Host sent %u bytes\n", len);
674 }
675
676 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
677 {
678         usbd_register_control_callback(
679                 dev,
680                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
681                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
682                 dfu_control_cb);
683         usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
684         usb_configured = 1;
685 }
686
687 static void reset_cb(void)
688 {
689         debug_printf("USB: Reset\n");
690         usb_configured = 0;
691 }
692
693 static volatile bool usb_event_pending;
694
695 void usb_lp_can_rx0_isr(void)
696 {
697         /*
698          *  We handle USB in the main loop to avoid race conditions between
699          *  USB interrupts and other code. However, we need an interrupt to
700          *  up the main loop from sleep.
701          *
702          *  We set up only the low-priority ISR, because high-priority ISR handles
703          *  only double-buffered bulk transfers and isochronous transfers.
704          */
705         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
706         usb_event_pending = 1;
707 }
708
709 static void usb_init(void)
710 {
711         // Simulate USB disconnect
712         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
713         gpio_clear(GPIOA, GPIO11 | GPIO12);
714         delay_ms(100);
715
716         usbd_dev = usbd_init(
717                 &st_usbfs_v1_usb_driver,
718                 &device,
719                 &config,
720                 usb_strings,
721                 ARRAY_SIZE(usb_strings),
722                 usbd_control_buffer,
723                 sizeof(usbd_control_buffer)
724         );
725         usbd_register_reset_callback(usbd_dev, reset_cb);
726         usbd_register_set_config_callback(usbd_dev, set_config_cb);
727         usb_event_pending = 1;
728 }
729
730 /*** Main ***/
731
732 int main(void)
733 {
734         clock_init();
735         gpio_init();
736         usart_init();
737
738         tick_init();
739         desig_get_unique_id_as_dfu(usb_serial_number);
740
741         debug_printf("Hello, world!\n");
742
743         tm_init();
744         rc_init();
745         usb_init();
746
747         u32 last_blink = 0;
748
749         for (;;) {
750                 if (ms_ticks - last_blink >= 1000) {
751                         debug_led_toggle();
752                         last_blink = ms_ticks;
753                         tm_show();
754                 }
755
756                 if (usart_get_flag(USART1, USART_SR_RXNE)) {
757                         uint ch = usart_recv(USART1);
758 #if 0
759                         if (ch == '1')
760                                 gpio_set(GPIOA, GPIO8);
761                         else if (ch == '0')
762                                 gpio_clear(GPIOA, GPIO8);
763 #else
764                         if (rc_key(ch))
765                                 ;
766 #endif
767                         else
768                                 debug_putc(ch);
769                 }
770
771                 if (usb_event_pending) {
772                         usbd_poll(usbd_dev);
773                         usb_event_pending = 0;
774                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
775                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
776                 }
777
778                 wait_for_interrupt();
779         }
780
781         return 0;
782 }