]> 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
38         rcc_periph_reset_pulse(RST_GPIOA);
39         rcc_periph_reset_pulse(RST_GPIOB);
40         rcc_periph_reset_pulse(RST_GPIOC);
41         rcc_periph_reset_pulse(RST_SPI2);
42         rcc_periph_reset_pulse(RST_USART1);
43         rcc_periph_reset_pulse(RST_USB);
44         rcc_periph_reset_pulse(RST_TIM3);
45 }
46
47 static void gpio_init(void)
48 {
49         // PA9 = TXD1 for debugging console
50         // PA10 = RXD1 for debugging console
51         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
52         gpio_set_mode(GPIOA, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO10);
53
54         // PC13 = BluePill LED
55         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
56         gpio_clear(GPIOC, GPIO13);
57
58         // PB13 = SCK2
59         // PB15 = MOSI2
60         gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO13);
61         gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO15);
62 }
63
64 static void usart_init(void)
65 {
66         usart_set_baudrate(USART1, 115200);
67         usart_set_databits(USART1, 8);
68         usart_set_stopbits(USART1, USART_STOPBITS_1);
69         usart_set_mode(USART1, USART_MODE_TX);
70         usart_set_parity(USART1, USART_PARITY_NONE);
71         usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
72
73         usart_enable(USART1);
74 }
75
76 /*** System ticks ***/
77
78 static volatile u32 ms_ticks;
79
80 void sys_tick_handler(void)
81 {
82         ms_ticks++;
83 }
84
85 static void tick_init(void)
86 {
87         systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
88         systick_counter_enable();
89         systick_interrupt_enable();
90 }
91
92 static void delay_ms(uint ms)
93 {
94         u32 start_ticks = ms_ticks;
95         while (ms_ticks - start_ticks < ms)
96                 ;
97 }
98
99 /*** Emulated TM1618 LED Driver ***/
100
101 /*
102  *  Theory of operation:
103  *
104  *  TM1618 communicates using a bi-directional SPI-like protocol.
105  *  The AC unit is sending a stream of commands like this once per ca. 4 ms:
106  *
107  *      00 - set mode: 4 grids, 8 segments
108  *      44 - will write to display memory, no auto-increment
109  *      Cx - set memory address to x
110  *      yy - data to write, two most-significant bits are always zero
111  *      8B - display ON, duty cycle 10/16
112  *
113  *  No read commands are issued, so we can simulate TM1618 using a pure SPI slave.
114  *
115  *  Commands are delimited using the STB* (strobe) pin, but since our opto-couplers
116  *  are negating, we cannot route this pin to SS (slave select) of our SPI.
117  *  We tried triggering an external interrupt by this pin, but it turned out
118  *  that the latency is too high.
119  *
120  *  Instead, we ignore STB* completely and implement a self-synchronizing receiver:
121  *
122  *    - The only byte which can have top 2 bits both set is the Cx command,
123  *      so we can use this to find memory addresses and data in the stream.
124  *      We can ignore all other commands.
125  *
126  *    - Whenever 1 ms passes since the last byte was received, we reset the SPI.
127  *      This allows us to recover from misaligned bytes.
128  */
129
130 static void tm_init(void)
131 {
132         // Configure SPI2 to receive
133         spi_set_receive_only_mode(SPI2);
134         spi_enable_software_slave_management(SPI2);
135         spi_set_nss_low(SPI2);
136         spi_send_lsb_first(SPI2);
137         spi_set_clock_polarity_0(SPI2);
138         spi_set_clock_phase_1(SPI2);
139         spi_enable_rx_buffer_not_empty_interrupt(SPI2);
140         nvic_enable_irq(NVIC_SPI2_IRQ);
141         spi_enable(SPI2);
142
143         // TIM3 will handle receive timeout
144         timer_set_prescaler(TIM3, CPU_CLOCK_MHZ-1);     // 1 tick = 1 μs
145         timer_set_mode(TIM3, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_DOWN);
146         timer_update_on_overflow(TIM3);
147         timer_disable_preload(TIM3);
148         timer_one_shot_mode(TIM3);
149         timer_enable_irq(TIM3, TIM_DIER_UIE);
150         nvic_enable_irq(NVIC_TIM3_IRQ);
151 }
152
153 /*
154  *  Data memory of TM1618:
155  *
156  *  [0]    .    .    .    -    -    -    -    -
157  *  [1]    .    .    -    -    HEAT .    .    .
158  *  [2]    .    .    .    DRY  -    SLP  MED  LOW
159  *  [3]    .    .    HIGH AUTO COOL .    .    .
160  *  [4]    .    .    .    B2   -    G2   D2   C2
161  *  [5]    .    .    E2   F2   A2   .    .    .
162  *  [6]    .    .    .    B1   -    G1   D1   C1
163  *  [7]    .    .    E1   F1   A1   .    .    .
164  *
165  *  "." is an always-zero bit not defined by TM1618, "-" is defined, but not used by AC.
166  */
167 static volatile byte tm_data[8];
168 static volatile uint tm_overruns;
169
170 static volatile byte tm_buffer[256];
171 static volatile uint tm_len;
172
173 /*
174  *
175  *  Display segments:
176  *
177  *      +--A--+
178  *      |     |
179  *      F     B
180  *      |     |
181  *      +--G--+
182  *      |     |
183  *      E     C
184  *      |     |
185  *      +--D--+
186  */
187
188 enum tm_seg {
189         SEGa = 0x0800,
190         SEGb = 0x0010,
191         SEGc = 0x0001,
192         SEGd = 0x0002,
193         SEGe = 0x2000,
194         SEGf = 0x1000,
195         SEGg = 0x0004,
196 };
197
198 static const u16 tm_digits[10] = {
199         [0] = SEGa | SEGb | SEGc | SEGd | SEGe | SEGf,
200         [1] = SEGb | SEGc,
201         [2] = SEGa | SEGb | SEGd | SEGe | SEGg,
202         [3] = SEGa | SEGb | SEGc | SEGd | SEGg,
203         [4] = SEGb | SEGc | SEGf | SEGg,
204         [5] = SEGa | SEGc | SEGd | SEGf | SEGg,
205         [6] = SEGa | SEGc | SEGd | SEGe | SEGf | SEGg,
206         [7] = SEGa | SEGb | SEGc,
207         [8] = SEGa | SEGb | SEGc | SEGd | SEGe | SEGf | SEGg,
208         [9] = SEGa | SEGb | SEGc | SEGd | SEGf | SEGg,
209 };
210
211 static volatile uint tm_timeouts;
212
213 void spi2_isr(void)
214 {
215         if (SPI_SR(SPI2) & SPI_SR_OVR)
216                 tm_overruns++;
217         if (SPI_SR(SPI2) & SPI_SR_RXNE) {
218                 byte x = SPI_DR(SPI2) ^ 0xff;
219 #if 0
220                 if (tm_len < ARRAY_SIZE(tm_buffer))
221                         tm_buffer[tm_len++] = x;
222 #endif
223                 static byte tm_address;
224                 if (tm_address) {
225                         tm_data[tm_address & 7] = x;
226                         tm_address = 0;
227                 } else if ((x & 0xc0) == 0xc0) {
228                         tm_address = x;
229                 }
230                 timer_set_period(TIM3, 999);
231                 timer_generate_event(TIM3, TIM_EGR_UG);
232                 timer_enable_counter(TIM3);
233         }
234 }
235
236 void tim3_isr(void)
237 {
238         if (TIM_SR(TIM3) & TIM_SR_UIF) {
239                 TIM_SR(TIM3) &= ~TIM_SR_UIF;
240                 tm_timeouts++;
241                 spi_set_nss_high(SPI2);
242                 spi_set_nss_low(SPI2);
243         }
244 }
245
246 static void tm_show(void)
247 {
248         debug_printf("TM:");
249         for (uint i=0; i<8; i++)
250                 debug_printf(" %02x", tm_data[i]);
251         debug_printf(" o=%d t=%d", tm_overruns, tm_timeouts);
252
253         debug_printf(" =>");
254         if (tm_data[1] & 0x08)
255                 debug_printf(" HEAT");
256         if (tm_data[2] & 0x10)
257                 debug_printf(" DRY");
258         if (tm_data[2] & 0x04)
259                 debug_printf(" SLEEP");
260         if (tm_data[2] & 0x02)
261                 debug_printf(" MED");
262         if (tm_data[2] & 0x01)
263                 debug_printf(" LOW");
264         if (tm_data[3] & 0x20)
265                 debug_printf(" HIGH");
266         if (tm_data[3] & 0x10)
267                 debug_printf(" AUTO");
268         if (tm_data[3] & 0x08)
269                 debug_printf(" COOL");
270
271         debug_putc(' ');
272         for (int i=0; i<2; i++) {
273                 uint x = (tm_data[7-2*i] << 8) | tm_data[6-2*i];
274                 uint j = 0;
275                 while (j < 10 && tm_digits[j] != x)
276                         j++;
277                 if (j == 10)
278                         debug_putc('?');
279                 else
280                         debug_putc('0' + j);
281         }
282
283         debug_putc('\n');
284
285 #if 0
286         static byte tm_dumped;
287         if (!tm_dumped && tm_len == ARRAY_SIZE(tm_buffer)) {
288                 for (uint i=0; i < tm_len; i++)
289                         debug_printf("%02x ", tm_buffer[i]);
290                 debug_putc('\n');
291                 // tm_dumped = 1;
292                 tm_len = 0;
293         }
294 #endif
295 }
296
297 /*** USB ***/
298
299 static usbd_device *usbd_dev;
300
301 enum usb_string {
302         STR_MANUFACTURER = 1,
303         STR_PRODUCT,
304         STR_SERIAL,
305 };
306
307 static char usb_serial_number[13];
308
309 static const char *usb_strings[] = {
310         "United Computer Wizards",
311         "Sinclair Air Conditioner",
312         usb_serial_number,
313 };
314
315 static const struct usb_device_descriptor device = {
316         .bLength = USB_DT_DEVICE_SIZE,
317         .bDescriptorType = USB_DT_DEVICE,
318         .bcdUSB = 0x0200,
319         .bDeviceClass = 0xFF,
320         .bDeviceSubClass = 0,
321         .bDeviceProtocol = 0,
322         .bMaxPacketSize0 = 64,
323         .idVendor = 0x4242,
324         .idProduct = 0x0007,
325         .bcdDevice = 0x0000,
326         .iManufacturer = STR_MANUFACTURER,
327         .iProduct = STR_PRODUCT,
328         .iSerialNumber = STR_SERIAL,
329         .bNumConfigurations = 1,
330 };
331
332 static const struct usb_endpoint_descriptor endpoints[] = {{
333         // Bulk end-point for sending values to the display
334         .bLength = USB_DT_ENDPOINT_SIZE,
335         .bDescriptorType = USB_DT_ENDPOINT,
336         .bEndpointAddress = 0x01,
337         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
338         .wMaxPacketSize = 64,
339         .bInterval = 1,
340 }};
341
342 static const struct usb_interface_descriptor iface = {
343         .bLength = USB_DT_INTERFACE_SIZE,
344         .bDescriptorType = USB_DT_INTERFACE,
345         .bInterfaceNumber = 0,
346         .bAlternateSetting = 0,
347         .bNumEndpoints = 1,
348         .bInterfaceClass = 0xFF,
349         .bInterfaceSubClass = 0,
350         .bInterfaceProtocol = 0,
351         .iInterface = 0,
352         .endpoint = endpoints,
353 };
354
355 static const struct usb_dfu_descriptor dfu_function = {
356         .bLength = sizeof(struct usb_dfu_descriptor),
357         .bDescriptorType = DFU_FUNCTIONAL,
358         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
359         .wDetachTimeout = 255,
360         .wTransferSize = 1024,
361         .bcdDFUVersion = 0x0100,
362 };
363
364 static const struct usb_interface_descriptor dfu_iface = {
365         .bLength = USB_DT_INTERFACE_SIZE,
366         .bDescriptorType = USB_DT_INTERFACE,
367         .bInterfaceNumber = 1,
368         .bAlternateSetting = 0,
369         .bNumEndpoints = 0,
370         .bInterfaceClass = 0xFE,
371         .bInterfaceSubClass = 1,
372         .bInterfaceProtocol = 1,
373         .iInterface = 0,
374
375         .extra = &dfu_function,
376         .extralen = sizeof(dfu_function),
377 };
378
379 static const struct usb_interface ifaces[] = {{
380         .num_altsetting = 1,
381         .altsetting = &iface,
382 }, {
383         .num_altsetting = 1,
384         .altsetting = &dfu_iface,
385 }};
386
387 static const struct usb_config_descriptor config = {
388         .bLength = USB_DT_CONFIGURATION_SIZE,
389         .bDescriptorType = USB_DT_CONFIGURATION,
390         .wTotalLength = 0,
391         .bNumInterfaces = 2,
392         .bConfigurationValue = 1,
393         .iConfiguration = 0,
394         .bmAttributes = 0x80,
395         .bMaxPower = 50,        // multiplied by 2 mA
396         .interface = ifaces,
397 };
398
399 static byte usb_configured;
400 static uint8_t usbd_control_buffer[64];
401
402 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
403 {
404         // Reset to bootloader, which implements the rest of DFU
405         debug_printf("Switching to DFU\n");
406         debug_flush();
407         scb_reset_core();
408 }
409
410 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
411         struct usb_setup_data *req,
412         uint8_t **buf UNUSED,
413         uint16_t *len UNUSED,
414         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
415 {
416         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
417                 return USBD_REQ_NOTSUPP;
418
419         *complete = dfu_detach_complete;
420         return USBD_REQ_HANDLED;
421 }
422
423 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
424 {
425         // We received a frame from the USB host
426         byte buf[8];
427         uint len = usbd_ep_read_packet(dev, 0x01, buf, 8);
428         debug_printf("USB: Host sent %u bytes\n", len);
429 }
430
431 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
432 {
433         usbd_register_control_callback(
434                 dev,
435                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
436                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
437                 dfu_control_cb);
438         usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
439         usb_configured = 1;
440 }
441
442 static void reset_cb(void)
443 {
444         debug_printf("USB: Reset\n");
445         usb_configured = 0;
446 }
447
448 static volatile bool usb_event_pending;
449
450 void usb_lp_can_rx0_isr(void)
451 {
452         /*
453          *  We handle USB in the main loop to avoid race conditions between
454          *  USB interrupts and other code. However, we need an interrupt to
455          *  up the main loop from sleep.
456          *
457          *  We set up only the low-priority ISR, because high-priority ISR handles
458          *  only double-buffered bulk transfers and isochronous transfers.
459          */
460         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
461         usb_event_pending = 1;
462 }
463
464 static void usb_init(void)
465 {
466         // Simulate USB disconnect
467         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
468         gpio_clear(GPIOA, GPIO11 | GPIO12);
469         delay_ms(100);
470
471         usbd_dev = usbd_init(
472                 &st_usbfs_v1_usb_driver,
473                 &device,
474                 &config,
475                 usb_strings,
476                 ARRAY_SIZE(usb_strings),
477                 usbd_control_buffer,
478                 sizeof(usbd_control_buffer)
479         );
480         usbd_register_reset_callback(usbd_dev, reset_cb);
481         usbd_register_set_config_callback(usbd_dev, set_config_cb);
482         usb_event_pending = 1;
483 }
484
485 /*** Main ***/
486
487 int main(void)
488 {
489         clock_init();
490         gpio_init();
491         usart_init();
492
493         tick_init();
494         desig_get_unique_id_as_dfu(usb_serial_number);
495
496         debug_printf("Hello, world!\n");
497
498         tm_init();
499         usb_init();
500
501         u32 last_blink = 0;
502
503         for (;;) {
504                 if (ms_ticks - last_blink >= 1000) {
505                         debug_led_toggle();
506                         last_blink = ms_ticks;
507                         tm_show();
508                 }
509
510                 if (usb_event_pending) {
511                         usbd_poll(usbd_dev);
512                         usb_event_pending = 0;
513                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
514                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
515                 }
516
517                 wait_for_interrupt();
518         }
519
520         return 0;
521 }