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