@@ -30,8 +30,10 @@ PROCESS(pbdrv_usb_process, "USB");
3030
3131static uint8_t usb_in_buf [USBD_PYBRICKS_MAX_PACKET_SIZE ];
3232static uint8_t usb_response_buf [1 + sizeof (uint32_t )];
33+ static uint8_t usb_status_buf [1 + 1 + sizeof (uint32_t )];
3334static volatile uint32_t usb_in_sz ;
3435static volatile uint32_t usb_response_sz ;
36+ static volatile uint32_t usb_status_sz ;
3537static volatile bool transmitting ;
3638
3739static USBD_HandleTypeDef husbd ;
@@ -144,6 +146,7 @@ static USBD_StatusTypeDef Pybricks_Itf_Init(void) {
144146 USBD_Pybricks_SetRxBuffer (& husbd , usb_in_buf );
145147 usb_in_sz = 0 ;
146148 usb_response_sz = 0 ;
149+ usb_status_sz = 0 ;
147150 transmitting = false;
148151
149152 return USBD_OK ;
@@ -195,6 +198,8 @@ static USBD_StatusTypeDef Pybricks_Itf_TransmitCplt(uint8_t *Buf, uint32_t *Len,
195198
196199 if (Buf == usb_response_buf ) {
197200 usb_response_sz = 0 ;
201+ } else if (Buf == usb_status_buf ) {
202+ usb_status_sz = 0 ;
198203 } else {
199204 ret = USBD_FAIL ;
200205 }
@@ -243,6 +248,9 @@ PROCESS_THREAD(pbdrv_usb_process, ev, data) {
243248 static PBIO_ONESHOT (pwrdn_oneshot );
244249 static bool bcd_busy ;
245250 static pbio_pybricks_error_t result ;
251+ static struct etimer timer ;
252+ static uint32_t prev_status_flags = ~0 ;
253+ static uint32_t new_status_flags ;
246254
247255 PROCESS_POLLHANDLER ({
248256 if (!bcd_busy && pbio_oneshot (!vbus_active , & no_vbus_oneshot )) {
@@ -264,6 +272,8 @@ PROCESS_THREAD(pbdrv_usb_process, ev, data) {
264272 // Prepare to receive the first packet
265273 USBD_Pybricks_ReceivePacket (& husbd );
266274
275+ etimer_set (& timer , 500 );
276+
267277 for (;;) {
268278 PROCESS_WAIT_EVENT ();
269279
@@ -310,7 +320,22 @@ PROCESS_THREAD(pbdrv_usb_process, ev, data) {
310320 continue ;
311321 }
312322
313- if (usb_response_sz ) {
323+ new_status_flags = pbsys_status_get_flags ();
324+
325+ // Transmit. Give priority to status updates.
326+ if ((new_status_flags != prev_status_flags ) || etimer_expired (& timer )) {
327+
328+ usb_status_buf [0 ] = USBD_PYBRICKS_MSG_EVENT ;
329+ usb_status_sz = 1 + pbio_pybricks_event_status_report (& usb_status_buf [1 ], new_status_flags );
330+
331+ etimer_restart (& timer );
332+ prev_status_flags = new_status_flags ;
333+
334+ transmitting = true;
335+ USBD_Pybricks_TransmitPacket (& husbd , usb_status_buf , usb_status_sz );
336+
337+ } else if (usb_response_sz ) {
338+
314339 transmitting = true;
315340 USBD_Pybricks_TransmitPacket (& husbd , usb_response_buf , usb_response_sz );
316341 }
0 commit comments