]> mj.ucw.cz Git - home-hw.git/blob - dmx/firmware/main.c
DMX: USB interface
[home-hw.git] / dmx / firmware / main.c
1 /*
2  *      DMX512 Interface
3  *
4  *      (c) 2020 Martin Mareš <mj@ucw.cz>
5  */
6
7 #include "util.h"
8 #include "interface.h"
9
10 #include <libopencm3/cm3/cortex.h>
11 #include <libopencm3/cm3/nvic.h>
12 #include <libopencm3/cm3/systick.h>
13 #include <libopencm3/cm3/scb.h>
14 #include <libopencm3/stm32/rcc.h>
15 #include <libopencm3/stm32/desig.h>
16 #include <libopencm3/stm32/gpio.h>
17 #include <libopencm3/stm32/timer.h>
18 #include <libopencm3/stm32/usart.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_in_hse_8mhz_out_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_TIM3);
34         rcc_periph_clock_enable(RCC_USART1);
35         rcc_periph_clock_enable(RCC_USART3);
36         rcc_periph_clock_enable(RCC_USB);
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_TIM3);
42         rcc_periph_reset_pulse(RST_USART1);
43         rcc_periph_reset_pulse(RST_USART3);
44         rcc_periph_reset_pulse(RST_USB);
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         // PB10 = TXD3 for DMX
59         // PB11 = RXD3 for DMX
60         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO10);
61         gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO11);
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 /*** DMX ***/
100
101 #define DMX_MAX_PACKET_SIZE 64
102
103 static volatile byte dmx_state;
104 static byte dmx_packet[DMX_MAX_PACKET_SIZE];
105 static byte dmx_pos, dmx_len;
106
107 static byte dmx_next_packet[DMX_MAX_PACKET_SIZE];
108 static byte dmx_next_len;
109
110 #undef DEBUG_DMX
111 #ifdef DEBUG_DMX
112 #define DMX_DEBUG(ch) debug_putc(ch)
113 #else
114 #define DMX_DEBUG(ch) do { } while (0)
115 #endif
116
117 enum dmx_state {
118         DMX_STATE_IDLE = 0,
119         DMX_STATE_BREAK,
120         DMX_STATE_MARK,
121         DMX_STATE_DATA,
122         DMX_STATE_LAST_BYTE,
123         DMX_STATE_GAP,
124 };
125
126 static void dmx_init(void)
127 {
128         usart_set_baudrate(USART3, 250000);
129         usart_set_databits(USART3, 8);
130         usart_set_stopbits(USART3, USART_STOPBITS_2);
131         usart_set_mode(USART3, USART_MODE_TX);
132         usart_set_parity(USART3, USART_PARITY_NONE);
133         usart_set_flow_control(USART3, USART_FLOWCONTROL_NONE);
134         nvic_enable_irq(NVIC_USART3_IRQ);
135
136         usart_enable(USART3);
137
138         timer_set_prescaler(TIM3, CPU_CLOCK_MHZ - 1);   // 1 MHz
139         timer_set_mode(TIM3, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
140         timer_update_on_overflow(TIM3);
141         timer_disable_preload(TIM3);
142         timer_one_shot_mode(TIM3);
143         timer_enable_irq(TIM3, TIM_DIER_UIE);
144         nvic_enable_irq(NVIC_TIM3_IRQ);
145
146         // Until we get data from USB, send "turn everything off" packets
147         memset(dmx_next_packet, 0, DMX_MAX_PACKET_SIZE);
148         dmx_next_len = DMX_MAX_PACKET_SIZE;
149 }
150
151 void tim3_isr(void)
152 {
153         if (TIM_SR(TIM3) & TIM_SR_UIF) {
154                 TIM_SR(TIM3) &= ~TIM_SR_UIF;
155                 switch (dmx_state) {
156                         case DMX_STATE_BREAK:
157                                 // Send mark for 50 μs
158                                 DMX_DEBUG('m');
159                                 dmx_state = DMX_STATE_MARK;
160                                 gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO10);
161                                 timer_set_period(TIM3, 199);
162                                 timer_generate_event(TIM3, TIM_EGR_UG);
163                                 timer_enable_counter(TIM3);
164                                 break;
165                         case DMX_STATE_MARK:
166                                 // Start sending data bytes
167                                 DMX_DEBUG('d');
168                                 dmx_state = DMX_STATE_DATA;
169                                 usart_enable_tx_interrupt(USART3);
170                                 break;
171                         case DMX_STATE_GAP:
172                                 DMX_DEBUG('>');
173                                 dmx_state = DMX_STATE_IDLE;
174                                 break;
175                 }
176         }
177 }
178
179 void usart3_isr(void)
180 {
181         u32 status = USART_SR(USART3);
182
183         if (dmx_state == DMX_STATE_DATA) {
184                 if (status & USART_SR_TXE) {
185                         if (dmx_pos < dmx_len) {
186                                 DMX_DEBUG('.');
187                                 usart_send(USART3, dmx_packet[dmx_pos++]);
188                         } else {
189                                 // The transmitter is double-buffered, so at this moment, it is transmitting
190                                 // the last byte of the frame. Wait until transfer is completed.
191                                 DMX_DEBUG('l');
192                                 usart_disable_tx_interrupt(USART3);
193                                 USART_CR1(USART3) |= USART_CR1_TCIE;
194                                 dmx_state = DMX_STATE_LAST_BYTE;
195                         }
196                 }
197         } else if (dmx_state == DMX_STATE_LAST_BYTE) {
198                 // Transfer of the last byte is complete, but we have to wait
199                 // before the start of the next packet: minimum time between two
200                 // breaks must be at least 1204 μs. We already sent a 200μs break,
201                 // 200μs mark, and dmx_len 44μs data slots.
202                 USART_CR1(USART3) &= ~USART_CR1_TCIE;
203                 uint sent = 200 + 200 + 44*dmx_len;
204                 if (sent < 1300) {
205                         DMX_DEBUG('g');
206                         dmx_state = DMX_STATE_GAP;
207                         timer_set_period(TIM3, 1300 - sent - 1);
208                         timer_generate_event(TIM3, TIM_EGR_UG);
209                         timer_enable_counter(TIM3);
210                 } else {
211                         DMX_DEBUG('>');
212                         dmx_state = DMX_STATE_IDLE;
213                 }
214         }
215 }
216
217 static void dmx_send(void)
218 {
219         if (dmx_state != DMX_STATE_IDLE)
220                 return;
221
222         if (!dmx_len)
223                 return;
224
225         dmx_pos = 0;
226
227         // Send break for 200 μs
228         DMX_DEBUG('<');
229         dmx_state = DMX_STATE_BREAK;
230         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO10);
231         gpio_clear(GPIOB, GPIO10);
232
233         timer_set_period(TIM3, 199);
234         timer_generate_event(TIM3, TIM_EGR_UG);
235         timer_enable_counter(TIM3);
236 }
237
238 /*** USB ***/
239
240 static usbd_device *usbd_dev;
241
242 enum usb_string {
243         STR_MANUFACTURER = 1,
244         STR_PRODUCT,
245         STR_SERIAL,
246 };
247
248 static char usb_serial_number[13];
249
250 static const char *usb_strings[] = {
251         "United Computer Wizards",
252         "DMX512 Interface",
253         usb_serial_number,
254 };
255
256 static const struct usb_device_descriptor device = {
257         .bLength = USB_DT_DEVICE_SIZE,
258         .bDescriptorType = USB_DT_DEVICE,
259         .bcdUSB = 0x0200,
260         .bDeviceClass = 0xFF,
261         .bDeviceSubClass = 0,
262         .bDeviceProtocol = 0,
263         .bMaxPacketSize0 = 64,
264         .idVendor = DMX_USB_VENDOR,
265         .idProduct = DMX_USB_PRODUCT,
266         .bcdDevice = DMX_USB_VERSION,
267         .iManufacturer = STR_MANUFACTURER,
268         .iProduct = STR_PRODUCT,
269         .iSerialNumber = STR_SERIAL,
270         .bNumConfigurations = 1,
271 };
272
273 static const struct usb_endpoint_descriptor endpoints[] = {{
274         // Bulk end-point for sending values to DMX
275         .bLength = USB_DT_ENDPOINT_SIZE,
276         .bDescriptorType = USB_DT_ENDPOINT,
277         .bEndpointAddress = 0x01,
278         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
279         .wMaxPacketSize = 64,
280         .bInterval = 1,
281 }};
282
283 static const struct usb_interface_descriptor iface = {
284         .bLength = USB_DT_INTERFACE_SIZE,
285         .bDescriptorType = USB_DT_INTERFACE,
286         .bInterfaceNumber = 0,
287         .bAlternateSetting = 0,
288         .bNumEndpoints = 1,
289         .bInterfaceClass = 0xFF,
290         .bInterfaceSubClass = 0,
291         .bInterfaceProtocol = 0,
292         .iInterface = 0,
293         .endpoint = endpoints,
294 };
295
296 static const struct usb_dfu_descriptor dfu_function = {
297         .bLength = sizeof(struct usb_dfu_descriptor),
298         .bDescriptorType = DFU_FUNCTIONAL,
299         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
300         .wDetachTimeout = 255,
301         .wTransferSize = 1024,
302         .bcdDFUVersion = 0x0100,
303 };
304
305 static const struct usb_interface_descriptor dfu_iface = {
306         .bLength = USB_DT_INTERFACE_SIZE,
307         .bDescriptorType = USB_DT_INTERFACE,
308         .bInterfaceNumber = 1,
309         .bAlternateSetting = 0,
310         .bNumEndpoints = 0,
311         .bInterfaceClass = 0xFE,
312         .bInterfaceSubClass = 1,
313         .bInterfaceProtocol = 1,
314         .iInterface = 0,
315
316         .extra = &dfu_function,
317         .extralen = sizeof(dfu_function),
318 };
319
320 static const struct usb_interface ifaces[] = {{
321         .num_altsetting = 1,
322         .altsetting = &iface,
323 }, {
324         .num_altsetting = 1,
325         .altsetting = &dfu_iface,
326 }};
327
328 static const struct usb_config_descriptor config = {
329         .bLength = USB_DT_CONFIGURATION_SIZE,
330         .bDescriptorType = USB_DT_CONFIGURATION,
331         .wTotalLength = 0,
332         .bNumInterfaces = 2,
333         .bConfigurationValue = 1,
334         .iConfiguration = 0,
335         .bmAttributes = 0x80,
336         .bMaxPower = 50,        // multiplied by 2 mA
337         .interface = ifaces,
338 };
339
340 static byte usb_configured;
341 static uint8_t usbd_control_buffer[64];
342
343 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
344 {
345         // Reset to bootloader, which implements the rest of DFU
346         debug_printf("Switching to DFU\n");
347         debug_flush();
348         scb_reset_core();
349 }
350
351 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
352         struct usb_setup_data *req,
353         uint8_t **buf UNUSED,
354         uint16_t *len UNUSED,
355         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
356 {
357         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
358                 return USBD_REQ_NOTSUPP;
359
360         *complete = dfu_detach_complete;
361         return USBD_REQ_HANDLED;
362 }
363
364 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
365 {
366         // We received a frame from the USB host
367         uint len = usbd_ep_read_packet(dev, 0x01, dmx_next_packet, DMX_MAX_PACKET_SIZE);
368         debug_printf("USB: Host sent %u bytes\n", len);
369         dmx_next_len = len;
370 }
371
372 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
373 {
374         usbd_register_control_callback(
375                 dev,
376                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
377                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
378                 dfu_control_cb);
379         usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
380         usb_configured = 1;
381 }
382
383 static void reset_cb(void)
384 {
385         debug_printf("USB: Reset\n");
386         usb_configured = 0;
387 }
388
389 static volatile bool usb_event_pending;
390
391 void usb_lp_can_rx0_isr(void)
392 {
393         /*
394          *  We handle USB in the main loop to avoid race conditions between
395          *  USB interrupts and other code. However, we need an interrupt to
396          *  up the main loop from sleep.
397          *
398          *  We set up only the low-priority ISR, because high-priority ISR handles
399          *  only double-buffered bulk transfers and isochronous transfers.
400          */
401         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
402         usb_event_pending = 1;
403 }
404
405 static void usb_init(void)
406 {
407         // Simulate USB disconnect
408         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
409         gpio_clear(GPIOA, GPIO11 | GPIO12);
410         delay_ms(100);
411
412         usbd_dev = usbd_init(
413                 &st_usbfs_v1_usb_driver,
414                 &device,
415                 &config,
416                 usb_strings,
417                 ARRAY_SIZE(usb_strings),
418                 usbd_control_buffer,
419                 sizeof(usbd_control_buffer)
420         );
421         usbd_register_reset_callback(usbd_dev, reset_cb);
422         usbd_register_set_config_callback(usbd_dev, set_config_cb);
423         usb_event_pending = 1;
424 }
425
426 /*** Main ***/
427
428 int main(void)
429 {
430         clock_init();
431         gpio_init();
432         tick_init();
433         usart_init();
434         desig_get_unique_id_as_dfu(usb_serial_number);
435
436         debug_printf("Hail, Lord Damian! Thy DMX interface is ready.\n");
437
438         usb_init();
439         dmx_init();
440
441         u32 last_blink = 0;
442         u32 last_send = 0;
443
444         for (;;) {
445                 if (ms_ticks - last_blink >= 100) {
446                         debug_led_toggle();
447                         last_blink = ms_ticks;
448                         dmx_send();
449                 }
450
451                 if (usb_event_pending) {
452                         usbd_poll(usbd_dev);
453                         usb_event_pending = 0;
454                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
455                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
456                 }
457
458                 if (dmx_state == DMX_STATE_IDLE) {
459                         if (dmx_next_len) {
460                                 // We have a new packet to send
461                                 debug_printf("Sending new packet: %d bytes\n", dmx_next_len);
462                                 memcpy(dmx_packet, dmx_next_packet, dmx_next_len);
463                                 dmx_len = dmx_next_len;
464                                 dmx_next_len = 0;
465                                 dmx_send();
466                                 last_send = ms_ticks;
467                         } else if (ms_ticks - last_send >= 100) {
468                                 // Re-send every 100 ms
469                                 // debug_printf("Re-send: %d bytes\n", dmx_len);
470                                 dmx_send();
471                                 last_send = ms_ticks;
472                         }
473                 }
474
475                 wait_for_interrupt();
476         }
477
478         return 0;
479 }