]> mj.ucw.cz Git - home-hw.git/blob - test-sinclair/main.c
Merge branch 'master' of ssh://git.ucw.cz/home/mj/GIT/home-hw
[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_ALTFN_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 enum rc_keys {
306         RC_POWER_OFF,
307         RC_POWER_ON,
308         RC_HIGH,
309         RC_MED,
310         RC_LO,
311         RC_SLEEP,
312         RC_DRY,
313         RC_WARM,
314         RC_COLD,
315         RC_T17,
316         RC_T18,
317         RC_T19,
318         RC_T20,
319         RC_T21,
320         RC_T22,
321         RC_T23,
322         RC_T24,
323         RC_T25,
324         RC_T26,
325         RC_T27,
326         RC_T28,
327         RC_T29,
328         RC_T30,
329         RC_MAX
330 };
331
332 static const char * const rc_patterns[RC_MAX] = {
333         [RC_POWER_OFF]  = "*#*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*A*B*A*A*B*A*A*#*$",
334         [RC_POWER_ON]   = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*A*B*A*A*A*A*B*#*$",
335         [RC_HIGH]       = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*B*A*A*A*B*A*B*A*B*A*A*B*#*$",
336         [RC_MED]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*B*A*A*A*B*B*A*B*A*B*B*B*B*#*$",
337         [RC_LO]         = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*B*A*A*A*B*A*B*A*B*A*B*B*A*B*#*$",
338         [RC_SLEEP]      = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*B*A*A*B*A*A*A*B*A*B*A*B*A*A*B*A*B*#*$",
339         [RC_DRY]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*B*A*A*B*A*A*B*A*B*A*B*A*B*B*#*$",
340         [RC_WARM]       = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*B*B*B*A*B*A*B*B*B*A*#*$",
341         [RC_COLD]       = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*A*B*A*A*A*A*B*#*$",
342         [RC_T17]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*A*A*B*A*B*A*A*B*#*$",
343         [RC_T18]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*A*A*B*B*B*A*A*A*#*$",
344         [RC_T19]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*A*B*A*A*A*B*B*B*#*$",
345         [RC_T20]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*A*B*A*B*A*B*B*A*#*$",
346         [RC_T21]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*A*B*B*A*A*B*A*B*#*$",
347         [RC_T22]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*A*B*B*B*A*B*A*A*#*$",
348         [RC_T23]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*A*A*A*A*A*B*B*#*$",
349         [RC_T24]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*A*A*B*A*A*B*A*#*$",
350         [RC_T25]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*A*B*A*A*A*A*B*#*$",
351         [RC_T26]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*A*B*B*A*A*A*A*#*$",
352         [RC_T27]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*B*A*A*B*B*B*B*#*$",
353         [RC_T28]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*B*A*B*B*B*B*A*#*$",
354         [RC_T29]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*B*B*A*B*B*A*B*#*$",
355         [RC_T30]        = "*#*A*A*A*A*A*A*B*B*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*A*B*A*A*A*A*A*A*A*A*B*B*B*B*B*B*A*A*#*$",
356 };
357
358 static const char rc_keys[] = "Oohmlsdwc7890123456&*()";
359
360 static void rc_init(void)
361 {
362         // TIM4 runs at 1 MHz and it is used for timing of RC pulses
363         timer_set_prescaler(TIM4, CPU_CLOCK_MHZ - 1);
364         timer_set_mode(TIM4, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
365         timer_update_on_overflow(TIM4);
366         timer_disable_preload(TIM4);
367         timer_one_shot_mode(TIM4);
368         timer_enable_irq(TIM4, TIM_DIER_UIE);
369         nvic_enable_irq(NVIC_TIM4_IRQ);
370 }
371
372 static volatile const char *rc_pattern_pos;
373 static volatile char rc_pending;
374
375 void tim4_isr(void)
376 {
377         if (TIM_SR(TIM4) & TIM_SR_UIF) {
378                 TIM_SR(TIM4) &= ~TIM_SR_UIF;
379
380                 if (!rc_pattern_pos)    // Just to be sure
381                         return;
382
383                 bool val;       // 1=pulse, 0=break
384                 uint duration;  // in μs
385
386                 switch (*rc_pattern_pos++) {
387                         case '#':
388                                 val = 0;
389                                 duration = 3600;
390                                 break;
391                         case '*':
392                                 val = 1;
393                                 duration = 565;
394                                 break;
395                         case 'A':
396                                 val = 0;
397                                 duration = 480;
398                                 break;
399                         case 'B':
400                                 val = 0;
401                                 duration = 1471;
402                                 break;
403                         case '$':
404                                 val = 0;
405                                 duration = 10000;
406                                 break;
407                         default:
408                                 // End of transmission
409                                 rc_pattern_pos = NULL;
410                                 rc_pending = 0;
411                                 return;
412                 }
413
414                 if (val)
415                         gpio_set(GPIOA, GPIO8);
416                 else
417                         gpio_clear(GPIOA, GPIO8);
418
419                 timer_set_period(TIM4, duration - 1);
420                 timer_generate_event(TIM4, TIM_EGR_UG);
421                 timer_enable_counter(TIM4);
422         }
423 }
424
425 static bool rc_send(char key)
426 {
427         if (rc_pending)
428                 return false;
429         if (!key)
430                 return false;
431
432         const char *s = strchr(rc_keys, key);
433         if (!s)
434                 return false;
435         rc_pending = key;
436         rc_pattern_pos = rc_patterns[s - rc_keys];
437         debug_printf("RC sending: %c\n", key);
438
439         timer_set_period(TIM4, 1);
440         timer_generate_event(TIM4, TIM_EGR_UG);
441         timer_enable_counter(TIM4);
442         return true;
443 }
444
445 /*** USB ***/
446
447 static usbd_device *usbd_dev;
448
449 enum usb_string {
450         STR_MANUFACTURER = 1,
451         STR_PRODUCT,
452         STR_SERIAL,
453 };
454
455 static char usb_serial_number[13];
456
457 static const char *usb_strings[] = {
458         "United Computer Wizards",
459         "Sinclair Air Conditioner",
460         usb_serial_number,
461 };
462
463 static const struct usb_device_descriptor device = {
464         .bLength = USB_DT_DEVICE_SIZE,
465         .bDescriptorType = USB_DT_DEVICE,
466         .bcdUSB = 0x0200,
467         .bDeviceClass = 0xFF,
468         .bDeviceSubClass = 0,
469         .bDeviceProtocol = 0,
470         .bMaxPacketSize0 = 64,
471         .idVendor = 0x4242,
472         .idProduct = 0x0007,
473         .bcdDevice = 0x0000,
474         .iManufacturer = STR_MANUFACTURER,
475         .iProduct = STR_PRODUCT,
476         .iSerialNumber = STR_SERIAL,
477         .bNumConfigurations = 1,
478 };
479
480 static const struct usb_endpoint_descriptor endpoints[] = {{
481         // Bulk end-point for sending values to the display
482         .bLength = USB_DT_ENDPOINT_SIZE,
483         .bDescriptorType = USB_DT_ENDPOINT,
484         .bEndpointAddress = 0x01,
485         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
486         .wMaxPacketSize = 64,
487         .bInterval = 1,
488 }};
489
490 static const struct usb_interface_descriptor iface = {
491         .bLength = USB_DT_INTERFACE_SIZE,
492         .bDescriptorType = USB_DT_INTERFACE,
493         .bInterfaceNumber = 0,
494         .bAlternateSetting = 0,
495         .bNumEndpoints = 1,
496         .bInterfaceClass = 0xFF,
497         .bInterfaceSubClass = 0,
498         .bInterfaceProtocol = 0,
499         .iInterface = 0,
500         .endpoint = endpoints,
501 };
502
503 static const struct usb_dfu_descriptor dfu_function = {
504         .bLength = sizeof(struct usb_dfu_descriptor),
505         .bDescriptorType = DFU_FUNCTIONAL,
506         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
507         .wDetachTimeout = 255,
508         .wTransferSize = 1024,
509         .bcdDFUVersion = 0x0100,
510 };
511
512 static const struct usb_interface_descriptor dfu_iface = {
513         .bLength = USB_DT_INTERFACE_SIZE,
514         .bDescriptorType = USB_DT_INTERFACE,
515         .bInterfaceNumber = 1,
516         .bAlternateSetting = 0,
517         .bNumEndpoints = 0,
518         .bInterfaceClass = 0xFE,
519         .bInterfaceSubClass = 1,
520         .bInterfaceProtocol = 1,
521         .iInterface = 0,
522
523         .extra = &dfu_function,
524         .extralen = sizeof(dfu_function),
525 };
526
527 static const struct usb_interface ifaces[] = {{
528         .num_altsetting = 1,
529         .altsetting = &iface,
530 }, {
531         .num_altsetting = 1,
532         .altsetting = &dfu_iface,
533 }};
534
535 static const struct usb_config_descriptor config = {
536         .bLength = USB_DT_CONFIGURATION_SIZE,
537         .bDescriptorType = USB_DT_CONFIGURATION,
538         .wTotalLength = 0,
539         .bNumInterfaces = 2,
540         .bConfigurationValue = 1,
541         .iConfiguration = 0,
542         .bmAttributes = 0x80,
543         .bMaxPower = 50,        // multiplied by 2 mA
544         .interface = ifaces,
545 };
546
547 static byte usb_configured;
548 static uint8_t usbd_control_buffer[64];
549
550 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
551 {
552         // Reset to bootloader, which implements the rest of DFU
553         debug_printf("Switching to DFU\n");
554         debug_flush();
555         scb_reset_core();
556 }
557
558 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
559         struct usb_setup_data *req,
560         uint8_t **buf UNUSED,
561         uint16_t *len UNUSED,
562         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
563 {
564         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
565                 return USBD_REQ_NOTSUPP;
566
567         *complete = dfu_detach_complete;
568         return USBD_REQ_HANDLED;
569 }
570
571 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
572 {
573         // We received a frame from the USB host
574         byte buf[8];
575         uint len = usbd_ep_read_packet(dev, 0x01, buf, 8);
576         debug_printf("USB: Host sent %u bytes\n", len);
577 }
578
579 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
580 {
581         usbd_register_control_callback(
582                 dev,
583                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
584                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
585                 dfu_control_cb);
586         usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
587         usb_configured = 1;
588 }
589
590 static void reset_cb(void)
591 {
592         debug_printf("USB: Reset\n");
593         usb_configured = 0;
594 }
595
596 static volatile bool usb_event_pending;
597
598 void usb_lp_can_rx0_isr(void)
599 {
600         /*
601          *  We handle USB in the main loop to avoid race conditions between
602          *  USB interrupts and other code. However, we need an interrupt to
603          *  up the main loop from sleep.
604          *
605          *  We set up only the low-priority ISR, because high-priority ISR handles
606          *  only double-buffered bulk transfers and isochronous transfers.
607          */
608         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
609         usb_event_pending = 1;
610 }
611
612 static void usb_init(void)
613 {
614         // Simulate USB disconnect
615         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
616         gpio_clear(GPIOA, GPIO11 | GPIO12);
617         delay_ms(100);
618
619         usbd_dev = usbd_init(
620                 &st_usbfs_v1_usb_driver,
621                 &device,
622                 &config,
623                 usb_strings,
624                 ARRAY_SIZE(usb_strings),
625                 usbd_control_buffer,
626                 sizeof(usbd_control_buffer)
627         );
628         usbd_register_reset_callback(usbd_dev, reset_cb);
629         usbd_register_set_config_callback(usbd_dev, set_config_cb);
630         usb_event_pending = 1;
631 }
632
633 /*** Main ***/
634
635 int main(void)
636 {
637         clock_init();
638         gpio_init();
639         usart_init();
640
641         tick_init();
642         desig_get_unique_id_as_dfu(usb_serial_number);
643
644         debug_printf("Hello, world!\n");
645
646         tm_init();
647         rc_init();
648         usb_init();
649
650         u32 last_blink = 0;
651
652         for (;;) {
653                 if (ms_ticks - last_blink >= 1000) {
654                         debug_led_toggle();
655                         last_blink = ms_ticks;
656                         tm_show();
657                 }
658
659                 if (usart_get_flag(USART1, USART_SR_RXNE)) {
660                         uint ch = usart_recv(USART1);
661                         debug_putc(ch);
662                 }
663
664                 if (usb_event_pending) {
665                         usbd_poll(usbd_dev);
666                         usb_event_pending = 0;
667                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
668                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
669                 }
670
671                 wait_for_interrupt();
672         }
673
674         return 0;
675 }