]> mj.ucw.cz Git - home-hw.git/blob - test-sinclair/main.c
test-sinclair: Rewritten RC code
[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 #define RC_POWER_OFF_HI         0b00000000000000000000
306 #define RC_POWER_OFF_LO         0b00000000000000010000000010100100
307
308 #define RC_DEFAULT_HI           0b00000011000000000000
309
310 // Various temperatures
311 #define RC_17_COOL_AUTO         0b00000000000000010000000000101001
312 #define RC_18_COOL_AUTO         0b00000000000000010000000000111000
313 #define RC_19_COOL_AUTO         0b00000000000000010000000001000111
314 #define RC_20_COOL_AUTO         0b00000000000000010000000001010110
315 #define RC_21_COOL_AUTO         0b00000000000000010000000001100101
316 #define RC_22_COOL_AUTO         0b00000000000000010000000001110100
317 #define RC_23_COOL_AUTO         0b00000000000000010000000010000011
318 #define RC_24_COOL_AUTO         0b00000000000000010000000010010010
319 #define RC_25_COOL_AUTO         0b00000000000000010000000010100001
320 #define RC_26_COOL_AUTO         0b00000000000000010000000010110000
321 #define RC_27_COOL_AUTO         0b00000000000000010000000011001111
322 #define RC_28_COOL_AUTO         0b00000000000000010000000011011110
323 #define RC_29_COOL_AUTO         0b00000000000000010000000011101101
324 #define RC_30_COOL_AUTO         0b00000000000000010000000011111100
325
326 // Various fan settings
327 #define RC_17_COOL_HI           0b00000000000000010000100000100001
328 #define RC_17_COOL_MED          0b00000000000000010001000100100111
329 #define RC_17_COOL_LO           0b00000000000000010010001000100101
330
331 // Stand-alone, no temperature nor fan setting
332 #define RC_DEHUMIDIFY           0b00000000000000010010010000100011
333
334 // Combines with a temperature setting, but no fan setting
335 #define RC_17_WARM              0b00000000000000010000001100100110
336
337 // All modes have a sleep variant, which we do not use yet
338 #define RC_17_COOL_AUTO_SLEEP   0b00000000000010010000000000100001
339
340 static const u32 rc_fan_settings[4] = {
341         0,
342         RC_17_COOL_LO ^ RC_17_COOL_AUTO,
343         RC_17_COOL_MED ^ RC_17_COOL_AUTO,
344         RC_17_COOL_HI ^ RC_17_COOL_AUTO,
345 };
346
347 static const u32 rc_temp_settings[14] = {
348 #define X(t) RC_##t##_COOL_AUTO ^ RC_17_COOL_AUTO
349         X(17),
350         X(18),
351         X(19),
352         X(20),
353         X(21),
354         X(22),
355         X(23),
356         X(24),
357         X(25),
358         X(26),
359         X(27),
360         X(28),
361         X(29),
362         X(30),
363 #undef X
364 };
365
366 enum rc_mode {
367         MODE_OFF,
368         MODE_COOL,
369         MODE_WARM,
370         MODE_DEHUMIDIFY,
371 };
372
373 static byte rc_mode;            // MODE_xxx
374 static byte rc_fan;             // 0-3
375 static byte rc_temp;            // 17-30
376
377 static void rc_init(void)
378 {
379         // TIM4 runs at 1 MHz and it is used for timing of RC pulses
380         timer_set_prescaler(TIM4, CPU_CLOCK_MHZ - 1);
381         timer_set_mode(TIM4, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
382         timer_update_on_overflow(TIM4);
383         timer_disable_preload(TIM4);
384         timer_one_shot_mode(TIM4);
385         timer_enable_irq(TIM4, TIM_DIER_UIE);
386         nvic_enable_irq(NVIC_TIM4_IRQ);
387 }
388
389 static u32 rc_pattern[2];
390 static uint rc_tick;
391
392 static void rc_encode(void)
393 {
394         if (rc_mode == MODE_OFF) {
395                 rc_pattern[0] = RC_POWER_OFF_HI;
396                 rc_pattern[1] = RC_POWER_OFF_LO;
397                 return;
398         }
399
400         rc_pattern[0] = RC_DEFAULT_HI;
401         uint t = rc_temp, f = rc_fan;
402
403         if (rc_mode == MODE_COOL) {
404                 rc_pattern[1] = RC_17_COOL_AUTO;
405         } else if (rc_mode == MODE_WARM) {
406                 rc_pattern[1] = RC_17_WARM;
407                 f = 0;
408         } else {
409                 rc_pattern[1] = RC_DEHUMIDIFY;
410                 f = t = 0;
411         }
412
413         rc_pattern[1] ^= rc_fan_settings[f];
414
415         if (t >= 17 && t < 17 + ARRAY_SIZE(rc_temp_settings))
416                 rc_pattern[1] ^= rc_temp_settings[t - 17];
417 }
418
419 void tim4_isr(void)
420 {
421         if (TIM_SR(TIM4) & TIM_SR_UIF) {
422                 TIM_SR(TIM4) &= ~TIM_SR_UIF;
423
424                 bool val;       // 1=pulse, 0=break
425                 uint duration;  // in μs
426
427                 switch (rc_tick++) {
428                         case 0:
429                                 // Better be safe
430                                 return;
431                         case 2:
432                         case 108:
433                                 // Initial / final marker
434                                 val = 0;
435                                 duration = 3600;
436                                 break;
437                         case 110:
438                                 // Inter-packet gap
439                                 val = 0;
440                                 duration = 10000;
441                                 break;
442                         case 111:
443                                 // End of message
444                                 rc_tick = 0;
445                                 return;
446                         default:
447                                 if (rc_tick % 2) {
448                                         val = 1;
449                                         duration = 565;
450                                 } else {
451                                         // Even ticks 4 to 106 transmit 52 bits of data
452                                         uint i = 12 + (rc_tick - 4) / 2;
453                                         val = 0;
454                                         if (rc_pattern[i>>5] & (1 << (i & 31)))
455                                                 duration = 1471;
456                                         else
457                                                 duration = 480;
458                                 }
459                 }
460
461                 if (val)
462                         gpio_set(GPIOA, GPIO8);
463                 else
464                         gpio_clear(GPIOA, GPIO8);
465
466                 timer_set_period(TIM4, duration - 1);
467                 timer_generate_event(TIM4, TIM_EGR_UG);
468                 timer_enable_counter(TIM4);
469         }
470 }
471
472 static void rc_send(void)
473 {
474         if (rc_tick)
475                 return;
476
477         rc_encode();
478         debug_printf("RC sending: %05x %08x\n", (uint) rc_pattern[0], (uint) rc_pattern[1]);
479         rc_tick = 1;
480
481         timer_set_period(TIM4, 1);
482         timer_generate_event(TIM4, TIM_EGR_UG);
483         timer_enable_counter(TIM4);
484 }
485
486 static bool rc_key(char key)
487 {
488         if (key == 'o') {
489                 rc_mode = MODE_OFF;
490                 rc_send();
491                 return true;
492         } else if (key == 'c') {
493                 rc_mode = MODE_COOL;
494                 rc_send();
495                 return true;
496         } else if (key == 'w') {
497                 rc_mode = MODE_WARM;
498                 rc_send();
499                 return true;
500         } else if (key == 'd') {
501                 rc_mode = MODE_DEHUMIDIFY;
502                 rc_send();
503                 return true;
504         } else if (key == 'a') {
505                 rc_fan = 0;
506                 rc_send();
507                 return true;
508         } else if (key == 'l') {
509                 rc_fan = 1;
510                 rc_send();
511                 return true;
512         } else if (key == 'm') {
513                 rc_fan = 2;
514                 rc_send();
515                 return true;
516         } else if (key == 'h') {
517                 rc_fan = 3;
518                 rc_send();
519                 return true;
520         } else if (key >= '7' && key <= '9') {
521                 rc_temp = key - '0' + 10;
522                 rc_send();
523                 return true;
524         } else if (key >= '0' && key <= '6') {
525                 rc_temp = key - '0' + 20;
526                 rc_send();
527                 return true;
528         } else if (key == '&') {
529                 rc_temp = 27;
530                 rc_send();
531                 return true;
532         } else if (key == '*') {
533                 rc_temp = 28;
534                 rc_send();
535                 return true;
536         } else if (key == '(') {
537                 rc_temp = 29;
538                 rc_send();
539                 return true;
540         } else if (key == ')') {
541                 rc_temp = 30;
542                 rc_send();
543                 return true;
544         }
545         return false;
546 }
547
548 /*** USB ***/
549
550 static usbd_device *usbd_dev;
551
552 enum usb_string {
553         STR_MANUFACTURER = 1,
554         STR_PRODUCT,
555         STR_SERIAL,
556 };
557
558 static char usb_serial_number[13];
559
560 static const char *usb_strings[] = {
561         "United Computer Wizards",
562         "Sinclair Air Conditioner",
563         usb_serial_number,
564 };
565
566 static const struct usb_device_descriptor device = {
567         .bLength = USB_DT_DEVICE_SIZE,
568         .bDescriptorType = USB_DT_DEVICE,
569         .bcdUSB = 0x0200,
570         .bDeviceClass = 0xFF,
571         .bDeviceSubClass = 0,
572         .bDeviceProtocol = 0,
573         .bMaxPacketSize0 = 64,
574         .idVendor = 0x4242,
575         .idProduct = 0x0007,
576         .bcdDevice = 0x0000,
577         .iManufacturer = STR_MANUFACTURER,
578         .iProduct = STR_PRODUCT,
579         .iSerialNumber = STR_SERIAL,
580         .bNumConfigurations = 1,
581 };
582
583 static const struct usb_endpoint_descriptor endpoints[] = {{
584         // Bulk end-point for sending values to the display
585         .bLength = USB_DT_ENDPOINT_SIZE,
586         .bDescriptorType = USB_DT_ENDPOINT,
587         .bEndpointAddress = 0x01,
588         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
589         .wMaxPacketSize = 64,
590         .bInterval = 1,
591 }};
592
593 static const struct usb_interface_descriptor iface = {
594         .bLength = USB_DT_INTERFACE_SIZE,
595         .bDescriptorType = USB_DT_INTERFACE,
596         .bInterfaceNumber = 0,
597         .bAlternateSetting = 0,
598         .bNumEndpoints = 1,
599         .bInterfaceClass = 0xFF,
600         .bInterfaceSubClass = 0,
601         .bInterfaceProtocol = 0,
602         .iInterface = 0,
603         .endpoint = endpoints,
604 };
605
606 static const struct usb_dfu_descriptor dfu_function = {
607         .bLength = sizeof(struct usb_dfu_descriptor),
608         .bDescriptorType = DFU_FUNCTIONAL,
609         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
610         .wDetachTimeout = 255,
611         .wTransferSize = 1024,
612         .bcdDFUVersion = 0x0100,
613 };
614
615 static const struct usb_interface_descriptor dfu_iface = {
616         .bLength = USB_DT_INTERFACE_SIZE,
617         .bDescriptorType = USB_DT_INTERFACE,
618         .bInterfaceNumber = 1,
619         .bAlternateSetting = 0,
620         .bNumEndpoints = 0,
621         .bInterfaceClass = 0xFE,
622         .bInterfaceSubClass = 1,
623         .bInterfaceProtocol = 1,
624         .iInterface = 0,
625
626         .extra = &dfu_function,
627         .extralen = sizeof(dfu_function),
628 };
629
630 static const struct usb_interface ifaces[] = {{
631         .num_altsetting = 1,
632         .altsetting = &iface,
633 }, {
634         .num_altsetting = 1,
635         .altsetting = &dfu_iface,
636 }};
637
638 static const struct usb_config_descriptor config = {
639         .bLength = USB_DT_CONFIGURATION_SIZE,
640         .bDescriptorType = USB_DT_CONFIGURATION,
641         .wTotalLength = 0,
642         .bNumInterfaces = 2,
643         .bConfigurationValue = 1,
644         .iConfiguration = 0,
645         .bmAttributes = 0x80,
646         .bMaxPower = 50,        // multiplied by 2 mA
647         .interface = ifaces,
648 };
649
650 static byte usb_configured;
651 static uint8_t usbd_control_buffer[64];
652
653 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
654 {
655         // Reset to bootloader, which implements the rest of DFU
656         debug_printf("Switching to DFU\n");
657         debug_flush();
658         scb_reset_core();
659 }
660
661 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
662         struct usb_setup_data *req,
663         uint8_t **buf UNUSED,
664         uint16_t *len UNUSED,
665         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
666 {
667         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
668                 return USBD_REQ_NOTSUPP;
669
670         *complete = dfu_detach_complete;
671         return USBD_REQ_HANDLED;
672 }
673
674 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
675 {
676         // We received a frame from the USB host
677         byte buf[8];
678         uint len = usbd_ep_read_packet(dev, 0x01, buf, 8);
679         debug_printf("USB: Host sent %u bytes\n", len);
680 }
681
682 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
683 {
684         usbd_register_control_callback(
685                 dev,
686                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
687                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
688                 dfu_control_cb);
689         usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
690         usb_configured = 1;
691 }
692
693 static void reset_cb(void)
694 {
695         debug_printf("USB: Reset\n");
696         usb_configured = 0;
697 }
698
699 static volatile bool usb_event_pending;
700
701 void usb_lp_can_rx0_isr(void)
702 {
703         /*
704          *  We handle USB in the main loop to avoid race conditions between
705          *  USB interrupts and other code. However, we need an interrupt to
706          *  up the main loop from sleep.
707          *
708          *  We set up only the low-priority ISR, because high-priority ISR handles
709          *  only double-buffered bulk transfers and isochronous transfers.
710          */
711         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
712         usb_event_pending = 1;
713 }
714
715 static void usb_init(void)
716 {
717         // Simulate USB disconnect
718         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
719         gpio_clear(GPIOA, GPIO11 | GPIO12);
720         delay_ms(100);
721
722         usbd_dev = usbd_init(
723                 &st_usbfs_v1_usb_driver,
724                 &device,
725                 &config,
726                 usb_strings,
727                 ARRAY_SIZE(usb_strings),
728                 usbd_control_buffer,
729                 sizeof(usbd_control_buffer)
730         );
731         usbd_register_reset_callback(usbd_dev, reset_cb);
732         usbd_register_set_config_callback(usbd_dev, set_config_cb);
733         usb_event_pending = 1;
734 }
735
736 /*** Main ***/
737
738 int main(void)
739 {
740         clock_init();
741         gpio_init();
742         usart_init();
743
744         tick_init();
745         desig_get_unique_id_as_dfu(usb_serial_number);
746
747         debug_printf("Hello, world!\n");
748
749         tm_init();
750         rc_init();
751         usb_init();
752
753         u32 last_blink = 0;
754
755         for (;;) {
756                 if (ms_ticks - last_blink >= 1000) {
757                         debug_led_toggle();
758                         last_blink = ms_ticks;
759                         tm_show();
760                 }
761
762                 if (usart_get_flag(USART1, USART_SR_RXNE)) {
763                         uint ch = usart_recv(USART1);
764 #if 0
765                         if (ch == '1')
766                                 gpio_set(GPIOA, GPIO8);
767                         else if (ch == '0')
768                                 gpio_clear(GPIOA, GPIO8);
769 #else
770                         if (rc_key(ch))
771                                 ;
772 #endif
773                         else
774                                 debug_putc(ch);
775                 }
776
777                 if (usb_event_pending) {
778                         usbd_poll(usbd_dev);
779                         usb_event_pending = 0;
780                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
781                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
782                 }
783
784                 wait_for_interrupt();
785         }
786
787         return 0;
788 }