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