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