From 7b85ba8d4fb34e76d34a2d581e89e856aa471cf5 Mon Sep 17 00:00:00 2001 From: jaseg Date: Mon, 21 Dec 2020 16:26:57 +0100 Subject: Move fw into direct subdir --- fw/hid-dials/Makefile | 187 ----- .../STM32_USB_Device_Library/Core/Inc/usbd_core.h | 167 ----- .../Core/Inc/usbd_ctlreq.h | 113 --- .../STM32_USB_Device_Library/Core/Inc/usbd_def.h | 330 --------- .../STM32_USB_Device_Library/Core/Inc/usbd_ioreq.h | 128 ---- .../STM32_USB_Device_Library/Core/Src/usbd_core.c | 565 --------------- .../Core/Src/usbd_ctlreq.c | 782 --------------------- .../STM32_USB_Device_Library/Core/Src/usbd_ioreq.c | 236 ------- fw/hid-dials/README.md | 20 - fw/hid-dials/STM32F072CBUx_FLASH.ld | 189 ----- fw/hid-dials/src/main.c | 474 ------------- fw/hid-dials/src/main.h | 71 -- fw/hid-dials/src/startup_stm32f072xb.s | 294 -------- fw/hid-dials/src/stm32f0xx_hal_conf.h | 319 --------- fw/hid-dials/src/stm32f0xx_hal_msp.c | 191 ----- fw/hid-dials/src/stm32f0xx_it.c | 176 ----- fw/hid-dials/src/stm32f0xx_it.h | 68 -- fw/hid-dials/src/system_stm32f0xx.c | 265 ------- fw/hid-dials/src/usb_device.c | 107 --- fw/hid-dials/src/usb_device.h | 115 --- fw/hid-dials/src/usbd_conf.c | 576 --------------- fw/hid-dials/src/usbd_conf.h | 82 --- fw/hid-dials/src/usbd_desc.c | 365 ---------- fw/hid-dials/src/usbd_desc.h | 156 ---- fw/hid-dials/src/usbd_hid.c | 373 ---------- fw/hid-dials/src/usbd_hid.h | 193 ----- fw/hid-dials/tools/butter_filter_gen.py | 93 --- fw/hid-dials/tools/crypto_test.c | 46 -- fw/hid-dials/tools/crypto_test_runner.py | 46 -- fw/hid-dials/tools/cwt_wavelet_header_gen.py | 29 - fw/hid-dials/tools/dsss_demod_test.c | 109 --- fw/hid-dials/tools/dsss_demod_test_runner.py | 241 ------- fw/hid-dials/tools/dsss_demod_test_waveform_gen.py | 86 --- fw/hid-dials/tools/e2e_test.c | 111 --- fw/hid-dials/tools/fft_window_header_gen.py | 59 -- fw/hid-dials/tools/fmeas_export_ocxo_2day.bin | Bin 4908532 -> 0 bytes fw/hid-dials/tools/freq_meas_test.c | 106 --- fw/hid-dials/tools/freq_meas_test_runner.py | 39 - fw/hid-dials/tools/gold_code_header_gen.py | 70 -- fw/hid-dials/tools/grid_freq_psd_spl_108pt.json | 1 - fw/hid-dials/tools/hum_generator.py | 111 --- fw/hid-dials/tools/ldparser.py | 126 ---- fw/hid-dials/tools/linkmem.py | 276 -------- fw/hid-dials/tools/linksize.py | 62 -- fw/hid-dials/tools/linktracer.py | 118 ---- fw/hid-dials/tools/mapparse.py | 129 ---- fw/hid-dials/tools/presig_gen.py | 141 ---- fw/hid-dials/tools/reed_solomon.py | 91 --- fw/hid-dials/upstream/cmsis-core | 1 - fw/hid-dials/upstream/st-cmsis-f0 | 1 - fw/hid-dials/upstream/st-hal-f0 | 1 - fw/hid-dials/upstream/st-usb-device | 1 - 52 files changed, 8636 deletions(-) delete mode 100644 fw/hid-dials/Makefile delete mode 100644 fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_core.h delete mode 100644 fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_ctlreq.h delete mode 100644 fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h delete mode 100644 fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_ioreq.h delete mode 100644 fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_core.c delete mode 100644 fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_ctlreq.c delete mode 100644 fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_ioreq.c delete mode 100644 fw/hid-dials/README.md delete mode 100644 fw/hid-dials/STM32F072CBUx_FLASH.ld delete mode 100644 fw/hid-dials/src/main.c delete mode 100644 fw/hid-dials/src/main.h delete mode 100644 fw/hid-dials/src/startup_stm32f072xb.s delete mode 100644 fw/hid-dials/src/stm32f0xx_hal_conf.h delete mode 100644 fw/hid-dials/src/stm32f0xx_hal_msp.c delete mode 100644 fw/hid-dials/src/stm32f0xx_it.c delete mode 100644 fw/hid-dials/src/stm32f0xx_it.h delete mode 100644 fw/hid-dials/src/system_stm32f0xx.c delete mode 100644 fw/hid-dials/src/usb_device.c delete mode 100644 fw/hid-dials/src/usb_device.h delete mode 100644 fw/hid-dials/src/usbd_conf.c delete mode 100644 fw/hid-dials/src/usbd_conf.h delete mode 100644 fw/hid-dials/src/usbd_desc.c delete mode 100644 fw/hid-dials/src/usbd_desc.h delete mode 100644 fw/hid-dials/src/usbd_hid.c delete mode 100644 fw/hid-dials/src/usbd_hid.h delete mode 100644 fw/hid-dials/tools/butter_filter_gen.py delete mode 100644 fw/hid-dials/tools/crypto_test.c delete mode 100644 fw/hid-dials/tools/crypto_test_runner.py delete mode 100644 fw/hid-dials/tools/cwt_wavelet_header_gen.py delete mode 100644 fw/hid-dials/tools/dsss_demod_test.c delete mode 100644 fw/hid-dials/tools/dsss_demod_test_runner.py delete mode 100644 fw/hid-dials/tools/dsss_demod_test_waveform_gen.py delete mode 100644 fw/hid-dials/tools/e2e_test.c delete mode 100644 fw/hid-dials/tools/fft_window_header_gen.py delete mode 100644 fw/hid-dials/tools/fmeas_export_ocxo_2day.bin delete mode 100644 fw/hid-dials/tools/freq_meas_test.c delete mode 100644 fw/hid-dials/tools/freq_meas_test_runner.py delete mode 100644 fw/hid-dials/tools/gold_code_header_gen.py delete mode 100644 fw/hid-dials/tools/grid_freq_psd_spl_108pt.json delete mode 100755 fw/hid-dials/tools/hum_generator.py delete mode 100644 fw/hid-dials/tools/ldparser.py delete mode 100644 fw/hid-dials/tools/linkmem.py delete mode 100644 fw/hid-dials/tools/linksize.py delete mode 100644 fw/hid-dials/tools/linktracer.py delete mode 100644 fw/hid-dials/tools/mapparse.py delete mode 100644 fw/hid-dials/tools/presig_gen.py delete mode 100644 fw/hid-dials/tools/reed_solomon.py delete mode 160000 fw/hid-dials/upstream/cmsis-core delete mode 160000 fw/hid-dials/upstream/st-cmsis-f0 delete mode 160000 fw/hid-dials/upstream/st-hal-f0 delete mode 160000 fw/hid-dials/upstream/st-usb-device (limited to 'fw/hid-dials') diff --git a/fw/hid-dials/Makefile b/fw/hid-dials/Makefile deleted file mode 100644 index b8f3ad4..0000000 --- a/fw/hid-dials/Makefile +++ /dev/null @@ -1,187 +0,0 @@ -######################################################################################################################## -# Dependency directories -######################################################################################################################## - -CMSIS_DEVICE_DIR ?= upstream/st-cmsis-f0 -CMSIS_CORE_DIR ?= upstream/cmsis-core -HAL_DIR ?= upstream/st-hal-f0 -ST_USBD_DIR ?= upstream/st-usb-device - -######################################################################################################################## -# Sources -######################################################################################################################## - -C_SOURCES := src/main.c \ - src/stm32f0xx_it.c \ - src/stm32f0xx_hal_msp.c \ - src/usb_device.c \ - src/usbd_conf.c \ - src/usbd_desc.c \ - src/usbd_hid.c \ - src/system_stm32f0xx.c - -C_SOURCES += $(HAL_DIR)/Src/stm32f0xx_ll_usb.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_adc.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_adc_ex.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_rcc.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_rcc_ex.c \ - $(HAL_DIR)/Src/stm32f0xx_hal.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_i2c.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_i2c_ex.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_gpio.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_dma.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_cortex.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_pwr.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_pwr_ex.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_flash.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_flash_ex.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_exti.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_tim.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_tim_ex.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_pcd.c \ - $(HAL_DIR)/Src/stm32f0xx_hal_pcd_ex.c - -C_SOURCES += $(ST_USBD_DIR)/Core/Src/usbd_core.c \ - $(ST_USBD_DIR)/Core/Src/usbd_ctlreq.c \ - $(ST_USBD_DIR)/Core/Src/usbd_ioreq.c \ - -CXX_SOURCES += - -######################################################################################################################## -# Build parameters -######################################################################################################################## - -BUILDDIR ?= build -BINARY := minikbd.elf -STARTUP_FILE := src/startup_stm32f072xb.s -LDSCRIPT := STM32F072CBUx_FLASH.ld - -ARCH_FLAGS := -mthumb -mcpu=cortex-m0 -mfloat-abi=soft -SYSTEM_FLAGS += -nostdlib -ffreestanding -nostartfiles - -CFLAGS := -O0 -std=gnu11 -CFLAGS += -DUSE_HAL_DRIVER -DSTM32F072xB -CFLAGS += -DSTM32F0 -DDEBUG=$(DEBUG) -# ST weirdness -CFLAGS += -DUSBD_CLASS_BOS_ENABLED=0 - -CFLAGS += -fno-common -ffunction-sections -fdata-sections - -CFLAGS += -I$(BUILDDIR) \ - -Isrc \ - -I$(CMSIS_DEVICE_DIR)/Include \ - -I$(CMSIS_CORE_DIR) \ - -I$(HAL_DIR)/Inc \ - -I$(ST_USBD_DIR)/Core/Inc \ - -I$(ST_USBD_DIR)/Class/HID/Inc -# for musl -CFLAGS += -Dhidden= - -CFLAGS += -Wall -Wextra -Wpedantic -Wshadow -Wimplicit-function-declaration -Wundef -Wno-unused-parameter -CFLAGS += -Wredundant-decls -Wmissing-prototypes -Wstrict-prototypes - -CFLAGS += $(ARCH_FLAGS) $(SYSTEM_FLAGS) - -LDFLAGS += $(ARCH_FLAGS) $(SYSTEM_FLAGS) - -LIBS += -lgcc -LDFLAGS += -Wl,--gc-sections - -LINKMEM_FLAGS ?= --trim-stubs=$(STARTUP_FILE:.s=.o) --trace-sections .isr_vector --highlight-subdirs $(BUILDDIR) - -OBJS := $(addprefix $(BUILDDIR)/,$(C_SOURCES:.c=.o) $(CXX_SOURCES:.cpp=.o)) -OBJS += $(BUILDDIR)/$(STARTUP_FILE:.s=.o) - -######################################################################################################################## -# Build tools -######################################################################################################################## - -PREFIX ?= arm-none-eabi- - -DEBUG ?= 1 - -CC := $(PREFIX)gcc -CXX := $(PREFIX)g++ -LD := $(PREFIX)gcc -AR := $(PREFIX)ar -AS := $(PREFIX)as -SIZE := $(PREFIX)size -NM := $(PREFIX)nm -OBJCOPY := $(PREFIX)objcopy -OBJDUMP := $(PREFIX)objdump -GDB := $(PREFIX)gdb - -HOST_CC ?= $(HOST_PREFIX)gcc -HOST_CXX ?= $(HOST_PREFIX)g++ -HOST_LD ?= $(HOST_PREFIX)gcc -HOST_AR ?= $(HOST_PREFIX)ar -HOST_AS ?= $(HOST_PREFIX)as -HOST_OBJCOPY ?= $(HOST_PREFIX)objcopy -HOST_OBJDUMP ?= $(HOST_PREFIX)objdump - -PYTHON3 ?= python3 -DOT ?= dot - -######################################################################################################################## -# Rules -######################################################################################################################## - -all: binsize - -.PHONY: binsize -binsize: $(BUILDDIR)/$(BINARY) $(BUILDDIR)/$(BINARY:.elf=-symbol-sizes.pdf) - $(LD) -T$(LDSCRIPT) $(LDFLAGS) -Wl,--print-memory-usage -o /dev/null $(OBJS) $(LIBS) - @echo - @echo "▐▬▬▬▌ SyMbOL sIzE HiGhScORe LiSt ▐▬▬▬▌" - $(NM) --print-size --size-sort --radix=d $< | tail -n 20 - -$(BUILDDIR)/generated: ; mkdir -p $@ - -.PRECIOUS: $(BUILDDIR)/$(BINARY) -$(BUILDDIR)/$(BINARY) $(BUILDDIR)/$(BINARY:.elf=.map) &: $(OBJS) - $(LD) -T$(LDSCRIPT) $(LDFLAGS) -o $@ -Wl,-Map=$(BUILDDIR)/$(BINARY:.elf=.map) $^ $(LIBS) - -build/$(BINARY:.elf=-symbol-sizes.dot): $(OBJS) - $(PYTHON3) tools/linkmem.py $(LINKMEM_FLAGS) $(LD) -T$(LDSCRIPT) $(LDFLAGS) $^ $(LIBS) > $@ - -%.pdf: %.dot - $(DOT) -T pdf $< -o $@ - -%.dot: %.elf - r2 -a arm -qc 'aa;agRd' $< 2>/dev/null >$@ - -$(BUILDDIR)/src/%.o: src/%.s - mkdir -p $(@D) - $(CC) $(COMMON_CFLAGS) $(CFLAGS) $(INT_CFLAGS) -o $@ -c $< - -$(BUILDDIR)/src/%.o: src/%.c - mkdir -p $(@D) - $(CC) $(COMMON_CFLAGS) $(CFLAGS) $(INT_CFLAGS) -o $@ -c $< - -$(BUILDDIR)/src/%.o: src/%.cpp - mkdir -p $(@D) - $(CXX) $(CXXFLAGS) -o $@ -c $< - -$(BUILDDIR)/generated/%.o: $(BUILDDIR)/generated/%.c - mkdir -p $(@D) - $(CC) $(COMMON_CFLAGS) $(CFLAGS) $(INT_CFLAGS) -o $@ -c $< - -$(BUILDDIR)/%.o: %.c - mkdir -p $(@D) - $(CC) $(COMMON_CFLAGS) $(CFLAGS) $(EXT_CFLAGS) -o $@ -c $< - -clean: - rm -rf $(BUILDDIR)/src - rm -rf $(BUILDDIR)/generated - rm -f $(BUILDDIR)/$(BINARY) - rm -f $(BUILDDIR)/$(BINARY:.elf=.map) - rm -f $(BUILDDIR)/$(BINARY:.elf=-symbol-sizes.dot) - rm -f $(BUILDDIR)/$(BINARY:.elf=-symbol-sizes.pdf) - rm -f $(BUILDDIR)/tools/freq_meas_test - -mrproper: clean - rm -rf build - -.PHONY: clean mrproper - --include $(OBJS:.o=.d) diff --git a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_core.h b/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_core.h deleted file mode 100644 index 6550cd7..0000000 --- a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_core.h +++ /dev/null @@ -1,167 +0,0 @@ -/** - ****************************************************************************** - * @file usbd_core.h - * @author MCD Application Team - * @version V2.4.2 - * @date 11-December-2015 - * @brief Header file for usbd_core.c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2015 STMicroelectronics

- * - * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/software_license_agreement_liberty_v2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __USBD_CORE_H -#define __USBD_CORE_H - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_conf.h" -#include "usbd_def.h" -#include "usbd_ioreq.h" -#include "usbd_ctlreq.h" - -/** @addtogroup STM32_USB_DEVICE_LIBRARY - * @{ - */ - -/** @defgroup USBD_CORE - * @brief This file is the Header file for usbd_core.c file - * @{ - */ - - -/** @defgroup USBD_CORE_Exported_Defines - * @{ - */ - -/** - * @} - */ - - -/** @defgroup USBD_CORE_Exported_TypesDefinitions - * @{ - */ - - -/** - * @} - */ - - - -/** @defgroup USBD_CORE_Exported_Macros - * @{ - */ - -/** - * @} - */ - -/** @defgroup USBD_CORE_Exported_Variables - * @{ - */ -#define USBD_SOF USBD_LL_SOF -/** - * @} - */ - -/** @defgroup USBD_CORE_Exported_FunctionsPrototype - * @{ - */ -USBD_StatusTypeDef USBD_Init(USBD_HandleTypeDef *pdev, USBD_DescriptorsTypeDef *pdesc, uint8_t id); -USBD_StatusTypeDef USBD_DeInit(USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_Start (USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_Stop (USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_RegisterClass(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass); - -USBD_StatusTypeDef USBD_RunTestMode (USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_SetClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx); -USBD_StatusTypeDef USBD_ClrClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx); - -USBD_StatusTypeDef USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, uint8_t *psetup); -USBD_StatusTypeDef USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev , uint8_t epnum, uint8_t *pdata); -USBD_StatusTypeDef USBD_LL_DataInStage(USBD_HandleTypeDef *pdev , uint8_t epnum, uint8_t *pdata); - -USBD_StatusTypeDef USBD_LL_Reset(USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev, USBD_SpeedTypeDef speed); -USBD_StatusTypeDef USBD_LL_Suspend(USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_LL_Resume(USBD_HandleTypeDef *pdev); - -USBD_StatusTypeDef USBD_LL_SOF(USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_LL_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum); -USBD_StatusTypeDef USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum); - -USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef *pdev); - -/* USBD Low Level Driver */ -USBD_StatusTypeDef USBD_LL_Init (USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_LL_DeInit (USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_LL_Stop (USBD_HandleTypeDef *pdev); -USBD_StatusTypeDef USBD_LL_OpenEP (USBD_HandleTypeDef *pdev, - uint8_t ep_addr, - uint8_t ep_type, - uint16_t ep_mps); - -USBD_StatusTypeDef USBD_LL_CloseEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); -USBD_StatusTypeDef USBD_LL_FlushEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); -USBD_StatusTypeDef USBD_LL_StallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); -USBD_StatusTypeDef USBD_LL_ClearStallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); -uint8_t USBD_LL_IsStallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); -USBD_StatusTypeDef USBD_LL_SetUSBAddress (USBD_HandleTypeDef *pdev, uint8_t dev_addr); -USBD_StatusTypeDef USBD_LL_Transmit (USBD_HandleTypeDef *pdev, - uint8_t ep_addr, - uint8_t *pbuf, - uint16_t size); - -USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, - uint8_t ep_addr, - uint8_t *pbuf, - uint16_t size); - -uint32_t USBD_LL_GetRxDataSize (USBD_HandleTypeDef *pdev, uint8_t ep_addr); -void USBD_LL_Delay (uint32_t Delay); - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __USBD_CORE_H */ - -/** - * @} - */ - -/** -* @} -*/ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ - - - diff --git a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_ctlreq.h b/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_ctlreq.h deleted file mode 100644 index 66380fd..0000000 --- a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_ctlreq.h +++ /dev/null @@ -1,113 +0,0 @@ -/** - ****************************************************************************** - * @file usbd_req.h - * @author MCD Application Team - * @version V2.4.2 - * @date 11-December-2015 - * @brief Header file for the usbd_req.c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2015 STMicroelectronics

- * - * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/software_license_agreement_liberty_v2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __USB_REQUEST_H -#define __USB_REQUEST_H - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_def.h" - - -/** @addtogroup STM32_USB_DEVICE_LIBRARY - * @{ - */ - -/** @defgroup USBD_REQ - * @brief header file for the usbd_req.c file - * @{ - */ - -/** @defgroup USBD_REQ_Exported_Defines - * @{ - */ -/** - * @} - */ - - -/** @defgroup USBD_REQ_Exported_Types - * @{ - */ -/** - * @} - */ - - - -/** @defgroup USBD_REQ_Exported_Macros - * @{ - */ -/** - * @} - */ - -/** @defgroup USBD_REQ_Exported_Variables - * @{ - */ -/** - * @} - */ - -/** @defgroup USBD_REQ_Exported_FunctionsPrototype - * @{ - */ - -USBD_StatusTypeDef USBD_StdDevReq (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); -USBD_StatusTypeDef USBD_StdItfReq (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); -USBD_StatusTypeDef USBD_StdEPReq (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); - - -void USBD_CtlError (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); - -void USBD_ParseSetupRequest (USBD_SetupReqTypedef *req, uint8_t *pdata); - -void USBD_GetString (uint8_t *desc, uint8_t *unicode, uint16_t *len); -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __USB_REQUEST_H */ - -/** - * @} - */ - -/** -* @} -*/ - - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h b/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h deleted file mode 100644 index 969e324..0000000 --- a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h +++ /dev/null @@ -1,330 +0,0 @@ -/** - ****************************************************************************** - * @file usbd_def.h - * @author MCD Application Team - * @version V2.4.2 - * @date 11-December-2015 - * @brief General defines for the usb device library - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2015 STMicroelectronics

- * - * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/software_license_agreement_liberty_v2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __USBD_DEF_H -#define __USBD_DEF_H - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_conf.h" - -/** @addtogroup STM32_USBD_DEVICE_LIBRARY - * @{ - */ - -/** @defgroup USB_DEF - * @brief general defines for the usb device library file - * @{ - */ - -/** @defgroup USB_DEF_Exported_Defines - * @{ - */ - -#ifndef NULL -#define NULL 0 -#endif - - -#define USB_LEN_DEV_QUALIFIER_DESC 0x0A -#define USB_LEN_DEV_DESC 0x12 -#define USB_LEN_CFG_DESC 0x09 -#define USB_LEN_IF_DESC 0x09 -#define USB_LEN_EP_DESC 0x07 -#define USB_LEN_OTG_DESC 0x03 -#define USB_LEN_LANGID_STR_DESC 0x04 -#define USB_LEN_OTHER_SPEED_DESC_SIZ 0x09 - -#define USBD_IDX_LANGID_STR 0x00 -#define USBD_IDX_MFC_STR 0x01 -#define USBD_IDX_PRODUCT_STR 0x02 -#define USBD_IDX_SERIAL_STR 0x03 -#define USBD_IDX_CONFIG_STR 0x04 -#define USBD_IDX_INTERFACE_STR 0x05 - -#define USB_REQ_TYPE_STANDARD 0x00 -#define USB_REQ_TYPE_CLASS 0x20 -#define USB_REQ_TYPE_VENDOR 0x40 -#define USB_REQ_TYPE_MASK 0x60 - -#define USB_REQ_RECIPIENT_DEVICE 0x00 -#define USB_REQ_RECIPIENT_INTERFACE 0x01 -#define USB_REQ_RECIPIENT_ENDPOINT 0x02 -#define USB_REQ_RECIPIENT_MASK 0x03 - -#define USB_REQ_GET_STATUS 0x00 -#define USB_REQ_CLEAR_FEATURE 0x01 -#define USB_REQ_SET_FEATURE 0x03 -#define USB_REQ_SET_ADDRESS 0x05 -#define USB_REQ_GET_DESCRIPTOR 0x06 -#define USB_REQ_SET_DESCRIPTOR 0x07 -#define USB_REQ_GET_CONFIGURATION 0x08 -#define USB_REQ_SET_CONFIGURATION 0x09 -#define USB_REQ_GET_INTERFACE 0x0A -#define USB_REQ_SET_INTERFACE 0x0B -#define USB_REQ_SYNCH_FRAME 0x0C - -#define USB_DESC_TYPE_DEVICE 1 -#define USB_DESC_TYPE_CONFIGURATION 2 -#define USB_DESC_TYPE_STRING 3 -#define USB_DESC_TYPE_INTERFACE 4 -#define USB_DESC_TYPE_ENDPOINT 5 -#define USB_DESC_TYPE_DEVICE_QUALIFIER 6 -#define USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION 7 -#define USB_DESC_TYPE_BOS 0x0F - -#define USB_CONFIG_REMOTE_WAKEUP 2 -#define USB_CONFIG_SELF_POWERED 1 - -#define USB_FEATURE_EP_HALT 0 -#define USB_FEATURE_REMOTE_WAKEUP 1 -#define USB_FEATURE_TEST_MODE 2 - -#define USB_DEVICE_CAPABITY_TYPE 0x10 - -#define USB_HS_MAX_PACKET_SIZE 512 -#define USB_FS_MAX_PACKET_SIZE 64 -#define USB_MAX_EP0_SIZE 64 - -/* Device Status */ -#define USBD_STATE_DEFAULT 1 -#define USBD_STATE_ADDRESSED 2 -#define USBD_STATE_CONFIGURED 3 -#define USBD_STATE_SUSPENDED 4 - - -/* EP0 State */ -#define USBD_EP0_IDLE 0 -#define USBD_EP0_SETUP 1 -#define USBD_EP0_DATA_IN 2 -#define USBD_EP0_DATA_OUT 3 -#define USBD_EP0_STATUS_IN 4 -#define USBD_EP0_STATUS_OUT 5 -#define USBD_EP0_STALL 6 - -#define USBD_EP_TYPE_CTRL 0 -#define USBD_EP_TYPE_ISOC 1 -#define USBD_EP_TYPE_BULK 2 -#define USBD_EP_TYPE_INTR 3 - - -/** - * @} - */ - - -/** @defgroup USBD_DEF_Exported_TypesDefinitions - * @{ - */ - -typedef struct usb_setup_req -{ - - uint8_t bmRequest; - uint8_t bRequest; - uint16_t wValue; - uint16_t wIndex; - uint16_t wLength; -}USBD_SetupReqTypedef; - -struct _USBD_HandleTypeDef; - -typedef struct _Device_cb -{ - uint8_t (*Init) (struct _USBD_HandleTypeDef *pdev , uint8_t cfgidx); - uint8_t (*DeInit) (struct _USBD_HandleTypeDef *pdev , uint8_t cfgidx); - /* Control Endpoints*/ - uint8_t (*Setup) (struct _USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef *req); - uint8_t (*EP0_TxSent) (struct _USBD_HandleTypeDef *pdev ); - uint8_t (*EP0_RxReady) (struct _USBD_HandleTypeDef *pdev ); - /* Class Specific Endpoints*/ - uint8_t (*DataIn) (struct _USBD_HandleTypeDef *pdev , uint8_t epnum); - uint8_t (*DataOut) (struct _USBD_HandleTypeDef *pdev , uint8_t epnum); - uint8_t (*SOF) (struct _USBD_HandleTypeDef *pdev); - uint8_t (*IsoINIncomplete) (struct _USBD_HandleTypeDef *pdev , uint8_t epnum); - uint8_t (*IsoOUTIncomplete) (struct _USBD_HandleTypeDef *pdev , uint8_t epnum); - - uint8_t *(*GetHSConfigDescriptor)(uint16_t *length); - uint8_t *(*GetFSConfigDescriptor)(uint16_t *length); - uint8_t *(*GetOtherSpeedConfigDescriptor)(uint16_t *length); - uint8_t *(*GetDeviceQualifierDescriptor)(uint16_t *length); -#if (USBD_SUPPORT_USER_STRING == 1) - uint8_t *(*GetUsrStrDescriptor)(struct _USBD_HandleTypeDef *pdev ,uint8_t index, uint16_t *length); -#endif - -} USBD_ClassTypeDef; - -/* Following USB Device Speed */ -typedef enum -{ - USBD_SPEED_HIGH = 0, - USBD_SPEED_FULL = 1, - USBD_SPEED_LOW = 2, -}USBD_SpeedTypeDef; - -/* Following USB Device status */ -typedef enum { - USBD_OK = 0, - USBD_BUSY, - USBD_FAIL, -}USBD_StatusTypeDef; - -/* USB Device descriptors structure */ -typedef struct -{ - uint8_t *(*GetDeviceDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); - uint8_t *(*GetLangIDStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); - uint8_t *(*GetManufacturerStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); - uint8_t *(*GetProductStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); - uint8_t *(*GetSerialStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); - uint8_t *(*GetConfigurationStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); - uint8_t *(*GetInterfaceStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); -#if (USBD_LPM_ENABLED == 1) - uint8_t *(*GetBOSDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); -#endif -} USBD_DescriptorsTypeDef; - -/* USB Device handle structure */ -typedef struct -{ - uint32_t status; - uint32_t total_length; - uint32_t rem_length; - uint32_t maxpacket; -} USBD_EndpointTypeDef; - -/* USB Device handle structure */ -typedef struct _USBD_HandleTypeDef -{ - uint8_t id; - uint32_t dev_config; - uint32_t dev_default_config; - uint32_t dev_config_status; - USBD_SpeedTypeDef dev_speed; - USBD_EndpointTypeDef ep_in[15]; - USBD_EndpointTypeDef ep_out[15]; - uint32_t ep0_state; - uint32_t ep0_data_len; - uint8_t dev_state; - uint8_t dev_old_state; - uint8_t dev_address; - uint8_t dev_connection_status; - uint8_t dev_test_mode; - uint32_t dev_remote_wakeup; - - USBD_SetupReqTypedef request; - USBD_DescriptorsTypeDef *pDesc; - USBD_ClassTypeDef *pClass; - void *pClassData; - void *pUserData; - void *pData; -} USBD_HandleTypeDef; - -/** - * @} - */ - - - -/** @defgroup USBD_DEF_Exported_Macros - * @{ - */ -#define SWAPBYTE(addr) (((uint16_t)(*((uint8_t *)(addr)))) + \ - (((uint16_t)(*(((uint8_t *)(addr)) + 1))) << 8)) - -#define LOBYTE(x) ((uint8_t)(x & 0x00FF)) -#define HIBYTE(x) ((uint8_t)((x & 0xFF00) >>8)) -#define MIN(a, b) (((a) < (b)) ? (a) : (b)) -#define MAX(a, b) (((a) > (b)) ? (a) : (b)) - - -#if defined ( __GNUC__ ) - #ifndef __weak - #define __weak __attribute__((weak)) - #endif /* __weak */ - #ifndef __packed - #define __packed __attribute__((__packed__)) - #endif /* __packed */ -#endif /* __GNUC__ */ - - -/* In HS mode and when the DMA is used, all variables and data structures dealing - with the DMA during the transaction process should be 4-bytes aligned */ - -#if defined (__GNUC__) /* GNU Compiler */ - #define __ALIGN_END __attribute__ ((aligned (4))) - #define __ALIGN_BEGIN -#else - #define __ALIGN_END - #if defined (__CC_ARM) /* ARM Compiler */ - #define __ALIGN_BEGIN __align(4) - #elif defined (__ICCARM__) /* IAR Compiler */ - #define __ALIGN_BEGIN - #elif defined (__TASKING__) /* TASKING Compiler */ - #define __ALIGN_BEGIN __align(4) - #endif /* __CC_ARM */ -#endif /* __GNUC__ */ - - -/** - * @} - */ - -/** @defgroup USBD_DEF_Exported_Variables - * @{ - */ - -/** - * @} - */ - -/** @defgroup USBD_DEF_Exported_FunctionsPrototype - * @{ - */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __USBD_DEF_H */ - -/** - * @} - */ - -/** -* @} -*/ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_ioreq.h b/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_ioreq.h deleted file mode 100644 index dbf8ca1..0000000 --- a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_ioreq.h +++ /dev/null @@ -1,128 +0,0 @@ -/** - ****************************************************************************** - * @file usbd_ioreq.h - * @author MCD Application Team - * @version V2.4.2 - * @date 11-December-2015 - * @brief Header file for the usbd_ioreq.c file - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2015 STMicroelectronics

- * - * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/software_license_agreement_liberty_v2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __USBD_IOREQ_H -#define __USBD_IOREQ_H - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_def.h" -#include "usbd_core.h" - -/** @addtogroup STM32_USB_DEVICE_LIBRARY - * @{ - */ - -/** @defgroup USBD_IOREQ - * @brief header file for the usbd_ioreq.c file - * @{ - */ - -/** @defgroup USBD_IOREQ_Exported_Defines - * @{ - */ -/** - * @} - */ - - -/** @defgroup USBD_IOREQ_Exported_Types - * @{ - */ - - -/** - * @} - */ - - - -/** @defgroup USBD_IOREQ_Exported_Macros - * @{ - */ - -/** - * @} - */ - -/** @defgroup USBD_IOREQ_Exported_Variables - * @{ - */ - -/** - * @} - */ - -/** @defgroup USBD_IOREQ_Exported_FunctionsPrototype - * @{ - */ - -USBD_StatusTypeDef USBD_CtlSendData (USBD_HandleTypeDef *pdev, - uint8_t *buf, - uint16_t len); - -USBD_StatusTypeDef USBD_CtlContinueSendData (USBD_HandleTypeDef *pdev, - uint8_t *pbuf, - uint16_t len); - -USBD_StatusTypeDef USBD_CtlPrepareRx (USBD_HandleTypeDef *pdev, - uint8_t *pbuf, - uint16_t len); - -USBD_StatusTypeDef USBD_CtlContinueRx (USBD_HandleTypeDef *pdev, - uint8_t *pbuf, - uint16_t len); - -USBD_StatusTypeDef USBD_CtlSendStatus (USBD_HandleTypeDef *pdev); - -USBD_StatusTypeDef USBD_CtlReceiveStatus (USBD_HandleTypeDef *pdev); - -uint16_t USBD_GetRxCount (USBD_HandleTypeDef *pdev , - uint8_t epnum); - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __USBD_IOREQ_H */ - -/** - * @} - */ - -/** -* @} -*/ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_core.c b/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_core.c deleted file mode 100644 index 86fc2de..0000000 --- a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_core.c +++ /dev/null @@ -1,565 +0,0 @@ -/** - ****************************************************************************** - * @file usbd_core.c - * @author MCD Application Team - * @version V2.4.2 - * @date 11-December-2015 - * @brief This file provides all the USBD core functions. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2015 STMicroelectronics

- * - * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/software_license_agreement_liberty_v2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_core.h" - -/** @addtogroup STM32_USBD_DEVICE_LIBRARY -* @{ -*/ - - -/** @defgroup USBD_CORE -* @brief usbd core module -* @{ -*/ - -/** @defgroup USBD_CORE_Private_TypesDefinitions -* @{ -*/ -/** -* @} -*/ - - -/** @defgroup USBD_CORE_Private_Defines -* @{ -*/ - -/** -* @} -*/ - - -/** @defgroup USBD_CORE_Private_Macros -* @{ -*/ -/** -* @} -*/ - - - - -/** @defgroup USBD_CORE_Private_FunctionPrototypes -* @{ -*/ - -/** -* @} -*/ - -/** @defgroup USBD_CORE_Private_Variables -* @{ -*/ - -/** -* @} -*/ - -/** @defgroup USBD_CORE_Private_Functions -* @{ -*/ - -/** -* @brief USBD_Init -* Initializes the device stack and load the class driver -* @param pdev: device instance -* @param pdesc: Descriptor structure address -* @param id: Low level core index -* @retval None -*/ -USBD_StatusTypeDef USBD_Init(USBD_HandleTypeDef *pdev, USBD_DescriptorsTypeDef *pdesc, uint8_t id) -{ - /* Check whether the USB Host handle is valid */ - if(pdev == NULL) - { - USBD_ErrLog("Invalid Device handle"); - return USBD_FAIL; - } - - /* Unlink previous class*/ - if(pdev->pClass != NULL) - { - pdev->pClass = NULL; - } - - /* Assign USBD Descriptors */ - if(pdesc != NULL) - { - pdev->pDesc = pdesc; - } - - /* Set Device initial State */ - pdev->dev_state = USBD_STATE_DEFAULT; - pdev->id = id; - /* Initialize low level driver */ - USBD_LL_Init(pdev); - - return USBD_OK; -} - -/** -* @brief USBD_DeInit -* Re-Initialize th device library -* @param pdev: device instance -* @retval status: status -*/ -USBD_StatusTypeDef USBD_DeInit(USBD_HandleTypeDef *pdev) -{ - /* Set Default State */ - pdev->dev_state = USBD_STATE_DEFAULT; - - /* Free Class Resources */ - pdev->pClass->DeInit(pdev, pdev->dev_config); - - /* Stop the low level driver */ - USBD_LL_Stop(pdev); - - /* Initialize low level driver */ - USBD_LL_DeInit(pdev); - - return USBD_OK; -} - - -/** - * @brief USBD_RegisterClass - * Link class driver to Device Core. - * @param pDevice : Device Handle - * @param pclass: Class handle - * @retval USBD Status - */ -USBD_StatusTypeDef USBD_RegisterClass(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass) -{ - USBD_StatusTypeDef status = USBD_OK; - if(pclass != 0) - { - /* link the class to the USB Device handle */ - pdev->pClass = pclass; - status = USBD_OK; - } - else - { - USBD_ErrLog("Invalid Class handle"); - status = USBD_FAIL; - } - - return status; -} - -/** - * @brief USBD_Start - * Start the USB Device Core. - * @param pdev: Device Handle - * @retval USBD Status - */ -USBD_StatusTypeDef USBD_Start (USBD_HandleTypeDef *pdev) -{ - - /* Start the low level driver */ - USBD_LL_Start(pdev); - - return USBD_OK; -} - -/** - * @brief USBD_Stop - * Stop the USB Device Core. - * @param pdev: Device Handle - * @retval USBD Status - */ -USBD_StatusTypeDef USBD_Stop (USBD_HandleTypeDef *pdev) -{ - /* Free Class Resources */ - pdev->pClass->DeInit(pdev, pdev->dev_config); - - /* Stop the low level driver */ - USBD_LL_Stop(pdev); - - return USBD_OK; -} - -/** -* @brief USBD_RunTestMode -* Launch test mode process -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_RunTestMode (USBD_HandleTypeDef *pdev) -{ - return USBD_OK; -} - - -/** -* @brief USBD_SetClassConfig -* Configure device and start the interface -* @param pdev: device instance -* @param cfgidx: configuration index -* @retval status -*/ - -USBD_StatusTypeDef USBD_SetClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx) -{ - USBD_StatusTypeDef ret = USBD_FAIL; - - if(pdev->pClass != NULL) - { - /* Set configuration and Start the Class*/ - if(pdev->pClass->Init(pdev, cfgidx) == 0) - { - ret = USBD_OK; - } - } - return ret; -} - -/** -* @brief USBD_ClrClassConfig -* Clear current configuration -* @param pdev: device instance -* @param cfgidx: configuration index -* @retval status: USBD_StatusTypeDef -*/ -USBD_StatusTypeDef USBD_ClrClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx) -{ - /* Clear configuration and De-initialize the Class process*/ - pdev->pClass->DeInit(pdev, cfgidx); - return USBD_OK; -} - - -/** -* @brief USBD_SetupStage -* Handle the setup stage -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, uint8_t *psetup) -{ - - USBD_ParseSetupRequest(&pdev->request, psetup); - - pdev->ep0_state = USBD_EP0_SETUP; - pdev->ep0_data_len = pdev->request.wLength; - - switch (pdev->request.bmRequest & 0x1F) - { - case USB_REQ_RECIPIENT_DEVICE: - USBD_StdDevReq (pdev, &pdev->request); - break; - - case USB_REQ_RECIPIENT_INTERFACE: - USBD_StdItfReq(pdev, &pdev->request); - break; - - case USB_REQ_RECIPIENT_ENDPOINT: - USBD_StdEPReq(pdev, &pdev->request); - break; - - default: - USBD_LL_StallEP(pdev , pdev->request.bmRequest & 0x80); - break; - } - return USBD_OK; -} - -/** -* @brief USBD_DataOutStage -* Handle data OUT stage -* @param pdev: device instance -* @param epnum: endpoint index -* @retval status -*/ -USBD_StatusTypeDef USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev , uint8_t epnum, uint8_t *pdata) -{ - USBD_EndpointTypeDef *pep; - - if(epnum == 0) - { - pep = &pdev->ep_out[0]; - - if ( pdev->ep0_state == USBD_EP0_DATA_OUT) - { - if(pep->rem_length > pep->maxpacket) - { - pep->rem_length -= pep->maxpacket; - - USBD_CtlContinueRx (pdev, - pdata, - MIN(pep->rem_length ,pep->maxpacket)); - } - else - { - if((pdev->pClass->EP0_RxReady != NULL)&& - (pdev->dev_state == USBD_STATE_CONFIGURED)) - { - pdev->pClass->EP0_RxReady(pdev); - } - USBD_CtlSendStatus(pdev); - } - } - } - else if((pdev->pClass->DataOut != NULL)&& - (pdev->dev_state == USBD_STATE_CONFIGURED)) - { - pdev->pClass->DataOut(pdev, epnum); - } - return USBD_OK; -} - -/** -* @brief USBD_DataInStage -* Handle data in stage -* @param pdev: device instance -* @param epnum: endpoint index -* @retval status -*/ -USBD_StatusTypeDef USBD_LL_DataInStage(USBD_HandleTypeDef *pdev ,uint8_t epnum, uint8_t *pdata) -{ - USBD_EndpointTypeDef *pep; - - if(epnum == 0) - { - pep = &pdev->ep_in[0]; - - if ( pdev->ep0_state == USBD_EP0_DATA_IN) - { - if(pep->rem_length > pep->maxpacket) - { - pep->rem_length -= pep->maxpacket; - - USBD_CtlContinueSendData (pdev, - pdata, - pep->rem_length); - - /* Prepare endpoint for premature end of transfer */ - USBD_LL_PrepareReceive (pdev, - 0, - NULL, - 0); - } - else - { /* last packet is MPS multiple, so send ZLP packet */ - if((pep->total_length % pep->maxpacket == 0) && - (pep->total_length >= pep->maxpacket) && - (pep->total_length < pdev->ep0_data_len )) - { - - USBD_CtlContinueSendData(pdev , NULL, 0); - pdev->ep0_data_len = 0; - - /* Prepare endpoint for premature end of transfer */ - USBD_LL_PrepareReceive (pdev, - 0, - NULL, - 0); - } - else - { - if((pdev->pClass->EP0_TxSent != NULL)&& - (pdev->dev_state == USBD_STATE_CONFIGURED)) - { - pdev->pClass->EP0_TxSent(pdev); - } - USBD_CtlReceiveStatus(pdev); - } - } - } - if (pdev->dev_test_mode == 1) - { - USBD_RunTestMode(pdev); - pdev->dev_test_mode = 0; - } - } - else if((pdev->pClass->DataIn != NULL)&& - (pdev->dev_state == USBD_STATE_CONFIGURED)) - { - pdev->pClass->DataIn(pdev, epnum); - } - return USBD_OK; -} - -/** -* @brief USBD_LL_Reset -* Handle Reset event -* @param pdev: device instance -* @retval status -*/ - -USBD_StatusTypeDef USBD_LL_Reset(USBD_HandleTypeDef *pdev) -{ - /* Open EP0 OUT */ - USBD_LL_OpenEP(pdev, - 0x00, - USBD_EP_TYPE_CTRL, - USB_MAX_EP0_SIZE); - - pdev->ep_out[0].maxpacket = USB_MAX_EP0_SIZE; - - /* Open EP0 IN */ - USBD_LL_OpenEP(pdev, - 0x80, - USBD_EP_TYPE_CTRL, - USB_MAX_EP0_SIZE); - - pdev->ep_in[0].maxpacket = USB_MAX_EP0_SIZE; - /* Upon Reset call user call back */ - pdev->dev_state = USBD_STATE_DEFAULT; - - if (pdev->pClassData) - pdev->pClass->DeInit(pdev, pdev->dev_config); - - - return USBD_OK; -} - - - - -/** -* @brief USBD_LL_Reset -* Handle Reset event -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev, USBD_SpeedTypeDef speed) -{ - pdev->dev_speed = speed; - return USBD_OK; -} - -/** -* @brief USBD_Suspend -* Handle Suspend event -* @param pdev: device instance -* @retval status -*/ - -USBD_StatusTypeDef USBD_LL_Suspend(USBD_HandleTypeDef *pdev) -{ - pdev->dev_old_state = pdev->dev_state; - pdev->dev_state = USBD_STATE_SUSPENDED; - return USBD_OK; -} - -/** -* @brief USBD_Resume -* Handle Resume event -* @param pdev: device instance -* @retval status -*/ - -USBD_StatusTypeDef USBD_LL_Resume(USBD_HandleTypeDef *pdev) -{ - pdev->dev_state = pdev->dev_old_state; - return USBD_OK; -} - -/** -* @brief USBD_SOF -* Handle SOF event -* @param pdev: device instance -* @retval status -*/ - -USBD_StatusTypeDef USBD_LL_SOF(USBD_HandleTypeDef *pdev) -{ - if(pdev->dev_state == USBD_STATE_CONFIGURED) - { - if(pdev->pClass->SOF != NULL) - { - pdev->pClass->SOF(pdev); - } - } - return USBD_OK; -} - -/** -* @brief USBD_IsoINIncomplete -* Handle iso in incomplete event -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_LL_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum) -{ - return USBD_OK; -} - -/** -* @brief USBD_IsoOUTIncomplete -* Handle iso out incomplete event -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum) -{ - return USBD_OK; -} - -/** -* @brief USBD_DevConnected -* Handle device connection event -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef *pdev) -{ - return USBD_OK; -} - -/** -* @brief USBD_DevDisconnected -* Handle device disconnection event -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef *pdev) -{ - /* Free Class Resources */ - pdev->dev_state = USBD_STATE_DEFAULT; - pdev->pClass->DeInit(pdev, pdev->dev_config); - - return USBD_OK; -} -/** -* @} -*/ - - -/** -* @} -*/ - - -/** -* @} -*/ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ - diff --git a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_ctlreq.c b/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_ctlreq.c deleted file mode 100644 index 7701a6d..0000000 --- a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_ctlreq.c +++ /dev/null @@ -1,782 +0,0 @@ -/** - ****************************************************************************** - * @file usbd_req.c - * @author MCD Application Team - * @version V2.4.2 - * @date 11-December-2015 - * @brief This file provides the standard USB requests following chapter 9. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2015 STMicroelectronics

- * - * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/software_license_agreement_liberty_v2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_ctlreq.h" -#include "usbd_ioreq.h" - - -/** @addtogroup STM32_USBD_STATE_DEVICE_LIBRARY - * @{ - */ - - -/** @defgroup USBD_REQ - * @brief USB standard requests module - * @{ - */ - -/** @defgroup USBD_REQ_Private_TypesDefinitions - * @{ - */ -/** - * @} - */ - - -/** @defgroup USBD_REQ_Private_Defines - * @{ - */ - -/** - * @} - */ - - -/** @defgroup USBD_REQ_Private_Macros - * @{ - */ -/** - * @} - */ - - -/** @defgroup USBD_REQ_Private_Variables - * @{ - */ -/** - * @} - */ - - -/** @defgroup USBD_REQ_Private_FunctionPrototypes - * @{ - */ -static void USBD_GetDescriptor(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req); - -static void USBD_SetAddress(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req); - -static void USBD_SetConfig(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req); - -static void USBD_GetConfig(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req); - -static void USBD_GetStatus(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req); - -static void USBD_SetFeature(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req); - -static void USBD_ClrFeature(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req); - -static uint8_t USBD_GetLen(uint8_t *buf); - -/** - * @} - */ - - -/** @defgroup USBD_REQ_Private_Functions - * @{ - */ - - -/** -* @brief USBD_StdDevReq -* Handle standard usb device requests -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -USBD_StatusTypeDef USBD_StdDevReq (USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef *req) -{ - USBD_StatusTypeDef ret = USBD_OK; - - switch (req->bRequest) - { - case USB_REQ_GET_DESCRIPTOR: - - USBD_GetDescriptor (pdev, req) ; - break; - - case USB_REQ_SET_ADDRESS: - USBD_SetAddress(pdev, req); - break; - - case USB_REQ_SET_CONFIGURATION: - USBD_SetConfig (pdev , req); - break; - - case USB_REQ_GET_CONFIGURATION: - USBD_GetConfig (pdev , req); - break; - - case USB_REQ_GET_STATUS: - USBD_GetStatus (pdev , req); - break; - - - case USB_REQ_SET_FEATURE: - USBD_SetFeature (pdev , req); - break; - - case USB_REQ_CLEAR_FEATURE: - USBD_ClrFeature (pdev , req); - break; - - default: - USBD_CtlError(pdev , req); - break; - } - - return ret; -} - -/** -* @brief USBD_StdItfReq -* Handle standard usb interface requests -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -USBD_StatusTypeDef USBD_StdItfReq (USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef *req) -{ - USBD_StatusTypeDef ret = USBD_OK; - - switch (pdev->dev_state) - { - case USBD_STATE_CONFIGURED: - - if (LOBYTE(req->wIndex) <= USBD_MAX_NUM_INTERFACES) - { - pdev->pClass->Setup (pdev, req); - - if((req->wLength == 0)&& (ret == USBD_OK)) - { - USBD_CtlSendStatus(pdev); - } - } - else - { - USBD_CtlError(pdev , req); - } - break; - - default: - USBD_CtlError(pdev , req); - break; - } - return USBD_OK; -} - -/** -* @brief USBD_StdEPReq -* Handle standard usb endpoint requests -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -USBD_StatusTypeDef USBD_StdEPReq (USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef *req) -{ - - uint8_t ep_addr; - USBD_StatusTypeDef ret = USBD_OK; - USBD_EndpointTypeDef *pep; - ep_addr = LOBYTE(req->wIndex); - - /* Check if it is a class request */ - if ((req->bmRequest & 0x60) == 0x20) - { - pdev->pClass->Setup (pdev, req); - - return USBD_OK; - } - - switch (req->bRequest) - { - - case USB_REQ_SET_FEATURE : - - switch (pdev->dev_state) - { - case USBD_STATE_ADDRESSED: - if ((ep_addr != 0x00) && (ep_addr != 0x80)) - { - USBD_LL_StallEP(pdev , ep_addr); - } - break; - - case USBD_STATE_CONFIGURED: - if (req->wValue == USB_FEATURE_EP_HALT) - { - if ((ep_addr != 0x00) && (ep_addr != 0x80)) - { - USBD_LL_StallEP(pdev , ep_addr); - - } - } - pdev->pClass->Setup (pdev, req); - USBD_CtlSendStatus(pdev); - - break; - - default: - USBD_CtlError(pdev , req); - break; - } - break; - - case USB_REQ_CLEAR_FEATURE : - - switch (pdev->dev_state) - { - case USBD_STATE_ADDRESSED: - if ((ep_addr != 0x00) && (ep_addr != 0x80)) - { - USBD_LL_StallEP(pdev , ep_addr); - } - break; - - case USBD_STATE_CONFIGURED: - if (req->wValue == USB_FEATURE_EP_HALT) - { - if ((ep_addr & 0x7F) != 0x00) - { - USBD_LL_ClearStallEP(pdev , ep_addr); - pdev->pClass->Setup (pdev, req); - } - USBD_CtlSendStatus(pdev); - } - break; - - default: - USBD_CtlError(pdev , req); - break; - } - break; - - case USB_REQ_GET_STATUS: - switch (pdev->dev_state) - { - case USBD_STATE_ADDRESSED: - if ((ep_addr & 0x7F) != 0x00) - { - USBD_LL_StallEP(pdev , ep_addr); - } - break; - - case USBD_STATE_CONFIGURED: - pep = ((ep_addr & 0x80) == 0x80) ? &pdev->ep_in[ep_addr & 0x7F]:\ - &pdev->ep_out[ep_addr & 0x7F]; - if(USBD_LL_IsStallEP(pdev, ep_addr)) - { - pep->status = 0x0001; - } - else - { - pep->status = 0x0000; - } - - USBD_CtlSendData (pdev, - (uint8_t *)&pep->status, - 2); - break; - - default: - USBD_CtlError(pdev , req); - break; - } - break; - - default: - break; - } - return ret; -} -/** -* @brief USBD_GetDescriptor -* Handle Get Descriptor requests -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -static void USBD_GetDescriptor(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req) -{ - uint16_t len; - uint8_t *pbuf; - - - switch (req->wValue >> 8) - { -#if (USBD_LPM_ENABLED == 1) - case USB_DESC_TYPE_BOS: - pbuf = pdev->pDesc->GetBOSDescriptor(pdev->dev_speed, &len); - break; -#endif - case USB_DESC_TYPE_DEVICE: - pbuf = pdev->pDesc->GetDeviceDescriptor(pdev->dev_speed, &len); - break; - - case USB_DESC_TYPE_CONFIGURATION: - if(pdev->dev_speed == USBD_SPEED_HIGH ) - { - pbuf = (uint8_t *)pdev->pClass->GetHSConfigDescriptor(&len); - pbuf[1] = USB_DESC_TYPE_CONFIGURATION; - } - else - { - pbuf = (uint8_t *)pdev->pClass->GetFSConfigDescriptor(&len); - pbuf[1] = USB_DESC_TYPE_CONFIGURATION; - } - break; - - case USB_DESC_TYPE_STRING: - switch ((uint8_t)(req->wValue)) - { - case USBD_IDX_LANGID_STR: - pbuf = pdev->pDesc->GetLangIDStrDescriptor(pdev->dev_speed, &len); - break; - - case USBD_IDX_MFC_STR: - pbuf = pdev->pDesc->GetManufacturerStrDescriptor(pdev->dev_speed, &len); - break; - - case USBD_IDX_PRODUCT_STR: - pbuf = pdev->pDesc->GetProductStrDescriptor(pdev->dev_speed, &len); - break; - - case USBD_IDX_SERIAL_STR: - pbuf = pdev->pDesc->GetSerialStrDescriptor(pdev->dev_speed, &len); - break; - - case USBD_IDX_CONFIG_STR: - pbuf = pdev->pDesc->GetConfigurationStrDescriptor(pdev->dev_speed, &len); - break; - - case USBD_IDX_INTERFACE_STR: - pbuf = pdev->pDesc->GetInterfaceStrDescriptor(pdev->dev_speed, &len); - break; - - default: -#if (USBD_SUPPORT_USER_STRING == 1) - pbuf = pdev->pClass->GetUsrStrDescriptor(pdev, (req->wValue) , &len); - break; -#else - USBD_CtlError(pdev , req); - return; -#endif - } - break; - case USB_DESC_TYPE_DEVICE_QUALIFIER: - - if(pdev->dev_speed == USBD_SPEED_HIGH ) - { - pbuf = (uint8_t *)pdev->pClass->GetDeviceQualifierDescriptor(&len); - break; - } - else - { - USBD_CtlError(pdev , req); - return; - } - - case USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION: - if(pdev->dev_speed == USBD_SPEED_HIGH ) - { - pbuf = (uint8_t *)pdev->pClass->GetOtherSpeedConfigDescriptor(&len); - pbuf[1] = USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION; - break; - } - else - { - USBD_CtlError(pdev , req); - return; - } - - default: - USBD_CtlError(pdev , req); - return; - } - - if((len != 0)&& (req->wLength != 0)) - { - - len = MIN(len , req->wLength); - - USBD_CtlSendData (pdev, - pbuf, - len); - } - -} - -/** -* @brief USBD_SetAddress -* Set device address -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -static void USBD_SetAddress(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req) -{ - uint8_t dev_addr; - - if ((req->wIndex == 0) && (req->wLength == 0)) - { - dev_addr = (uint8_t)(req->wValue) & 0x7F; - - if (pdev->dev_state == USBD_STATE_CONFIGURED) - { - USBD_CtlError(pdev , req); - } - else - { - pdev->dev_address = dev_addr; - USBD_LL_SetUSBAddress(pdev, dev_addr); - USBD_CtlSendStatus(pdev); - - if (dev_addr != 0) - { - pdev->dev_state = USBD_STATE_ADDRESSED; - } - else - { - pdev->dev_state = USBD_STATE_DEFAULT; - } - } - } - else - { - USBD_CtlError(pdev , req); - } -} - -/** -* @brief USBD_SetConfig -* Handle Set device configuration request -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -static void USBD_SetConfig(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req) -{ - - static uint8_t cfgidx; - - cfgidx = (uint8_t)(req->wValue); - - if (cfgidx > USBD_MAX_NUM_CONFIGURATION ) - { - USBD_CtlError(pdev , req); - } - else - { - switch (pdev->dev_state) - { - case USBD_STATE_ADDRESSED: - if (cfgidx) - { - pdev->dev_config = cfgidx; - pdev->dev_state = USBD_STATE_CONFIGURED; - if(USBD_SetClassConfig(pdev , cfgidx) == USBD_FAIL) - { - USBD_CtlError(pdev , req); - return; - } - USBD_CtlSendStatus(pdev); - } - else - { - USBD_CtlSendStatus(pdev); - } - break; - - case USBD_STATE_CONFIGURED: - if (cfgidx == 0) - { - pdev->dev_state = USBD_STATE_ADDRESSED; - pdev->dev_config = cfgidx; - USBD_ClrClassConfig(pdev , cfgidx); - USBD_CtlSendStatus(pdev); - - } - else if (cfgidx != pdev->dev_config) - { - /* Clear old configuration */ - USBD_ClrClassConfig(pdev , pdev->dev_config); - - /* set new configuration */ - pdev->dev_config = cfgidx; - if(USBD_SetClassConfig(pdev , cfgidx) == USBD_FAIL) - { - USBD_CtlError(pdev , req); - return; - } - USBD_CtlSendStatus(pdev); - } - else - { - USBD_CtlSendStatus(pdev); - } - break; - - default: - USBD_CtlError(pdev , req); - break; - } - } -} - -/** -* @brief USBD_GetConfig -* Handle Get device configuration request -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -static void USBD_GetConfig(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req) -{ - - if (req->wLength != 1) - { - USBD_CtlError(pdev , req); - } - else - { - switch (pdev->dev_state ) - { - case USBD_STATE_ADDRESSED: - pdev->dev_default_config = 0; - USBD_CtlSendData (pdev, - (uint8_t *)&pdev->dev_default_config, - 1); - break; - - case USBD_STATE_CONFIGURED: - - USBD_CtlSendData (pdev, - (uint8_t *)&pdev->dev_config, - 1); - break; - - default: - USBD_CtlError(pdev , req); - break; - } - } -} - -/** -* @brief USBD_GetStatus -* Handle Get Status request -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -static void USBD_GetStatus(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req) -{ - - - switch (pdev->dev_state) - { - case USBD_STATE_ADDRESSED: - case USBD_STATE_CONFIGURED: - -#if ( USBD_SELF_POWERED == 1) - pdev->dev_config_status = USB_CONFIG_SELF_POWERED; -#else - pdev->dev_config_status = 0; -#endif - - if (pdev->dev_remote_wakeup) - { - pdev->dev_config_status |= USB_CONFIG_REMOTE_WAKEUP; - } - - USBD_CtlSendData (pdev, - (uint8_t *)& pdev->dev_config_status, - 2); - break; - - default : - USBD_CtlError(pdev , req); - break; - } -} - - -/** -* @brief USBD_SetFeature -* Handle Set device feature request -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -static void USBD_SetFeature(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req) -{ - - if (req->wValue == USB_FEATURE_REMOTE_WAKEUP) - { - pdev->dev_remote_wakeup = 1; - pdev->pClass->Setup (pdev, req); - USBD_CtlSendStatus(pdev); - } - -} - - -/** -* @brief USBD_ClrFeature -* Handle clear device feature request -* @param pdev: device instance -* @param req: usb request -* @retval status -*/ -static void USBD_ClrFeature(USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req) -{ - switch (pdev->dev_state) - { - case USBD_STATE_ADDRESSED: - case USBD_STATE_CONFIGURED: - if (req->wValue == USB_FEATURE_REMOTE_WAKEUP) - { - pdev->dev_remote_wakeup = 0; - pdev->pClass->Setup (pdev, req); - USBD_CtlSendStatus(pdev); - } - break; - - default : - USBD_CtlError(pdev , req); - break; - } -} - -/** -* @brief USBD_ParseSetupRequest -* Copy buffer into setup structure -* @param pdev: device instance -* @param req: usb request -* @retval None -*/ - -void USBD_ParseSetupRequest(USBD_SetupReqTypedef *req, uint8_t *pdata) -{ - req->bmRequest = *(uint8_t *) (pdata); - req->bRequest = *(uint8_t *) (pdata + 1); - req->wValue = SWAPBYTE (pdata + 2); - req->wIndex = SWAPBYTE (pdata + 4); - req->wLength = SWAPBYTE (pdata + 6); - -} - -/** -* @brief USBD_CtlError -* Handle USB low level Error -* @param pdev: device instance -* @param req: usb request -* @retval None -*/ - -void USBD_CtlError( USBD_HandleTypeDef *pdev , - USBD_SetupReqTypedef *req) -{ - USBD_LL_StallEP(pdev , 0x80); - USBD_LL_StallEP(pdev , 0); -} - - -/** - * @brief USBD_GetString - * Convert Ascii string into unicode one - * @param desc : descriptor buffer - * @param unicode : Formatted string buffer (unicode) - * @param len : descriptor length - * @retval None - */ -void USBD_GetString(uint8_t *desc, uint8_t *unicode, uint16_t *len) -{ - uint8_t idx = 0; - - if (desc != NULL) - { - *len = USBD_GetLen(desc) * 2 + 2; - unicode[idx++] = *len; - unicode[idx++] = USB_DESC_TYPE_STRING; - - while (*desc != '\0') - { - unicode[idx++] = *desc++; - unicode[idx++] = 0x00; - } - } -} - -/** - * @brief USBD_GetLen - * return the string length - * @param buf : pointer to the ascii string buffer - * @retval string length - */ -static uint8_t USBD_GetLen(uint8_t *buf) -{ - uint8_t len = 0; - - while (*buf != '\0') - { - len++; - buf++; - } - - return len; -} -/** - * @} - */ - - -/** - * @} - */ - - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_ioreq.c b/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_ioreq.c deleted file mode 100644 index d66d777..0000000 --- a/fw/hid-dials/Middlewares/ST/STM32_USB_Device_Library/Core/Src/usbd_ioreq.c +++ /dev/null @@ -1,236 +0,0 @@ -/** - ****************************************************************************** - * @file usbd_ioreq.c - * @author MCD Application Team - * @version V2.4.2 - * @date 11-December-2015 - * @brief This file provides the IO requests APIs for control endpoints. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2015 STMicroelectronics

- * - * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/software_license_agreement_liberty_v2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_ioreq.h" - -/** @addtogroup STM32_USB_DEVICE_LIBRARY - * @{ - */ - - -/** @defgroup USBD_IOREQ - * @brief control I/O requests module - * @{ - */ - -/** @defgroup USBD_IOREQ_Private_TypesDefinitions - * @{ - */ -/** - * @} - */ - - -/** @defgroup USBD_IOREQ_Private_Defines - * @{ - */ - -/** - * @} - */ - - -/** @defgroup USBD_IOREQ_Private_Macros - * @{ - */ -/** - * @} - */ - - -/** @defgroup USBD_IOREQ_Private_Variables - * @{ - */ - -/** - * @} - */ - - -/** @defgroup USBD_IOREQ_Private_FunctionPrototypes - * @{ - */ -/** - * @} - */ - - -/** @defgroup USBD_IOREQ_Private_Functions - * @{ - */ - -/** -* @brief USBD_CtlSendData -* send data on the ctl pipe -* @param pdev: device instance -* @param buff: pointer to data buffer -* @param len: length of data to be sent -* @retval status -*/ -USBD_StatusTypeDef USBD_CtlSendData (USBD_HandleTypeDef *pdev, - uint8_t *pbuf, - uint16_t len) -{ - /* Set EP0 State */ - pdev->ep0_state = USBD_EP0_DATA_IN; - pdev->ep_in[0].total_length = len; - pdev->ep_in[0].rem_length = len; - /* Start the transfer */ - USBD_LL_Transmit (pdev, 0x00, pbuf, len); - - return USBD_OK; -} - -/** -* @brief USBD_CtlContinueSendData -* continue sending data on the ctl pipe -* @param pdev: device instance -* @param buff: pointer to data buffer -* @param len: length of data to be sent -* @retval status -*/ -USBD_StatusTypeDef USBD_CtlContinueSendData (USBD_HandleTypeDef *pdev, - uint8_t *pbuf, - uint16_t len) -{ - /* Start the next transfer */ - USBD_LL_Transmit (pdev, 0x00, pbuf, len); - - return USBD_OK; -} - -/** -* @brief USBD_CtlPrepareRx -* receive data on the ctl pipe -* @param pdev: device instance -* @param buff: pointer to data buffer -* @param len: length of data to be received -* @retval status -*/ -USBD_StatusTypeDef USBD_CtlPrepareRx (USBD_HandleTypeDef *pdev, - uint8_t *pbuf, - uint16_t len) -{ - /* Set EP0 State */ - pdev->ep0_state = USBD_EP0_DATA_OUT; - pdev->ep_out[0].total_length = len; - pdev->ep_out[0].rem_length = len; - /* Start the transfer */ - USBD_LL_PrepareReceive (pdev, - 0, - pbuf, - len); - - return USBD_OK; -} - -/** -* @brief USBD_CtlContinueRx -* continue receive data on the ctl pipe -* @param pdev: device instance -* @param buff: pointer to data buffer -* @param len: length of data to be received -* @retval status -*/ -USBD_StatusTypeDef USBD_CtlContinueRx (USBD_HandleTypeDef *pdev, - uint8_t *pbuf, - uint16_t len) -{ - - USBD_LL_PrepareReceive (pdev, - 0, - pbuf, - len); - return USBD_OK; -} -/** -* @brief USBD_CtlSendStatus -* send zero lzngth packet on the ctl pipe -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_CtlSendStatus (USBD_HandleTypeDef *pdev) -{ - - /* Set EP0 State */ - pdev->ep0_state = USBD_EP0_STATUS_IN; - - /* Start the transfer */ - USBD_LL_Transmit (pdev, 0x00, NULL, 0); - - return USBD_OK; -} - -/** -* @brief USBD_CtlReceiveStatus -* receive zero lzngth packet on the ctl pipe -* @param pdev: device instance -* @retval status -*/ -USBD_StatusTypeDef USBD_CtlReceiveStatus (USBD_HandleTypeDef *pdev) -{ - /* Set EP0 State */ - pdev->ep0_state = USBD_EP0_STATUS_OUT; - - /* Start the transfer */ - USBD_LL_PrepareReceive ( pdev, - 0, - NULL, - 0); - - return USBD_OK; -} - - -/** -* @brief USBD_GetRxCount -* returns the received data length -* @param pdev: device instance -* @param ep_addr: endpoint address -* @retval Rx Data blength -*/ -uint16_t USBD_GetRxCount (USBD_HandleTypeDef *pdev , uint8_t ep_addr) -{ - return USBD_LL_GetRxDataSize(pdev, ep_addr); -} - -/** - * @} - */ - - -/** - * @} - */ - - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/README.md b/fw/hid-dials/README.md deleted file mode 100644 index a6f5438..0000000 --- a/fw/hid-dials/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# HID implementation for IBM-dials-retrofit - -Works, currently hardcoded: - - - Dial 1: Volume Up/Down - - Dial 2: nothing - - Dial 3: KiCAD switch layer (v) - - Dial 4: KiCAD rotate part (r|R) - - Dial 5: KiCAD change grid settings (n|N) - - Dial 6: nothing - - Dial 7: KiCAD change track width (w|W) - - Dial 8: KiCAD zoom (+|-) - - Build with `make` - - Flash with `dfu-util -a 0 -s 0x08000000:leave -D build/hid-dials.bin` - - Todo: - - - [ ] Add filesystem and csv alike config files diff --git a/fw/hid-dials/STM32F072CBUx_FLASH.ld b/fw/hid-dials/STM32F072CBUx_FLASH.ld deleted file mode 100644 index ea1b89e..0000000 --- a/fw/hid-dials/STM32F072CBUx_FLASH.ld +++ /dev/null @@ -1,189 +0,0 @@ -/* -****************************************************************************** -** - -** File : LinkerScript.ld -** -** Author : Auto-generated by System Workbench for STM32 -** -** Abstract : Linker script for STM32F072CBUx series -** 128Kbytes FLASH and 16Kbytes RAM -** -** Set heap size, stack size and stack location according -** to application requirements. -** -** Set memory bank area and size if external memory is used. -** -** Target : STMicroelectronics STM32 -** -** Distribution: The file is distributed “as is,” without any warranty -** of any kind. -** -***************************************************************************** -** @attention -** -**

© COPYRIGHT(c) 2019 STMicroelectronics

-** -** Redistribution and use in source and binary forms, with or without modification, -** are permitted provided that the following conditions are met: -** 1. Redistributions of source code must retain the above copyright notice, -** this list of conditions and the following disclaimer. -** 2. Redistributions in binary form must reproduce the above copyright notice, -** this list of conditions and the following disclaimer in the documentation -** and/or other materials provided with the distribution. -** 3. Neither the name of STMicroelectronics nor the names of its contributors -** may be used to endorse or promote products derived from this software -** without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -***************************************************************************** -*/ - -/* Entry Point */ -ENTRY(Reset_Handler) - -/* Highest address of the user mode stack */ -_estack = 0x20004000; /* end of RAM */ -/* Generate a link error if heap and stack don't fit into RAM */ -_Min_Heap_Size = 0x200; /* required amount of heap */ -_Min_Stack_Size = 0x400; /* required amount of stack */ - -/* Specify the memory areas */ -MEMORY -{ -RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 16K -FLASH (rx) : ORIGIN = 0x8000000, LENGTH = 128K -} - -/* Define output sections */ -SECTIONS -{ - /* The startup code goes first into FLASH */ - .isr_vector : - { - . = ALIGN(4); - KEEP(*(.isr_vector)) /* Startup code */ - . = ALIGN(4); - } >FLASH - - /* The program code and other data goes into FLASH */ - .text : - { - . = ALIGN(4); - *(.text) /* .text sections (code) */ - *(.text*) /* .text* sections (code) */ - *(.glue_7) /* glue arm to thumb code */ - *(.glue_7t) /* glue thumb to arm code */ - *(.eh_frame) - - KEEP (*(.init)) - KEEP (*(.fini)) - - . = ALIGN(4); - _etext = .; /* define a global symbols at end of code */ - } >FLASH - - /* Constant data goes into FLASH */ - .rodata : - { - . = ALIGN(4); - *(.rodata) /* .rodata sections (constants, strings, etc.) */ - *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ - . = ALIGN(4); - } >FLASH - - .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH - .ARM : { - __exidx_start = .; - *(.ARM.exidx*) - __exidx_end = .; - } >FLASH - - .preinit_array : - { - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP (*(.preinit_array*)) - PROVIDE_HIDDEN (__preinit_array_end = .); - } >FLASH - .init_array : - { - PROVIDE_HIDDEN (__init_array_start = .); - KEEP (*(SORT(.init_array.*))) - KEEP (*(.init_array*)) - PROVIDE_HIDDEN (__init_array_end = .); - } >FLASH - .fini_array : - { - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP (*(SORT(.fini_array.*))) - KEEP (*(.fini_array*)) - PROVIDE_HIDDEN (__fini_array_end = .); - } >FLASH - - /* used by the startup to initialize data */ - _sidata = LOADADDR(.data); - - /* Initialized data sections goes into RAM, load LMA copy after code */ - .data : - { - . = ALIGN(4); - _sdata = .; /* create a global symbol at data start */ - *(.data) /* .data sections */ - *(.data*) /* .data* sections */ - - . = ALIGN(4); - _edata = .; /* define a global symbol at data end */ - } >RAM AT> FLASH - - - /* Uninitialized data section */ - . = ALIGN(4); - .bss : - { - /* This is used by the startup in order to initialize the .bss secion */ - _sbss = .; /* define a global symbol at bss start */ - __bss_start__ = _sbss; - *(.bss) - *(.bss*) - *(COMMON) - - . = ALIGN(4); - _ebss = .; /* define a global symbol at bss end */ - __bss_end__ = _ebss; - } >RAM - - /* User_heap_stack section, used to check that there is enough RAM left */ - ._user_heap_stack : - { - . = ALIGN(8); - PROVIDE ( end = . ); - PROVIDE ( _end = . ); - . = . + _Min_Heap_Size; - . = . + _Min_Stack_Size; - . = ALIGN(8); - } >RAM - - - - /* Remove information from the standard libraries */ - /DISCARD/ : - { - libc.a ( * ) - libm.a ( * ) - libgcc.a ( * ) - } - - .ARM.attributes 0 : { *(.ARM.attributes) } -} - - diff --git a/fw/hid-dials/src/main.c b/fw/hid-dials/src/main.c deleted file mode 100644 index b84e24b..0000000 --- a/fw/hid-dials/src/main.c +++ /dev/null @@ -1,474 +0,0 @@ - -#include - -#include "main.h" -#include "usb_device.h" -#include "usbd_hid.h" - -#define HID_MEDIA_REPORT 2 -#define HYSTERESIS 200 - -ADC_HandleTypeDef hadc; -DMA_HandleTypeDef hdma_adc; - -void SystemClock_Config(void); -static void MX_GPIO_Init(void); -static void key_matrix_select(int row); -static int key_matrix_query(int debounce_time); -static uint32_t poll_encoders(void); -static uint32_t poll_keys(void); - -enum keybits { - /* These match up with the record descriptor in usbd_hid.c */ - KEYBITS_NEXT = 0x01, - KEYBITS_PREV = 0x02, - KEYBITS_STOP = 0x04, - KEYBITS_PLAY_PAUSE = 0x08, - KEYBITS_MUTE = 0x10, - KEYBITS_VOL_UP = 0x20, - KEYBITS_VOL_DOWN = 0x40, -}; - -enum key_names { - KEY_2 = 0, - KEY_3 = 1, - KEY_1 = 2, - KEY_ENC = 3, - KEY_4 = 4 -}; - -enum keymap_rows { - KEYMAP_BOTTOM_LEFT_ENC = 0, - KEYMAP_TOP_RIGHT_ENC = 1, -}; - -enum key_matrix_params { - KEY_MATRIX_ROWS = 5, - KEY_MATRIX_COLS = 2, -}; - -void sendKeybits(uint8_t keybits); - -struct key_t -{ - uint8_t id; - uint8_t modifier; - uint8_t reserved; - uint8_t keycode[6]; -} key; - -uint16_t ADCreg[8]; -uint16_t ADCval[8]; -uint16_t ADClast[8]; - -/* FIXME debug remove */ -TIM_TypeDef *tim1 = TIM1; -TIM_TypeDef *tim3 = TIM3; - -int main(void) -{ - HAL_Init(); - - SystemClock_Config(); - - MX_GPIO_Init(); - MX_USB_HID_INIT(); - - __HAL_RCC_TIM1_CLK_ENABLE(); - __HAL_RCC_TIM3_CLK_ENABLE(); - - TIM1->SMCR = 3; // Encoder mode 3 - TIM1->CCER = 0; // rising edge polarity - TIM1->ARR = 0xFFFF; // count from 0-ARR or ARR-0 - TIM1->CCMR1 = 0x0101; // f_DTS/16, N=8, IC1->TI1, IC2->TI2 - TIM1->CNT = 0; // Initialize counter - TIM1->EGR = 1; // Generate an update event - TIM1->CR1 = 1; // Enable the counter - - TIM3->SMCR = 3; // Encoder mode 3 - TIM3->CCER = 0; // rising edge polarity - TIM3->ARR = 0xFFFF; // count from 0-ARR or ARR-0 - TIM3->CCMR1 = 0x0101; // f_DTS/16, N=8, IC1->TI1, IC2->TI2 - TIM3->CNT = 0; // Initialize counter - TIM3->EGR = 1; // Generate an update event - TIM3->CR1 = 1; // Enable the counter - - while (1) { - uint32_t keybits = poll_encoders(); - for (int i=0; i<10; i++) { - keybits |= poll_keys(); - HAL_Delay(1); - } - sendKeybits(keybits); - } -} - -void * _sbrk(ptrdiff_t __incr); -void * _sbrk(ptrdiff_t __incr) { - /* FIXME Do we even need this? */ - return NULL; -} - -void _init(void); -void _init() { - /* FIXME Do we even need this? */ -} - -static uint32_t poll_encoders() { - static bool tx_vol_reset = 0; - static uint16_t tim1_last = 0, tim3_last = 0; /* timers init to 0 */ - static int vol_delta = 0; - - uint16_t tim1_now = TIM1->CNT, tim3_now = TIM3->CNT; - int16_t tim1_delta = (int16_t)(tim1_now - tim1_last); - int16_t tim3_delta = (int16_t)(tim3_now - tim3_last); - - /* Gang both encoders */ - vol_delta += tim3_delta - tim1_delta; - -#define VOL_DELTA_INC 4 - uint8_t keybits = 0; - if (!tx_vol_reset) { - /* Customize encoder action here */ - if (vol_delta >= VOL_DELTA_INC) { - keybits |= KEYBITS_VOL_UP; - vol_delta -= VOL_DELTA_INC; - tx_vol_reset = 1; - } else if (vol_delta <= -VOL_DELTA_INC) { - keybits |= KEYBITS_VOL_DOWN; - vol_delta += VOL_DELTA_INC; - tx_vol_reset = 1; - } - } else { - tx_vol_reset = 0; - } - - tim1_last = tim1_now; - tim3_last = tim3_now; - return keybits; -} - -static uint32_t poll_keys() { - int debounce_time = 5; /* 5 * 10 ms loop timing increments */ - uint32_t val = key_matrix_query(debounce_time); - uint32_t state = val&0xffff, edges = val>>16; - uint32_t pressed = state & edges; - (void)edges; /* unused */ - uint32_t keybits = 0; - - if (pressed & (1 << KEY_3)) - keybits |= KEYBITS_PLAY_PAUSE; - if (pressed & (1 << KEY_3 << KEY_MATRIX_ROWS)) - keybits |= KEYBITS_PREV; - if (pressed & (1 << KEY_4 << KEY_MATRIX_ROWS)) - keybits |= KEYBITS_NEXT; - if (pressed & (1 << KEY_ENC << KEY_MATRIX_ROWS)) - keybits |= KEYBITS_MUTE; - - return keybits; -} - -const uint8_t _asciimap[128] = -{ - 0x00, // NUL - 0x00, // SOH - 0x00, // STX - 0x00, // ETX - 0x00, // EOT - 0x00, // ENQ - 0x00, // ACK - 0x00, // BEL - 0x2a, // BS Backspace - 0x2b, // TAB Tab - 0x28, // LF Enter - 0x00, // VT - 0x00, // FF - 0x00, // CR - 0x00, // SO - 0x00, // SI - 0x00, // DEL - 0x00, // DC1 - 0x00, // DC2 - 0x00, // DC3 - 0x00, // DC4 - 0x00, // NAK - 0x00, // SYN - 0x00, // ETB - 0x00, // CAN - 0x00, // EM - 0x00, // SUB - 0x00, // ESC - 0x00, // FS - 0x00, // GS - 0x00, // RS - 0x00, // US - - 0x2c, // ' ' - 0x1e|0x80, // ! - 0x34|0x80, // " - 0x20|0x80, // # - 0x21|0x80, // $ - 0x22|0x80, // % - 0x24|0x80, // & - 0x34, // ' - 0x26|0x80, // ( - 0x27|0x80, // ) - 0x25|0x80, // * - 0x2e|0x80, // + - 0x36, // , - 0x2d, // - - 0x37, // . - 0x38, // / - 0x27, // 0 - 0x1e, // 1 - 0x1f, // 2 - 0x20, // 3 - 0x21, // 4 - 0x22, // 5 - 0x23, // 6 - 0x24, // 7 - 0x25, // 8 - 0x26, // 9 - 0x33|0x80, // : - 0x33, // ; - 0x36|0x80, // < - 0x2e, // = - 0x37|0x80, // > - 0x38|0x80, // ? - 0x1f|0x80, // @ - 0x04|0x80, // A - 0x05|0x80, // B - 0x06|0x80, // C - 0x07|0x80, // D - 0x08|0x80, // E - 0x09|0x80, // F - 0x0a|0x80, // G - 0x0b|0x80, // H - 0x0c|0x80, // I - 0x0d|0x80, // J - 0x0e|0x80, // K - 0x0f|0x80, // L - 0x10|0x80, // M - 0x11|0x80, // N - 0x12|0x80, // O - 0x13|0x80, // P - 0x14|0x80, // Q - 0x15|0x80, // R - 0x16|0x80, // S - 0x17|0x80, // T - 0x18|0x80, // U - 0x19|0x80, // V - 0x1a|0x80, // W - 0x1b|0x80, // X - 0x1c|0x80, // Y - 0x1d|0x80, // Z - 0x2f, // [ - 0x31, // bslash - 0x30, // ] - 0x23|0x80, // ^ - 0x2d|0x80, // _ - 0x35, // ` - 0x04, // a - 0x05, // b - 0x06, // c - 0x07, // d - 0x08, // e - 0x09, // f - 0x0a, // g - 0x0b, // h - 0x0c, // i - 0x0d, // j - 0x0e, // k - 0x0f, // l - 0x10, // m - 0x11, // n - 0x12, // o - 0x13, // p - 0x14, // q - 0x15, // r - 0x16, // s - 0x17, // t - 0x18, // u - 0x19, // v - 0x1a, // w - 0x1b, // x - 0x1c, // y - 0x1d, // z - 0x2f|0x80, // { - 0x31|0x80, // | - 0x30|0x80, // } - 0x35|0x80, // ~ - 0 // DEL -}; - - -void sendChar(uint8_t ch){ - if( ch > 128 ) ch -=128; - - key.id = 1; - key.keycode[0]=_asciimap[ch]&0x7F; - key.keycode[1]=0; - - if ( _asciimap[ch] & 0x80) key.modifier |= 0x02; - - for(int i=0; i< 4;i++){ - USBD_HID_SendReport(&hUsbDeviceFS, (uint8_t *)&key, sizeof(key)); - HAL_Delay(10); - } - memset(key.keycode, 0 , sizeof(key.keycode)); - key.modifier = 0; - USBD_HID_SendReport(&hUsbDeviceFS, (uint8_t *)&key, sizeof(key)); - HAL_Delay(10); -} - -void sendCharWrong(uint8_t ch){ - key.id = 1; - key.keycode[0]=ch&0x7F; - key.keycode[1]=0; - - if ( _asciimap[ch] & 0x80) key.modifier |= 0x02; - - for(int i=0; i< 4;i++){ - USBD_HID_SendReport(&hUsbDeviceFS, (uint8_t *)&key, sizeof(key)); - HAL_Delay(10); - } - memset(key.keycode, 0 , sizeof(key.keycode)); - key.modifier = 0; - USBD_HID_SendReport(&hUsbDeviceFS, (uint8_t *)&key, sizeof(key)); - HAL_Delay(10); -} - -void sendKeybits(uint8_t keybits){ - uint8_t report[2]; - report[0]= HID_MEDIA_REPORT; - report[1]= keybits; - USBD_HID_SendReport(&hUsbDeviceFS, report, 2); -} - -void SystemClock_Config(void) -{ - RCC_OscInitTypeDef RCC_OscInitStruct = {0}; - RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; - RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; - - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI14|RCC_OSCILLATORTYPE_HSI48; - RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; - RCC_OscInitStruct.HSI14State = RCC_HSI14_ON; - RCC_OscInitStruct.HSI14CalibrationValue = 16; - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; - HAL_RCC_OscConfig(&RCC_OscInitStruct); - - RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK - |RCC_CLOCKTYPE_PCLK1; - RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI48; - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; - RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; - HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1); - - PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB; - PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_HSI48; - HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit); - -} - -static void MX_GPIO_Init(void) { - __HAL_RCC_GPIOB_CLK_ENABLE(); - __HAL_RCC_GPIOA_CLK_ENABLE(); - - /* Left encoder (SW2) A/B inputs: PA9/PA8 (TIM1 CH1/2) - * Right encoder (SW7) A/B inputs: PB4/PB5 (TIM3 CH1/2) - * Key matrix: PB2 -> encoder switches left/right - * PB8 -> SW3/8 - * PB1 -> SW4/9 - * PA15 -> SW5/10 - * PA0 -> SW6/11 - * key matrix inputs: PA1/PA4 - * - * Physical key layout: - * - * +------------|USB|------------+ - * | SW9 SW11 SW10 SW8 | - * | SW2 SW7 | - * | SW4 SW6 SW5 SW3 | - * +-----------------------------+ - * - * Logical key layout: - * - * +------------|USB|------------+ - * | KT1 KT2 KT3 KT4 | - * | EL ER | - * | KB1 KB2 KB3 KB4 | - * +-----------------------------+ - * - */ - GPIOA->MODER = 0x28000000 | (2<<(8*2)) | (2<<(9*2)) | (1<<(15*2))| (1<<(0*2)); - GPIOB->MODER = (2<<(4*2)) | (2<<(5*2)) | (1<<(1*2)) | (1<<(2*2)) | (1<<(8*2)); - GPIOA->PUPDR = 0x24000000 | (1<<(8*2)) | (1<<(9*2)) | (2<<(1*2)) | (2<<(4*2)); - GPIOB->PUPDR = (1<<(4*2)) | (1<<(5*2)); - GPIOA->AFR[1]= 0x00000022; - GPIOB->AFR[0]= 0x00110000; -} - -static void key_matrix_select(int row) { - uint16_t bsrr_a = 0, bsrr_b = 0; - /* A0 -> A15 -> B1 -> B2 -> B8 */ - switch (row) { - case 0: bsrr_a = 1<<0; break; - case 1: bsrr_a = 1<<15; break; - case 2: bsrr_b = 1<<1; break; - case 3: bsrr_b = 1<<2; break; - case 4: bsrr_b = 1<<8; break; - } - uint16_t mask_a = (1<<15) | (1<<0), mask_b = (1<<1) | (1<<2) | (1<<8); - /* Reset all pins except for selected pin */ - GPIOA->BSRR = (mask_a<<16) ^ ((bsrr_a<<16) | bsrr_a) ; - GPIOB->BSRR = (mask_b<<16) ^ ((bsrr_b<<16) | bsrr_b) ; -} - -static int key_matrix_query(int debounce_time) { - static int debounce_states[KEY_MATRIX_COLS][KEY_MATRIX_ROWS] = {0}; - static int key_matrix_row = -1; - static uint32_t matrix_state = 0; - uint32_t matrix_state_edges = 0; - if (key_matrix_row < 0) { /* On first iteration just set outputs and return */ - key_matrix_row = 0; - key_matrix_select(0); - return 0; - } - - int input = GPIOA->IDR; - int pressed[KEY_MATRIX_COLS] = { input & (1<<4), input & (1<<1) }; - for (int i=0; i 0) { - /* debounce timer running */ - debounce_states[i][key_matrix_row]--; - } else { - uint32_t bit = 1 << key_matrix_row << (KEY_MATRIX_ROWS * i); - uint32_t old_matrix_state = matrix_state; - if (pressed[i]) - matrix_state |= bit; - else - matrix_state &= ~bit; - - uint32_t edge = old_matrix_state ^ matrix_state; - if (edge) - debounce_states[i][key_matrix_row] = debounce_time; - matrix_state_edges |= edge; - } - } - - key_matrix_row = (key_matrix_row+1) % KEY_MATRIX_ROWS; - key_matrix_select(key_matrix_row); - return (matrix_state_edges<<16) | matrix_state; -} - -void Error_Handler(void) -{ - while(1){ - HAL_GPIO_WritePin(GPIOB,GPIO_PIN_13,1); - HAL_Delay(100); - HAL_GPIO_WritePin(GPIOB,GPIO_PIN_13,0); - HAL_Delay(100); - } -} - diff --git a/fw/hid-dials/src/main.h b/fw/hid-dials/src/main.h deleted file mode 100644 index a80f8f4..0000000 --- a/fw/hid-dials/src/main.h +++ /dev/null @@ -1,71 +0,0 @@ -/* USER CODE BEGIN Header */ -/** - ****************************************************************************** - * @file : main.h - * @brief : Header for main.c file. - * This file contains the common defines of the application. - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2020 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ -/* USER CODE END Header */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __MAIN_H -#define __MAIN_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f0xx_hal.h" - -/* Private includes ----------------------------------------------------------*/ -/* USER CODE BEGIN Includes */ - -/* USER CODE END Includes */ - -/* Exported types ------------------------------------------------------------*/ -/* USER CODE BEGIN ET */ - -/* USER CODE END ET */ - -/* Exported constants --------------------------------------------------------*/ -/* USER CODE BEGIN EC */ - -/* USER CODE END EC */ - -/* Exported macro ------------------------------------------------------------*/ -/* USER CODE BEGIN EM */ - -/* USER CODE END EM */ - -/* Exported functions prototypes ---------------------------------------------*/ -void Error_Handler(void); - -/* USER CODE BEGIN EFP */ - -/* USER CODE END EFP */ - -/* Private defines -----------------------------------------------------------*/ -/* USER CODE BEGIN Private defines */ - -/* USER CODE END Private defines */ - -#ifdef __cplusplus -} -#endif - -#endif /* __MAIN_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/startup_stm32f072xb.s b/fw/hid-dials/src/startup_stm32f072xb.s deleted file mode 100644 index 9d431a9..0000000 --- a/fw/hid-dials/src/startup_stm32f072xb.s +++ /dev/null @@ -1,294 +0,0 @@ -/** - ****************************************************************************** - * @file startup_stm32f072xb.s - * @author MCD Application Team - * @brief STM32F072x8/STM32F072xB devices vector table for GCC toolchain. - * This module performs: - * - Set the initial SP - * - Set the initial PC == Reset_Handler, - * - Set the vector table entries with the exceptions ISR address - * - Branches to main in the C library (which eventually - * calls main()). - * After Reset the Cortex-M0 processor is in Thread mode, - * priority is Privileged, and the Stack is set to Main. - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2016 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ - - .syntax unified - .cpu cortex-m0 - .fpu softvfp - .thumb - -.global g_pfnVectors -.global Default_Handler - -/* start address for the initialization values of the .data section. -defined in linker script */ -.word _sidata -/* start address for the .data section. defined in linker script */ -.word _sdata -/* end address for the .data section. defined in linker script */ -.word _edata -/* start address for the .bss section. defined in linker script */ -.word _sbss -/* end address for the .bss section. defined in linker script */ -.word _ebss - - .section .text.Reset_Handler - .weak Reset_Handler - .type Reset_Handler, %function -Reset_Handler: - ldr r0, =_estack - mov sp, r0 /* set stack pointer */ - -/* Copy the data segment initializers from flash to SRAM */ - ldr r0, =_sdata - ldr r1, =_edata - ldr r2, =_sidata - movs r3, #0 - b LoopCopyDataInit - -CopyDataInit: - ldr r4, [r2, r3] - str r4, [r0, r3] - adds r3, r3, #4 - -LoopCopyDataInit: - adds r4, r0, r3 - cmp r4, r1 - bcc CopyDataInit - -/* Zero fill the bss segment. */ - ldr r2, =_sbss - ldr r4, =_ebss - movs r3, #0 - b LoopFillZerobss - -FillZerobss: - str r3, [r2] - adds r2, r2, #4 - -LoopFillZerobss: - cmp r2, r4 - bcc FillZerobss - -/* Call the clock system intitialization function.*/ - bl SystemInit -/* Call static constructors */ - bl __libc_init_array -/* Call the application's entry point.*/ - bl main - -LoopForever: - b LoopForever - - -.size Reset_Handler, .-Reset_Handler - -/** - * @brief This is the code that gets called when the processor receives an - * unexpected interrupt. This simply enters an infinite loop, preserving - * the system state for examination by a debugger. - * - * @param None - * @retval : None -*/ - .section .text.Default_Handler,"ax",%progbits -Default_Handler: -Infinite_Loop: - b Infinite_Loop - .size Default_Handler, .-Default_Handler -/****************************************************************************** -* -* The minimal vector table for a Cortex M0. Note that the proper constructs -* must be placed on this to ensure that it ends up at physical address -* 0x0000.0000. -* -******************************************************************************/ - .section .isr_vector,"a",%progbits - .type g_pfnVectors, %object - .size g_pfnVectors, .-g_pfnVectors - - -g_pfnVectors: - .word _estack - .word Reset_Handler - .word NMI_Handler - .word HardFault_Handler - .word 0 - .word 0 - .word 0 - .word 0 - .word 0 - .word 0 - .word 0 - .word SVC_Handler - .word 0 - .word 0 - .word PendSV_Handler - .word SysTick_Handler - .word WWDG_IRQHandler /* Window WatchDog */ - .word PVD_VDDIO2_IRQHandler /* PVD and VDDIO2 through EXTI Line detect */ - .word RTC_IRQHandler /* RTC through the EXTI line */ - .word FLASH_IRQHandler /* FLASH */ - .word RCC_CRS_IRQHandler /* RCC and CRS */ - .word EXTI0_1_IRQHandler /* EXTI Line 0 and 1 */ - .word EXTI2_3_IRQHandler /* EXTI Line 2 and 3 */ - .word EXTI4_15_IRQHandler /* EXTI Line 4 to 15 */ - .word TSC_IRQHandler /* TSC */ - .word DMA1_Channel1_IRQHandler /* DMA1 Channel 1 */ - .word DMA1_Channel2_3_IRQHandler /* DMA1 Channel 2 and Channel 3 */ - .word DMA1_Channel4_5_6_7_IRQHandler /* DMA1 Channel 4, Channel 5, Channel 6 and Channel 7*/ - .word ADC1_COMP_IRQHandler /* ADC1, COMP1 and COMP2 */ - .word TIM1_BRK_UP_TRG_COM_IRQHandler /* TIM1 Break, Update, Trigger and Commutation */ - .word TIM1_CC_IRQHandler /* TIM1 Capture Compare */ - .word TIM2_IRQHandler /* TIM2 */ - .word TIM3_IRQHandler /* TIM3 */ - .word TIM6_DAC_IRQHandler /* TIM6 and DAC */ - .word TIM7_IRQHandler /* TIM7 */ - .word TIM14_IRQHandler /* TIM14 */ - .word TIM15_IRQHandler /* TIM15 */ - .word TIM16_IRQHandler /* TIM16 */ - .word TIM17_IRQHandler /* TIM17 */ - .word I2C1_IRQHandler /* I2C1 */ - .word I2C2_IRQHandler /* I2C2 */ - .word SPI1_IRQHandler /* SPI1 */ - .word SPI2_IRQHandler /* SPI2 */ - .word USART1_IRQHandler /* USART1 */ - .word USART2_IRQHandler /* USART2 */ - .word USART3_4_IRQHandler /* USART3 and USART4 */ - .word CEC_CAN_IRQHandler /* CEC and CAN */ - .word USB_IRQHandler /* USB */ - -/******************************************************************************* -* -* Provide weak aliases for each Exception handler to the Default_Handler. -* As they are weak aliases, any function with the same name will override -* this definition. -* -*******************************************************************************/ - - .weak NMI_Handler - .thumb_set NMI_Handler,Default_Handler - - .weak HardFault_Handler - .thumb_set HardFault_Handler,Default_Handler - - .weak SVC_Handler - .thumb_set SVC_Handler,Default_Handler - - .weak PendSV_Handler - .thumb_set PendSV_Handler,Default_Handler - - .weak SysTick_Handler - .thumb_set SysTick_Handler,Default_Handler - - .weak WWDG_IRQHandler - .thumb_set WWDG_IRQHandler,Default_Handler - - .weak PVD_VDDIO2_IRQHandler - .thumb_set PVD_VDDIO2_IRQHandler,Default_Handler - - .weak RTC_IRQHandler - .thumb_set RTC_IRQHandler,Default_Handler - - .weak FLASH_IRQHandler - .thumb_set FLASH_IRQHandler,Default_Handler - - .weak RCC_CRS_IRQHandler - .thumb_set RCC_CRS_IRQHandler,Default_Handler - - .weak EXTI0_1_IRQHandler - .thumb_set EXTI0_1_IRQHandler,Default_Handler - - .weak EXTI2_3_IRQHandler - .thumb_set EXTI2_3_IRQHandler,Default_Handler - - .weak EXTI4_15_IRQHandler - .thumb_set EXTI4_15_IRQHandler,Default_Handler - - .weak TSC_IRQHandler - .thumb_set TSC_IRQHandler,Default_Handler - - .weak DMA1_Channel1_IRQHandler - .thumb_set DMA1_Channel1_IRQHandler,Default_Handler - - .weak DMA1_Channel2_3_IRQHandler - .thumb_set DMA1_Channel2_3_IRQHandler,Default_Handler - - .weak DMA1_Channel4_5_6_7_IRQHandler - .thumb_set DMA1_Channel4_5_6_7_IRQHandler,Default_Handler - - .weak ADC1_COMP_IRQHandler - .thumb_set ADC1_COMP_IRQHandler,Default_Handler - - .weak TIM1_BRK_UP_TRG_COM_IRQHandler - .thumb_set TIM1_BRK_UP_TRG_COM_IRQHandler,Default_Handler - - .weak TIM1_CC_IRQHandler - .thumb_set TIM1_CC_IRQHandler,Default_Handler - - .weak TIM2_IRQHandler - .thumb_set TIM2_IRQHandler,Default_Handler - - .weak TIM3_IRQHandler - .thumb_set TIM3_IRQHandler,Default_Handler - - .weak TIM6_DAC_IRQHandler - .thumb_set TIM6_DAC_IRQHandler,Default_Handler - - .weak TIM7_IRQHandler - .thumb_set TIM7_IRQHandler,Default_Handler - - .weak TIM14_IRQHandler - .thumb_set TIM14_IRQHandler,Default_Handler - - .weak TIM15_IRQHandler - .thumb_set TIM15_IRQHandler,Default_Handler - - .weak TIM16_IRQHandler - .thumb_set TIM16_IRQHandler,Default_Handler - - .weak TIM17_IRQHandler - .thumb_set TIM17_IRQHandler,Default_Handler - - .weak I2C1_IRQHandler - .thumb_set I2C1_IRQHandler,Default_Handler - - .weak I2C2_IRQHandler - .thumb_set I2C2_IRQHandler,Default_Handler - - .weak SPI1_IRQHandler - .thumb_set SPI1_IRQHandler,Default_Handler - - .weak SPI2_IRQHandler - .thumb_set SPI2_IRQHandler,Default_Handler - - .weak USART1_IRQHandler - .thumb_set USART1_IRQHandler,Default_Handler - - .weak USART2_IRQHandler - .thumb_set USART2_IRQHandler,Default_Handler - - .weak USART3_4_IRQHandler - .thumb_set USART3_4_IRQHandler,Default_Handler - - .weak CEC_CAN_IRQHandler - .thumb_set CEC_CAN_IRQHandler,Default_Handler - - .weak USB_IRQHandler - .thumb_set USB_IRQHandler,Default_Handler - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ - diff --git a/fw/hid-dials/src/stm32f0xx_hal_conf.h b/fw/hid-dials/src/stm32f0xx_hal_conf.h deleted file mode 100644 index 78c43f6..0000000 --- a/fw/hid-dials/src/stm32f0xx_hal_conf.h +++ /dev/null @@ -1,319 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f0xx_hal_conf.h - * @brief HAL configuration file. - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2016 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F0xx_HAL_CONF_H -#define __STM32F0xx_HAL_CONF_H - -#ifdef __cplusplus - extern "C" { -#endif - -/* Exported types ------------------------------------------------------------*/ -/* Exported constants --------------------------------------------------------*/ - -/* ########################## Module Selection ############################## */ -/** - * @brief This is the list of modules to be used in the HAL driver - */ -#define HAL_MODULE_ENABLED - #define HAL_ADC_MODULE_ENABLED -/*#define HAL_CRYP_MODULE_ENABLED */ -/*#define HAL_CAN_MODULE_ENABLED */ -/*#define HAL_CEC_MODULE_ENABLED */ -/*#define HAL_COMP_MODULE_ENABLED */ -/*#define HAL_CRC_MODULE_ENABLED */ -/*#define HAL_CRYP_MODULE_ENABLED */ -/*#define HAL_TSC_MODULE_ENABLED */ -/*#define HAL_DAC_MODULE_ENABLED */ -/*#define HAL_I2S_MODULE_ENABLED */ -/*#define HAL_IWDG_MODULE_ENABLED */ -/*#define HAL_LCD_MODULE_ENABLED */ -/*#define HAL_LPTIM_MODULE_ENABLED */ -/*#define HAL_RNG_MODULE_ENABLED */ -/*#define HAL_RTC_MODULE_ENABLED */ -/*#define HAL_SPI_MODULE_ENABLED */ -/*#define HAL_TIM_MODULE_ENABLED */ -/*#define HAL_UART_MODULE_ENABLED */ -/*#define HAL_USART_MODULE_ENABLED */ -/*#define HAL_IRDA_MODULE_ENABLED */ -/*#define HAL_SMARTCARD_MODULE_ENABLED */ -/*#define HAL_SMBUS_MODULE_ENABLED */ -/*#define HAL_WWDG_MODULE_ENABLED */ -#define HAL_PCD_MODULE_ENABLED -#define HAL_CORTEX_MODULE_ENABLED -#define HAL_DMA_MODULE_ENABLED -#define HAL_FLASH_MODULE_ENABLED -#define HAL_GPIO_MODULE_ENABLED -#define HAL_EXTI_MODULE_ENABLED -#define HAL_PWR_MODULE_ENABLED -#define HAL_RCC_MODULE_ENABLED -#define HAL_I2C_MODULE_ENABLED - -/* ########################## HSE/HSI Values adaptation ##################### */ -/** - * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. - * This value is used by the RCC HAL module to compute the system frequency - * (when HSE is used as system clock source, directly or through the PLL). - */ -#if !defined (HSE_VALUE) - #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ -#endif /* HSE_VALUE */ - -/** - * @brief In the following line adjust the External High Speed oscillator (HSE) Startup - * Timeout value - */ -#if !defined (HSE_STARTUP_TIMEOUT) - #define HSE_STARTUP_TIMEOUT ((uint32_t)100) /*!< Time out for HSE start up, in ms */ -#endif /* HSE_STARTUP_TIMEOUT */ - -/** - * @brief Internal High Speed oscillator (HSI) value. - * This value is used by the RCC HAL module to compute the system frequency - * (when HSI is used as system clock source, directly or through the PLL). - */ -#if !defined (HSI_VALUE) - #define HSI_VALUE ((uint32_t)8000000) /*!< Value of the Internal oscillator in Hz*/ -#endif /* HSI_VALUE */ - -/** - * @brief In the following line adjust the Internal High Speed oscillator (HSI) Startup - * Timeout value - */ -#if !defined (HSI_STARTUP_TIMEOUT) - #define HSI_STARTUP_TIMEOUT ((uint32_t)5000) /*!< Time out for HSI start up */ -#endif /* HSI_STARTUP_TIMEOUT */ - -/** - * @brief Internal High Speed oscillator for ADC (HSI14) value. - */ -#if !defined (HSI14_VALUE) -#define HSI14_VALUE ((uint32_t)14000000) /*!< Value of the Internal High Speed oscillator for ADC in Hz. - The real value may vary depending on the variations - in voltage and temperature. */ -#endif /* HSI14_VALUE */ - -/** - * @brief Internal High Speed oscillator for USB (HSI48) value. - */ -#if !defined (HSI48_VALUE) -#define HSI48_VALUE ((uint32_t)48000000) /*!< Value of the Internal High Speed oscillator for USB in Hz. - The real value may vary depending on the variations - in voltage and temperature. */ -#endif /* HSI48_VALUE */ - -/** - * @brief Internal Low Speed oscillator (LSI) value. - */ -#if !defined (LSI_VALUE) - #define LSI_VALUE ((uint32_t)40000) -#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz - The real value may vary depending on the variations - in voltage and temperature. */ -/** - * @brief External Low Speed oscillator (LSI) value. - */ -#if !defined (LSE_VALUE) - #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ -#endif /* LSE_VALUE */ - -#if !defined (LSE_STARTUP_TIMEOUT) - #define LSE_STARTUP_TIMEOUT ((uint32_t)5000) /*!< Time out for LSE start up, in ms */ -#endif /* LSE_STARTUP_TIMEOUT */ - -/* Tip: To avoid modifying this file each time you need to use different HSE, - === you can define the HSE value in your toolchain compiler preprocessor. */ - -/* ########################### System Configuration ######################### */ -/** - * @brief This is the HAL system configuration section - */ -#define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ -#define TICK_INT_PRIORITY ((uint32_t)0) /*!< tick interrupt priority (lowest by default) */ - /* Warning: Must be set to higher priority for HAL_Delay() */ - /* and HAL_GetTick() usage under interrupt context */ -#define USE_RTOS 0 -#define PREFETCH_ENABLE 1 -#define INSTRUCTION_CACHE_ENABLE 0 -#define DATA_CACHE_ENABLE 0 -#define USE_SPI_CRC 0U - -#define USE_HAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */ -#define USE_HAL_CAN_REGISTER_CALLBACKS 0U /* CAN register callback disabled */ -#define USE_HAL_COMP_REGISTER_CALLBACKS 0U /* COMP register callback disabled */ -#define USE_HAL_CEC_REGISTER_CALLBACKS 0U /* CEC register callback disabled */ -#define USE_HAL_DAC_REGISTER_CALLBACKS 0U /* DAC register callback disabled */ -#define USE_HAL_I2C_REGISTER_CALLBACKS 0U /* I2C register callback disabled */ -#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U /* SMBUS register callback disabled */ -#define USE_HAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */ -#define USE_HAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */ -#define USE_HAL_IRDA_REGISTER_CALLBACKS 0U /* IRDA register callback disabled */ -#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U /* SMARTCARD register callback disabled */ -#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U /* WWDG register callback disabled */ -#define USE_HAL_RTC_REGISTER_CALLBACKS 0U /* RTC register callback disabled */ -#define USE_HAL_SPI_REGISTER_CALLBACKS 0U /* SPI register callback disabled */ -#define USE_HAL_I2S_REGISTER_CALLBACKS 0U /* I2S register callback disabled */ -#define USE_HAL_TIM_REGISTER_CALLBACKS 0U /* TIM register callback disabled */ -#define USE_HAL_TSC_REGISTER_CALLBACKS 0U /* TSC register callback disabled */ -#define USE_HAL_PCD_REGISTER_CALLBACKS 0U /* PCD register callback disabled */ - -/* ########################## Assert Selection ############################## */ -/** - * @brief Uncomment the line below to expanse the "assert_param" macro in the - * HAL drivers code - */ -/* #define USE_FULL_ASSERT 1U */ - -/* Includes ------------------------------------------------------------------*/ -/** - * @brief Include module's header file - */ - -#ifdef HAL_RCC_MODULE_ENABLED - #include "stm32f0xx_hal_rcc.h" -#endif /* HAL_RCC_MODULE_ENABLED */ - -#ifdef HAL_GPIO_MODULE_ENABLED - #include "stm32f0xx_hal_gpio.h" -#endif /* HAL_GPIO_MODULE_ENABLED */ - -#ifdef HAL_EXTI_MODULE_ENABLED - #include "stm32f0xx_hal_exti.h" -#endif /* HAL_EXTI_MODULE_ENABLED */ - -#ifdef HAL_DMA_MODULE_ENABLED - #include "stm32f0xx_hal_dma.h" -#endif /* HAL_DMA_MODULE_ENABLED */ - -#ifdef HAL_CORTEX_MODULE_ENABLED - #include "stm32f0xx_hal_cortex.h" -#endif /* HAL_CORTEX_MODULE_ENABLED */ - -#ifdef HAL_ADC_MODULE_ENABLED - #include "stm32f0xx_hal_adc.h" -#endif /* HAL_ADC_MODULE_ENABLED */ - -#ifdef HAL_CAN_MODULE_ENABLED - #include "stm32f0xx_hal_can.h" -#endif /* HAL_CAN_MODULE_ENABLED */ - -#ifdef HAL_CEC_MODULE_ENABLED - #include "stm32f0xx_hal_cec.h" -#endif /* HAL_CEC_MODULE_ENABLED */ - -#ifdef HAL_COMP_MODULE_ENABLED - #include "stm32f0xx_hal_comp.h" -#endif /* HAL_COMP_MODULE_ENABLED */ - -#ifdef HAL_CRC_MODULE_ENABLED - #include "stm32f0xx_hal_crc.h" -#endif /* HAL_CRC_MODULE_ENABLED */ - -#ifdef HAL_DAC_MODULE_ENABLED - #include "stm32f0xx_hal_dac.h" -#endif /* HAL_DAC_MODULE_ENABLED */ - -#ifdef HAL_FLASH_MODULE_ENABLED - #include "stm32f0xx_hal_flash.h" -#endif /* HAL_FLASH_MODULE_ENABLED */ - -#ifdef HAL_I2C_MODULE_ENABLED - #include "stm32f0xx_hal_i2c.h" -#endif /* HAL_I2C_MODULE_ENABLED */ - -#ifdef HAL_I2S_MODULE_ENABLED - #include "stm32f0xx_hal_i2s.h" -#endif /* HAL_I2S_MODULE_ENABLED */ - -#ifdef HAL_IRDA_MODULE_ENABLED - #include "stm32f0xx_hal_irda.h" -#endif /* HAL_IRDA_MODULE_ENABLED */ - -#ifdef HAL_IWDG_MODULE_ENABLED - #include "stm32f0xx_hal_iwdg.h" -#endif /* HAL_IWDG_MODULE_ENABLED */ - -#ifdef HAL_PCD_MODULE_ENABLED - #include "stm32f0xx_hal_pcd.h" -#endif /* HAL_PCD_MODULE_ENABLED */ - -#ifdef HAL_PWR_MODULE_ENABLED - #include "stm32f0xx_hal_pwr.h" -#endif /* HAL_PWR_MODULE_ENABLED */ - -#ifdef HAL_RTC_MODULE_ENABLED - #include "stm32f0xx_hal_rtc.h" -#endif /* HAL_RTC_MODULE_ENABLED */ - -#ifdef HAL_SMARTCARD_MODULE_ENABLED - #include "stm32f0xx_hal_smartcard.h" -#endif /* HAL_SMARTCARD_MODULE_ENABLED */ - -#ifdef HAL_SMBUS_MODULE_ENABLED - #include "stm32f0xx_hal_smbus.h" -#endif /* HAL_SMBUS_MODULE_ENABLED */ - -#ifdef HAL_SPI_MODULE_ENABLED - #include "stm32f0xx_hal_spi.h" -#endif /* HAL_SPI_MODULE_ENABLED */ - -#ifdef HAL_TIM_MODULE_ENABLED - #include "stm32f0xx_hal_tim.h" -#endif /* HAL_TIM_MODULE_ENABLED */ - -#ifdef HAL_TSC_MODULE_ENABLED - #include "stm32f0xx_hal_tsc.h" -#endif /* HAL_TSC_MODULE_ENABLED */ - -#ifdef HAL_UART_MODULE_ENABLED - #include "stm32f0xx_hal_uart.h" -#endif /* HAL_UART_MODULE_ENABLED */ - -#ifdef HAL_USART_MODULE_ENABLED - #include "stm32f0xx_hal_usart.h" -#endif /* HAL_USART_MODULE_ENABLED */ - -#ifdef HAL_WWDG_MODULE_ENABLED - #include "stm32f0xx_hal_wwdg.h" -#endif /* HAL_WWDG_MODULE_ENABLED */ - -/* Exported macro ------------------------------------------------------------*/ -#ifdef USE_FULL_ASSERT -/** - * @brief The assert_param macro is used for function's parameters check. - * @param expr If expr is false, it calls assert_failed function - * which reports the name of the source file and the source - * line number of the call that failed. - * If expr is true, it returns no value. - * @retval None - */ - #define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) -/* Exported functions ------------------------------------------------------- */ - void assert_failed(uint8_t* file, uint32_t line); -#else - #define assert_param(expr) ((void)0U) -#endif /* USE_FULL_ASSERT */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F0xx_HAL_CONF_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/stm32f0xx_hal_msp.c b/fw/hid-dials/src/stm32f0xx_hal_msp.c deleted file mode 100644 index 8695580..0000000 --- a/fw/hid-dials/src/stm32f0xx_hal_msp.c +++ /dev/null @@ -1,191 +0,0 @@ -/* USER CODE BEGIN Header */ -/** - ****************************************************************************** - * File Name : stm32f0xx_hal_msp.c - * Description : This file provides code for the MSP Initialization - * and de-Initialization codes. - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2020 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ -/* USER CODE END Header */ - -/* Includes ------------------------------------------------------------------*/ -#include "main.h" -/* USER CODE BEGIN Includes */ - -/* USER CODE END Includes */ -extern DMA_HandleTypeDef hdma_adc; - -/* Private typedef -----------------------------------------------------------*/ -/* USER CODE BEGIN TD */ - -/* USER CODE END TD */ - -/* Private define ------------------------------------------------------------*/ -/* USER CODE BEGIN Define */ - -/* USER CODE END Define */ - -/* Private macro -------------------------------------------------------------*/ -/* USER CODE BEGIN Macro */ - -/* USER CODE END Macro */ - -/* Private variables ---------------------------------------------------------*/ -/* USER CODE BEGIN PV */ - -/* USER CODE END PV */ - -/* Private function prototypes -----------------------------------------------*/ -/* USER CODE BEGIN PFP */ - -/* USER CODE END PFP */ - -/* External functions --------------------------------------------------------*/ -/* USER CODE BEGIN ExternalFunctions */ - -/* USER CODE END ExternalFunctions */ - -/* USER CODE BEGIN 0 */ - -/* USER CODE END 0 */ -/** - * Initializes the Global MSP. - */ -void HAL_MspInit(void) -{ - /* USER CODE BEGIN MspInit 0 */ - - /* USER CODE END MspInit 0 */ - - __HAL_RCC_SYSCFG_CLK_ENABLE(); - __HAL_RCC_PWR_CLK_ENABLE(); - - /* System interrupt init*/ - - /* USER CODE BEGIN MspInit 1 */ - - /* USER CODE END MspInit 1 */ -} - -/** -* @brief ADC MSP Initialization -* This function configures the hardware resources used in this example -* @param hadc: ADC handle pointer -* @retval None -*/ -void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) -{ - GPIO_InitTypeDef GPIO_InitStruct = {0}; - if(hadc->Instance==ADC1) - { - /* USER CODE BEGIN ADC1_MspInit 0 */ - - /* USER CODE END ADC1_MspInit 0 */ - /* Peripheral clock enable */ - __HAL_RCC_ADC1_CLK_ENABLE(); - - __HAL_RCC_GPIOA_CLK_ENABLE(); - __HAL_RCC_GPIOB_CLK_ENABLE(); - /**ADC GPIO Configuration - PA0 ------> ADC_IN0 - PA1 ------> ADC_IN1 - PA2 ------> ADC_IN2 - PA3 ------> ADC_IN3 - PA4 ------> ADC_IN4 - PA5 ------> ADC_IN5 - PA6 ------> ADC_IN6 - PA7 ------> ADC_IN7 - PB0 ------> ADC_IN8 - */ - GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3 - |GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7; - GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; - GPIO_InitStruct.Pull = GPIO_NOPULL; - HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - - GPIO_InitStruct.Pin = GPIO_PIN_0; - GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; - GPIO_InitStruct.Pull = GPIO_NOPULL; - HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); - - /* ADC1 DMA Init */ - /* ADC Init */ - hdma_adc.Instance = DMA1_Channel1; - hdma_adc.Init.Direction = DMA_PERIPH_TO_MEMORY; - hdma_adc.Init.PeriphInc = DMA_PINC_DISABLE; - hdma_adc.Init.MemInc = DMA_MINC_ENABLE; - hdma_adc.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD; - hdma_adc.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD; - hdma_adc.Init.Mode = DMA_CIRCULAR; - hdma_adc.Init.Priority = DMA_PRIORITY_MEDIUM; - if (HAL_DMA_Init(&hdma_adc) != HAL_OK) - { - Error_Handler(); - } - - __HAL_LINKDMA(hadc,DMA_Handle,hdma_adc); - - /* USER CODE BEGIN ADC1_MspInit 1 */ - - /* USER CODE END ADC1_MspInit 1 */ - } - -} - -/** -* @brief ADC MSP De-Initialization -* This function freeze the hardware resources used in this example -* @param hadc: ADC handle pointer -* @retval None -*/ -void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) -{ - if(hadc->Instance==ADC1) - { - /* USER CODE BEGIN ADC1_MspDeInit 0 */ - - /* USER CODE END ADC1_MspDeInit 0 */ - /* Peripheral clock disable */ - __HAL_RCC_ADC1_CLK_DISABLE(); - - /**ADC GPIO Configuration - PA0 ------> ADC_IN0 - PA1 ------> ADC_IN1 - PA2 ------> ADC_IN2 - PA3 ------> ADC_IN3 - PA4 ------> ADC_IN4 - PA5 ------> ADC_IN5 - PA6 ------> ADC_IN6 - PA7 ------> ADC_IN7 - PB0 ------> ADC_IN8 - */ - HAL_GPIO_DeInit(GPIOA, GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3 - |GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7); - - HAL_GPIO_DeInit(GPIOB, GPIO_PIN_0); - - /* ADC1 DMA DeInit */ - HAL_DMA_DeInit(hadc->DMA_Handle); - /* USER CODE BEGIN ADC1_MspDeInit 1 */ - - /* USER CODE END ADC1_MspDeInit 1 */ - } - -} - -/* USER CODE BEGIN 1 */ - -/* USER CODE END 1 */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/stm32f0xx_it.c b/fw/hid-dials/src/stm32f0xx_it.c deleted file mode 100644 index 3d94908..0000000 --- a/fw/hid-dials/src/stm32f0xx_it.c +++ /dev/null @@ -1,176 +0,0 @@ -/* USER CODE BEGIN Header */ -/** - ****************************************************************************** - * @file stm32f0xx_it.c - * @brief Interrupt Service Routines. - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2020 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ -/* USER CODE END Header */ - -/* Includes ------------------------------------------------------------------*/ -#include "main.h" -#include "stm32f0xx_it.h" -/* Private includes ----------------------------------------------------------*/ -/* USER CODE BEGIN Includes */ -/* USER CODE END Includes */ - -/* Private typedef -----------------------------------------------------------*/ -/* USER CODE BEGIN TD */ - -/* USER CODE END TD */ - -/* Private define ------------------------------------------------------------*/ -/* USER CODE BEGIN PD */ - -/* USER CODE END PD */ - -/* Private macro -------------------------------------------------------------*/ -/* USER CODE BEGIN PM */ - -/* USER CODE END PM */ - -/* Private variables ---------------------------------------------------------*/ -/* USER CODE BEGIN PV */ - -/* USER CODE END PV */ - -/* Private function prototypes -----------------------------------------------*/ -/* USER CODE BEGIN PFP */ - -/* USER CODE END PFP */ - -/* Private user code ---------------------------------------------------------*/ -/* USER CODE BEGIN 0 */ - -/* USER CODE END 0 */ - -/* External variables --------------------------------------------------------*/ -extern DMA_HandleTypeDef hdma_adc; -extern PCD_HandleTypeDef hpcd_USB_FS; - -/* USER CODE BEGIN EV */ - -/* USER CODE END EV */ - -/******************************************************************************/ -/* Cortex-M0 Processor Interruption and Exception Handlers */ -/******************************************************************************/ -/** - * @brief This function handles Non maskable interrupt. - */ -void NMI_Handler(void) -{ - /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ - - /* USER CODE END NonMaskableInt_IRQn 0 */ - /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ - - /* USER CODE END NonMaskableInt_IRQn 1 */ -} - -/** - * @brief This function handles Hard fault interrupt. - */ -void HardFault_Handler(void) -{ - /* USER CODE BEGIN HardFault_IRQn 0 */ - - /* USER CODE END HardFault_IRQn 0 */ - while (1) - { - /* USER CODE BEGIN W1_HardFault_IRQn 0 */ - /* USER CODE END W1_HardFault_IRQn 0 */ - } -} - -/** - * @brief This function handles System service call via SWI instruction. - */ -void SVC_Handler(void) -{ - /* USER CODE BEGIN SVC_IRQn 0 */ - - /* USER CODE END SVC_IRQn 0 */ - /* USER CODE BEGIN SVC_IRQn 1 */ - - /* USER CODE END SVC_IRQn 1 */ -} - -/** - * @brief This function handles Pendable request for system service. - */ -void PendSV_Handler(void) -{ - /* USER CODE BEGIN PendSV_IRQn 0 */ - - /* USER CODE END PendSV_IRQn 0 */ - /* USER CODE BEGIN PendSV_IRQn 1 */ - - /* USER CODE END PendSV_IRQn 1 */ -} - -/** - * @brief This function handles System tick timer. - */ -void SysTick_Handler(void) -{ - /* USER CODE BEGIN SysTick_IRQn 0 */ - - /* USER CODE END SysTick_IRQn 0 */ - HAL_IncTick(); - /* USER CODE BEGIN SysTick_IRQn 1 */ - - /* USER CODE END SysTick_IRQn 1 */ -} - -/******************************************************************************/ -/* STM32F0xx Peripheral Interrupt Handlers */ -/* Add here the Interrupt Handlers for the used peripherals. */ -/* For the available peripheral interrupt handler names, */ -/* please refer to the startup file (startup_stm32f0xx.s). */ -/******************************************************************************/ - -/** - * @brief This function handles DMA1 channel 1 global interrupt. - */ -void DMA1_Channel1_IRQHandler(void) -{ - /* USER CODE BEGIN DMA1_Channel1_IRQn 0 */ - - /* USER CODE END DMA1_Channel1_IRQn 0 */ - HAL_DMA_IRQHandler(&hdma_adc); - /* USER CODE BEGIN DMA1_Channel1_IRQn 1 */ - - /* USER CODE END DMA1_Channel1_IRQn 1 */ -} - -/** -* @brief This function handles USB global Interrupt / USB wake-up interrupt through EXTI line 18. -*/ -void USB_IRQHandler(void) -{ - /* USER CODE BEGIN USB_IRQn 0 */ - - /* USER CODE END USB_IRQn 0 */ - HAL_PCD_IRQHandler(&hpcd_USB_FS); - /* USER CODE BEGIN USB_IRQn 1 */ - - /* USER CODE END USB_IRQn 1 */ -} - - -/* USER CODE BEGIN 1 */ - -/* USER CODE END 1 */ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/stm32f0xx_it.h b/fw/hid-dials/src/stm32f0xx_it.h deleted file mode 100644 index daef239..0000000 --- a/fw/hid-dials/src/stm32f0xx_it.h +++ /dev/null @@ -1,68 +0,0 @@ -/* USER CODE BEGIN Header */ -/** - ****************************************************************************** - * @file stm32f0xx_it.h - * @brief This file contains the headers of the interrupt handlers. - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2020 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ -/* USER CODE END Header */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F0xx_IT_H -#define __STM32F0xx_IT_H - -#ifdef __cplusplus - extern "C" { -#endif - -/* Private includes ----------------------------------------------------------*/ -/* USER CODE BEGIN Includes */ - -/* USER CODE END Includes */ - -/* Exported types ------------------------------------------------------------*/ -/* USER CODE BEGIN ET */ - -/* USER CODE END ET */ - -/* Exported constants --------------------------------------------------------*/ -/* USER CODE BEGIN EC */ - -/* USER CODE END EC */ - -/* Exported macro ------------------------------------------------------------*/ -/* USER CODE BEGIN EM */ - -/* USER CODE END EM */ - -/* Exported functions prototypes ---------------------------------------------*/ -void NMI_Handler(void); -void HardFault_Handler(void); -void SVC_Handler(void); -void PendSV_Handler(void); -void SysTick_Handler(void); -void DMA1_Channel1_IRQHandler(void); -void USB_IRQHandler(void); - -/* USER CODE BEGIN EFP */ - -/* USER CODE END EFP */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F0xx_IT_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/system_stm32f0xx.c b/fw/hid-dials/src/system_stm32f0xx.c deleted file mode 100644 index 6a3202b..0000000 --- a/fw/hid-dials/src/system_stm32f0xx.c +++ /dev/null @@ -1,265 +0,0 @@ -/** - ****************************************************************************** - * @file system_stm32f0xx.c - * @author MCD Application Team - * @brief CMSIS Cortex-M0 Device Peripheral Access Layer System Source File. - * - * 1. This file provides two functions and one global variable to be called from - * user application: - * - SystemInit(): This function is called at startup just after reset and - * before branch to main program. This call is made inside - * the "startup_stm32f0xx.s" file. - * - * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used - * by the user application to setup the SysTick - * timer or configure other parameters. - * - * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must - * be called whenever the core clock is changed - * during program execution. - * - * 2. After each device reset the HSI (8 MHz) is used as system clock source. - * Then SystemInit() function is called, in "startup_stm32f0xx.s" file, to - * configure the system clock before to branch to main program. - * - * 3. This file configures the system clock as follows: - *============================================================================= - * Supported STM32F0xx device - *----------------------------------------------------------------------------- - * System Clock source | HSI - *----------------------------------------------------------------------------- - * SYSCLK(Hz) | 8000000 - *----------------------------------------------------------------------------- - * HCLK(Hz) | 8000000 - *----------------------------------------------------------------------------- - * AHB Prescaler | 1 - *----------------------------------------------------------------------------- - * APB1 Prescaler | 1 - *----------------------------------------------------------------------------- - *============================================================================= - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2016 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32f0xx_system - * @{ - */ - -/** @addtogroup STM32F0xx_System_Private_Includes - * @{ - */ - -#include "stm32f0xx.h" - -/** - * @} - */ - -/** @addtogroup STM32F0xx_System_Private_TypesDefinitions - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32F0xx_System_Private_Defines - * @{ - */ -#if !defined (HSE_VALUE) - #define HSE_VALUE ((uint32_t)8000000) /*!< Default value of the External oscillator in Hz. - This value can be provided and adapted by the user application. */ -#endif /* HSE_VALUE */ - -#if !defined (HSI_VALUE) - #define HSI_VALUE ((uint32_t)8000000) /*!< Default value of the Internal oscillator in Hz. - This value can be provided and adapted by the user application. */ -#endif /* HSI_VALUE */ - -#if !defined (HSI48_VALUE) -#define HSI48_VALUE ((uint32_t)48000000) /*!< Default value of the HSI48 Internal oscillator in Hz. - This value can be provided and adapted by the user application. */ -#endif /* HSI48_VALUE */ -/** - * @} - */ - -/** @addtogroup STM32F0xx_System_Private_Macros - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32F0xx_System_Private_Variables - * @{ - */ - /* This variable is updated in three ways: - 1) by calling CMSIS function SystemCoreClockUpdate() - 2) by calling HAL API function HAL_RCC_GetHCLKFreq() - 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency - Note: If you use this function to configure the system clock there is no need to - call the 2 first functions listed above, since SystemCoreClock variable is - updated automatically. - */ -uint32_t SystemCoreClock = 8000000; - -const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; -const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; - -/** - * @} - */ - -/** @addtogroup STM32F0xx_System_Private_FunctionPrototypes - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32F0xx_System_Private_Functions - * @{ - */ - -/** - * @brief Setup the microcontroller system. - * @param None - * @retval None - */ -void SystemInit(void) -{ - /* NOTE :SystemInit(): This function is called at startup just after reset and - before branch to main program. This call is made inside - the "startup_stm32f0xx.s" file. - User can setups the default system clock (System clock source, PLL Multiplier - and Divider factors, AHB/APBx prescalers and Flash settings). - */ -} - -/** - * @brief Update SystemCoreClock variable according to Clock Register Values. - * The SystemCoreClock variable contains the core clock (HCLK), it can - * be used by the user application to setup the SysTick timer or configure - * other parameters. - * - * @note Each time the core clock (HCLK) changes, this function must be called - * to update SystemCoreClock variable value. Otherwise, any configuration - * based on this variable will be incorrect. - * - * @note - The system frequency computed by this function is not the real - * frequency in the chip. It is calculated based on the predefined - * constant and the selected clock source: - * - * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) - * - * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) - * - * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) - * or HSI_VALUE(*) multiplied/divided by the PLL factors. - * - * (*) HSI_VALUE is a constant defined in stm32f0xx_hal.h file (default value - * 8 MHz) but the real value may vary depending on the variations - * in voltage and temperature. - * - * (**) HSE_VALUE is a constant defined in stm32f0xx_hal.h file (default value - * 8 MHz), user has to ensure that HSE_VALUE is same as the real - * frequency of the crystal used. Otherwise, this function may - * have wrong result. - * - * - The result of this function could be not correct when using fractional - * value for HSE crystal. - * - * @param None - * @retval None - */ -void SystemCoreClockUpdate (void) -{ - uint32_t tmp = 0, pllmull = 0, pllsource = 0, predivfactor = 0; - - /* Get SYSCLK source -------------------------------------------------------*/ - tmp = RCC->CFGR & RCC_CFGR_SWS; - - switch (tmp) - { - case RCC_CFGR_SWS_HSI: /* HSI used as system clock */ - SystemCoreClock = HSI_VALUE; - break; - case RCC_CFGR_SWS_HSE: /* HSE used as system clock */ - SystemCoreClock = HSE_VALUE; - break; - case RCC_CFGR_SWS_PLL: /* PLL used as system clock */ - /* Get PLL clock source and multiplication factor ----------------------*/ - pllmull = RCC->CFGR & RCC_CFGR_PLLMUL; - pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; - pllmull = ( pllmull >> 18) + 2; - predivfactor = (RCC->CFGR2 & RCC_CFGR2_PREDIV) + 1; - - if (pllsource == RCC_CFGR_PLLSRC_HSE_PREDIV) - { - /* HSE used as PLL clock source : SystemCoreClock = HSE/PREDIV * PLLMUL */ - SystemCoreClock = (HSE_VALUE/predivfactor) * pllmull; - } -#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) - else if (pllsource == RCC_CFGR_PLLSRC_HSI48_PREDIV) - { - /* HSI48 used as PLL clock source : SystemCoreClock = HSI48/PREDIV * PLLMUL */ - SystemCoreClock = (HSI48_VALUE/predivfactor) * pllmull; - } -#endif /* STM32F042x6 || STM32F048xx || STM32F072xB || STM32F078xx || STM32F091xC || STM32F098xx */ - else - { -#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6) \ - || defined(STM32F078xx) || defined(STM32F071xB) || defined(STM32F072xB) \ - || defined(STM32F070xB) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) - /* HSI used as PLL clock source : SystemCoreClock = HSI/PREDIV * PLLMUL */ - SystemCoreClock = (HSI_VALUE/predivfactor) * pllmull; -#else - /* HSI used as PLL clock source : SystemCoreClock = HSI/2 * PLLMUL */ - SystemCoreClock = (HSI_VALUE >> 1) * pllmull; -#endif /* STM32F042x6 || STM32F048xx || STM32F070x6 || - STM32F071xB || STM32F072xB || STM32F078xx || STM32F070xB || - STM32F091xC || STM32F098xx || STM32F030xC */ - } - break; - default: /* HSI used as system clock */ - SystemCoreClock = HSI_VALUE; - break; - } - /* Compute HCLK clock frequency ----------------*/ - /* Get HCLK prescaler */ - tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; - /* HCLK clock frequency */ - SystemCoreClock >>= tmp; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ - diff --git a/fw/hid-dials/src/usb_device.c b/fw/hid-dials/src/usb_device.c deleted file mode 100644 index dc6a44f..0000000 --- a/fw/hid-dials/src/usb_device.c +++ /dev/null @@ -1,107 +0,0 @@ -/** - ****************************************************************************** - * @file : usb_device.c - * @version : v2.0_Cube - * @brief : This file implements the USB Device - ****************************************************************************** - * This notice applies to any and all portions of this file - * that are not between comment pairs USER CODE BEGIN and - * USER CODE END. Other portions of this file, whether - * inserted by the user or by software development tools - * are owned by their respective copyright owners. - * - * Copyright (c) 2018 STMicroelectronics International N.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ - -#include "usb_device.h" -#include "usbd_core.h" -#include "usbd_desc.h" - -/* USER CODE BEGIN Includes */ -#include "usbd_hid.h" - -/* USER CODE END Includes */ - -/* USER CODE BEGIN PV */ -/* Private variables ---------------------------------------------------------*/ - -/* USER CODE END PV */ - -/* USER CODE BEGIN PFP */ -/* Private function prototypes -----------------------------------------------*/ - -/* USER CODE END PFP */ - -/* USB Device Core handle declaration. */ -USBD_HandleTypeDef hUsbDeviceFS; - -/* - * -- Insert your variables declaration here -- - */ -/* USER CODE BEGIN 0 */ - -/* USER CODE END 0 */ - -/* - * -- Insert your external function declaration here -- - */ -/* USER CODE BEGIN 1 */ - -void MX_USB_HID_INIT(void) -{ - USBD_Init(&hUsbDeviceFS, &FS_Desc, DEVICE_FS); - - USBD_RegisterClass(&hUsbDeviceFS, &USBD_HID); - - USBD_Start(&hUsbDeviceFS); -} - -/* USER CODE END 1 */ - - - -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/usb_device.h b/fw/hid-dials/src/usb_device.h deleted file mode 100644 index 5437462..0000000 --- a/fw/hid-dials/src/usb_device.h +++ /dev/null @@ -1,115 +0,0 @@ -/** - ****************************************************************************** - * @file : usb_device.h - * @version : v2.0_Cube - * @brief : Header for usb_device.c file. - ****************************************************************************** - * This notice applies to any and all portions of this file - * that are not between comment pairs USER CODE BEGIN and - * USER CODE END. Other portions of this file, whether - * inserted by the user or by software development tools - * are owned by their respective copyright owners. - * - * Copyright (c) 2018 STMicroelectronics International N.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __USB_DEVICE__H__ -#define __USB_DEVICE__H__ - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f0xx.h" -#include "stm32f0xx_hal.h" -#include "usbd_def.h" - -/* USER CODE BEGIN INCLUDE */ - -extern void MX_USB_HID_INIT(void); - -/* USER CODE END INCLUDE */ - -/** @addtogroup USBD_OTG_DRIVER - * @{ - */ - -/** @defgroup USBD_DEVICE USBD_DEVICE - * @brief Device file for Usb otg low level driver. - * @{ - */ - -/** @defgroup USBD_DEVICE_Exported_Variables USBD_DEVICE_Exported_Variables - * @brief Public variables. - * @{ - */ - -/** USB device core handle. */ -extern USBD_HandleTypeDef hUsbDeviceFS; - -/** - * @} - */ - -/** @defgroup USBD_DEVICE_Exported_FunctionsPrototype USBD_DEVICE_Exported_FunctionsPrototype - * @brief Declaration of public functions for Usb device. - * @{ - */ - -/** USB Device initialization function. */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __USB_DEVICE__H__ */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/usbd_conf.c b/fw/hid-dials/src/usbd_conf.c deleted file mode 100644 index ccc4b16..0000000 --- a/fw/hid-dials/src/usbd_conf.c +++ /dev/null @@ -1,576 +0,0 @@ -#include "stm32f0xx.h" -#include "stm32f0xx_hal.h" -#include "usbd_def.h" -#include "usbd_core.h" - - -PCD_HandleTypeDef hpcd_USB_FS; - -void HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef *hpcd, uint8_t state); - -void HAL_PCD_MspInit(PCD_HandleTypeDef* pcdHandle) -{ - __HAL_RCC_USB_CLK_ENABLE(); - - HAL_NVIC_SetPriority(USB_IRQn, 1, 0); - HAL_NVIC_EnableIRQ(USB_IRQn); -} - -void HAL_PCD_MspDeInit(PCD_HandleTypeDef* pcdHandle) -{ - __HAL_RCC_USB_CLK_DISABLE(); - - HAL_NVIC_DisableIRQ(USB_IRQn); -} - -void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) -{ - USBD_LL_SetupStage((USBD_HandleTypeDef*)hpcd->pData, (uint8_t *)hpcd->Setup); -} - -void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) -{ - USBD_LL_DataOutStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->OUT_ep[epnum].xfer_buff); -} - -void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) -{ - USBD_LL_DataInStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->IN_ep[epnum].xfer_buff); -} - -void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) -{ - USBD_LL_SOF((USBD_HandleTypeDef*)hpcd->pData); -} - -void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) -{ - USBD_SpeedTypeDef speed = USBD_SPEED_FULL; - - /* Set USB current speed. */ - switch (hpcd->Init.speed) - { - case PCD_SPEED_FULL: - speed = USBD_SPEED_FULL; - break; - - default: - speed = USBD_SPEED_FULL; - break; - } - USBD_LL_SetSpeed((USBD_HandleTypeDef*)hpcd->pData, speed); - - /* Reset Device. */ - USBD_LL_Reset((USBD_HandleTypeDef*)hpcd->pData); -} - -/** - * @brief Suspend callback. - * When Low power mode is enabled the debug cannot be used (IAR, Keil doesn't support it) - * @param hpcd: PCD handle - * @retval None - */ -void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) -{ - /* Inform USB library that core enters in suspend Mode. */ - USBD_LL_Suspend((USBD_HandleTypeDef*)hpcd->pData); - /* Enter in STOP mode. */ - /* USER CODE BEGIN 2 */ - if (hpcd->Init.low_power_enable) - { - /* Set SLEEPDEEP bit and SleepOnExit of Cortex System Control Register. */ - SCB->SCR |= (uint32_t)((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); - } - /* USER CODE END 2 */ -} - -/** - * @brief Resume callback. - * When Low power mode is enabled the debug cannot be used (IAR, Keil doesn't support it) - * @param hpcd: PCD handle - * @retval None - */ -void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) -{ - /* USER CODE BEGIN 3 */ - - /* USER CODE END 3 */ - USBD_LL_Resume((USBD_HandleTypeDef*)hpcd->pData); -} - -/** - * @brief ISOOUTIncomplete callback. - * @param hpcd: PCD handle - * @param epnum: Endpoint number - * @retval None - */ -void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) -{ - USBD_LL_IsoOUTIncomplete((USBD_HandleTypeDef*)hpcd->pData, epnum); -} - -/** - * @brief ISOINIncomplete callback. - * @param hpcd: PCD handle - * @param epnum: Endpoint number - * @retval None - */ -void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) -{ - USBD_LL_IsoINIncomplete((USBD_HandleTypeDef*)hpcd->pData, epnum); -} - -/** - * @brief Connect callback. - * @param hpcd: PCD handle - * @retval None - */ -void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) -{ - USBD_LL_DevConnected((USBD_HandleTypeDef*)hpcd->pData); -} - -/** - * @brief Disconnect callback. - * @param hpcd: PCD handle - * @retval None - */ -void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) -{ - USBD_LL_DevDisconnected((USBD_HandleTypeDef*)hpcd->pData); -} - -/******************************************************************************* - LL Driver Interface (USB Device Library --> PCD) - *******************************************************************************/ - -/** - * @brief Initializes the low level portion of the device driver. - * @param pdev: Device handle - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev) -{ - /* Init USB Ip. */ - /* Link the driver to the stack. */ - hpcd_USB_FS.pData = pdev; - pdev->pData = &hpcd_USB_FS; - - hpcd_USB_FS.Instance = USB; - hpcd_USB_FS.Init.dev_endpoints = 8; - hpcd_USB_FS.Init.speed = PCD_SPEED_FULL; - hpcd_USB_FS.Init.ep0_mps = EP_MPS_64; - hpcd_USB_FS.Init.phy_itface = PCD_PHY_EMBEDDED; - hpcd_USB_FS.Init.low_power_enable = DISABLE; - hpcd_USB_FS.Init.lpm_enable = DISABLE; - hpcd_USB_FS.Init.battery_charging_enable = DISABLE; - if (HAL_PCD_Init(&hpcd_USB_FS) != HAL_OK) - { - //_Error_Handler(__FILE__, __LINE__); - } - - HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x00 , PCD_SNG_BUF, 0x18); - HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x80 , PCD_SNG_BUF, 0x58); - HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x81 , PCD_SNG_BUF, 0xC0); - HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x01 , PCD_SNG_BUF, 0x110); - HAL_PCDEx_PMAConfig((PCD_HandleTypeDef*)pdev->pData , 0x82 , PCD_SNG_BUF, 0x100); - return USBD_OK; -} - -/** - * @brief De-Initializes the low level portion of the device driver. - * @param pdev: Device handle - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_DeInit(USBD_HandleTypeDef *pdev) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_DeInit(pdev->pData); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Starts the low level portion of the device driver. - * @param pdev: Device handle - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_Start(pdev->pData); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Stops the low level portion of the device driver. - * @param pdev: Device handle - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_Stop(USBD_HandleTypeDef *pdev) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_Stop(pdev->pData); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Opens an endpoint of the low level driver. - * @param pdev: Device handle - * @param ep_addr: Endpoint number - * @param ep_type: Endpoint type - * @param ep_mps: Endpoint max packet size - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_OpenEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t ep_type, uint16_t ep_mps) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_EP_Open(pdev->pData, ep_addr, ep_mps, ep_type); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Closes an endpoint of the low level driver. - * @param pdev: Device handle - * @param ep_addr: Endpoint number - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_CloseEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_EP_Close(pdev->pData, ep_addr); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Flushes an endpoint of the Low Level Driver. - * @param pdev: Device handle - * @param ep_addr: Endpoint number - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_FlushEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_EP_Flush(pdev->pData, ep_addr); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Sets a Stall condition on an endpoint of the Low Level Driver. - * @param pdev: Device handle - * @param ep_addr: Endpoint number - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_StallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_EP_SetStall(pdev->pData, ep_addr); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Clears a Stall condition on an endpoint of the Low Level Driver. - * @param pdev: Device handle - * @param ep_addr: Endpoint number - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_ClearStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_EP_ClrStall(pdev->pData, ep_addr); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Returns Stall condition. - * @param pdev: Device handle - * @param ep_addr: Endpoint number - * @retval Stall (1: Yes, 0: No) - */ -uint8_t USBD_LL_IsStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) -{ - PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef*) pdev->pData; - - if((ep_addr & 0x80) == 0x80) - { - return hpcd->IN_ep[ep_addr & 0x7F].is_stall; - } - else - { - return hpcd->OUT_ep[ep_addr & 0x7F].is_stall; - } -} - -/** - * @brief Assigns a USB address to the device. - * @param pdev: Device handle - * @param dev_addr: Device address - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_SetUSBAddress(USBD_HandleTypeDef *pdev, uint8_t dev_addr) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_SetAddress(pdev->pData, dev_addr); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Transmits data over an endpoint. - * @param pdev: Device handle - * @param ep_addr: Endpoint number - * @param pbuf: Pointer to data to be sent - * @param size: Data size - * @retval USBD status - */ -USBD_StatusTypeDef USBD_LL_Transmit(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t size) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_EP_Transmit(pdev->pData, ep_addr, pbuf, size); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -/** - * @brief Prepares an endpoint for reception. - * @param pdev: Device handle - * @param ep_addr: Endpoint number - * @param pbuf: Pointer to data to be received - * @param size: Data size - * @retval USBD status - */ - -USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t size) -{ - HAL_StatusTypeDef hal_status = HAL_OK; - USBD_StatusTypeDef usb_status = USBD_OK; - - hal_status = HAL_PCD_EP_Receive(pdev->pData, ep_addr, pbuf, size); - - switch (hal_status) { - case HAL_OK : - usb_status = USBD_OK; - break; - case HAL_ERROR : - usb_status = USBD_FAIL; - break; - case HAL_BUSY : - usb_status = USBD_BUSY; - break; - case HAL_TIMEOUT : - usb_status = USBD_FAIL; - break; - default : - usb_status = USBD_FAIL; - break; - } - return usb_status; -} - -uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr) -{ - return HAL_PCD_EP_GetRxCount((PCD_HandleTypeDef*) pdev->pData, ep_addr); -} - -void USBD_LL_Delay(uint32_t Delay /* ms */) -{ - HAL_Delay(Delay); -} - diff --git a/fw/hid-dials/src/usbd_conf.h b/fw/hid-dials/src/usbd_conf.h deleted file mode 100644 index c194c70..0000000 --- a/fw/hid-dials/src/usbd_conf.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef __USBD_CONF__H__ -#define __USBD_CONF__H__ - -#ifdef __cplusplus - extern "C" { -#endif - -#include -#include -#include -#include "stm32f0xx.h" -#include "stm32f0xx_hal.h" - -#define USBD_MAX_NUM_INTERFACES 1 -#define USBD_MAX_NUM_CONFIGURATION 1 -#define USBD_MAX_STR_DESC_SIZ 512 -#define USBD_SUPPORT_USER_STRING 0 -#define USBD_DEBUG_LEVEL 0 -#define USBD_SELF_POWERED 1 -#define MAX_STATIC_ALLOC_SIZE 512 - -/****************************************/ -/* #define for FS and HS identification */ -#define DEVICE_FS 0 - -/** - * @} - */ - -/** @defgroup USBD_CONF_Exported_Macros USBD_CONF_Exported_Macros - * @brief Aliases. - * @{ - */ - -/* Memory management macros */ - -/** Alias for memory allocation. */ -#define USBD_malloc malloc -//(uint32_t *)USBD_static_malloc - -/** Alias for memory release. */ -#define USBD_free free - -/** Alias for memory set. */ -#define USBD_memset /* Not used */ - -/** Alias for memory copy. */ -#define USBD_memcpy /* Not used */ - -/** Alias for delay. */ -#define USBD_Delay HAL_Delay - -/* DEBUG macros */ - -#if (USBD_DEBUG_LEVEL > 0) -#define USBD_UsrLog(...) printf(__VA_ARGS__);\ - printf("\n"); -#else -#define USBD_UsrLog(...) -#endif - -#if (USBD_DEBUG_LEVEL > 1) - -#define USBD_ErrLog(...) printf("ERROR: ") ;\ - printf(__VA_ARGS__);\ - printf("\n"); -#else -#define USBD_ErrLog(...) -#endif - -#if (USBD_DEBUG_LEVEL > 2) -#define USBD_DbgLog(...) printf("DEBUG : ") ;\ - printf(__VA_ARGS__);\ - printf("\n"); -#else -#define USBD_DbgLog(...) -#endif - -/* Set unset defines */ -#include "usbd_def.h" - -#endif /* __USBD_CONF__H__ */ diff --git a/fw/hid-dials/src/usbd_desc.c b/fw/hid-dials/src/usbd_desc.c deleted file mode 100644 index bdcaca4..0000000 --- a/fw/hid-dials/src/usbd_desc.c +++ /dev/null @@ -1,365 +0,0 @@ -/** - ****************************************************************************** - * @file : usbd_desc.c - * @version : v2.0_Cube - * @brief : This file implements the USB device descriptors. - ****************************************************************************** - * This notice applies to any and all portions of this file - * that are not between comment pairs USER CODE BEGIN and - * USER CODE END. Other portions of this file, whether - * inserted by the user or by software development tools - * are owned by their respective copyright owners. - * - * Copyright (c) 2018 STMicroelectronics International N.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_core.h" -#include "usbd_desc.h" -#include "usbd_conf.h" - -/* USER CODE BEGIN INCLUDE */ - -/* USER CODE END INCLUDE */ - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ - -/* USER CODE BEGIN PV */ -/* Private variables ---------------------------------------------------------*/ - -/* USER CODE END PV */ - -/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY - * @{ - */ - -/** @addtogroup USBD_DESC - * @{ - */ - -/** @defgroup USBD_DESC_Private_TypesDefinitions USBD_DESC_Private_TypesDefinitions - * @brief Private types. - * @{ - */ - -/* USER CODE BEGIN PRIVATE_TYPES */ - -/* USER CODE END PRIVATE_TYPES */ - -/** - * @} - */ - -/** @defgroup USBD_DESC_Private_Defines USBD_DESC_Private_Defines - * @brief Private defines. - * @{ - */ - -/* - *************************************************[ATTENTION]************************************************ - * - * VID 0x1209 and PID 0x0001 is experimental IDs from http://pid.codes . - * You must get your own IDs, and change to your own IDs in order to avoid conflicting to other USB devices. - * - ************************************************************************************************************ -*/ - -#define USBD_VID 0x1209 -#define USBD_LANGID_STRING 1041 -#define USBD_MANUFACTURER_STRING "jaseg.de" -#define USBD_PID_FS 0x0002 // FIXME -#define USBD_PRODUCT_STRING_FS "MultiHID" -#define USBD_SERIALNUMBER_STRING_FS "000000000001" -#define USBD_CONFIGURATION_STRING_FS "HID Config" -#define USBD_INTERFACE_STRING_FS "HID Interface" - - - -/* USER CODE BEGIN PRIVATE_DEFINES */ - -/* USER CODE END PRIVATE_DEFINES */ - -/** - * @} - */ - -/* USER CODE BEGIN 0 */ - -/* USER CODE END 0 */ - -/** @defgroup USBD_DESC_Private_Macros USBD_DESC_Private_Macros - * @brief Private macros. - * @{ - */ - -/* USER CODE BEGIN PRIVATE_MACRO */ - -/* USER CODE END PRIVATE_MACRO */ - -/** - * @} - */ - -/** @defgroup USBD_DESC_Private_FunctionPrototypes USBD_DESC_Private_FunctionPrototypes - * @brief Private functions declaration. - * @{ - */ - -uint8_t * USBD_FS_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); -uint8_t * USBD_FS_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); -uint8_t * USBD_FS_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); -uint8_t * USBD_FS_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); -uint8_t * USBD_FS_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); -uint8_t * USBD_FS_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); -uint8_t * USBD_FS_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); - -#ifdef USB_SUPPORT_USER_STRING_DESC -uint8_t * USBD_FS_USRStringDesc(USBD_SpeedTypeDef speed, uint8_t idx, uint16_t *length); -#endif /* USB_SUPPORT_USER_STRING_DESC */ - -/** - * @} - */ - -/** @defgroup USBD_DESC_Private_Variables USBD_DESC_Private_Variables - * @brief Private variables. - * @{ - */ - -USBD_DescriptorsTypeDef FS_Desc = -{ - USBD_FS_DeviceDescriptor -, USBD_FS_LangIDStrDescriptor -, USBD_FS_ManufacturerStrDescriptor -, USBD_FS_ProductStrDescriptor -, USBD_FS_SerialStrDescriptor -, USBD_FS_ConfigStrDescriptor -, USBD_FS_InterfaceStrDescriptor -}; - -#if defined ( __ICCARM__ ) /* IAR Compiler */ - #pragma data_alignment=4 -#endif /* defined ( __ICCARM__ ) */ -/** USB standard device descriptor. */ -__ALIGN_BEGIN uint8_t USBD_FS_DeviceDesc[USB_LEN_DEV_DESC] __ALIGN_END = -{ - 0x12, /*bLength */ - USB_DESC_TYPE_DEVICE, /*bDescriptorType*/ - 0x00, /*bcdUSB */ - 0x02, - 0x02, /*bDeviceClass*/ - 0x02, /*bDeviceSubClass*/ - 0x00, /*bDeviceProtocol*/ - USB_MAX_EP0_SIZE, /*bMaxPacketSize*/ - LOBYTE(USBD_VID), /*idVendor*/ - HIBYTE(USBD_VID), /*idVendor*/ - LOBYTE(USBD_PID_FS), /*idProduct*/ - HIBYTE(USBD_PID_FS), /*idProduct*/ - 0x00, /*bcdDevice rel. 2.00*/ - 0x02, - USBD_IDX_MFC_STR, /*Index of manufacturer string*/ - USBD_IDX_PRODUCT_STR, /*Index of product string*/ - USBD_IDX_SERIAL_STR, /*Index of serial number string*/ - USBD_MAX_NUM_CONFIGURATION /*bNumConfigurations*/ -}; - -/* USB_DeviceDescriptor */ - -/** - * @} - */ - -/** @defgroup USBD_DESC_Private_Variables USBD_DESC_Private_Variables - * @brief Private variables. - * @{ - */ - -#if defined ( __ICCARM__ ) /* IAR Compiler */ - #pragma data_alignment=4 -#endif /* defined ( __ICCARM__ ) */ - -/** USB lang indentifier descriptor. */ -__ALIGN_BEGIN uint8_t USBD_LangIDDesc[USB_LEN_LANGID_STR_DESC] __ALIGN_END = -{ - USB_LEN_LANGID_STR_DESC, - USB_DESC_TYPE_STRING, - LOBYTE(USBD_LANGID_STRING), - HIBYTE(USBD_LANGID_STRING) -}; - -#if defined ( __ICCARM__ ) /* IAR Compiler */ - #pragma data_alignment=4 -#endif /* defined ( __ICCARM__ ) */ -/* Internal string descriptor. */ -__ALIGN_BEGIN uint8_t USBD_StrDesc[USBD_MAX_STR_DESC_SIZ] __ALIGN_END; - -/** - * @} - */ - -/** @defgroup USBD_DESC_Private_Functions USBD_DESC_Private_Functions - * @brief Private functions. - * @{ - */ - -/** - * @brief Return the device descriptor - * @param speed : Current device speed - * @param length : Pointer to data length variable - * @retval Pointer to descriptor buffer - */ -uint8_t * USBD_FS_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) -{ - *length = sizeof(USBD_FS_DeviceDesc); - return USBD_FS_DeviceDesc; -} - -/** - * @brief Return the LangID string descriptor - * @param speed : Current device speed - * @param length : Pointer to data length variable - * @retval Pointer to descriptor buffer - */ -uint8_t * USBD_FS_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) -{ - *length = sizeof(USBD_LangIDDesc); - return USBD_LangIDDesc; -} - -/** - * @brief Return the product string descriptor - * @param speed : Current device speed - * @param length : Pointer to data length variable - * @retval Pointer to descriptor buffer - */ -uint8_t * USBD_FS_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) -{ - if(speed == 0) - { - USBD_GetString((uint8_t *)USBD_PRODUCT_STRING_FS, USBD_StrDesc, length); - } - else - { - USBD_GetString((uint8_t *)USBD_PRODUCT_STRING_FS, USBD_StrDesc, length); - } - return USBD_StrDesc; -} - -/** - * @brief Return the manufacturer string descriptor - * @param speed : Current device speed - * @param length : Pointer to data length variable - * @retval Pointer to descriptor buffer - */ -uint8_t * USBD_FS_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) -{ - USBD_GetString((uint8_t *)USBD_MANUFACTURER_STRING, USBD_StrDesc, length); - return USBD_StrDesc; -} - -/** - * @brief Return the serial number string descriptor - * @param speed : Current device speed - * @param length : Pointer to data length variable - * @retval Pointer to descriptor buffer - */ -uint8_t * USBD_FS_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) -{ - if(speed == USBD_SPEED_HIGH) - { - USBD_GetString((uint8_t *)USBD_SERIALNUMBER_STRING_FS, USBD_StrDesc, length); - } - else - { - USBD_GetString((uint8_t *)USBD_SERIALNUMBER_STRING_FS, USBD_StrDesc, length); - } - return USBD_StrDesc; -} - -/** - * @brief Return the configuration string descriptor - * @param speed : Current device speed - * @param length : Pointer to data length variable - * @retval Pointer to descriptor buffer - */ -uint8_t * USBD_FS_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) -{ - if(speed == USBD_SPEED_HIGH) - { - USBD_GetString((uint8_t *)USBD_CONFIGURATION_STRING_FS, USBD_StrDesc, length); - } - else - { - USBD_GetString((uint8_t *)USBD_CONFIGURATION_STRING_FS, USBD_StrDesc, length); - } - return USBD_StrDesc; -} - -/** - * @brief Return the interface string descriptor - * @param speed : Current device speed - * @param length : Pointer to data length variable - * @retval Pointer to descriptor buffer - */ -uint8_t * USBD_FS_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) -{ - if(speed == 0) - { - USBD_GetString((uint8_t *)USBD_INTERFACE_STRING_FS, USBD_StrDesc, length); - } - else - { - USBD_GetString((uint8_t *)USBD_INTERFACE_STRING_FS, USBD_StrDesc, length); - } - return USBD_StrDesc; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/usbd_desc.h b/fw/hid-dials/src/usbd_desc.h deleted file mode 100644 index 9abf0af..0000000 --- a/fw/hid-dials/src/usbd_desc.h +++ /dev/null @@ -1,156 +0,0 @@ -/** - ****************************************************************************** - * @file : usbd_desc.h - * @version : v2.0_Cube - * @brief : Header for usbd_desc.c file. - ****************************************************************************** - * This notice applies to any and all portions of this file - * that are not between comment pairs USER CODE BEGIN and - * USER CODE END. Other portions of this file, whether - * inserted by the user or by software development tools - * are owned by their respective copyright owners. - * - * Copyright (c) 2018 STMicroelectronics International N.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __USBD_DESC__H__ -#define __USBD_DESC__H__ - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_def.h" - -/* USER CODE BEGIN INCLUDE */ - -/* USER CODE END INCLUDE */ - -/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY - * @{ - */ - -/** @defgroup USBD_DESC USBD_DESC - * @brief Usb device descriptors module. - * @{ - */ - -/** @defgroup USBD_DESC_Exported_Defines USBD_DESC_Exported_Defines - * @brief Defines. - * @{ - */ - -/* USER CODE BEGIN EXPORTED_DEFINES */ - -/* USER CODE END EXPORTED_DEFINES */ - -/** - * @} - */ - -/** @defgroup USBD_DESC_Exported_TypesDefinitions USBD_DESC_Exported_TypesDefinitions - * @brief Types. - * @{ - */ - -/* USER CODE BEGIN EXPORTED_TYPES */ - -/* USER CODE END EXPORTED_TYPES */ - -/** - * @} - */ - -/** @defgroup USBD_DESC_Exported_Macros USBD_DESC_Exported_Macros - * @brief Aliases. - * @{ - */ - -/* USER CODE BEGIN EXPORTED_MACRO */ - -/* USER CODE END EXPORTED_MACRO */ - -/** - * @} - */ - -/** @defgroup USBD_DESC_Exported_Variables USBD_DESC_Exported_Variables - * @brief Public variables. - * @{ - */ - -/** Descriptor for the Usb device. */ -extern USBD_DescriptorsTypeDef FS_Desc; - -/* USER CODE BEGIN EXPORTED_VARIABLES */ - -/* USER CODE END EXPORTED_VARIABLES */ - -/** - * @} - */ - -/** @defgroup USBD_DESC_Exported_FunctionsPrototype USBD_DESC_Exported_FunctionsPrototype - * @brief Public functions declaration. - * @{ - */ - -/* USER CODE BEGIN EXPORTED_FUNCTIONS */ - -/* USER CODE END EXPORTED_FUNCTIONS */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __USBD_DESC__H__ */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/src/usbd_hid.c b/fw/hid-dials/src/usbd_hid.c deleted file mode 100644 index 4d313b4..0000000 --- a/fw/hid-dials/src/usbd_hid.c +++ /dev/null @@ -1,373 +0,0 @@ -#include "usbd_hid.h" -#include "usbd_desc.h" -#include "usbd_ctlreq.h" - - -static uint8_t USBD_HID_Init (USBD_HandleTypeDef *pdev, uint8_t cfgidx); -static uint8_t USBD_HID_DeInit (USBD_HandleTypeDef *pdev, uint8_t cfgidx); -static uint8_t USBD_HID_Setup (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); -static uint8_t *USBD_HID_GetCfgDesc (uint16_t *length); -static uint8_t *USBD_HID_GetDeviceQualifierDesc (uint16_t *length); -static uint8_t USBD_HID_DataIn (USBD_HandleTypeDef *pdev, uint8_t epnum); -static uint8_t USBD_HID_DataOut (USBD_HandleTypeDef *pdev, uint8_t epnum); - -USBD_ClassTypeDef USBD_HID = -{ - USBD_HID_Init, - USBD_HID_DeInit, - USBD_HID_Setup, - NULL, /* EP0_TxSent */ - NULL, /* EP0_RxReady */ - USBD_HID_DataIn, - USBD_HID_DataOut, - NULL, /* SOF */ - NULL, - NULL, - USBD_HID_GetCfgDesc, - USBD_HID_GetCfgDesc, - USBD_HID_GetCfgDesc, - USBD_HID_GetDeviceQualifierDesc, -}; - -/* USB HID device configuration descriptor */ -__ALIGN_BEGIN static uint8_t USBD_HID_CfgDesc[USB_HID_CONFIG_DESC_SIZ] __ALIGN_END = -{ - 0x09, /* bLength: Configuration Descriptor size */ - USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */ - USB_HID_CONFIG_DESC_SIZ, - /* wTotalLength: Bytes returned */ - 0x00, - 0x01, /*bNumInterfaces: 1 interface*/ - 0x01, /*bConfigurationValue: Configuration value*/ - 0x00, /*iConfiguration: Index of string descriptor describing - the configuration*/ - 0xE0, /*bmAttributes: bus powered and Support Remote Wake-up */ - 0x32, /*MaxPower 100 mA: this current is used for detecting Vbus*/ - - /* Interface descriptor */ - /* 09 */ - 0x09, /*bLength: Interface Descriptor size*/ - USB_DESC_TYPE_INTERFACE,/*bDescriptorType: Interface descriptor type*/ - 0x00, /*bInterfaceNumber: Number of Interface*/ - 0x00, /*bAlternateSetting: Alternate setting*/ - HID_NUM_EP, - - 0x03, /*bInterfaceClass: HID*/ - - 0x01, /*bInterfaceSubClass : 1=BOOT, 0=no boot*/ - 0x01, /*nInterfaceProtocol : 0=none, 1=keyboard, 2=mouse*/ - 0, /*iInterface: Index of string descriptor*/ - /* HID descriptor */ - /* 18 */ - 0x09, /*bLength: HID Descriptor size*/ - HID_DESCRIPTOR_TYPE, /*bDescriptorType: HID*/ - 0x11, /*bcdHID: HID Class Spec release number*/ - 0x01, - 0x00, /*bCountryCode: Hardware target country*/ - 0x01, /*bNumDescriptors: Number of HID class descriptors to follow*/ - 0x22, /*bDescriptorType*/ - HID_REPORT_DESC_SIZE,/*wItemLength: Total length of Report descriptor*/ - 0x00, - /* HID endpoint descriptor */ - /* 27 */ - 0x07, /*bLength: Endpoint Descriptor size*/ - USB_DESC_TYPE_ENDPOINT, /*bDescriptorType:*/ - - HID_EPIN_ADDR, /*bEndpointAddress: Endpoint Address (IN)*/ - 0x03, /*bmAttributes: Interrupt endpoint*/ - HID_EPIN_SIZE, /*wMaxPacketSize: 4 Byte max */ - 0x00, - HID_FS_BINTERVAL, /*bInterval: Polling Interval (10 ms)*/ - /* 34 */ -#if HID_LED_SUPPORT - 0x07, /*bLength: Endpoint Descriptor size*/ - USB_DESC_TYPE_ENDPOINT, /*bDescriptorType:*/ - - HID_EPOUT_ADDR, /*bEndpointAddress: Endpoint Address (IN)*/ - 0x03, /*bmAttributes: Interrupt endpoint*/ - HID_EPOUT_SIZE, /*wMaxPacketSize: 4 Byte max */ - 0x00, - HID_FS_BINTERVAL, /*bInterval: Polling Interval (10 ms)*/ -#endif - /* 41 */ - -} ; - -/* USB HID device Configuration Descriptor */ -__ALIGN_BEGIN static uint8_t USBD_HID_Desc[USB_HID_DESC_SIZ] __ALIGN_END = -{ - /* 18 */ - 0x09, /*bLength: HID Descriptor size*/ - HID_DESCRIPTOR_TYPE, /*bDescriptorType: HID*/ - 0x11, /*bcdHID: HID Class Spec release number*/ - 0x01, - 0x00, /*bCountryCode: Hardware target country*/ - 0x01, /*bNumDescriptors: Number of HID class descriptors to follow*/ - 0x22, /*bDescriptorType*/ - HID_REPORT_DESC_SIZE,/*wItemLength: Total length of Report descriptor*/ - 0x00, -}; - -/* USB Standard Device Descriptor */ -__ALIGN_BEGIN static uint8_t USBD_HID_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END = -{ - USB_LEN_DEV_QUALIFIER_DESC, - USB_DESC_TYPE_DEVICE_QUALIFIER, - 0x00, - 0x02, - 0x00, - 0x00, - 0x00, - 0x40, - 0x01, - 0x00, -}; - -__ALIGN_BEGIN static uint8_t HID_ReportDesc[HID_REPORT_DESC_SIZE] __ALIGN_END = -{ - 0x05, 0x01, // USAGE_PAGE (Generic Desktop) - 0x09, 0x06, // USAGE (Keyboard) - 0xa1, 0x01, // COLLECTION (Application) - 0x85, 0x01, /* Report ID */ - 0x05, 0x07, // USAGE_PAGE (Keyboard) - 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) - 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x25, 0x01, // LOGICAL_MAXIMUM (1) - 0x75, 0x01, // REPORT_SIZE (1) - 0x95, 0x08, // REPORT_COUNT (8) - 0x81, 0x02, // INPUT (Data,Var,Abs) - 0x95, 0x01, // REPORT_COUNT (1) - 0x75, 0x08, // REPORT_SIZE (8) - 0x81, 0x03, // INPUT (Cnst,Var,Abs) - 0x95, 0x05, // REPORT_COUNT (5) - 0x75, 0x01, // REPORT_SIZE (1) - 0x05, 0x08, // USAGE_PAGE (LEDs) - 0x19, 0x01, // USAGE_MINIMUM (Num Lock) - 0x29, 0x05, // USAGE_MAXIMUM (Kana) - 0x91, 0x02, // OUTPUT (Data,Var,Abs) - 0x95, 0x01, // REPORT_COUNT (1) - 0x75, 0x03, // REPORT_SIZE (3) - 0x91, 0x03, // OUTPUT (Cnst,Var,Abs) - 0x95, 0x06, // REPORT_COUNT (6) - 0x75, 0x08, // REPORT_SIZE (8) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x25, 0x65, // LOGICAL_MAXIMUM (101) - 0x05, 0x07, // USAGE_PAGE (Keyboard) - 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) - 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application) - 0x81, 0x00, // INPUT (Data,Ary,Abs) - 0xc0, // End Collection - // - 0x05, 0x0C, /* Usage Page (Consumer Devices) */ - 0x09, 0x01, /* Usage (Consumer Control) */ - 0xA1, 0x01, /* Collection (Application) */ - 0x85, 0x02, /* Report ID=2 */ - 0x05, 0x0C, /* Usage Page (Consumer Devices) */ - 0x15, 0x00, /* Logical Minimum (0) */ - 0x25, 0x01, /* Logical Maximum (1) */ - 0x75, 0x01, /* Report Size (1) */ - 0x95, 0x07, /* Report Count (7) */ - 0x09, 0xB5, /* Usage (Scan Next Track) */ - 0x09, 0xB6, /* Usage (Scan Previous Track) */ - 0x09, 0xB7, /* Usage (Stop) */ - 0x09, 0xCD, /* Usage (Play / Pause) */ - 0x09, 0xE2, /* Usage (Mute) */ - 0x09, 0xE9, /* Usage (Volume Up) */ - 0x09, 0xEA, /* Usage (Volume Down) */ - 0x81, 0x02, /* Input (Data, Variable, Absolute) */ - 0x95, 0x01, /* Report Count (1) */ - 0x81, 0x01, /* Input (Constant) */ - 0xC0, // End Collection - - // how to format the 3 byte report - // byte 0 report ID = 0x02 (VOLUME_REPORT) - // byte 1 media code for ex VOL_UP 0xE9 , VOL_DONW 0xEA ... etc - // byte 2 0x00 - // a second report with 0 code shal be send to avoid "key repaeat" -}; - -uint32_t nOutData; -uint8_t OutDataBuffer[HID_EPOUT_SIZE]; // local copy for user (usb fly at same time) -uint8_t OutData[HID_EPOUT_SIZE]; // live usb buffer - - -static uint8_t USBD_HID_Init (USBD_HandleTypeDef *pdev, uint8_t cfgidx) -{ - USBD_LL_OpenEP(pdev, HID_EPIN_ADDR, USBD_EP_TYPE_INTR, HID_EPIN_SIZE); -#if HID_LED_SUPPORT - USBD_LL_OpenEP(pdev, HID_EPOUT_ADDR, USBD_EP_TYPE_INTR, HID_EPOUT_SIZE); -#endif - - pdev->pClassData = USBD_malloc(sizeof (USBD_HID_HandleTypeDef)); - - if(pdev->pClassData == NULL) - return 1; - -#if HID_LED_SUPPORT - USBD_LL_PrepareReceive(pdev, HID_EPOUT_ADDR, OutData, HID_EPOUT_SIZE); -#endif - ((USBD_HID_HandleTypeDef *)pdev->pClassData)->state = HID_IDLE; - return 0; -} - -static uint8_t USBD_HID_DeInit (USBD_HandleTypeDef *pdev, - uint8_t cfgidx) -{ - USBD_LL_CloseEP(pdev, HID_EPIN_ADDR); - USBD_LL_CloseEP(pdev, HID_EPOUT_ADDR); - - if(pdev->pClassData != NULL) { - USBD_free(pdev->pClassData); - pdev->pClassData = NULL; - } - - return USBD_OK; -} - -static uint8_t USBD_HID_Setup (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req) -{ - uint16_t len = 0; - uint8_t *pbuf = NULL; - USBD_HID_HandleTypeDef *hhid = (USBD_HID_HandleTypeDef*) pdev->pClassData; - - switch (req->bmRequest & USB_REQ_TYPE_MASK) - { - case USB_REQ_TYPE_CLASS : - switch (req->bRequest) { - case HID_REQ_SET_PROTOCOL: - hhid->Protocol = (uint8_t)(req->wValue); - break; - - case HID_REQ_GET_PROTOCOL: - USBD_CtlSendData (pdev, - (uint8_t *)&hhid->Protocol, - 1); - break; - - case HID_REQ_SET_IDLE: - hhid->IdleState = (uint8_t)(req->wValue >> 8); - break; - - case HID_REQ_GET_IDLE: - USBD_CtlSendData (pdev, - (uint8_t *)&hhid->IdleState, - 1); - break; - - default: - USBD_CtlError (pdev, req); - return USBD_FAIL; - } - break; - - case USB_REQ_TYPE_STANDARD: - switch (req->bRequest) { - case USB_REQ_GET_DESCRIPTOR: - if( req->wValue >> 8 == HID_REPORT_DESC) - { - len = MIN(HID_REPORT_DESC_SIZE , req->wLength); - pbuf = HID_ReportDesc; - } - else if( req->wValue >> 8 == HID_DESCRIPTOR_TYPE) - { - pbuf = USBD_HID_Desc; - len = MIN(USB_HID_DESC_SIZ , req->wLength); - } - - USBD_CtlSendData (pdev, - pbuf, - len); - - break; - - case USB_REQ_GET_INTERFACE : - USBD_CtlSendData (pdev, - (uint8_t *)&hhid->AltSetting, - 1); - break; - - case USB_REQ_SET_INTERFACE : - hhid->AltSetting = (uint8_t)(req->wValue); - break; - } - } - return USBD_OK; -} - -uint8_t USBD_HID_SendReport (USBD_HandleTypeDef *pdev, uint8_t *report, uint16_t len) -{ - USBD_HID_HandleTypeDef *hhid = (USBD_HID_HandleTypeDef*)pdev->pClassData; - - if (pdev->dev_state != USBD_STATE_CONFIGURED ) - return USBD_OK; - - if(hhid->state == HID_IDLE) - return USBD_OK; - - hhid->state = HID_BUSY; - USBD_LL_Transmit(pdev, HID_EPIN_ADDR, report, len); - return USBD_OK; -} - -uint32_t USBD_HID_GetPollingInterval (USBD_HandleTypeDef *pdev) -{ - uint32_t polling_interval = 0; - - /* HIGH-speed endpoints */ - if(pdev->dev_speed == USBD_SPEED_HIGH) - { - /* Sets the data transfer polling interval for high speed transfers. - Values between 1..16 are allowed. Values correspond to interval - of 2 ^ (bInterval-1). This option (8 ms, corresponds to HID_HS_BINTERVAL */ - polling_interval = (((1 <<(HID_HS_BINTERVAL - 1)))/8); - } - else /* LOW and FULL-speed endpoints */ - { - /* Sets the data transfer polling interval for low and full - speed transfers */ - polling_interval = HID_FS_BINTERVAL; - } - - return ((uint32_t)(polling_interval)); -} - -static uint8_t *USBD_HID_GetCfgDesc (uint16_t *length) -{ - *length = sizeof (USBD_HID_CfgDesc); - return USBD_HID_CfgDesc; -} - - -static uint8_t USBD_HID_DataIn (USBD_HandleTypeDef *pdev, - uint8_t epnum) -{ - /* Ensure that the FIFO is empty before a new transfer, this condition could - be caused by a new transfer before the end of the previous transfer */ - ((USBD_HID_HandleTypeDef *)pdev->pClassData)->state = HID_IDLE; - return USBD_OK; -} - - -__weak void USBD_HID_GetReport(uint8_t *buf, int len){ -} - -static uint8_t USBD_HID_DataOut (USBD_HandleTypeDef *pdev, uint8_t epnum) -{ - int len; - - nOutData++; - // data cpy so we can be ready for next usb out and used received data safely - len = USBD_LL_GetRxDataSize (pdev, epnum); - memcpy(OutDataBuffer, OutData, len); - USBD_LL_PrepareReceive(pdev, HID_EPOUT_ADDR, OutData, HID_EPOUT_SIZE); - USBD_HID_GetReport(OutDataBuffer, len); - return USBD_OK; -} - -static uint8_t *USBD_HID_GetDeviceQualifierDesc (uint16_t *length) -{ - *length = sizeof (USBD_HID_DeviceQualifierDesc); - return USBD_HID_DeviceQualifierDesc; -} - diff --git a/fw/hid-dials/src/usbd_hid.h b/fw/hid-dials/src/usbd_hid.h deleted file mode 100644 index fa2f0a2..0000000 --- a/fw/hid-dials/src/usbd_hid.h +++ /dev/null @@ -1,193 +0,0 @@ -/** - ****************************************************************************** - * @file usbd_hid.h - * @author MCD Application Team - * @version V2.4.2 - * @date 11-December-2015 - * @brief Header file for the usbd_hid_core.c file. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2015 STMicroelectronics

- * - * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/software_license_agreement_liberty_v2 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __USB_HID_H -#define __USB_HID_H - -#ifdef __cplusplus - extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "usbd_ioreq.h" - -/** @addtogroup STM32_USB_DEVICE_LIBRARY - * @{ - */ - -/** @defgroup USBD_HID - * @brief This file is the Header file for usbd_hid.c - * @{ - */ - -/** set this to 0/1 if to have led or not - * it can be defined in the build configuraton symbol */ -#ifndef HID_LED_SUPPORT -# define HID_LED_SUPPORT 0 -#endif - - /** define VOLUME_REPORT to tehr eport ID to use for volume or 0 if not support*/ -#define HID_MEDIA_REPORT 2 -#ifdef HID_MEDIA_REPORT -# define HID_MEDIA_SIZE 25 -#else -# define HID_MEDIA_SIZE 0 -#endif - -#if HID_MEDIA_REPORT == 1 -# error "volume report can't be 1 already sued for stad report" -#endif - -/** @defgroup USBD_HID_Exported_Defines - * @{ - */ -#define HID_EPIN_ADDR 0x81 - -#define HID_EPOUT_ADDR 0x01 -#define HID_EPOUT_SIZE 0x08 - -#define HID_EPIN_SIZE 16 - - #if HID_LED_SUPPORT -# define CFG_ADD_SIZE 7 /* one ep */ -# define HID_NUM_EP 2 -#else -# define CFG_ADD_SIZE 0 -# define HID_NUM_EP 1 -#endif - -#define USB_HID_CONFIG_DESC_SIZ (34+CFG_ADD_SIZE) - -#define USB_HID_DESC_SIZ 9 - - - -#if HID_LED_SUPPORT -# define HID_LED_SIZE 18 -#else -# define HID_LED_SIZE 0 -#endif - - - -#define HID_REPORT_DESC_SIZE 104 - - -#define HID_DESCRIPTOR_TYPE 0x21 -#define HID_REPORT_DESC 0x22 - -#define HID_HS_BINTERVAL 0x07 -#define HID_FS_BINTERVAL 0x0A -#define HID_POLLING_INTERVAL 0x0A - -#define HID_REQ_SET_PROTOCOL 0x0B -#define HID_REQ_GET_PROTOCOL 0x03 - -#define HID_REQ_SET_IDLE 0x0A -#define HID_REQ_GET_IDLE 0x02 - -#define HID_REQ_SET_REPORT 0x09 -#define HID_REQ_GET_REPORT 0x01 -/** - * @} - */ - - -/** @defgroup USBD_CORE_Exported_TypesDefinitions - * @{ - */ -typedef enum -{ - HID_IDLE = 0, - HID_BUSY, -} -HID_StateTypeDef; - - -typedef struct -{ - uint32_t Protocol; - uint32_t IdleState; - uint32_t AltSetting; - HID_StateTypeDef state; -} -USBD_HID_HandleTypeDef; -/** - * @} - */ - - - -/** @defgroup USBD_CORE_Exported_Macros - * @{ - */ - -/** - * @} - */ - -/** @defgroup USBD_CORE_Exported_Variables - * @{ - */ - -extern USBD_ClassTypeDef USBD_HID; -#define USBD_HID_CLASS &USBD_HID -/** - * @} - */ - -/** @defgroup USB_CORE_Exported_Functions - * @{ - */ -uint8_t USBD_HID_SendReport (USBD_HandleTypeDef *pdev, - uint8_t *report, - uint16_t len); - -uint32_t USBD_HID_GetPollingInterval (USBD_HandleTypeDef *pdev); - - -/** user redifinable */ -void USBD_HID_GetReport(uint8_t * OutData, int len); -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __USB_HID_H */ -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/fw/hid-dials/tools/butter_filter_gen.py b/fw/hid-dials/tools/butter_filter_gen.py deleted file mode 100644 index 0bb81bc..0000000 --- a/fw/hid-dials/tools/butter_filter_gen.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python3 - -import math -import sys -import contextlib - -import scipy.signal as sig -import numpy as np - - -@contextlib.contextmanager -def wrap(left='{', right='}', file=None, end=''): - print(left, file=file, end=end) - yield - print(right, file=file, end=end) - -@contextlib.contextmanager -def print_include_guards(macro_name): - print(f'#ifndef {macro_name}') - print(f'#define {macro_name}') - print() - yield - print() - print(f'#endif /* {macro_name} */') - -macro_float = lambda f: f'{f}'.replace('.', 'F').replace('-', 'N').replace('+', 'P') - -ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4]) - -SI_TABLE = {-18: 'a', -15: 'f', -12: 'p', -9: 'n', -6: 'µ', -3: 'm', 0: '', 3: 'k', 6: 'M', 9: 'G', 12: 'T', 15: 'P', 18: 'E'} -def siprefix(x, space=' ', unit=''): - l = math.log10(x)//3*3 - if l in SI_TABLE: - return f'{x/10**l}{space}{SI_TABLE[l]}{unit}' - return f'{x}{space}{unit}' - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('-m', '--macro-name', default='butter_filter', help='Prefix for output macro names') - parser.add_argument('fc', type=float, help='Corner frequency [Hz]') - parser.add_argument('fs', type=float, help='Sampling rate [Hz]') - parser.add_argument('n', type=int, nargs='?', default=6, help='Filter order') - args = parser.parse_args() - - sos = sig.butter(args.n, args.fc, fs=args.fs, output='sos') - - print('/* THIS IS A GENERATED FILE. DO NOT EDIT! */') - print() - with print_include_guards(f'__BUTTER_FILTER_GENERATED_{args.n}_{macro_float(args.fc)}_{macro_float(args.fs)}__'): - - print(f'/* {ordinal(args.n)} order Butterworth IIR filter coefficients') - print(f' *') - print(f' * corner frequency f_c = {siprefix(args.fc)}Hz') - print(f' * sampling rate f_s = {siprefix(args.fs)}Hz') - print(f' */') - print() - print(f'#define {args.macro_name.upper()}_ORDER {args.n}') - print(f'#define {args.macro_name.upper()}_CLEN {(args.n+1)//2}') - - # scipy.signal.butter by default returns extremely small bs for the first biquad and large ones for subsequent - # sections. Balance magnitudes to reduce possible rounding errors. - first_biquad_bs = sos[0][:3] - approx_mag = round(math.log10(np.mean(first_biquad_bs))) - mags = [approx_mag // len(sos)] * len(sos) - mags[0] += approx_mag - sum(mags) - sos[0][:3] /= 10**approx_mag - sos = np.array([ sec * np.array([10**mag, 10**mag, 10**mag, 1, 1, 1]) for mag, sec in zip(mags, sos) ]) - - ones = np.ones([100000]) - _, steady_state = sig.sosfilt(sos, ones, zi=np.zeros([(args.n+1)//2, 2])) - - print(f'#define {args.macro_name.upper()}_COEFF ', end='') - for sec in sos: - bs, ases = sec[:3], sec[4:6] - - with wrap(): - print('.b=', end='') - with wrap(): - print(', '.join(f'{v}' for v in bs), end='') - print(', .a=', end='') - with wrap(): - print(', '.join(f'{v}' for v in ases), end='') - print(', ', end='') - print() - - print(f'#define {args.macro_name.upper()}_STEADY_STATE ', end='') - for sec in steady_state: - with wrap(): - print(', '.join(f'{v}' for v in sec), end='') - print(', ', end='') - print() - diff --git a/fw/hid-dials/tools/crypto_test.c b/fw/hid-dials/tools/crypto_test.c deleted file mode 100644 index 410fac2..0000000 --- a/fw/hid-dials/tools/crypto_test.c +++ /dev/null @@ -1,46 +0,0 @@ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "crypto.h" - -void oob_trigger_activated(enum trigger_domain domain, int serial) { - printf("oob_trigger_activated(%d, %d)\n", domain, serial); - fflush(stdout); -} - -void print_usage() { - fprintf(stderr, "Usage: crypto_test [auth_key_hex]\n"); -} - -int main(int argc, char **argv) { - if (argc != 2) { - fprintf(stderr, "Error: Invalid arguments.\n"); - print_usage(); - return 1; - } - - uint8_t auth_key[16]; - - for (size_t i=0; argv[1][i+0] != '\0' && argv[1][i+1] != '\0' && i/2015.12e}f,' for f in win) - print(textwrap.fill(par, - initial_indent=' '*4, subsequent_indent=' '*4, - width=120, - replace_whitespace=False, drop_whitespace=False)) - print('};') - print() - print(f'const float * const {args.variable} __attribute__((weak)) = {varname};') - diff --git a/fw/hid-dials/tools/dsss_demod_test.c b/fw/hid-dials/tools/dsss_demod_test.c deleted file mode 100644 index f7df111..0000000 --- a/fw/hid-dials/tools/dsss_demod_test.c +++ /dev/null @@ -1,109 +0,0 @@ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "dsss_demod.h" - -void handle_dsss_received(symbol_t data[static TRANSMISSION_SYMBOLS]) { - printf("data sequence received: [ "); - for (size_t i=0; i>1)); - printf("%2d", data[i]); - if (i+1 < TRANSMISSION_SYMBOLS) - printf(", "); - } - printf(" ]\n"); -} - -void print_usage() { - fprintf(stderr, "Usage: dsss_demod_test [test_data.bin] [optional recording channel number]\n"); -} - -int main(int argc, char **argv) { - if (argc != 2 && argc != 3) { - fprintf(stderr, "Error: Invalid arguments.\n"); - print_usage(); - return 1; - } - - int fd = open(argv[1], O_RDONLY); - struct stat st; - if (fstat(fd, &st)) { - fprintf(stderr, "Error querying test data file size: %s\n", strerror(errno)); - return 2; - } - - if (st.st_size < 0 || st.st_size > 10000000) { - fprintf(stderr, "Error reading test data: too much test data (size=%zd)\n", st.st_size); - return 2; - } - - if (st.st_size % sizeof(float) != 0) { - fprintf(stderr, "Error reading test data: file size is not divisible by %zd (size=%zd)\n", sizeof(float), st.st_size); - return 2; - } - - char *buf = malloc(st.st_size); - if (!buf) { - fprintf(stderr, "Error allocating memory"); - return 2; - } - - int record_channel = -1; - if (argc == 3) { - char *endptr; - record_channel = strtoul(argv[2], &endptr, 10); - if (!endptr || *endptr != '\0') { - fprintf(stderr, "Invalid channel number \"%s\"\n", argv[2]); - return 1; - } - } - - if (record_channel != -1) - fprintf(stderr, "Reading %zd samples test data...", st.st_size/sizeof(float)); - ssize_t nread = 0; - while (nread < st.st_size) { - ssize_t rc = read(fd, buf + nread, st.st_size - nread); - - if (rc == -EINTR || rc == -EAGAIN) - continue; - - if (rc < 0) { - fprintf(stderr, "\nError reading test data: %s\n", strerror(errno)); - return 2; - } - - if (rc == 0) { - fprintf(stderr, "\nError reading test data: Unexpected end of file\n"); - return 2; - } - - nread += rc; - } - if (record_channel != -1) - fprintf(stderr, " done.\n"); - - const size_t n_samples = st.st_size / sizeof(float); - float *buf_f = (float *)buf; - - if (record_channel != -1) - fprintf(stderr, "Starting simulation.\n"); - - struct dsss_demod_state demod; - dsss_demod_init(&demod); - for (size_t i=0; i 0 else test_data[-shift:] - b = decoded if shift < 0 else decoded[shift:] - for i, (ref, found) in enumerate(itertools.zip_longest(a, b)): - if ref is None: # end of signal - break - if ref != found: - failures += 1 - match_result.append(failures) - failures = min(match_result) - return failures/len(test_data) - -ResultParams = namedtuple('ResultParams', ['nbits', 'thf', 'decimation', 'symbols', 'seed', 'amplitude', 'background']) - -def run_test(seed, amplitude_spec, background, nbits, decimation, symbols, thfs, lookup_binary, cachedir): - noise_gen, noise_params = load_noise_gen(background) - - test_data = np.random.RandomState(seed=seed).randint(0, 2 * (2**nbits), symbols) - - signal = np.repeat(dsss_modulate(test_data, nbits) * 2.0 - 1, decimation) - # We're re-using the seed here. This is not a problem. - noise = noise_gen(seed, len(signal), *noise_params) - amplitudes = amplitude_spec[0] * 10 ** np.linspace(0, amplitude_spec[1], amplitude_spec[2]) - # DEBUG - my_pid = multiprocessing.current_process().pid - wql = len(amplitudes) * len(thfs) - print(f'[{my_pid}] starting, got workqueue of length {wql}') - i = 0 - # Map lsb to sign to match test program - # test_data = (test_data>>1) * (2*(test_data&1) - 1) - # END DEBUG - - output = [] - for amp in amplitudes: - with tempfile.NamedTemporaryFile(dir=cachedir) as f: - waveform = signal*amp + noise - f.write(waveform.astype('float32').tobytes()) - f.flush() - # DEBUG - fcopy = f'/tmp/test-{path.basename(f.name)}' - import shutil - shutil.copy(f.name, fcopy) - # END DEBUG - - for thf in thfs: - rpars = ResultParams(nbits, thf, decimation, symbols, seed, amp, background) - cmdline = [lookup_binary(nbits, thf, decimation, symbols), f.name] - # DEBUG - starttime = time.time() - # END DEBUG - try: - proc = subprocess.run(cmdline, stdout=subprocess.PIPE, encoding='utf-8', check=True, timeout=300) - - lines = proc.stdout.splitlines() - matched = [ l.partition('[')[2].partition(']')[0] - for l in lines if l.strip().startswith('data sequence received:') ] - matched = [ [ int(elem) for elem in l.split(',') ] for l in matched ] - - ser = min(sequence_matcher(test_data, match) for match in matched) if matched else None - output.append((rpars, ser)) - # DEBUG - #print(f'[{my_pid}] ran {i}/{wql}: time={time.time() - starttime}\n {ser=}\n {rpars}\n {" ".join(cmdline)}\n {fcopy}', flush=True) - i += 1 - # END DEBUG - - except subprocess.TimeoutExpired: - output.append((rpars, None)) - # DEBUG - print(f'[{my_pid}] ran {i}/{wql}: Timeout!\n {rpars}\n {" ".join(cmdline)}\n {fcopy}', flush=True) - i += 1 - # END DEBUG - print(f'[{my_pid}] finished.') - return output - -def parallel_generator(db, table, columns, builder, param_list, desc, context={}, params_mapper=lambda *args: args, - disable_cache=False): - with multiprocessing.Pool(multiprocessing.cpu_count()) as pool: - with db as conn: - jobs = [] - for params in param_list: - found_res = conn.execute( - f'SELECT result FROM {table} WHERE ({",".join(columns)}) = ({",".join("?"*len(columns))})', - params_mapper(*params)).fetchone() - - if found_res and not disable_cache: - yield params, json.loads(*found_res) - - else: - jobs.append((params, pool.apply_async(builder, params, context))) - - pool.close() - print('Using', len(param_list) - len(jobs), 'cached jobs', flush=True) - with tqdm(total=len(jobs), desc=desc) as tq: - for i, (params, res) in enumerate(jobs): - # DEBUG - print('Got result', i, params, res) - # END DEBUG - tq.update(1) - result = res.get() - with db as conn: - conn.execute(f'INSERT INTO {table} VALUES ({"?,"*len(params)}?,?)', - (*params_mapper(*params), json.dumps(result), timestamp())) - yield params, result - pool.join() - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('-d', '--dump', help='Write results to JSON file') - parser.add_argument('-c', '--cachedir', default='dsss_test_cache', help='Directory to store build output and data in') - parser.add_argument('-n', '--no-cache', action='store_true', help='Disable result cache') - parser.add_argument('-b', '--batches', type=int, default=1, help='Number of batches to split the computation into') - parser.add_argument('-i', '--index', type=int, default=0, help='Batch index to compute') - parser.add_argument('-p', '--prepare', action='store_true', help='Prepare mode: compile runners, then exit.') - args = parser.parse_args() - - DecoderParams = namedtuple('DecoderParams', ['nbits', 'thf', 'decimation', 'symbols']) -# dec_paramses = [ DecoderParams(nbits=nbits, thf=thf, decimation=decimation, symbols=20) -# for nbits in [5, 6] -# for thf in [4.5, 4.0, 5.0] -# for decimation in [10, 5, 22] ] - dec_paramses = [ DecoderParams(nbits=nbits, thf=thf, decimation=decimation, symbols=100) - for nbits in [5, 6] - for thf in [3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0] - for decimation in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 16, 22, 30, 40, 50] ] -# dec_paramses = [ DecoderParams(nbits=nbits, thf=thf, decimation=decimation, symbols=100) -# for nbits in [5, 6, 7, 8] -# for thf in [1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0] -# for decimation in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 16, 22, 30, 40, 50] ] - - build_cache_dir = path.join(args.cachedir, 'builds') - data_cache_dir = path.join(args.cachedir, 'data') - os.makedirs(build_cache_dir, exist_ok=True) - os.makedirs(data_cache_dir, exist_ok=True) - - build_db = sqlite3.connect(path.join(args.cachedir, 'build_db.sqlite3')) - build_db.execute('CREATE TABLE IF NOT EXISTS builds (nbits, thf, decimation, symbols, result, timestamp)') - timestamp = lambda: int(time.time()*1000) - - builds = dict(parallel_generator(build_db, table='builds', columns=['nbits', 'thf', 'decimation', 'symbols'], - builder=build_test_binary, param_list=dec_paramses, desc='Building decoders', - context=dict(cachedir=build_cache_dir))) - print('Done building decoders.') - if args.prepare: - sys.exit(0) - - GeneratorParams = namedtuple('GeneratorParams', ['seed', 'amplitude_spec', 'background']) - gen_params = [ GeneratorParams(rep, (5e-3, 1, 5), background) - #GeneratorParams(rep, (0.05e-3, 3.5, 50), background) - for rep in range(50) - for background in ['meas://fmeas_export_ocxo_2day.bin', 'synth://grid_freq_psd_spl_108pt.json'] ] -# gen_params = [ GeneratorParams(rep, (5e-3, 1, 5), background) -# for rep in range(1) -# for background in ['meas://fmeas_export_ocxo_2day.bin'] ] - - data_db = sqlite3.connect(path.join(args.cachedir, 'data_db.sqlite3')) - data_db.execute('CREATE TABLE IF NOT EXISTS waveforms' - '(seed, amplitude_spec, background, nbits, decimation, symbols, thresholds, result, timestamp)') - - 'SELECT FROM waveforms GROUP BY (amplitude_spec, background, nbits, decimation, symbols, thresholds, result)' - - dec_param_groups = defaultdict(lambda: []) - for nbits, thf, decimation, symbols in dec_paramses: - dec_param_groups[(nbits, decimation, symbols)].append(thf) - waveform_params = [ (*gp, *dp, thfs) for gp in gen_params for dp, thfs in dec_param_groups.items() ] - print(f'Generated {len(waveform_params)} parameter sets') - - # Separate out our batch - waveform_params = waveform_params[args.index::args.batches] - - def lookup_binary(*params): - return path.join(build_cache_dir, builds[tuple(params)], 'tools/dsss_demod_test') - - def params_mapper(seed, amplitude_spec, background, nbits, decimation, symbols, thresholds): - amplitude_spec = ','.join(str(x) for x in amplitude_spec) - thresholds = ','.join(str(x) for x in thresholds) - return seed, amplitude_spec, background, nbits, decimation, symbols, thresholds - - results = [] - for _params, chunk in parallel_generator(data_db, 'waveforms', - ['seed', 'amplitude_spec', 'background', 'nbits', 'decimation', 'symbols', 'thresholds'], - params_mapper=params_mapper, - builder=run_test, - param_list=waveform_params, desc='Simulating demodulation', - context=dict(cachedir=data_cache_dir, lookup_binary=lookup_binary), - disable_cache=args.no_cache): - results += chunk - - if args.dump: - with open(args.dump, 'w') as f: - json.dump(results, f) - diff --git a/fw/hid-dials/tools/dsss_demod_test_waveform_gen.py b/fw/hid-dials/tools/dsss_demod_test_waveform_gen.py deleted file mode 100644 index 414c553..0000000 --- a/fw/hid-dials/tools/dsss_demod_test_waveform_gen.py +++ /dev/null @@ -1,86 +0,0 @@ - -from os import path -import json -import functools - -import numpy as np -import numbers -import math -from scipy import signal as sig -import scipy.fftpack - -sampling_rate = 10 # sp/s - -# From https://github.com/mubeta06/python/blob/master/signal_processing/sp/gold.py -preferred_pairs = {5:[[2],[1,2,3]], 6:[[5],[1,4,5]], 7:[[4],[4,5,6]], - 8:[[1,2,3,6,7],[1,2,7]], 9:[[5],[3,5,6]], - 10:[[2,5,9],[3,4,6,8,9]], 11:[[9],[3,6,9]]} - -def gen_gold(seq1, seq2): - gold = [seq1, seq2] - for shift in range(len(seq1)): - gold.append(seq1 ^ np.roll(seq2, -shift)) - return gold - -def gold(n): - n = int(n) - if not n in preferred_pairs: - raise KeyError('preferred pairs for %s bits unknown' % str(n)) - t0, t1 = preferred_pairs[n] - (seq0, _st0), (seq1, _st1) = sig.max_len_seq(n, taps=t0), sig.max_len_seq(n, taps=t1) - return gen_gold(seq0, seq1) - -def modulate(data, nbits=5): - # 0, 1 -> -1, 1 - mask = np.array(gold(nbits))*2 - 1 - - sel = mask[data>>1] - data_lsb_centered = ((data&1)*2 - 1) - - signal = (np.multiply(sel, np.tile(data_lsb_centered, (2**nbits-1, 1)).T).flatten() + 1) // 2 - return np.hstack([ np.zeros(len(mask)), signal, np.zeros(len(mask)) ]) - -def load_noise_meas_params(capture_file): - with open(capture_file, 'rb') as f: - meas_data = np.copy(np.frombuffer(f.read(), dtype='float32')) - meas_data -= np.mean(meas_data) - return (meas_data,) - -def mains_noise_measured(seed, n, meas_data): - last_valid = len(meas_data) - n - st = np.random.RandomState(seed) - start = st.randint(last_valid) - return meas_data[start:start+n] + 50.00 - -def load_noise_synth_params(specfile): - with open(specfile) as f: - d = json.load(f) - return {'spl_x': np.linspace(*d['x_spec']), - 'spl_N': d['x_spec'][2], - 'psd_spl': (d['t'], d['c'], d['k']) } - -def mains_noise_synthetic(seed, n, psd_spl, spl_N, spl_x): - st = np.random.RandomState(seed) - noise = st.normal(size=spl_N) * 2 - spec = scipy.fftpack.fft(noise) **2 - - spec *= np.exp(scipy.interpolate.splev(spl_x, psd_spl)) - - spec **= 1/2 - - renoise = scipy.fftpack.ifft(spec) - return renoise[10000:][:n] + 50.00 - -@functools.lru_cache() -def load_noise_gen(url): - schema, refpath = url.split('://') - if not path.isabs(refpath): - refpath = path.abspath(path.join(path.dirname(__file__), refpath)) - - if schema == 'meas': - return mains_noise_measured, load_noise_meas_params(refpath) - elif schema == 'synth': - return mains_noise_synthetic, load_noise_synth_params(refpath) - else: - raise ValueError('Invalid schema', schema) - diff --git a/fw/hid-dials/tools/e2e_test.c b/fw/hid-dials/tools/e2e_test.c deleted file mode 100644 index 935f70d..0000000 --- a/fw/hid-dials/tools/e2e_test.c +++ /dev/null @@ -1,111 +0,0 @@ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "freq_meas.h" -#include "dsss_demod.h" - -typedef uint16_t adc_data_t; - -void handle_dsss_received(uint8_t data[static TRANSMISSION_SYMBOLS]) { - printf("data sequence received: [ "); - for (size_t i=0; i>1)); - if (i+1 < TRANSMISSION_SYMBOLS) - printf(", "); - } - printf(" ]\n"); -} - -void print_usage(void); -void print_usage() { - fprintf(stderr, "Usage: e2e_test [emulated_adc_data.bin]\n"); -} - -int main(int argc, char **argv) { - if (argc != 2) { - fprintf(stderr, "Error: Invalid arguments.\n"); - print_usage(); - return 1; - } - - int fd = open(argv[1], O_RDONLY); - struct stat st; - if (fstat(fd, &st)) { - fprintf(stderr, "Error querying test data file size: %s\n", strerror(errno)); - return 2; - } - - if (st.st_size < 0 || st.st_size > 100000000) { - fprintf(stderr, "Error reading test data: too much test data (size=%zd)\n", st.st_size); - return 2; - } - - if (st.st_size % sizeof(adc_data_t) != 0) { - fprintf(stderr, "Error reading test data: file size is not divisible by %zd (size=%zd)\n", sizeof(adc_data_t), st.st_size); - return 2; - } - - char *buf = malloc(st.st_size); - if (!buf) { - fprintf(stderr, "Error allocating memory"); - return 2; - } - - const size_t n_samples = st.st_size / sizeof(adc_data_t); - fprintf(stderr, "Reading %zd samples test data...", n_samples); - ssize_t nread = 0; - while (nread < st.st_size) { - ssize_t rc = read(fd, buf + nread, st.st_size - nread); - - if (rc == -EINTR || rc == -EAGAIN) - continue; - - if (rc < 0) { - fprintf(stderr, "\nError reading test data: %s\n", strerror(errno)); - return 2; - } - - if (rc == 0) { - fprintf(stderr, "\nError reading test data: Unexpected end of file\n"); - return 2; - } - - nread += rc; - } - fprintf(stderr, " done. Read %zd bytes.\n", nread); - - adc_data_t *buf_d = (adc_data_t *)buf; - - struct dsss_demod_state demod; - dsss_demod_init(&demod); - - fprintf(stderr, "Starting simulation.\n"); - size_t iterations = (n_samples-FMEAS_FFT_LEN)/(FMEAS_FFT_LEN/2); - for (size_t i=0; i013.8g},' for f in win) - print(textwrap.fill(par, - initial_indent=' '*4, subsequent_indent=' '*4, - width=120, - replace_whitespace=False, drop_whitespace=False)) - print('};') - print() - print(f'const float * const {args.variable} __attribute__((weak)) = {varname};') - diff --git a/fw/hid-dials/tools/fmeas_export_ocxo_2day.bin b/fw/hid-dials/tools/fmeas_export_ocxo_2day.bin deleted file mode 100644 index c0cd8a8..0000000 Binary files a/fw/hid-dials/tools/fmeas_export_ocxo_2day.bin and /dev/null differ diff --git a/fw/hid-dials/tools/freq_meas_test.c b/fw/hid-dials/tools/freq_meas_test.c deleted file mode 100644 index e2900ad..0000000 --- a/fw/hid-dials/tools/freq_meas_test.c +++ /dev/null @@ -1,106 +0,0 @@ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "freq_meas.h" - -void print_usage(void); - -void print_usage() { - fprintf(stderr, "Usage: freq_meas_test [test_data.bin]\n"); -} - -int main(int argc, char **argv) { - if (argc != 2) { - fprintf(stderr, "Error: Invalid arguments.\n"); - print_usage(); - return 1; - } - - int fd = open(argv[1], O_RDONLY); - struct stat st; - if (fstat(fd, &st)) { - fprintf(stderr, "Error querying test data file size: %s\n", strerror(errno)); - return 2; - } - - if (st.st_size < 0 || st.st_size > 1000000) { - fprintf(stderr, "Error reading test data: too much test data (size=%zd)\n", st.st_size); - return 2; - } - - if (st.st_size % sizeof(float) != 0) { - fprintf(stderr, "Error reading test data: file size is not divisible by %zd (size=%zd)\n", sizeof(float), st.st_size); - return 2; - } - - char *buf = malloc(st.st_size); - if (!buf) { - fprintf(stderr, "Error allocating memory"); - return 2; - } - - fprintf(stderr, "Reading %zd samples test data...", st.st_size/sizeof(float)); - ssize_t nread = 0; - while (nread < st.st_size) { - ssize_t rc = read(fd, buf + nread, st.st_size - nread); - - if (rc == -EINTR || rc == -EAGAIN) - continue; - - if (rc < 0) { - fprintf(stderr, "\nError reading test data: %s\n", strerror(errno)); - return 2; - } - - if (rc == 0) { - fprintf(stderr, "\nError reading test data: Unexpected end of file\n"); - return 2; - } - - nread += rc; - } - fprintf(stderr, " done.\n"); - - const size_t n_samples = st.st_size / sizeof(float); - float *buf_f = (float *)buf; - - int16_t *sim_adc_buf = calloc(sizeof(int16_t), n_samples); - if (!sim_adc_buf) { - fprintf(stderr, "Error allocating memory\n"); - return 2; - } - - fprintf(stderr, "Converting and truncating test data..."); - for (size_t i=0; i') - print('#include ') - print() - print(f'/* {args.n} bit gold sequences: {2**args.n+1} sequences of length {2**args.n-1} bit.') - print(f' *') - print(f' * Each code is packed left-aligned into {nbytes} bytes in big-endian byte order.') - print(f' */') - print(f'const uint8_t {args.variable}[{2**args.n+1}][{nbytes}] = {{') - for i, code in enumerate(gold(args.n)): - par = '{' + ' '.join(f'0x{d:02x},' for d in np.packbits(code)) + f'}}, /* {i: 3d} "{"".join(str(x) for x in code)}" */' - print(textwrap.fill(par, initial_indent=' '*4, subsequent_indent=' '*4, width=120)) - print('};') - print() - else: - print('/* THIS IS A GENERATED FILE. DO NOT EDIT! */') - with print_include_guards(f'__GOLD_CODE_GENERATED_HEADER_{args.n}__'): - print(f'extern const uint8_t {args.variable}[{2**args.n+1}][{nbytes}];') diff --git a/fw/hid-dials/tools/grid_freq_psd_spl_108pt.json b/fw/hid-dials/tools/grid_freq_psd_spl_108pt.json deleted file mode 100644 index 5a0ff41..0000000 --- a/fw/hid-dials/tools/grid_freq_psd_spl_108pt.json +++ /dev/null @@ -1 +0,0 @@ -{"x_spec": [3.2595692805152726e-05, 5.0, 613575], "t": [3.2595692805152726e-05, 3.2595692805152726e-05, 3.2595692805152726e-05, 3.2595692805152726e-05, 0.0001423024947075771, 0.00015800362803968106, 0.00017543716661470822, 0.00019479425764873777, 0.0002162871388378975, 0.00024015146540428407, 0.00026664889389955537, 0.00029606995109590574, 0.00032873721941990017, 0.0003650088738553592, 0.0004052826090950758, 0.00045000000000000004, 0.000499651343175437, 0.0005547810327489297, 0.0006159935292916862, 0.0006839599873288199, 0.0007594256141046668, 0.0008432178402871724, 0.0009362553921977272, 0.0010395583650374223, 0.0011542594075560205, 0.001281616140796111, 0.0014230249470757708, 0.001580036280396809, 0.0017543716661470824, 0.0019479425764873776, 0.002162871388378975, 0.0024015146540428403, 0.002666488938995554, 0.002960699510959057, 0.0032873721941990056, 0.0036500887385535925, 0.004052826090950754, 0.0045000000000000005, 0.00499651343175437, 0.005547810327489296, 0.006159935292916869, 0.0068395998732882, 0.007594256141046669, 0.008432178402871724, 0.009362553921977271, 0.010395583650374221, 0.011542594075560205, 0.012816161407961109, 0.014230249470757707, 0.01580036280396809, 0.017543716661470823, 0.01947942576487376, 0.02162871388378975, 0.024015146540428405, 0.026664889389955565, 0.02960699510959057, 0.03287372194199005, 0.036500887385535925, 0.04052826090950754, 0.045, 0.0499651343175437, 0.05547810327489296, 0.06159935292916863, 0.06839599873288206, 0.07594256141046668, 0.08432178402871732, 0.09362553921977272, 0.10395583650374222, 0.11542594075560206, 0.12816161407961107, 0.14230249470757705, 0.15800362803968088, 0.1754371666147082, 0.1947942576487376, 0.21628713883789774, 0.24015146540428406, 0.26664889389955565, 0.2960699510959057, 0.32873721941990053, 0.36500887385535924, 0.40528260909507535, 0.45, 0.499651343175437, 0.5547810327489296, 0.6159935292916868, 0.6839599873288206, 0.7594256141046669, 0.8432178402871732, 0.9362553921977271, 1.0395583650374223, 1.1542594075560206, 1.2816161407961109, 1.4230249470757708, 1.5800362803968104, 1.7543716661470823, 1.9479425764873777, 2.162871388378975, 2.4015146540428405, 2.6664889389955535, 2.960699510959057, 3.287372194199002, 3.6500887385535927, 4.052826090950758, 4.5, 5.0, 5.0, 5.0, 5.0], "c": [0.7720161468716866, -0.5547528253056444, 0.30706059086000753, 0.19422577014134906, -1.1954636661840032, 0.9215976941641111, -0.6668136393976918, -1.341269161156733, -0.16311330594842666, -1.7639636752234251, -1.238385544822954, -0.32649555618555554, -0.03086589610280171, -2.358195657381619, -0.5759152419849985, 0.1892225800004134, -1.8122889670546236, -0.8109120798216202, -0.5500991736738969, -4.680192969256771, -2.8007700704649876, 0.16866469558571784, -1.1040811840849307, -3.0243574268705546, -4.018139927365795, -4.100581028618109, -0.556354762846191, -7.414377514669229, 1.36396325920194, -6.002559557058508, -2.2113451390305365, -4.578944771104116, -4.372644849632638, -3.945339124673235, -4.778747958903158, -2.370174137632325, -5.7372466088109295, -4.707506574819875, -4.834404729330929, -5.005244244061701, -5.82644896783577, -4.717966026411524, -6.146374820241562, -4.972788381244952, -5.854957092953355, -5.702174935205885, -6.222035857079607, -6.2128389666872, -6.212821706753751, -6.253599689326325, -6.681685577659057, -6.372364384360678, -6.771223202540934, -6.856809137231159, -6.986412256164045, -7.190466178818742, -7.577896455149433, -7.515731696006047, -7.598155006351761, -7.824526916149126, -8.141496591776512, -8.36794927682997, -8.80307396767114, -8.828816533544659, -9.357524260470413, -9.658130054343863, -10.005768472049466, -10.499801262514108, -11.028689820560558, -11.413688641742898, -11.906162042727946, -12.232342460719975, -12.438432746733596, -13.088338100203112, -12.308710772618745, -11.685074853925329, -11.397838681243094, -12.265219694936695, -13.600359694898529, -14.031425961884718, -12.236885080485473, -13.527508426900974, -13.698402018452601, -13.397911198962568, -14.144410560196603, -13.905769594095293, -14.410874830544122, -14.531727635304264, -14.59275291853806, -14.35404826562502, -14.58670053318149, -14.432515268864977, -14.363428024828353, -14.429222027493264, -14.73947634127499, -14.717315405960353, -14.678539669792505, -14.825278423641382, -14.80936417940876, -14.943375264882789, -14.680885181815674, -14.54841244844906, -14.634365225950589, -14.609444790868906, 0.0, 0.0, 0.0, 0.0], "k": 3} \ No newline at end of file diff --git a/fw/hid-dials/tools/hum_generator.py b/fw/hid-dials/tools/hum_generator.py deleted file mode 100755 index fbcabac..0000000 --- a/fw/hid-dials/tools/hum_generator.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -import binascii -import struct - -import numpy as np -import pydub - -from dsss_demod_test_waveform_gen import load_noise_gen, modulate as dsss_modulate - -np.set_printoptions(linewidth=240) - -def generate_noisy_signal( - test_data=32, - test_nbits=5, - test_decimation=10, - test_signal_amplitude=20e-3, - noise_level=10e-3, - noise_spec='synth://grid_freq_psd_spl_108pt.json', - seed=0): - - #test_data = np.random.RandomState(seed=0).randint(0, 2 * (2**test_nbits), test_duration) - #test_data = np.array([0, 1, 2, 3] * 50) - if isinstance(test_data, int): - test_data = np.array(range(test_data)) - - - signal = np.repeat(dsss_modulate(test_data, test_nbits) * 2.0 - 1, test_decimation) - - noise_gen, noise_params = load_noise_gen(noise_spec) - noise = noise_gen(seed, len(signal), **noise_params) - return np.absolute(noise + signal*test_signal_amplitude) - -def write_raw_frequencies_bin(outfile, **kwargs): - with open(outfile, 'wb') as f: - for x in generate_noisy_signal(**kwargs): - f.write(struct.pack('f', x)) - -def synthesize_sine(freqs, freqs_sampling_rate=10.0, output_sampling_rate=44100): - duration = len(freqs) / freqs_sampling_rate # seconds - afreq_out = np.interp(np.linspace(0, duration, int(duration*output_sampling_rate)), np.linspace(0, duration, len(freqs)), freqs) - return np.sin(np.cumsum(2*np.pi * afreq_out / output_sampling_rate)) - -def write_flac(filename, signal, sampling_rate=44100): - signal -= np.min(signal) - signal /= np.max(signal) - signal -= 0.5 - signal *= 2**16 - 1 - le_bytes = signal.astype(np.int16).tobytes() - seg = pydub.AudioSegment(data=le_bytes, sample_width=2, frame_rate=sampling_rate, channels=1) - seg.export(filename, format='flac') - -def write_synthetic_hum_flac(filename, output_sampling_rate=44100, freqs_sampling_rate=10.0, **kwargs): - signal = generate_noisy_signal(**kwargs) - print(signal) - write_flac(filename, synthesize_sine(signal, freqs_sampling_rate, output_sampling_rate), - sampling_rate=output_sampling_rate) - -def emulate_adc_signal(adc_bits=12, adc_offset=0.4, adc_amplitude=0.25, freq_sampling_rate=10.0, output_sampling_rate=1000, **kwargs): - signal = synthesize_sine(generate_noisy_signal(), freq_sampling_rate, output_sampling_rate) - signal = signal*adc_amplitude + adc_offset - smin, smax = np.min(signal), np.max(signal) - if smin < 0.0 or smax > 1.0: - raise UserWarning('Amplitude or offset too large: Signal out of bounds with min/max [{smin}, {smax}] of ADC range') - signal *= 2**adc_bits -1 - return signal - -def save_adc_signal(fn, signal, dtype=np.uint16): - with open(fn, 'wb') as f: - f.write(signal.astype(dtype).tobytes()) - -def write_emulated_adc_signal_bin(filename, **kwargs): - save_adc_signal(filename, emulate_adc_signal(**kwargs)) - -def hum_cmd(args): - write_synthetic_hum_flac(args.out_flac, - output_sampling_rate=args.audio_sampling_rate, - freqs_sampling_rate=args.frequency_sampling_rate, - test_data = np.array(list(binascii.unhexlify(args.data))), - test_nbits = args.symbol_bits, - test_decimation = args.decimation, - test_signal_amplitude = args.signal_level/1e3, - noise_level = args.noise_level/1e3, - noise_spec=args.noise_spec, - seed = args.random_seed) - - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - cmd_parser = parser.add_subparsers(required=True) - hum_parser = cmd_parser.add_parser('hum', help='Generated artificial modulated mains hum') - # output parameters - hum_parser.add_argument('-a', '--audio-sampling-rate', type=int, default=44100) - - # modulation parameters - hum_parser.add_argument('-f', '--frequency-sampling-rate', type=float, default=10.0*100/128) - hum_parser.add_argument('-b', '--symbol-bits', type=int, default=5, help='bits per symbol (excluding sign bit)') - hum_parser.add_argument('-n', '--noise-level', type=float, default=1.0, help='Scale synthetic noise level') - hum_parser.add_argument('-s', '--signal-level', type=float, default=20.0, help='Synthetic noise level in mHz') - hum_parser.add_argument('-d', '--decimation', type=int, default=10, help='DSSS modulation decimation in frequency measurement cycles') - hum_parser.add_argument('-r', '--random-seed', type=int, default=0) - hum_parser.add_argument('--noise-spec', type=str, default='synth://grid_freq_psd_spl_108pt.json') - hum_parser.add_argument('out_flac', metavar='out.flac', help='FLAC output file') - hum_parser.add_argument('data', help='modulation data hex string') - hum_parser.set_defaults(func=hum_cmd) - - args = parser.parse_args() - args.func(args) - diff --git a/fw/hid-dials/tools/ldparser.py b/fw/hid-dials/tools/ldparser.py deleted file mode 100644 index c620fe2..0000000 --- a/fw/hid-dials/tools/ldparser.py +++ /dev/null @@ -1,126 +0,0 @@ - -import sys - -import pyparsing as pp -from pyparsing import pyparsing_common as ppc - -LPAREN, RPAREN, LBRACE, RBRACE, LBROK, RBROK, COLON, SEMICOLON, EQUALS, COMMA = map(pp.Suppress, '(){}<>:;=,') - -parse_suffix_int = lambda lit: int(lit[:-1]) * (10**(3*(1 + 'kmgtpe'.find(lit[-1].lower())))) -si_suffix = pp.oneOf('k m g t p e', caseless=True) - -numeric_literal = pp.Regex('0x[0-9a-fA-F]+').setName('hex int').setParseAction(pp.tokenMap(int, 16)) \ - | (pp.Regex('[0-9]+[kKmMgGtTpPeE]')).setName('size int').setParseAction(pp.tokenMap(parse_suffix_int)) \ - | pp.Word(pp.nums).setName('int').setParseAction(pp.tokenMap(int)) -access_def = pp.Regex('[rR]?[wW]?[xX]?').setName('access literal').setParseAction(pp.tokenMap(str.lower)) - -origin_expr = pp.Suppress(pp.CaselessKeyword('ORIGIN')) + EQUALS + numeric_literal -length_expr = pp.Suppress(pp.CaselessKeyword('LENGTH')) + EQUALS + numeric_literal -mem_expr = pp.Group(ppc.identifier + LPAREN + access_def + RPAREN + COLON + origin_expr + COMMA + length_expr) -mem_contents = pp.ZeroOrMore(mem_expr) - -mem_toplevel = pp.CaselessKeyword("MEMORY") + pp.Group(LBRACE + pp.Optional(mem_contents, []) + RBRACE) - -glob = pp.Word(pp.alphanums + '._*') -match_expr = pp.Forward() -assignment = pp.Forward() -funccall = pp.Group(pp.Word(pp.alphas + '_') + LPAREN + (assignment | numeric_literal | match_expr | glob | ppc.identifier) + RPAREN + pp.Optional(SEMICOLON)) -value = numeric_literal | funccall | ppc.identifier | '.' -formula = (value + pp.oneOf('+ = * / %') + value) | value -# suppress stray semicolons -assignment << (SEMICOLON | pp.Group((ppc.identifier | '.') + EQUALS + (formula | value) + pp.Optional(SEMICOLON))) -match_expr << (glob + LPAREN + pp.OneOrMore(funccall | glob) + RPAREN) - -section_contents = pp.ZeroOrMore(assignment | funccall | match_expr); - -section_name = pp.Regex('\.[a-zA-Z0-9_.]+') -section_def = pp.Group(section_name + pp.Optional(numeric_literal) + COLON + LBRACE + pp.Group(section_contents) + - RBRACE + pp.Optional(RBROK + ppc.identifier + pp.Optional('AT' + RBROK + ppc.identifier))) -sec_contents = pp.ZeroOrMore(section_def | assignment) - -sections_toplevel = pp.Group(pp.CaselessKeyword("SECTIONS").suppress() + LBRACE + sec_contents + RBRACE) - -toplevel_elements = mem_toplevel | funccall | sections_toplevel | assignment -ldscript = pp.Group(pp.ZeroOrMore(toplevel_elements)) -ldscript.ignore(pp.cppStyleComment) - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('linker_script', type=argparse.FileType('r')) - args = parser.parse_args() - - #print(mem_expr.parseString('FLASH (rx) : ORIGIN = 0x0800000, LENGTH = 512K', parseAll=True)) - # print(ldscript.parseString(''' - # /* Entry Point */ - # ENTRY(Reset_Handler) - # - # /* Highest address of the user mode stack */ - # _estack = 0x20020000; /* end of RAM */ - # /* Generate a link error if heap and stack don't fit into RAM */ - # _Min_Heap_Size = 0x200;; /* required amount of heap */ - # _Min_Stack_Size = 0x400;; /* required amount of stack */ - # ''', parseAll=True)) - - print(ldscript.parseFile(args.linker_script, parseAll=True)) - #print(funccall.parseString('KEEP(*(.isr_vector))')) - #print(section_contents.parseString(''' - # . = ALIGN(4); - # KEEP(*(.isr_vector)) /* Startup code */ - # . = ALIGN(4); - # ''', parseAll=True)) - - #print(section_def.parseString(''' - # .text : - # { - # . = ALIGN(4); - # *(.text) /* .text sections (code) */ - # *(.text*) /* .text* sections (code) */ - # *(.glue_7) /* glue arm to thumb code */ - # *(.glue_7t) /* glue thumb to arm code */ - # *(.eh_frame) - # - # KEEP (*(.init)) - # KEEP (*(.fini)) - # - # . = ALIGN(4); - # _etext = .; /* define a global symbols at end of code */ - # } >FLASH - # ''', parseAll=True)) - - #print(section_def.parseString('.ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH', parseAll=True)) - - #print(assignment.parseString('__preinit_array_start = .', parseAll=True)) - #print(assignment.parseString('a = 23', parseAll=True)) - #print(funccall.parseString('foo (a=23)', parseAll=True)) - #print(funccall.parseString('PROVIDE_HIDDEN (__preinit_array_start = .);', parseAll=True)) - #print(section_def.parseString(''' - # .preinit_array : - # { - # PROVIDE_HIDDEN (__preinit_array_start = .); - # KEEP (*(.preinit_array*)) - # PROVIDE_HIDDEN (__preinit_array_end = .); - # } >FLASH''', parseAll=True)) - #print(match_expr.parseString('*(SORT(.init_array.*))', parseAll=True)) - #print(funccall.parseString('KEEP (*(SORT(.init_array.*)))', parseAll=True)) - #print(section_def.parseString(''' - # .init_array : - # { - # PROVIDE_HIDDEN (__init_array_start = .); - # KEEP (*(SORT(.init_array.*))) - # KEEP (*(.init_array*)) - # PROVIDE_HIDDEN (__init_array_end = .); - # } >FLASH - # ''', parseAll=True)) - - #print(match_expr.parseString('*(.ARM.extab* .gnu.linkonce.armextab.*)', parseAll=True)) - #print(formula.parseString('. + _Min_Heap_Size', parseAll=True)) - #print(assignment.parseString('. = . + _Min_Heap_Size;', parseAll=True)) - #print(sections_toplevel.parseString(''' - # SECTIONS - # { - # .ARMattributes : { } - # } - # ''', parseAll=True)) - #sys.exit(0) - diff --git a/fw/hid-dials/tools/linkmem.py b/fw/hid-dials/tools/linkmem.py deleted file mode 100644 index 934a571..0000000 --- a/fw/hid-dials/tools/linkmem.py +++ /dev/null @@ -1,276 +0,0 @@ - -import tempfile -import os -from os import path -import sys -import re -import subprocess -from contextlib import contextmanager -from collections import defaultdict -import colorsys - -import cxxfilt -from elftools.elf.elffile import ELFFile -from elftools.elf.enums import ENUM_ST_SHNDX -from elftools.elf.descriptions import describe_symbol_type, describe_sh_type -import libarchive -import matplotlib.cm - -@contextmanager -def chdir(newdir): - old_cwd = os.getcwd() - try: - os.chdir(newdir) - yield - finally: - os.chdir(old_cwd) - -def keep_last(it, first=None): - last = first - for elem in it: - yield last, elem - last = elem - -def delim(start, end, it, first_only=True): - found = False - for elem in it: - if end(elem): - if first_only: - return - found = False - elif start(elem): - found = True - elif found: - yield elem - -def delim_prefix(start, end, it): - yield from delim(lambda l: l.startswith(start), lambda l: end is not None and l.startswith(end), it) - -def trace_source_files(linker, cmdline, trace_sections=[], total_sections=['.text', '.data', '.rodata']): - with tempfile.TemporaryDirectory() as tempdir: - out_path = path.join(tempdir, 'output.elf') - output = subprocess.check_output([linker, '-o', out_path, f'-Wl,--print-map', *cmdline]) - lines = [ line.strip() for line in output.decode().splitlines() ] - # FIXME also find isr vector table references - - defs = {} - objs = defaultdict(lambda: 0) - aliases = {} - sec_name = None - last_loc = None - last_sym = None - line_cont = None - for last_line, line in keep_last(delim_prefix('Linker script and memory map', 'OUTPUT', lines), first=''): - if not line or line.startswith('LOAD '): - sec_name = None - continue - - # first part of continuation line - if m := re.match('^(\.[0-9a-zA-Z-_.]+)$', line): - line_cont = line - sec_name = None - continue - - if line_cont: - line = line_cont + ' ' + line - line_cont = None - - # -ffunction-sections/-fdata-sections section - if m := re.match('^(\.[0-9a-zA-Z-_.]+)\.([0-9a-zA-Z-_.]+)\s+(0x[0-9a-f]+)\s+(0x[0-9a-f]+)\s+(\S+)$', line): - sec, sym, loc, size, obj = m.groups() - *_, sym = sym.rpartition('.') - sym = cxxfilt.demangle(sym) - size = int(size, 16) - obj = path.abspath(obj) - - if sec not in total_sections: - size = 0 - - objs[obj] += size - defs[sym] = (sec, size, obj) - - sec_name, last_loc, last_sym = sec, loc, sym - continue - - # regular (no -ffunction-sections/-fdata-sections) section - if m := re.match('^(\.[0-9a-zA-Z-_]+)\s+(0x[0-9a-f]+)\s+(0x[0-9a-f]+)\s+(\S+)$', line): - sec, _loc, size, obj = m.groups() - size = int(size, 16) - obj = path.abspath(obj) - - if sec in total_sections: - objs[obj] += size - - sec_name = sec - last_loc, last_sym = None, None - continue - - # symbol def - if m := re.match('^(0x[0-9a-f]+)\s+(\S+)$', line): - loc, sym = m.groups() - sym = cxxfilt.demangle(sym) - loc = int(loc, 16) - if sym in defs: - continue - - if loc == last_loc: - assert last_sym is not None - aliases[sym] = last_sym - else: - assert sec_name - defs[sym] = (sec_name, None, obj) - last_loc, last_sym = loc, sym - - continue - - refs = defaultdict(lambda: set()) - for sym, (sec, size, obj) in defs.items(): - fn, _, member = re.match('^([^()]+)(\((.+)\))?$', obj).groups() - fn = path.abspath(fn) - - if member: - subprocess.check_call(['ar', 'x', '--output', tempdir, fn, member]) - fn = path.join(tempdir, member) - - with open(fn, 'rb') as f: - elf = ELFFile(f) - - symtab = elf.get_section_by_name('.symtab') - - symtab_demangled = { cxxfilt.demangle(nsym.name).replace(' ', ''): i - for i, nsym in enumerate(symtab.iter_symbols()) } - - s = set() - sec_map = { sec.name: i for i, sec in enumerate(elf.iter_sections()) } - matches = [ i for name, i in sec_map.items() if re.match(f'\.rel\..*\.{sym}', name) ] - if matches: - sec = elf.get_section(matches[0]) - for reloc in sec.iter_relocations(): - refsym = symtab.get_symbol(reloc['r_info_sym']) - name = refsym.name if refsym.name else elf.get_section(refsym['st_shndx']).name.split('.')[-1] - s.add(name) - refs[sym] = s - - for tsec in trace_sections: - matches = [ i for name, i in sec_map.items() if name == f'.rel{tsec}' ] - s = set() - if matches: - sec = elf.get_section(matches[0]) - for reloc in sec.iter_relocations(): - refsym = symtab.get_symbol(reloc['r_info_sym']) - s.add(refsym.name) - refs[tsec.replace('.', '_')] |= s - - return objs, aliases, defs, refs - -@contextmanager -def wrap(leader='', print=print, left='{', right='}'): - print(leader, left) - yield lambda *args, **kwargs: print(' ', *args, **kwargs) - print(right) - -def mangle(name): - return re.sub('[^a-zA-Z0-9_]', '_', name) - -hexcolor = lambda r, g, b, *_a: f'#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}' -def vhex(val): - r,g,b,_a = matplotlib.cm.viridis(1.0-val) - fc = hexcolor(r, g, b) - h,s,v = colorsys.rgb_to_hsv(r,g,b) - cc = '#000000' if v > 0.8 else '#ffffff' - return fc, cc - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('--trace-sections', type=str, action='append', default=[]) - parser.add_argument('--trim-stubs', type=str, action='append', default=[]) - parser.add_argument('--highlight-subdirs', type=str, default=None) - parser.add_argument('linker_binary') - parser.add_argument('linker_args', nargs=argparse.REMAINDER) - args = parser.parse_args() - - trace_sections = args.trace_sections - trace_sections_mangled = { sec.replace('.', '_') for sec in trace_sections } - objs, aliases, syms, refs = trace_source_files(args.linker_binary, args.linker_args, trace_sections) - - clusters = defaultdict(lambda: []) - for sym, (sec, size, obj) in syms.items(): - clusters[obj].append((sym, sec, size)) - - max_ssize = max(size or 0 for _sec, size, _obj in syms.values()) - max_osize = max(objs.values()) - - subdir_prefix = path.abspath(args.highlight_subdirs) + '/' if args.highlight_subdirs else '### NO HIGHLIGHT ###' - first_comp = lambda le_path: path.dirname(le_path).partition(os.sep)[0] - subdir_colors = sorted({ first_comp(obj[len(subdir_prefix):]) for obj in objs if obj.startswith(subdir_prefix) }) - subdir_colors = { path: hexcolor(*matplotlib.cm.Pastel1(i/len(subdir_colors))) for i, path in enumerate(subdir_colors) } - - subdir_sizes = defaultdict(lambda: 0) - for obj, size in objs.items(): - if not isinstance(size, int): - continue - if obj.startswith(subdir_prefix): - subdir_sizes[first_comp(obj[len(subdir_prefix):])] += size - else: - subdir_sizes[''] += size - - print('Subdir sizes:', file=sys.stderr) - for subdir, size in sorted(subdir_sizes.items(), key=lambda x: x[1]): - print(f'{subdir:>20}: {size:>6,d} B', file=sys.stderr) - - def lookup_highlight(path): - if args.highlight_subdirs: - if obj.startswith(subdir_prefix): - highlight_head = first_comp(path[len(subdir_prefix):]) - return subdir_colors[highlight_head], highlight_head - else: - return '#e0e0e0', None - else: - return '#ddf7f4', None - - with wrap('digraph G', print) as lvl1print: - print('size="23.4,16.5!";') - print('graph [fontsize=40];') - print('node [fontsize=40];') - #print('ratio="fill";') - - print('rankdir=LR;') - print('ranksep=5;') - print('nodesep=0.2;') - print() - - for i, (obj, obj_syms) in enumerate(clusters.items()): - with wrap(f'subgraph cluster_{i}', lvl1print) as lvl2print: - print('style = "filled";') - highlight_color, highlight_head = lookup_highlight(obj) - print(f'bgcolor = "{highlight_color}";') - print('pencolor = none;') - fc, cc = vhex(objs[obj]/max_osize) - highlight_subdir_part = f'{highlight_head} / ' if highlight_head else '' - lvl2print(f'label = <
' - f'{highlight_subdir_part}' - f'{path.basename(obj)} ({objs[obj]}B)' - f'
>;') - lvl2print() - for sym, sec, size in obj_syms: - has_size = isinstance(size, int) and size > 0 - size_s = f' ({size}B)' if has_size else '' - fc, cc = vhex(size/max_ssize) if has_size else ('#ffffff', '#000000') - shape = 'box' if sec == '.text' else 'oval' - lvl2print(f'{mangle(sym)}[label = "{sym}{size_s}", style="rounded,filled", shape="{shape}", fillcolor="{fc}", fontname="carlito", fontcolor="{cc}" color=none];') - lvl1print() - - edges = set() - for start, ends in refs.items(): - for end in ends: - end = aliases.get(end, end) - if (start in syms or start in trace_sections_mangled) and end in syms: - edges.add((start, end)) - - for start, end in edges: - lvl1print(f'{mangle(start)} -> {mangle(end)} [style="bold", color="#333333"];') - - for sec in trace_sections: - lvl1print(f'{sec.replace(".", "_")} [label = "section {sec}", shape="box", style="filled,bold"];') - diff --git a/fw/hid-dials/tools/linksize.py b/fw/hid-dials/tools/linksize.py deleted file mode 100644 index c41a951..0000000 --- a/fw/hid-dials/tools/linksize.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python3 - -def parse_linker_script(data): - pass - -def link(groups): - defined_symbols = {} - undefined_symbols = set() - for group, files in groups: - while True: - found_something = False - - for fn in files: - symbols = load_symbols(fn) - for symbol in symbols: - if symbol in defined_symbols: - - if not group or not found_something: - break - - -if __name__ == '__main__': - - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('-T', '--script', type=str, help='Linker script to use') - parser.add_argument('-o', '--output', type=str, help='Output file to produce') - args, rest = parser.parse_known_intermixed_args() - print(rest) - - addprefix = lambda *xs: [ prefix + opt for opt in xs for prefix in ('', '-Wl,') ] - START_GROUP = addprefix('-(', '--start-group') - END_GROUP = addprefix('-)', '--end-group') - GROUP_OPTS = [*START_GROUP, *END_GROUP] - input_files = [ arg for arg in rest if not arg.startswith('-') or arg in GROUP_OPTS ] - - def input_file_iter(input_files): - group = False - files = [] - for arg in input_files: - if arg in START_GROUP: - assert not group - - if files: - yield False, files # nested -Wl,--start-group - group, files = True, [] - - elif arg in END_GROUP: - assert group # missing -Wl,--start-group - if files: - yield True, files - group, files = False, [] - - else: - files.append(arg) - - assert not group # missing -Wl,--end-group - if files: - yield False, files - - - diff --git a/fw/hid-dials/tools/linktracer.py b/fw/hid-dials/tools/linktracer.py deleted file mode 100644 index 0c53a60..0000000 --- a/fw/hid-dials/tools/linktracer.py +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/env python3 - -import re -import subprocess -import tempfile -import pprint - -ARCHIVE_RE = r'([^(]*)(\([^)]*\))?' - -def trace_source_files(linker, cmdline): - with tempfile.NamedTemporaryFile() as mapfile: - output = subprocess.check_output([linker, f'-Wl,--Map={mapfile.name}', *cmdline]) - - # intentionally use generator here - idx = 0 - lines = [ line.rstrip() for line in mapfile.read().decode().splitlines() if line.strip() ] - - for idx, line in enumerate(lines[idx:], start=idx): - #print('Dropping', line) - if line == 'Linker script and memory map': - break - - idx += 1 - objects = [] - symbols = {} - sections = {} - current_object = None - last_offset = None - last_symbol = None - cont_sec = None - cont_ind = None - current_section = None - for idx, line in enumerate(lines[idx:], start=idx): - print(f'Processing >{line}') - if line.startswith('LOAD'): - _load, obj = line.split() - objects.append(obj) - continue - - if line.startswith('OUTPUT'): - break - - m = re.match(r'^( ?)([^ ]+)? +(0x[0-9a-z]+) +(0x[0-9a-z]+)?(.*)?$', line) - if m is None: - m = re.match(r'^( ?)([^ ]+)?$', line) - if m: - cont_ind, cont_sec = m.groups() - else: - cont_ind, cont_sec = None, None - last_offset, last_symbol = None, None - continue - indent, sec, offx, size, sym_or_src = m.groups() - if sec is None: - sec = cont_sec - ind = cont_ind - cont_sec = None - cont_ind = None - print(f'vals: indent={indent} sec={sec} offx={offx} size={size} sym_or_src={sym_or_src}') - if not re.match('^[a-zA-Z_0-9<>():*]+$', sym_or_src): - continue - - if indent == '': - print(f'Section: {sec} 0x{size:x}') - current_section = sec - sections[sec] = size - last_offset = None - last_symbol = None - continue - - if offx is not None: - offx = int(offx, 16) - if size is not None: - size = int(size, 16) - - if size is not None and sym_or_src is not None: - # archive/object line - archive, _member = re.match(ARCHIVE_RE, sym_or_src).groups() - current_object = archive - last_offset = offx - else: - if sym_or_src is not None: - assert size is None - if last_offset is not None: - last_size = offx - last_offset - symbols[last_symbol] = (last_size, current_section) - print(f'Symbol: {last_symbol} 0x{last_size:x} @{current_section}') - last_offset = offx - last_symbol = sym_or_src - - idx += 1 - - for idx, line in enumerate(lines[idx:], start=idx): - if line == 'Cross Reference Table': - break - - idx += 1 - - # map which symbol was pulled from which object in the end - used_defs = {} - for line in lines: - *left, right = line.split() - - archive, _member = re.match(ARCHIVE_RE, right).groups() - if left: - used_defs[''.join(left)] = archive - - #pprint.pprint(symbols) - - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('linker_binary') - parser.add_argument('linker_args', nargs=argparse.REMAINDER) - args = parser.parse_args() - - source_files = trace_source_files(args.linker_binary, args.linker_args) - diff --git a/fw/hid-dials/tools/mapparse.py b/fw/hid-dials/tools/mapparse.py deleted file mode 100644 index c1f460a..0000000 --- a/fw/hid-dials/tools/mapparse.py +++ /dev/null @@ -1,129 +0,0 @@ - -import re -from collections import defaultdict, namedtuple - -Section = namedtuple('Section', ['name', 'offset', 'objects']) -ObjectEntry = namedtuple('ObjectEntry', ['filename', 'object', 'offset', 'size']) -FileEntry = namedtuple('FileEntry', ['section', 'object', 'offset', 'length']) - -class Memory: - def __init__(self, name, origin, length, attrs=''): - self.name, self.origin, self.length, self.attrs = name, origin, length, attrs - self.sections = {} - self.files = defaultdict(lambda: []) - self.totals = defaultdict(lambda: 0) - - def add_toplevel(self, name, offx, length): - self.sections[name] = Section(offx, length, []) - - def add_obj(self, name, offx, length, fn, obj): - base_section, sep, subsec = name[1:].partition('.') - base_section = '.'+base_section - if base_section in self.sections: - sec = secname, secoffx, secobjs = self.sections[base_section] - secobjs.append(ObjectEntry(fn, obj, offx, length)) - else: - sec = None - self.files[fn].append(FileEntry(sec, obj, offx, length)) - self.totals[fn] += length - -class MapFile: - def __init__(self, s): - self._lines = s.splitlines() - self.memcfg = {} - self.defaultmem = Memory('default', 0, 0xffffffffffffffff) - self._parse() - - def __getitem__(self, offx_or_name): - ''' Lookup a memory area by name or address ''' - if offx_or_name in self.memcfg: - return self.memcfg[offx_or_name] - - elif isinstance(offx_or_name, int): - for mem in self.memcfg.values(): - if mem.origin <= offx_or_name < mem.origin+mem.length: - return mem - else: - return self.defaultmem - - raise ValueError('Invalid argument type for indexing') - - def _skip(self, regex): - matcher = re.compile(regex) - for l in self: - if matcher.match(l): - break - - def __iter__(self): - while self._lines: - yield self._lines.pop(0) - - def _parse(self): - self._skip('^Memory Configuration') - - # Parse memory segmentation info - self._skip('^Name') - for l in self: - if not l: - break - name, origin, length, *attrs = l.split() - if not name.startswith('*'): - self.memcfg[name] = Memory(name, int(origin, 16), int(length, 16), attrs[0] if attrs else '') - - # Parse section information - toplevel_m = re.compile('^(\.[a-zA-Z0-9_.]+)\s+(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)') - secondlevel_m = re.compile('^ (\.[a-zA-Z0-9_.]+)\s+(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)\s+(.*)$') - secondlevel_linebreak_m = re.compile('^ (\.[a-zA-Z0-9_.]+)\n') - filelike = re.compile('^(/?[^()]*\.[a-zA-Z0-9-_]+)(\(.*\))?') - linebreak_section = None - for l in self: - # Toplevel section - match = toplevel_m.match(l) - if match: - name, offx, length = match.groups() - offx, length = int(offx, 16), int(length, 16) - self[offx].add_toplevel(name, offx, length) - - match = secondlevel_linebreak_m.match(l) - if match: - linebreak_section, = match.groups() - continue - - if linebreak_section: - l = ' {} {}'.format(linebreak_section, l) - linebreak_section = None - - # Second-level section - match = secondlevel_m.match(l) - if match: - name, offx, length, misc = match.groups() - match = filelike.match(misc) - if match: - fn, obj = match.groups() - obj = obj.strip('()') if obj else None - offx, length = int(offx, 16), int(length, 16) - self[offx].add_obj(name, offx, length, fn, obj) - - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser(description='Parser GCC map file') - parser.add_argument('mapfile', type=argparse.FileType('r'), help='The GCC .map file to parse') - parser.add_argument('-m', '--memory', type=str, help='The memory segments to print, comma-separated') - args = parser.parse_args() - mf = MapFile(args.mapfile.read()) - args.mapfile.close() - - mems = args.memory.split(',') if args.memory else mf.memcfg.keys() - - for name in mems: - mem = mf.memcfg[name] - print('Symbols by file for memory', name) - for tot, fn in reversed(sorted( (tot, fn) for fn, tot in mem.totals.items() )): - print(' {:>8} {}'.format(tot, fn)) - for length, offx, sec, obj in reversed(sorted(( (length, offx, sec, obj) for sec, obj, offx, length in - mem.files[fn] ), key=lambda e: e[0] )): - name = sec.name if sec else None - print(' {:>8} {:>#08x} {}'.format(length, offx, obj)) - #print('{:>16} 0x{:016x} 0x{:016x} ({:>24}) {}'.format(name, origin, length, length, attrs)) - diff --git a/fw/hid-dials/tools/presig_gen.py b/fw/hid-dials/tools/presig_gen.py deleted file mode 100644 index c5dafe7..0000000 --- a/fw/hid-dials/tools/presig_gen.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env python3 - -import os -import sys -import textwrap -import uuid -import hmac -import binascii -import time -from datetime import datetime - -LINKING_KEY_SIZE = 15 -PRESIG_VERSION = '000.001' -DOMAINS = ['all', 'country', 'region', 'vendor', 'series'] - -def format_hex(data, indent=4, wrap=True): - indent = ' '*indent - par = ', '.join(f'0x{b:02x}' for b in data) - par = textwrap.fill(par, width=120, - initial_indent=indent, subsequent_indent=indent, - replace_whitespace=False, drop_whitespace=False) - if wrap: - return f'{{\n{par}\n}}' - return par - -def domain_string(domain, value): - return f'smart reset domain string v{PRESIG_VERSION}: domain:{domain}={value}' - -def keygen_cmd(args): - if os.path.exists(args.keyfile) and not args.force: - print("Error: keyfile already exists. We won't overwrite it. Instead please remove it manually.", - file=sys.stderr) - return 1 - - root_key = os.urandom(LINKING_KEY_SIZE) - - with open(args.keyfile, 'wb') as f: - f.write(binascii.hexlify(root_key)) - f.write(b'\n') - return 0 - -def gen_at_height(domain, value, height, key): - # nanananananana BLOCKCHAIN! - - ds = domain_string(domain, value).encode('utf-8') - - for height in range(height+1): - key = hmac.digest(key, ds, 'sha512')[:LINKING_KEY_SIZE] - - return key - -def auth_cmd(args): - with open(args.keyfile, 'r') as f: - root_key = binascii.unhexlify(f.read().strip()) - - vals = [ (domain, getattr(args, domain)) for domain in DOMAINS if getattr(args, domain) is not None ] - if not vals: - vals = [('all', 'all')] - for domain, value in vals: - auth = gen_at_height(domain, value, args.height, root_key) - print(f'{domain}="{value}" @{args.height}: {binascii.hexlify(auth).decode()}') - - -def prekey_cmd(args): - with open(args.keyfile, 'r') as f: - root_key = binascii.unhexlify(f.read().strip()) - - print('#include ') - print('#include ') - print() - print('#include "crypto.h"') - print() - - bundle_id = uuid.uuid4().bytes - print(f'/* bundle id {binascii.hexlify(bundle_id).decode()} */') - print(f'uint8_t presig_bundle_id[16] = {format_hex(bundle_id)};') - print() - print(f'/* generated on {datetime.now()} */') - print(f'uint64_t bundle_timestamp = {int(time.time())};') - print() - print(f'int presig_height = {args.max_height};') - print() - - print('const char *presig_domain_strings[_TRIGGER_DOMAIN_COUNT] = {') - for domain in DOMAINS: - ds = domain_string(domain, getattr(args, domain)) - assert '"' not in ds - print(f' [TRIGGER_DOMAIN_{domain.upper()}] = "{ds}",') - print('};') - print() - - print('uint8_t presig_keys[_TRIGGER_DOMAIN_COUNT][PRESIG_MSG_LEN] = {') - for domain in DOMAINS: - key = gen_at_height(domain, getattr(args, domain), args.max_height, root_key) - print(f' [TRIGGER_DOMAIN_{domain.upper()}] = {{{format_hex(key, indent=0, wrap=False)}}},') - print('};') - - print() - print('static inline void __hack_asserts_only(void) {') - print(f' static_assert(_TRIGGER_DOMAIN_COUNT == {len(DOMAINS)});') - print(f' static_assert(PRESIG_MSG_LEN == {LINKING_KEY_SIZE});') - print('}') - print() - - - -TEST_VENDOR = 'Darthenschmidt Cyberei und Verschleierungstechnik GmbH' -TEST_SERIES = 'Frobnicator v0.23.7' -TEST_REGION = 'Neuland' -TEST_COUNTRY = 'Germany' - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument('keyfile', help='Key file to use') - - subparsers = parser.add_subparsers(title='subcommands') - keygen_parser = subparsers.add_parser('keygen', help='Generate a new key') - keygen_parser.add_argument('-f', '--force', action='store_true', help='Force overwriting existing keyfile') - keygen_parser.set_defaults(func=keygen_cmd) - - auth_parser = subparsers.add_parser('auth', help='Generate one-time authentication string') - auth_parser.add_argument('height', type=int, help='Authentication string height, counting from 0 (root key)') - auth_parser.set_defaults(func=auth_cmd) - auth_parser.add_argument('-a', '--all', action='store_const', const='all', help='Vendor name for vendor domain') - auth_parser.add_argument('-v', '--vendor', type=str, nargs='?', const=TEST_VENDOR, help='Vendor name for vendor domain') - auth_parser.add_argument('-s', '--series', type=str, nargs='?', const=TEST_SERIES, help='Series identifier for series domain') - auth_parser.add_argument('-r', '--region', type=str, nargs='?', const=TEST_REGION, help='Region name for region domain') - auth_parser.add_argument('-c', '--country', type=str, nargs='?', const=TEST_COUNTRY, help='Country name for country domain') - - prekey_parser = subparsers.add_parser('prekey', help='Generate prekey data .C source code file') - prekey_parser.add_argument('-m', '--max-height', type=int, default=8, help='Height of generated prekey') - prekey_parser.add_argument('-v', '--vendor', type=str, default=TEST_VENDOR, help='Vendor name for vendor domain') - prekey_parser.add_argument('-s', '--series', type=str, default=TEST_SERIES, help='Series identifier for series domain') - prekey_parser.add_argument('-r', '--region', type=str, default=TEST_REGION, help='Region name for region domain') - prekey_parser.add_argument('-c', '--country', type=str, default=TEST_COUNTRY, help='Country name for country domain') - prekey_parser.set_defaults(func=prekey_cmd, all='all') - - args = parser.parse_args() - sys.exit(args.func(args)) - diff --git a/fw/hid-dials/tools/reed_solomon.py b/fw/hid-dials/tools/reed_solomon.py deleted file mode 100644 index c4ca6e4..0000000 --- a/fw/hid-dials/tools/reed_solomon.py +++ /dev/null @@ -1,91 +0,0 @@ -import os, sys -import ctypes as C -import argparse -import binascii -import numpy as np -import timeit -import statistics - -lib = C.CDLL('rslib.so') - -lib.rslib_encode.argtypes = [C.c_int, C.c_size_t, C.POINTER(C.c_char), C.POINTER(C.c_char)] -lib.rslib_decode.argtypes = [C.c_int, C.c_size_t, C.POINTER(C.c_char)] -lib.rslib_gexp.argtypes = [C.c_int, C.c_int] -lib.rslib_gexp.restype = C.c_int -lib.rslib_decode.restype = C.c_int -lib.rslib_npar.restype = C.c_size_t - -def npar(): - return lib.rslib_npar() - -def encode(data: bytes, nbits=8): - out = C.create_string_buffer(len(data) + lib.rslib_npar()) - lib.rslib_encode(nbits, len(data), data, out) - return out.raw - -def decode(data: bytes, nbits=8): - inout = C.create_string_buffer(data) - lib.rslib_decode(nbits, len(data), inout) - return inout.raw[:-lib.rslib_npar() - 1] - -def cmdline_func_test(args, print=lambda *args, **kwargs: None, benchmark=False): - st = np.random.RandomState(seed=args.seed) - - lfsr = [lib.rslib_gexp(i, args.bits) for i in range(2**args.bits - 1)] - print('LFSR', len(set(lfsr)), lfsr) - assert all(0 < x < 2**args.bits for x in lfsr) - assert len(set(lfsr)) == 2**args.bits - 1 - - print('Seed', args.seed) - for i in range(args.repeat): - print(f'Run {i}') - test_data = bytes(st.randint(2**args.bits, size=args.message_length, dtype=np.uint8)) - print(' Raw:', binascii.hexlify(test_data).decode()) - encoded = encode(test_data, nbits=args.bits) - print(' Encoded:', binascii.hexlify(encoded).decode()) - - indices = st.permutation(len(encoded)) - encoded = list(encoded) - for pos in indices[:args.errors]: - encoded[pos] = st.randint(2**args.bits) - encoded = bytes(encoded) - print(' Modified:', ''.join(f'\033[91m{b:02x}\033[0m' if pos in indices[:args.errors] else f'{b:02x}' for pos, b in enumerate(encoded))) - - if benchmark: - rpt = 10000 - delta = timeit.timeit('decode(encoded, nbits=args.bits)', - globals={'args': args, 'decode': decode, 'encoded': encoded}, - number=rpt)/rpt - print(f'Decoding runtime: {delta*1e6:.3f}μs') - decoded = decode(encoded, nbits=args.bits) - print(' Decoded:', binascii.hexlify(decoded).decode()) - print(' Delta:', binascii.hexlify( - bytes(x^y for x, y in zip(test_data, decoded)) - ).decode().replace('0', '.')) - assert test_data == decoded - -def cmdline_func_encode(args, **kwargs): - data = np.frombuffer(binascii.unhexlify(args.hex_str), dtype=np.uint8) - # Map 8 bit input to 6 bit symbol string - data = np.packbits(np.pad(np.unpackbits(data).reshape((-1, 6)), ((0,0),(2, 0))).flatten()) - encoded = encode(data.tobytes(), nbits=args.bits) - print('symbol array:', ', '.join(f'0x{x:02x}' for x in encoded)) - print('hex string:', binascii.hexlify(encoded).decode()) - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - cmd_parser = parser.add_subparsers(required=True) - test_parser = cmd_parser.add_parser('test', help='Test reed-solomon implementation') - test_parser.add_argument('-m', '--message-length', type=int, default=6, help='Test message (plaintext) length in bytes') - test_parser.add_argument('-e', '--errors', type=int, default=2, help='Number of byte errors to insert into simulation') - test_parser.add_argument('-r', '--repeat', type=int, default=1000, help='Repeat experiment -r times') - test_parser.add_argument('-b', '--bits', type=int, default=8, help='Symbol bit size') - test_parser.add_argument('-s', '--seed', type=int, default=0, help='Random seed') - test_parser.set_defaults(func=cmdline_func_test) - enc_parser = cmd_parser.add_parser('encode', help='RS-Encode given hex string') - enc_parser.set_defaults(func=cmdline_func_encode) - enc_parser.add_argument('-b', '--bits', type=int, default=8, help='Symbol bit size') - enc_parser.add_argument('hex_str', type=str, help='Input data as hex string') - args = parser.parse_args() - args.func(args) - diff --git a/fw/hid-dials/upstream/cmsis-core b/fw/hid-dials/upstream/cmsis-core deleted file mode 160000 index 84a7bf7..0000000 --- a/fw/hid-dials/upstream/cmsis-core +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 84a7bf753760ad7442d8762d2780560e6a734d96 diff --git a/fw/hid-dials/upstream/st-cmsis-f0 b/fw/hid-dials/upstream/st-cmsis-f0 deleted file mode 160000 index 20e23a9..0000000 --- a/fw/hid-dials/upstream/st-cmsis-f0 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 20e23a96fe294368389655878c44813c989b7a9c diff --git a/fw/hid-dials/upstream/st-hal-f0 b/fw/hid-dials/upstream/st-hal-f0 deleted file mode 160000 index 5eeaad1..0000000 --- a/fw/hid-dials/upstream/st-hal-f0 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5eeaad10dc3816830abd9b3bfd74c6974453e907 diff --git a/fw/hid-dials/upstream/st-usb-device b/fw/hid-dials/upstream/st-usb-device deleted file mode 160000 index 60d163f..0000000 --- a/fw/hid-dials/upstream/st-usb-device +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 60d163f271987fd322e22f63c095836e1dc703f6 -- cgit