]> mj.ucw.cz Git - home-hw.git/blob - test-shutters/main.c
test-shutters: USB interface via control requests
[home-hw.git] / test-shutters / main.c
1 /*
2  *      Testing Shutter Controller
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
37         rcc_periph_reset_pulse(RST_GPIOA);
38         rcc_periph_reset_pulse(RST_GPIOB);
39         rcc_periph_reset_pulse(RST_GPIOC);
40         rcc_periph_reset_pulse(RST_USART1);
41         rcc_periph_reset_pulse(RST_USB);
42 }
43
44 static void gpio_init(void)
45 {
46         // PA9 = TXD1 for debugging console
47         // PA10 = RXD1 for debugging console
48         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
49         gpio_set_mode(GPIOA, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO10);
50
51         // PC13 = BluePill LED
52         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
53         gpio_clear(GPIOC, GPIO13);
54
55         // PB6 = SSR (active low)
56         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO6);
57         gpio_set(GPIOB, GPIO6);
58
59         // PA0 = current sense
60         gpio_set_mode(GPIOA, GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, GPIO0);
61         gpio_set(GPIOA, GPIO0);
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, 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 /*** USB ***/
100
101 static usbd_device *usbd_dev;
102
103 enum usb_string {
104         STR_MANUFACTURER = 1,
105         STR_PRODUCT,
106         STR_SERIAL,
107 };
108
109 static char usb_serial_number[13];
110
111 static const char *usb_strings[] = {
112         "United Computer Wizards",
113         "Shutter Control Test",
114         usb_serial_number,
115 };
116
117 static const struct usb_device_descriptor device = {
118         .bLength = USB_DT_DEVICE_SIZE,
119         .bDescriptorType = USB_DT_DEVICE,
120         .bcdUSB = 0x0200,
121         .bDeviceClass = 0xFF,
122         .bDeviceSubClass = 0,
123         .bDeviceProtocol = 0,
124         .bMaxPacketSize0 = 64,
125         .idVendor = 0x4242,
126         .idProduct = 0x0007,
127         .bcdDevice = 0x0000,
128         .iManufacturer = STR_MANUFACTURER,
129         .iProduct = STR_PRODUCT,
130         .iSerialNumber = STR_SERIAL,
131         .bNumConfigurations = 1,
132 };
133
134 static const struct usb_interface_descriptor iface = {
135         .bLength = USB_DT_INTERFACE_SIZE,
136         .bDescriptorType = USB_DT_INTERFACE,
137         .bInterfaceNumber = 0,
138         .bAlternateSetting = 0,
139         .bNumEndpoints = 0,
140         .bInterfaceClass = 0xFF,
141         .bInterfaceSubClass = 0,
142         .bInterfaceProtocol = 0,
143         .iInterface = 0,
144         .endpoint = NULL,
145 };
146
147 static const struct usb_dfu_descriptor dfu_function = {
148         .bLength = sizeof(struct usb_dfu_descriptor),
149         .bDescriptorType = DFU_FUNCTIONAL,
150         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
151         .wDetachTimeout = 255,
152         .wTransferSize = 1024,
153         .bcdDFUVersion = 0x0100,
154 };
155
156 static const struct usb_interface_descriptor dfu_iface = {
157         .bLength = USB_DT_INTERFACE_SIZE,
158         .bDescriptorType = USB_DT_INTERFACE,
159         .bInterfaceNumber = 1,
160         .bAlternateSetting = 0,
161         .bNumEndpoints = 0,
162         .bInterfaceClass = 0xFE,
163         .bInterfaceSubClass = 1,
164         .bInterfaceProtocol = 1,
165         .iInterface = 0,
166
167         .extra = &dfu_function,
168         .extralen = sizeof(dfu_function),
169 };
170
171 static const struct usb_interface ifaces[] = {{
172         .num_altsetting = 1,
173         .altsetting = &iface,
174 }, {
175         .num_altsetting = 1,
176         .altsetting = &dfu_iface,
177 }};
178
179 static const struct usb_config_descriptor config = {
180         .bLength = USB_DT_CONFIGURATION_SIZE,
181         .bDescriptorType = USB_DT_CONFIGURATION,
182         .wTotalLength = 0,
183         .bNumInterfaces = 2,
184         .bConfigurationValue = 1,
185         .iConfiguration = 0,
186         .bmAttributes = 0x80,
187         .bMaxPower = 50,        // multiplied by 2 mA
188         .interface = ifaces,
189 };
190
191 static byte usb_configured;
192 static uint8_t usbd_control_buffer[64];
193
194 uint csense_counters[2] = { 0, 0 };
195
196 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
197 {
198         // Reset to bootloader, which implements the rest of DFU
199         debug_printf("Switching to DFU\n");
200         debug_flush();
201         scb_reset_core();
202 }
203
204 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
205         struct usb_setup_data *req,
206         uint8_t **buf UNUSED,
207         uint16_t *len UNUSED,
208         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
209 {
210         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
211                 return USBD_REQ_NOTSUPP;
212
213         *complete = dfu_detach_complete;
214         return USBD_REQ_HANDLED;
215 }
216
217 static enum usbd_request_return_codes control_cb(
218         usbd_device *dev UNUSED,
219         struct usb_setup_data *req,
220         uint8_t **buf,
221         uint16_t *len,
222         void (**complete)(usbd_device *dev, struct usb_setup_data *req) UNUSED)
223 {
224         uint index = req->wIndex;
225         uint value = req->wValue;
226
227         if (req->bmRequestType == (USB_REQ_TYPE_IN | USB_REQ_TYPE_VENDOR | USB_REQ_TYPE_DEVICE)) {
228                 debug_printf("Control request IN %02x (index=%d, len=%d)\n", req->bRequest, index, *len);
229
230                 const byte *reply = NULL;
231                 uint reply_len = 0;
232
233                 switch (req->bRequest) {
234                         case 0:
235                                 reply = (const byte *) &csense_counters;
236                                 reply_len = sizeof(csense_counters);
237                                 break;
238                         default:
239                                 return USBD_REQ_NOTSUPP;
240                 }
241
242                 uint n = MIN(*len, reply_len);
243                 memcpy(*buf, reply, n);
244                 *len = n;
245                 return USBD_REQ_HANDLED;
246         } else if (req->bmRequestType == (USB_REQ_TYPE_OUT | USB_REQ_TYPE_VENDOR | USB_REQ_TYPE_DEVICE)) {
247                 debug_printf("Control request OUT %02x (index=%d, val=%d, len=%d)\n", req->bRequest, index, value, *len);
248
249                 switch (req->bRequest) {
250                         case 1:
251                                 if (*len != 0)
252                                         return USBD_REQ_NOTSUPP;
253                                 if (value & 1)
254                                         gpio_clear(GPIOB, GPIO6);
255                                 else
256                                         gpio_set(GPIOB, GPIO6);
257                                 break;
258                         default:
259                                 return USBD_REQ_NOTSUPP;
260                 }
261
262                 return USBD_REQ_HANDLED;
263         } else {
264                 return USBD_REQ_NOTSUPP;
265         }
266 }
267
268 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
269 {
270         usbd_register_control_callback(
271                 dev,
272                 USB_REQ_TYPE_VENDOR,
273                 USB_REQ_TYPE_TYPE,
274                 control_cb);
275         usbd_register_control_callback(
276                 dev,
277                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
278                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
279                 dfu_control_cb);
280         usb_configured = 1;
281 }
282
283 static void reset_cb(void)
284 {
285         debug_printf("USB: Reset\n");
286         usb_configured = 0;
287 }
288
289 static volatile bool usb_event_pending;
290
291 void usb_lp_can_rx0_isr(void)
292 {
293         /*
294          *  We handle USB in the main loop to avoid race conditions between
295          *  USB interrupts and other code. However, we need an interrupt to
296          *  up the main loop from sleep.
297          *
298          *  We set up only the low-priority ISR, because high-priority ISR handles
299          *  only double-buffered bulk transfers and isochronous transfers.
300          */
301         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
302         usb_event_pending = 1;
303 }
304
305 static void usb_init(void)
306 {
307         // Simulate USB disconnect
308         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
309         gpio_clear(GPIOA, GPIO11 | GPIO12);
310         delay_ms(100);
311
312         usbd_dev = usbd_init(
313                 &st_usbfs_v1_usb_driver,
314                 &device,
315                 &config,
316                 usb_strings,
317                 ARRAY_SIZE(usb_strings),
318                 usbd_control_buffer,
319                 sizeof(usbd_control_buffer)
320         );
321         usbd_register_reset_callback(usbd_dev, reset_cb);
322         usbd_register_set_config_callback(usbd_dev, set_config_cb);
323         usb_event_pending = 1;
324 }
325
326 /*** Main ***/
327
328 int main(void)
329 {
330         clock_init();
331         gpio_init();
332         usart_init();
333
334         tick_init();
335         desig_get_unique_id_as_dfu(usb_serial_number);
336
337         debug_printf("Hello, world!\n");
338
339         usb_init();
340
341         u32 last_blink = 0;
342
343         for (;;) {
344                 if (ms_ticks - last_blink >= 1000) {
345                         debug_led_toggle();
346                         last_blink = ms_ticks;
347                         debug_printf("C: %u %u\n", csense_counters[0], csense_counters[1]);
348                 }
349
350                 csense_counters[gpio_get(GPIOA, GPIO0)]++;
351
352                 if (usart_get_flag(USART1, USART_SR_RXNE)) {
353                         uint ch = usart_recv(USART1);
354                         if (ch == '1') {
355                                 gpio_clear(GPIOB, GPIO6);
356                         } else if (ch == '0') {
357                                 gpio_set(GPIOB, GPIO6);
358                         } else {
359                                 debug_putc(ch);
360                         }
361                 }
362
363                 if (usb_event_pending) {
364                         usbd_poll(usbd_dev);
365                         usb_event_pending = 0;
366                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
367                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
368                 }
369
370                 wait_for_interrupt();
371         }
372
373         return 0;
374 }