]> mj.ucw.cz Git - home-hw.git/blob - bsb/firmware/main.c
e7237e1cf5101cc6f7fdb8b269a34fa5c2773e8e
[home-hw.git] / bsb / firmware / main.c
1 /*
2  *      Boiler System Bus Gateway
3  *
4  *      (c) 2020 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/timer.h>
17 #include <libopencm3/stm32/usart.h>
18 #include <libopencm3/usb/dfu.h>
19 #include <libopencm3/usb/usbd.h>
20
21 #include <string.h>
22
23 /*** Hardware init ***/
24
25 static void clock_init(void)
26 {
27         rcc_clock_setup_in_hse_8mhz_out_72mhz();
28
29         rcc_periph_clock_enable(RCC_GPIOA);
30         rcc_periph_clock_enable(RCC_GPIOB);
31         rcc_periph_clock_enable(RCC_GPIOC);
32         rcc_periph_clock_enable(RCC_USART1);
33         rcc_periph_clock_enable(RCC_USB);
34
35         rcc_periph_reset_pulse(RST_GPIOA);
36         rcc_periph_reset_pulse(RST_GPIOB);
37         rcc_periph_reset_pulse(RST_GPIOC);
38         rcc_periph_reset_pulse(RST_USART1);
39         rcc_periph_reset_pulse(RST_USB);
40 }
41
42 static void gpio_init(void)
43 {
44         // PA9 = TXD1 for debugging console
45         // PA10 = RXD1 for debugging console
46         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
47         gpio_set_mode(GPIOA, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO10);
48
49         // PC13 = BluePill LED
50         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
51         gpio_clear(GPIOC, GPIO13);
52
53         // PB0 = yellow LED*, PB1 = green LED*
54         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO0 | GPIO1);
55         gpio_set(GPIOB, GPIO0 | GPIO1);
56
57         // PB10 = TXD3 for BSB
58         // PB11 = RXD3 for BSB
59         // FIXME: TX turned off temporarily
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_RX);
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, 72000000);
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 /*** BSB ***/
100
101 #define BSB_MAX_SIZE 32
102 #define BSB_RX_TIMEOUT 2  // 1-2 ms => 2-4 byte periods of silence
103
104 static byte bsb_rx_buf[BSB_MAX_SIZE];
105 static byte bsb_rx_len;
106 static volatile u32 bsb_rx_timestamp;
107
108 // Passing received frames to the main loop
109 static byte bsb_rx_frame[BSB_MAX_SIZE];
110 static volatile byte bsb_rx_frame_len;
111 static byte bsb_rx_frame_led;
112
113 struct bsb_stat {
114         u32 rx_noise;
115         u32 rx_errors;
116         u32 rx_invalid;
117         u32 rx_overruns;
118         u32 rx_timeouts;
119 };
120
121 static struct bsb_stat bsb_stat;
122
123 void usart3_isr(void)
124 {
125         u32 status = USART_SR(USART3);
126
127         if (status & USART_SR_RXNE) {
128                 uint ch = usart_recv(USART3);
129                 bsb_rx_timestamp = ms_ticks;
130
131                 if (status & (USART_SR_FE | USART_SR_ORE | USART_SR_NE)) {
132                         bsb_stat.rx_errors++;
133                         bsb_rx_len = 0;
134                 } else if (!bsb_rx_len && ch != 0xdc) {
135                         // Waiting for start of frame
136                         bsb_stat.rx_noise++;
137                 } else {
138                         bsb_rx_buf[bsb_rx_len++] = ch;
139                         if (bsb_rx_len < 4) {
140                                 // First three bytes: SOF, source addr, destination addr
141                         } else if (bsb_rx_len == 4) {
142                                 // Received length byte
143                                 if (bsb_rx_buf[3] < 7 || bsb_rx_buf[3] > BSB_MAX_SIZE) {
144                                         bsb_stat.rx_invalid++;
145                                         bsb_rx_len = 0;
146                                 }
147                         } else if (bsb_rx_len == bsb_rx_buf[3]) {
148                                 // Received a complete frame: pass it to the main loop
149                                 if (bsb_rx_frame_len) {
150                                         // The previous one was not sent yet
151                                         bsb_stat.rx_overruns++;
152                                 } else {
153                                         memcpy(bsb_rx_frame, bsb_rx_buf, bsb_rx_buf[3]);
154                                         barrier();
155                                         bsb_rx_frame_len = bsb_rx_buf[3];
156                                         bsb_rx_frame_led = 100;
157                                         gpio_clear(GPIOB, GPIO1);
158                                 }
159                         }
160                 }
161         }
162 }
163
164 static void bsb_init(void)
165 {
166         usart_set_baudrate(USART3, 4800);
167         usart_set_databits(USART3, 9);
168         usart_set_stopbits(USART3, USART_STOPBITS_1);
169         usart_set_mode(USART3, USART_MODE_TX_RX);
170         usart_set_parity(USART3, USART_PARITY_ODD);
171         usart_set_flow_control(USART3, USART_FLOWCONTROL_NONE);
172
173         usart_enable(USART3);
174         nvic_enable_irq(NVIC_USART3_IRQ);
175         usart_enable_rx_interrupt(USART3);
176 }
177
178 /*** USB ***/
179
180 static usbd_device *usbd_dev;
181
182 static const struct usb_device_descriptor device = {
183         .bLength = USB_DT_DEVICE_SIZE,
184         .bDescriptorType = USB_DT_DEVICE,
185         .bcdUSB = 0x0200,
186         .bDeviceClass = 0xFF,
187         .bDeviceSubClass = 0,
188         .bDeviceProtocol = 0,
189         .bMaxPacketSize0 = 64,
190         .idVendor = 0x4242,
191         .idProduct = 0x0003,
192         .bcdDevice = 0x0200,
193         .iManufacturer = 1,
194         .iProduct = 2,
195         .iSerialNumber = 3,
196         .bNumConfigurations = 1,
197 };
198
199 static const struct usb_endpoint_descriptor endpoints[] = {{
200         .bLength = USB_DT_ENDPOINT_SIZE,
201         .bDescriptorType = USB_DT_ENDPOINT,
202         .bEndpointAddress = 0x81,
203         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
204         .wMaxPacketSize = 64,
205         .bInterval = 1,
206 },{
207         .bLength = USB_DT_ENDPOINT_SIZE,
208         .bDescriptorType = USB_DT_ENDPOINT,
209         .bEndpointAddress = 0x82,
210         .bmAttributes = USB_ENDPOINT_ATTR_INTERRUPT,
211         .wMaxPacketSize = 64,
212         .bInterval = 1,
213 }};
214
215 static const struct usb_interface_descriptor iface = {
216         .bLength = USB_DT_INTERFACE_SIZE,
217         .bDescriptorType = USB_DT_INTERFACE,
218         .bInterfaceNumber = 0,
219         .bAlternateSetting = 0,
220         .bNumEndpoints = 2,
221         .bInterfaceClass = 0xFF,
222         .bInterfaceSubClass = 0,
223         .bInterfaceProtocol = 0,
224         .iInterface = 0,
225         .endpoint = endpoints,
226 };
227
228 static const struct usb_dfu_descriptor dfu_function = {
229         .bLength = sizeof(struct usb_dfu_descriptor),
230         .bDescriptorType = DFU_FUNCTIONAL,
231         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
232         .wDetachTimeout = 255,
233         .wTransferSize = 1024,
234         .bcdDFUVersion = 0x0100,
235 };
236
237 static const struct usb_interface_descriptor dfu_iface = {
238         .bLength = USB_DT_INTERFACE_SIZE,
239         .bDescriptorType = USB_DT_INTERFACE,
240         .bInterfaceNumber = 1,
241         .bAlternateSetting = 0,
242         .bNumEndpoints = 0,
243         .bInterfaceClass = 0xFE,
244         .bInterfaceSubClass = 1,
245         .bInterfaceProtocol = 1,
246         .iInterface = 0,
247
248         .extra = &dfu_function,
249         .extralen = sizeof(dfu_function),
250 };
251
252 static const struct usb_interface ifaces[] = {{
253         .num_altsetting = 1,
254         .altsetting = &iface,
255 }, {
256         .num_altsetting = 1,
257         .altsetting = &dfu_iface,
258 }};
259
260 static const struct usb_config_descriptor config = {
261         .bLength = USB_DT_CONFIGURATION_SIZE,
262         .bDescriptorType = USB_DT_CONFIGURATION,
263         .wTotalLength = 0,
264         .bNumInterfaces = 2,
265         .bConfigurationValue = 1,
266         .iConfiguration = 0,
267         .bmAttributes = 0x80,
268         .bMaxPower = 50,        // multiplied by 2 mA
269         .interface = ifaces,
270 };
271
272 static char usb_serial_number[13];
273
274 static const char *usb_strings[] = {
275         "United Computer Wizards",
276         "BSB Gateway",
277         usb_serial_number,
278 };
279
280 static byte usb_configured;
281 static byte usb_rx_pending;
282 static uint8_t usbd_control_buffer[64];
283
284 static enum usbd_request_return_codes control_cb(
285         usbd_device *dev UNUSED,
286         struct usb_setup_data *req,
287         uint8_t **buf,
288         uint16_t *len,
289         void (**complete)(usbd_device *dev, struct usb_setup_data *req) UNUSED)
290 {
291         if (req->bmRequestType != 0xc0 || req->bRequest != 0x00)
292                 return USBD_REQ_NOTSUPP;
293
294         // We support reading of statistics via control requests
295         debug_printf("USB: Control request: Read statistics\n");
296         uint n = MIN(*len, sizeof(bsb_stat));
297         memcpy(*buf, (char *) &bsb_stat, n);
298         *len = n;
299
300         return USBD_REQ_HANDLED;
301 }
302
303 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
304 {
305         // Reset to bootloader, which implements the rest of DFU
306         debug_printf("Switching to DFU\n");
307         debug_flush();
308         scb_reset_core();
309 }
310
311 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
312         struct usb_setup_data *req,
313         uint8_t **buf UNUSED,
314         uint16_t *len UNUSED,
315         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
316 {
317         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
318                 return USBD_REQ_NOTSUPP;
319
320         *complete = dfu_detach_complete;
321         return USBD_REQ_HANDLED;
322 }
323
324 static void ep81_cb(usbd_device *dev, uint8_t ep UNUSED)
325 {
326         byte buf[4];
327         put_u32_be(buf, ms_ticks);
328         usbd_ep_write_packet(dev, 0x81, buf, sizeof(buf));
329         debug_printf("USB: Bulk write\n");
330 }
331
332 static void rx_cb(usbd_device *dev UNUSED, uint8_t ep UNUSED)
333 {
334         // Received packet passed through interrupt end-point
335         debug_printf("USB: RX EP done\n");
336         usb_rx_pending = 0;
337 }
338
339 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
340 {
341         usbd_register_control_callback(dev,
342                 USB_REQ_TYPE_VENDOR,
343                 USB_REQ_TYPE_TYPE,
344                 control_cb);
345         usbd_register_control_callback(dev,
346                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
347                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
348                 dfu_control_cb);
349         usbd_ep_setup(dev, 0x81, USB_ENDPOINT_ATTR_BULK, 64, ep81_cb);
350         usbd_ep_setup(dev, 0x82, USB_ENDPOINT_ATTR_BULK, 64, rx_cb);
351         ep81_cb(dev, 0);
352         usb_configured = 1;
353 }
354
355 static void reset_cb(void)
356 {
357         debug_printf("USB: Reset\n");
358         usb_configured = 0;
359 }
360
361 static volatile bool usb_event_pending;
362
363 void usb_lp_can_rx0_isr(void)
364 {
365         /*
366          *  We handle USB in the main loop to avoid race conditions between
367          *  USB interrupts and other code. However, we need an interrupt to
368          *  up the main loop from sleep.
369          *
370          *  We set up only the low-priority ISR, because high-priority ISR handles
371          *  only double-buffered bulk transfers and isochronous transfers.
372          */
373         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
374         usb_event_pending = 1;
375 }
376
377 static void usb_init(void)
378 {
379         // Simulate USB disconnect
380         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
381         gpio_clear(GPIOA, GPIO11 | GPIO12);
382         delay_ms(1000);
383
384         usbd_dev = usbd_init(
385                 &st_usbfs_v1_usb_driver,
386                 &device,
387                 &config,
388                 usb_strings,
389                 ARRAY_SIZE(usb_strings),
390                 usbd_control_buffer,
391                 sizeof(usbd_control_buffer)
392         );
393         usbd_register_reset_callback(usbd_dev, reset_cb);
394         usbd_register_set_config_callback(usbd_dev, set_config_cb);
395         usb_event_pending = 1;
396 }
397
398 /*** Main ***/
399
400 int main(void)
401 {
402         clock_init();
403         gpio_init();
404         tick_init();
405         usart_init();
406         desig_get_unique_id_as_dfu(usb_serial_number);
407
408         debug_printf("Hello, kitty!\n");
409
410         bsb_init();
411         usb_init();
412
413         u32 last_ds_step = 0;
414
415         for (;;) {
416                 if (ms_ticks - last_ds_step >= 100) {
417                         debug_led_toggle();
418                         gpio_toggle(GPIOB, GPIO0);
419                         last_ds_step = ms_ticks;
420                 }
421
422                 if (usb_event_pending) {
423                         usbd_poll(usbd_dev);
424                         usb_event_pending = 0;
425                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
426                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
427                 }
428
429                 if (usb_configured) {
430                         // Passing of received packets to USB
431                         if (!usb_rx_pending) {
432                                 if (bsb_rx_frame_len) {
433                                         barrier();
434                                         usbd_ep_write_packet(usbd_dev, 0x82, bsb_rx_frame, bsb_rx_frame_len);
435                                         usb_rx_pending = 1;
436                                         barrier();
437                                         bsb_rx_frame_len = 0;
438                                         debug_printf("USB: RX started\n");
439                                 }
440                         }
441                 }
442
443                 // Packet timeouts
444                 cm_disable_interrupts();
445                 barrier();
446                 if (bsb_rx_len && (bsb_rx_timestamp - ms_ticks) >= BSB_RX_TIMEOUT) {
447                         bsb_rx_len = 0;
448                         bsb_stat.rx_timeouts++;
449                 }
450                 if (bsb_rx_frame_led) {
451                         if (!--bsb_rx_frame_led)
452                                 gpio_set(GPIOB, GPIO1);
453                 }
454                 cm_enable_interrupts();
455
456                 wait_for_interrupt();
457         }
458
459         return 0;
460 }