]> mj.ucw.cz Git - home-hw.git/blob - clock/firmware/main.c
Auto: Meditation mode turned off
[home-hw.git] / clock / firmware / main.c
1 /*
2  *      Workshop Clock
3  *
4  *      (c) 2020-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/i2c.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 static void ep82_send(u32 key_code);
25
26 /*** Hardware init ***/
27
28 static void clock_init(void)
29 {
30         rcc_clock_setup_pll(&rcc_hse_configs[RCC_CLOCK_HSE8_72MHZ]);
31
32         rcc_periph_clock_enable(RCC_GPIOA);
33         rcc_periph_clock_enable(RCC_GPIOB);
34         rcc_periph_clock_enable(RCC_GPIOC);
35         rcc_periph_clock_enable(RCC_I2C1);
36         rcc_periph_clock_enable(RCC_USART1);
37         rcc_periph_clock_enable(RCC_USB);
38         rcc_periph_clock_enable(RCC_TIM1);
39
40         rcc_periph_reset_pulse(RST_GPIOA);
41         rcc_periph_reset_pulse(RST_GPIOB);
42         rcc_periph_reset_pulse(RST_GPIOC);
43         rcc_periph_reset_pulse(RST_I2C1);
44         rcc_periph_reset_pulse(RST_USART1);
45         rcc_periph_reset_pulse(RST_USB);
46         rcc_periph_reset_pulse(RST_TIM1);
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         // PB7 = SDA for display controller
61         // PB6 = SCL for display controller
62         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO6 | GPIO7);
63
64         // PA8 = SFH5110 output (5V tolerant) connected to TIM1_CH1
65         gpio_set_mode(GPIOC, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO8);
66 }
67
68 static void usart_init(void)
69 {
70         usart_set_baudrate(USART1, 115200);
71         usart_set_databits(USART1, 8);
72         usart_set_stopbits(USART1, USART_STOPBITS_1);
73         usart_set_mode(USART1, USART_MODE_TX);
74         usart_set_parity(USART1, USART_PARITY_NONE);
75         usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
76
77         usart_enable(USART1);
78 }
79
80 /*** System ticks ***/
81
82 static volatile u32 ms_ticks;
83
84 void sys_tick_handler(void)
85 {
86         ms_ticks++;
87 }
88
89 static void tick_init(void)
90 {
91         systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
92         systick_counter_enable();
93         systick_interrupt_enable();
94 }
95
96 static void delay_ms(uint ms)
97 {
98         u32 start_ticks = ms_ticks;
99         while (ms_ticks - start_ticks < ms)
100                 ;
101 }
102
103 /*** Display ***/
104
105 /*
106  *      Display digits:
107  *
108  *                 ---- 40 ----
109  *               |              |
110  *               |              |
111  *              20              80
112  *               |              |
113  *               |              |
114  *                 ---- 10 ----
115  *               |              |
116  *               |              |
117  *              08              02
118  *               |              |
119  *               |              |
120  *                 ---- 04 ----
121  *                                      (01)
122  */
123
124 static byte disp[4];
125 static byte ctrl = 0x56;
126
127 static const byte disp_font[] = {
128         [0] = 0xee,
129         [1] = 0x82,
130         [2] = 0xdc,
131         [3] = 0xd6,
132         [4] = 0xb2,
133         [5] = 0x76,
134         [6] = 0x7e,
135         [7] = 0xc2,
136         [8] = 0xfe,
137         [9] = 0xf6,
138         [10] = 0xea,
139         [11] = 0x3e,
140         [12] = 0x6c,
141         [13] = 0x9e,
142         [14] = 0x7c,
143         [15] = 0x78,
144 };
145
146 static void display_update(void)
147 {
148         // debug_puts("Display update\n");
149
150         byte cmds[4];
151         cmds[0] = 0;
152         cmds[1] = ctrl;
153         cmds[2] = ((disp[1] & 0x88) >> 3) | ((disp[1] & 0x44) >> 1) | ((disp[1] & 0x22) << 1) | ((disp[1] & 0x11) << 3);
154         cmds[3] = disp[0];
155         i2c_transfer7(I2C1, 0x76/2, (byte *) cmds, sizeof(cmds), NULL, 0);
156
157         cmds[2] = ((disp[3] & 0x88) >> 3) | ((disp[3] & 0x44) >> 1) | ((disp[3] & 0x22) << 1) | ((disp[3] & 0x11) << 3);
158         cmds[3] = disp[2];
159         i2c_transfer7(I2C1, 0x70/2, (byte *) cmds, sizeof(cmds), NULL, 0);
160
161         // debug_puts("Update done\n");
162 }
163
164 static void display_init(void)
165 {
166         debug_puts("I2C init\n");
167         i2c_peripheral_disable(I2C1);
168         i2c_set_speed(I2C1, i2c_speed_sm_100k, rcc_apb1_frequency / 1000000);
169         i2c_peripheral_enable(I2C1);
170
171         disp[0] = 0x10;
172         disp[1] = 0x10;
173         disp[2] = 0x10;
174         disp[3] = 0x10;
175         display_update();
176 }
177
178 /*** Infrared Remote Control ***/
179
180 static void ir_init(void)
181 {
182         debug_puts("IR init\n");
183
184         // TIM1 will measure pulses and spaces between them with 1μs resolution
185         timer_set_prescaler(TIM1, 71);          // 72 MHz / 72 = 1 MHz
186         timer_set_mode(TIM1, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
187         timer_set_period(TIM1, 65535);
188         timer_update_on_overflow(TIM1);
189
190         // IC1 will trigger on TI1 (TIM1_CH1) falling edge
191         timer_ic_set_input(TIM1, TIM_IC1, TIM_IC_IN_TI1);
192         // timer_ic_set_filter(TIM1, TIM_IC1, TIM_IC_OFF);
193         timer_set_oc_polarity_low(TIM1, TIM_OC1);       // OC functions affect IC, too
194
195         // IC2 will trigger on TI1 (TIM1_CH1) rising edge
196         timer_ic_set_input(TIM1, TIM_IC2, TIM_IC_IN_TI1);
197         timer_set_oc_polarity_high(TIM1, TIM_OC2);
198
199         // OC3 will trigger on a break longer than 50 ms
200         timer_set_oc_mode(TIM1, TIM_OC3, TIM_OCM_ACTIVE);
201         timer_set_oc_value(TIM1, TIM_OC3, 30000);
202
203         // Program slave controller to reset the timer on IC1
204         timer_slave_set_trigger(TIM1, TIM_SMCR_TS_TI1FP1);
205         timer_slave_set_mode(TIM1, TIM_SMCR_SMS_RM);
206
207         // Request interrupts
208         timer_enable_irq(TIM1, TIM_DIER_CC1IE | TIM_DIER_CC2IE | TIM_DIER_CC3IE);
209         nvic_enable_irq(NVIC_TIM1_CC_IRQ);
210
211         // Enable ICs and OCs
212         timer_enable_oc_output(TIM1, TIM_OC1);
213         timer_enable_oc_output(TIM1, TIM_OC2);
214         timer_enable_oc_output(TIM1, TIM_OC3);
215
216         timer_enable_counter(TIM1);
217 }
218
219 // Circular queue of pulse durations
220 #define IR_MAX_PULSES 32
221 static u32 ir_pulses[IR_MAX_PULSES];    // Top 16 bits = mark, bottom 16 bits = space
222 static u16 ir_last_pulse;
223 static uint ir_pulses_rx, ir_pulses_tx;
224
225 #define IR_INF 0xffff
226
227 #define IR_MARK(x) (uint)((x) >> 16)
228 #define IR_SPACE(x) (uint)((x) & 0xffff)
229
230 static inline bool between(uint x, uint min, uint max)
231 {
232         return x >= min && x <= max;
233 }
234
235 static void ir_record_pulse(uint mark, uint space)
236 {
237         uint i = ir_pulses_tx;
238         ir_pulses_tx = (i + 1) % IR_MAX_PULSES;
239         if (ir_pulses_tx != ir_pulses_rx) {
240                 ir_pulses[i] = (mark << 16) | space;
241         } else {
242                 // Overflow detected
243                 ir_pulses[i] = (IR_INF << 16) | IR_INF;
244         }
245 }
246
247 void tim1_cc_isr(void)
248 {
249         if (TIM_SR(TIM1) & TIM_SR_CC1IF) {
250                 TIM_SR(TIM1) &= ~TIM_SR_CC1IF;
251                 u16 now = TIM_CCR1(TIM1);
252                 if (ir_last_pulse) {
253                         ir_record_pulse(ir_last_pulse, now - ir_last_pulse);
254                         ir_last_pulse = 0;
255                 }
256         }
257         if (TIM_SR(TIM1) & TIM_SR_CC2IF) {
258                 TIM_SR(TIM1) &= ~TIM_SR_CC2IF;
259                 ir_last_pulse = TIM_CCR2(TIM1);
260         }
261         if (TIM_SR(TIM1) & TIM_SR_CC3IF) {
262                 TIM_SR(TIM1) &= ~TIM_SR_CC3IF;
263                 if (ir_last_pulse) {
264                         ir_record_pulse(ir_last_pulse, IR_INF);
265                         ir_last_pulse = 0;
266                 }
267         }
268 }
269
270 static u32 ir_get_pulse(void)
271 {
272         u32 out = 0;
273
274         cm_disable_interrupts();
275         if (ir_pulses_rx != ir_pulses_tx) {
276                 out = ir_pulses[ir_pulses_rx];
277                 ir_pulses_rx = (ir_pulses_rx + 1) % IR_MAX_PULSES;
278         }
279         cm_enable_interrupts();
280         return out;
281 }
282
283 // Decoder for Onkyo RC-748S
284
285 static u32 ir_blink_start;
286
287 static void ir_decode(void)
288 {
289         u32 pulse = ir_get_pulse();
290         if (!pulse)
291                 return;
292
293         uint mark = IR_MARK(pulse);
294         uint space = IR_SPACE(pulse);
295
296 #ifdef IR_TEST
297         debug_printf("IR: %d %d\n", mark, space);
298         if (space == 65535)
299                 debug_putc('\n');
300         return;
301 #endif
302
303         static u16 ir_bits;
304         static u32 ir_code;
305 #define IR_ERR 0xff
306
307         // debug_printf("IR(%d): %d %d\n", ir_bits, mark, space);
308
309         if (space == IR_INF) {
310                 ir_bits = 0;
311         } else if (ir_bits == IR_ERR) {
312                 // Error state
313         } else if (ir_bits == 0) {
314                 // Start?
315                 if (between(mark, 8900, 9200)) {
316                         if (between(space, 4200, 4600)) {
317                                 ir_bits = 1;
318                                 ir_code = 0;
319                         } else if (between(space, 2000, 2300)) {
320                                 debug_printf("IR: => REP\n");
321                                 ir_bits = IR_ERR;
322                         }
323                 }
324         } else {
325                 if (between(mark, 500, 700)) {
326                         ir_bits++;
327                         if (between(space, 400, 700)) {
328                                 // 0
329                         } else if (between(space, 1500, 1800)) {
330                                 // 1
331                                 ir_code |= 1U << (33 - ir_bits);
332                         } else {
333                                 ir_bits = IR_ERR;
334                         }
335                         if (ir_bits == 33) {
336                                 debug_printf("IR: => %08x\n", (uint)ir_code);
337                                 disp[3] |= 0x01;
338                                 ir_blink_start = ms_ticks;
339                                 display_update();
340                                 ir_bits = IR_ERR;
341                                 ep82_send(ir_code);
342                         }
343                 } else {
344                         ir_bits = IR_ERR;
345                 }
346         }
347 }
348
349 /*** USB ***/
350
351 static usbd_device *usbd_dev;
352
353 enum usb_string {
354         STR_MANUFACTURER = 1,
355         STR_PRODUCT,
356         STR_SERIAL,
357 };
358
359 static char usb_serial_number[13];
360
361 static const char *usb_strings[] = {
362         "United Computer Wizards",
363         "Workshop Clock",
364         usb_serial_number,
365 };
366
367 static const struct usb_device_descriptor device = {
368         .bLength = USB_DT_DEVICE_SIZE,
369         .bDescriptorType = USB_DT_DEVICE,
370         .bcdUSB = 0x0200,
371         .bDeviceClass = 0xFF,
372         .bDeviceSubClass = 0,
373         .bDeviceProtocol = 0,
374         .bMaxPacketSize0 = 64,
375         .idVendor = 0x4242,
376         .idProduct = 0x000d,
377         .bcdDevice = 0x0000,
378         .iManufacturer = STR_MANUFACTURER,
379         .iProduct = STR_PRODUCT,
380         .iSerialNumber = STR_SERIAL,
381         .bNumConfigurations = 1,
382 };
383
384 static const struct usb_endpoint_descriptor endpoints[] = {{
385         // Bulk end-point for sending values to the display
386         .bLength = USB_DT_ENDPOINT_SIZE,
387         .bDescriptorType = USB_DT_ENDPOINT,
388         .bEndpointAddress = 0x01,
389         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
390         .wMaxPacketSize = 64,
391         .bInterval = 1,
392 }, {
393         // Bulk end-point for receiving remote control keys
394         .bLength = USB_DT_ENDPOINT_SIZE,
395         .bDescriptorType = USB_DT_ENDPOINT,
396         .bEndpointAddress = 0x82,
397         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
398         .wMaxPacketSize = 4,
399         .bInterval = 1,
400 }};
401
402 static const struct usb_interface_descriptor iface = {
403         .bLength = USB_DT_INTERFACE_SIZE,
404         .bDescriptorType = USB_DT_INTERFACE,
405         .bInterfaceNumber = 0,
406         .bAlternateSetting = 0,
407         .bNumEndpoints = 2,
408         .bInterfaceClass = 0xFF,
409         .bInterfaceSubClass = 0,
410         .bInterfaceProtocol = 0,
411         .iInterface = 0,
412         .endpoint = endpoints,
413 };
414
415 static const struct usb_dfu_descriptor dfu_function = {
416         .bLength = sizeof(struct usb_dfu_descriptor),
417         .bDescriptorType = DFU_FUNCTIONAL,
418         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
419         .wDetachTimeout = 255,
420         .wTransferSize = 1024,
421         .bcdDFUVersion = 0x0100,
422 };
423
424 static const struct usb_interface_descriptor dfu_iface = {
425         .bLength = USB_DT_INTERFACE_SIZE,
426         .bDescriptorType = USB_DT_INTERFACE,
427         .bInterfaceNumber = 1,
428         .bAlternateSetting = 0,
429         .bNumEndpoints = 0,
430         .bInterfaceClass = 0xFE,
431         .bInterfaceSubClass = 1,
432         .bInterfaceProtocol = 1,
433         .iInterface = 0,
434
435         .extra = &dfu_function,
436         .extralen = sizeof(dfu_function),
437 };
438
439 static const struct usb_interface ifaces[] = {{
440         .num_altsetting = 1,
441         .altsetting = &iface,
442 }, {
443         .num_altsetting = 1,
444         .altsetting = &dfu_iface,
445 }};
446
447 static const struct usb_config_descriptor config = {
448         .bLength = USB_DT_CONFIGURATION_SIZE,
449         .bDescriptorType = USB_DT_CONFIGURATION,
450         .wTotalLength = 0,
451         .bNumInterfaces = 2,
452         .bConfigurationValue = 1,
453         .iConfiguration = 0,
454         .bmAttributes = 0x80,
455         .bMaxPower = 50,        // multiplied by 2 mA
456         .interface = ifaces,
457 };
458
459 static bool usb_configured;
460 static uint8_t usbd_control_buffer[64];
461
462 static bool usb_tx_in_flight;
463 static byte ep82_tx_buffer[4];
464
465 static byte disp_alive;
466
467 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
468 {
469         // Reset to bootloader, which implements the rest of DFU
470         debug_printf("Switching to DFU\n");
471         debug_flush();
472         scb_reset_core();
473 }
474
475 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
476         struct usb_setup_data *req,
477         uint8_t **buf UNUSED,
478         uint16_t *len UNUSED,
479         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
480 {
481         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
482                 return USBD_REQ_NOTSUPP;
483
484         *complete = dfu_detach_complete;
485         return USBD_REQ_HANDLED;
486 }
487
488 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
489 {
490         // We received a frame from the USB host
491         byte buf[8];
492         uint len = usbd_ep_read_packet(dev, 0x01, buf, 8);
493         debug_printf("USB: Host sent %u bytes\n", len);
494         if (len >= 5) {
495                 for (uint i=0; i<4; i++) {
496                         disp[i] &= 0x01;
497                         if (buf[i] < 16)
498                                 disp[i] |= disp_font[buf[i]];
499                 }
500                 disp[1] &= 0xfe;
501                 if (buf[4])
502                         disp[1] |= 0x01;
503                 display_update();
504                 disp_alive = 10;
505         }
506 }
507
508 static void ep82_send(u32 key_code)
509 {
510         if (!usb_configured)
511                 return;
512
513         if (usb_tx_in_flight) {
514                 debug_printf("USB: Send overrun!\n");
515                 return;
516         }
517
518         debug_printf("USB: Sending key to host\n");
519         put_u32_be(ep82_tx_buffer, key_code);
520         usbd_ep_write_packet(usbd_dev, 0x82, ep82_tx_buffer, 4);
521         usb_tx_in_flight = true;
522 }
523
524 static void ep82_cb(usbd_device *dev UNUSED, uint8_t ep UNUSED)
525 {
526         // We completed sending a frame to the USB host
527         usb_tx_in_flight = false;
528         debug_printf("USB: Key sending complete\n");
529 }
530
531 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
532 {
533         usbd_register_control_callback(
534                 dev,
535                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
536                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
537                 dfu_control_cb);
538         usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
539         usbd_ep_setup(dev, 0x82, USB_ENDPOINT_ATTR_BULK, 4, ep82_cb);
540         usb_configured = true;
541         usb_tx_in_flight = false;
542 }
543
544 static void reset_cb(void)
545 {
546         debug_printf("USB: Reset\n");
547         usb_configured = false;
548 }
549
550 static volatile bool usb_event_pending;
551
552 void usb_lp_can_rx0_isr(void)
553 {
554         /*
555          *  We handle USB in the main loop to avoid race conditions between
556          *  USB interrupts and other code. However, we need an interrupt to
557          *  up the main loop from sleep.
558          *
559          *  We set up only the low-priority ISR, because high-priority ISR handles
560          *  only double-buffered bulk transfers and isochronous transfers.
561          */
562         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
563         usb_event_pending = 1;
564 }
565
566 static void usb_init(void)
567 {
568         // Simulate USB disconnect
569         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
570         gpio_clear(GPIOA, GPIO11 | GPIO12);
571         delay_ms(100);
572
573         usbd_dev = usbd_init(
574                 &st_usbfs_v1_usb_driver,
575                 &device,
576                 &config,
577                 usb_strings,
578                 ARRAY_SIZE(usb_strings),
579                 usbd_control_buffer,
580                 sizeof(usbd_control_buffer)
581         );
582         usbd_register_reset_callback(usbd_dev, reset_cb);
583         usbd_register_set_config_callback(usbd_dev, set_config_cb);
584         usb_event_pending = 1;
585 }
586
587 /*** Main ***/
588
589 int main(void)
590 {
591         clock_init();
592         gpio_init();
593         usart_init();
594
595         tick_init();
596         desig_get_unique_id_as_dfu(usb_serial_number);
597
598         debug_printf("Hello, world!\n");
599
600         usb_init();
601         display_init();
602         ir_init();
603
604         u32 last_blink = 0;
605
606         for (;;) {
607                 if (ms_ticks - last_blink >= 500) {
608                         debug_led_toggle();
609                         last_blink = ms_ticks;
610                         if (disp_alive) {
611                                 if (!--disp_alive) {
612                                         disp[0] = (disp[0] & 0x01) | 0x10;
613                                         disp[1] = (disp[1] & 0x01) | 0x10;
614                                         disp[2] = (disp[2] & 0x01) | 0x10;
615                                         disp[3] = (disp[3] & 0x01) | 0x10;
616                                 }
617                         }
618                         display_update();
619                 }
620
621                 if ((disp[3] & 0x01) && ms_ticks - ir_blink_start >= 100) {
622                         disp[3] &= 0xfe;
623                         display_update();
624                 }
625
626                 ir_decode();
627
628                 if (usb_event_pending) {
629                         usbd_poll(usbd_dev);
630                         usb_event_pending = 0;
631                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
632                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
633                 }
634
635                 wait_for_interrupt();
636         }
637
638         return 0;
639 }