Naming and coding style convention, new linter tool. (#945)

* Makefile, Scripts: new linter
* About: remove ID from IC
* Firmware: remove double define for DIVC/DIVR
* Scripts: check folder names too. Docker: replace syntax check with make lint.
* Reformat Sources and Migrate to new file naming convention
* Docker: symlink clang-format-12 to clang-format
* Add coding style guide
This commit is contained in:
あく
2022-01-05 19:10:18 +03:00
committed by GitHub
parent c98e54da10
commit 389ff92cc1
899 changed files with 379242 additions and 373418 deletions
+74
View File
@@ -0,0 +1,74 @@
#include <furi_hal.h>
#include <comp.h>
#include <tim.h>
#include <gpio.h>
#include <stm32wbxx_ll_cortex.h>
#include <fatfs.h>
#define TAG "FuriHal"
void furi_hal_init() {
furi_hal_clock_init();
furi_hal_rtc_init();
furi_hal_console_init();
furi_hal_interrupt_init();
furi_hal_delay_init();
MX_GPIO_Init();
FURI_LOG_I(TAG, "GPIO OK");
furi_hal_bootloader_init();
furi_hal_version_init();
furi_hal_spi_init();
MX_TIM1_Init();
FURI_LOG_I(TAG, "TIM1 OK");
MX_TIM2_Init();
FURI_LOG_I(TAG, "TIM2 OK");
MX_TIM16_Init();
FURI_LOG_I(TAG, "TIM16 OK");
MX_COMP1_Init();
FURI_LOG_I(TAG, "COMP1 OK");
furi_hal_crypto_init();
// VCP + USB
furi_hal_usb_init();
furi_hal_usb_set_config(&usb_cdc_single);
furi_hal_vcp_init();
FURI_LOG_I(TAG, "USB OK");
furi_hal_i2c_init();
// High Level
furi_hal_power_init();
furi_hal_light_init();
furi_hal_vibro_init();
furi_hal_subghz_init();
furi_hal_nfc_init();
furi_hal_rfid_init();
furi_hal_bt_init();
furi_hal_compress_icon_init();
// FreeRTOS glue
furi_hal_os_init();
// FatFS driver initialization
MX_FATFS_Init();
FURI_LOG_I(TAG, "FATFS OK");
// Partial null pointer dereference protection
LL_MPU_Disable();
LL_MPU_ConfigRegion(
LL_MPU_REGION_NUMBER0,
0x00,
0x0,
LL_MPU_REGION_SIZE_1MB | LL_MPU_REGION_PRIV_RO_URO | LL_MPU_ACCESS_BUFFERABLE |
LL_MPU_ACCESS_CACHEABLE | LL_MPU_ACCESS_SHAREABLE | LL_MPU_TEX_LEVEL1 |
LL_MPU_INSTRUCTION_ACCESS_ENABLE);
LL_MPU_Enable(LL_MPU_CTRL_PRIVILEGED_DEFAULT);
}
@@ -0,0 +1,25 @@
#include <furi_hal_bootloader.h>
#include <furi_hal_rtc.h>
#include <furi.h>
#define TAG "FuriHalBoot"
// Boot request enum
#define BOOT_REQUEST_TAINTED 0x00000000
#define BOOT_REQUEST_CLEAN 0xDADEDADE
#define BOOT_REQUEST_DFU 0xDF00B000
void furi_hal_bootloader_init() {
#ifndef DEBUG
furi_hal_rtc_set_register(FuriHalRtcRegisterBoot, BOOT_REQUEST_TAINTED);
#endif
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_bootloader_set_mode(FuriHalBootloaderMode mode) {
if(mode == FuriHalBootloaderModeNormal) {
furi_hal_rtc_set_register(FuriHalRtcRegisterBoot, BOOT_REQUEST_CLEAN);
} else if(mode == FuriHalBootloaderModeDFU) {
furi_hal_rtc_set_register(FuriHalRtcRegisterBoot, BOOT_REQUEST_DFU);
}
}
+378
View File
@@ -0,0 +1,378 @@
#include <furi_hal_bt.h>
#include <ble.h>
#include <stm32wbxx.h>
#include <shci.h>
#include <cmsis_os2.h>
#include <furi_hal_version.h>
#include <furi_hal_bt_hid.h>
#include <furi_hal_bt_serial.h>
#include "battery_service.h"
#include <furi.h>
#define TAG "FuriHalBt"
#define FURI_HAL_BT_DEFAULT_MAC_ADDR \
{ 0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x72 }
osMutexId_t furi_hal_bt_core2_mtx = NULL;
static FuriHalBtStack furi_hal_bt_stack = FuriHalBtStackUnknown;
typedef void (*FuriHalBtProfileStart)(void);
typedef void (*FuriHalBtProfileStop)(void);
typedef struct {
FuriHalBtProfileStart start;
FuriHalBtProfileStart stop;
GapConfig config;
uint16_t appearance_char;
uint16_t advertise_service_uuid;
} FuriHalBtProfileConfig;
FuriHalBtProfileConfig profile_config[FuriHalBtProfileNumber] = {
[FuriHalBtProfileSerial] =
{
.start = furi_hal_bt_serial_start,
.stop = furi_hal_bt_serial_stop,
.config =
{
.adv_service_uuid = 0x3080,
.appearance_char = 0x8600,
.bonding_mode = true,
.pairing_method = GapPairingPinCodeShow,
.mac_address = FURI_HAL_BT_DEFAULT_MAC_ADDR,
},
},
[FuriHalBtProfileHidKeyboard] =
{
.start = furi_hal_bt_hid_start,
.stop = furi_hal_bt_hid_stop,
.config =
{
.adv_service_uuid = HUMAN_INTERFACE_DEVICE_SERVICE_UUID,
.appearance_char = GAP_APPEARANCE_KEYBOARD,
.bonding_mode = true,
.pairing_method = GapPairingPinCodeVerifyYesNo,
.mac_address = FURI_HAL_BT_DEFAULT_MAC_ADDR,
},
},
};
FuriHalBtProfileConfig* current_profile = NULL;
void furi_hal_bt_init() {
if(!furi_hal_bt_core2_mtx) {
furi_hal_bt_core2_mtx = osMutexNew(NULL);
furi_assert(furi_hal_bt_core2_mtx);
}
// Explicitly tell that we are in charge of CLK48 domain
if(!HAL_HSEM_IsSemTaken(CFG_HW_CLK48_CONFIG_SEMID)) {
HAL_HSEM_FastTake(CFG_HW_CLK48_CONFIG_SEMID);
}
// Start Core2
ble_glue_init();
}
void furi_hal_bt_lock_core2() {
furi_assert(furi_hal_bt_core2_mtx);
furi_check(osMutexAcquire(furi_hal_bt_core2_mtx, osWaitForever) == osOK);
}
void furi_hal_bt_unlock_core2() {
furi_assert(furi_hal_bt_core2_mtx);
furi_check(osMutexRelease(furi_hal_bt_core2_mtx) == osOK);
}
static bool furi_hal_bt_radio_stack_is_supported(WirelessFwInfo_t* info) {
bool supported = false;
if(info->StackType == INFO_STACK_TYPE_BLE_HCI) {
furi_hal_bt_stack = FuriHalBtStackHciLayer;
supported = true;
} else if(info->StackType == INFO_STACK_TYPE_BLE_LIGHT) {
if(info->VersionMajor >= FURI_HAL_BT_STACK_VERSION_MAJOR &&
info->VersionMinor >= FURI_HAL_BT_STACK_VERSION_MINOR) {
furi_hal_bt_stack = FuriHalBtStackLight;
supported = true;
}
} else {
furi_hal_bt_stack = FuriHalBtStackUnknown;
}
return supported;
}
bool furi_hal_bt_start_radio_stack() {
bool res = false;
furi_assert(furi_hal_bt_core2_mtx);
osMutexAcquire(furi_hal_bt_core2_mtx, osWaitForever);
// Explicitly tell that we are in charge of CLK48 domain
if(!HAL_HSEM_IsSemTaken(CFG_HW_CLK48_CONFIG_SEMID)) {
HAL_HSEM_FastTake(CFG_HW_CLK48_CONFIG_SEMID);
}
do {
// Wait until FUS is started or timeout
WirelessFwInfo_t info = {};
if(!ble_glue_wait_for_fus_start(&info)) {
FURI_LOG_E(TAG, "FUS start failed");
LL_C2_PWR_SetPowerMode(LL_PWR_MODE_SHUTDOWN);
ble_glue_thread_stop();
break;
}
// Check weather we support radio stack
if(!furi_hal_bt_radio_stack_is_supported(&info)) {
FURI_LOG_E(TAG, "Unsupported radio stack");
LL_C2_PWR_SetPowerMode(LL_PWR_MODE_SHUTDOWN);
ble_glue_thread_stop();
break;
}
// Starting radio stack
if(!ble_glue_start()) {
FURI_LOG_E(TAG, "Failed to start radio stack");
LL_C2_PWR_SetPowerMode(LL_PWR_MODE_SHUTDOWN);
ble_glue_thread_stop();
ble_app_thread_stop();
break;
}
res = true;
} while(false);
osMutexRelease(furi_hal_bt_core2_mtx);
return res;
}
FuriHalBtStack furi_hal_bt_get_radio_stack() {
return furi_hal_bt_stack;
}
bool furi_hal_bt_start_app(FuriHalBtProfile profile, GapEventCallback event_cb, void* context) {
furi_assert(event_cb);
furi_assert(profile < FuriHalBtProfileNumber);
bool ret = false;
do {
if(!ble_glue_is_radio_stack_ready()) {
FURI_LOG_E(TAG, "Can't start BLE App - radio stack did not start");
break;
}
if(furi_hal_bt_stack != FuriHalBtStackLight) {
FURI_LOG_E(TAG, "Can't start Ble App - unsupported radio stack");
break;
}
// Set mac address
memcpy(
profile_config[profile].config.mac_address,
furi_hal_version_get_ble_mac(),
sizeof(profile_config[profile].config.mac_address));
// Set advertise name
strlcpy(
profile_config[profile].config.adv_name,
furi_hal_version_get_ble_local_device_name_ptr(),
FURI_HAL_VERSION_DEVICE_NAME_LENGTH);
// Configure GAP
GapConfig* config = &profile_config[profile].config;
if(profile == FuriHalBtProfileSerial) {
config->adv_service_uuid |= furi_hal_version_get_hw_color();
} else if(profile == FuriHalBtProfileHidKeyboard) {
// Change MAC address for HID profile
config->mac_address[2]++;
// Change name Flipper -> Keynote
const char* clicker_str = "Keynote";
memcpy(&config->adv_name[1], clicker_str, strlen(clicker_str));
}
if(!gap_init(config, event_cb, context)) {
gap_thread_stop();
FURI_LOG_E(TAG, "Failed to init GAP");
break;
}
// Start selected profile services
if(furi_hal_bt_stack == FuriHalBtStackLight) {
profile_config[profile].start();
}
ret = true;
} while(false);
current_profile = &profile_config[profile];
return ret;
}
bool furi_hal_bt_change_app(FuriHalBtProfile profile, GapEventCallback event_cb, void* context) {
furi_assert(event_cb);
furi_assert(profile < FuriHalBtProfileNumber);
bool ret = true;
FURI_LOG_I(TAG, "Stop current profile services");
current_profile->stop();
FURI_LOG_I(TAG, "Disconnect and stop advertising");
furi_hal_bt_stop_advertising();
FURI_LOG_I(TAG, "Shutdow 2nd core");
LL_C2_PWR_SetPowerMode(LL_PWR_MODE_SHUTDOWN);
FURI_LOG_I(TAG, "Stop BLE related RTOS threads");
ble_app_thread_stop();
gap_thread_stop();
FURI_LOG_I(TAG, "Reset SHCI");
SHCI_C2_Reinit();
osDelay(100);
ble_glue_thread_stop();
FURI_LOG_I(TAG, "Start BT initialization");
furi_hal_bt_init();
furi_hal_bt_start_radio_stack();
ret = furi_hal_bt_start_app(profile, event_cb, context);
if(ret) {
current_profile = &profile_config[profile];
}
return ret;
}
static bool furi_hal_bt_is_active() {
return gap_get_state() > GapStateIdle;
}
void furi_hal_bt_start_advertising() {
if(gap_get_state() == GapStateIdle) {
gap_start_advertising();
}
}
void furi_hal_bt_stop_advertising() {
if(furi_hal_bt_is_active()) {
gap_stop_advertising();
while(furi_hal_bt_is_active()) {
osDelay(1);
}
}
}
void furi_hal_bt_update_battery_level(uint8_t battery_level) {
if(battery_svc_is_started()) {
battery_svc_update_level(battery_level);
}
}
void furi_hal_bt_get_key_storage_buff(uint8_t** key_buff_addr, uint16_t* key_buff_size) {
ble_app_get_key_storage_buff(key_buff_addr, key_buff_size);
}
void furi_hal_bt_set_key_storage_change_callback(
BleGlueKeyStorageChangedCallback callback,
void* context) {
furi_assert(callback);
ble_glue_set_key_storage_changed_callback(callback, context);
}
void furi_hal_bt_nvm_sram_sem_acquire() {
while(HAL_HSEM_FastTake(CFG_HW_BLE_NVM_SRAM_SEMID) != HAL_OK) {
osDelay(1);
}
}
void furi_hal_bt_nvm_sram_sem_release() {
HAL_HSEM_Release(CFG_HW_BLE_NVM_SRAM_SEMID, 0);
}
void furi_hal_bt_dump_state(string_t buffer) {
if(furi_hal_bt_is_alive()) {
uint8_t HCI_Version;
uint16_t HCI_Revision;
uint8_t LMP_PAL_Version;
uint16_t Manufacturer_Name;
uint16_t LMP_PAL_Subversion;
tBleStatus ret = hci_read_local_version_information(
&HCI_Version, &HCI_Revision, &LMP_PAL_Version, &Manufacturer_Name, &LMP_PAL_Subversion);
string_cat_printf(
buffer,
"Ret: %d, HCI_Version: %d, HCI_Revision: %d, LMP_PAL_Version: %d, Manufacturer_Name: %d, LMP_PAL_Subversion: %d",
ret,
HCI_Version,
HCI_Revision,
LMP_PAL_Version,
Manufacturer_Name,
LMP_PAL_Subversion);
} else {
string_cat_printf(buffer, "BLE not ready");
}
}
bool furi_hal_bt_is_alive() {
return ble_glue_is_alive();
}
void furi_hal_bt_start_tone_tx(uint8_t channel, uint8_t power) {
aci_hal_set_tx_power_level(0, power);
aci_hal_tone_start(channel, 0);
}
void furi_hal_bt_stop_tone_tx() {
aci_hal_tone_stop();
}
void furi_hal_bt_start_packet_tx(uint8_t channel, uint8_t pattern, uint8_t datarate) {
hci_le_enhanced_transmitter_test(channel, 0x25, pattern, datarate);
}
void furi_hal_bt_start_packet_rx(uint8_t channel, uint8_t datarate) {
hci_le_enhanced_receiver_test(channel, datarate, 0);
}
uint16_t furi_hal_bt_stop_packet_test() {
uint16_t num_of_packets = 0;
hci_le_test_end(&num_of_packets);
return num_of_packets;
}
void furi_hal_bt_start_rx(uint8_t channel) {
aci_hal_rx_start(channel);
}
float furi_hal_bt_get_rssi() {
float val;
uint8_t rssi_raw[3];
if(aci_hal_read_raw_rssi(rssi_raw) != BLE_STATUS_SUCCESS) {
return 0.0f;
}
// Some ST magic with rssi
uint8_t agc = rssi_raw[2] & 0xFF;
int rssi = (((int)rssi_raw[1] << 8) & 0xFF00) + (rssi_raw[0] & 0xFF);
if(rssi == 0 || agc > 11) {
val = -127.0;
} else {
val = agc * 6.0f - 127.0f;
while(rssi > 30) {
val += 6.0;
rssi >>= 1;
}
val += (417 * rssi + 18080) >> 10;
}
return val;
}
uint32_t furi_hal_bt_get_transmitted_packets() {
uint32_t packets = 0;
aci_hal_le_tx_test_packet_number(&packets);
return packets;
}
void furi_hal_bt_stop_rx() {
aci_hal_rx_stop();
}
bool furi_hal_bt_start_scan(GapScanCallback callback, void* context) {
if(furi_hal_bt_stack != FuriHalBtStackHciLayer) {
return false;
}
gap_start_scan(callback, context);
return true;
}
void furi_hal_bt_stop_scan() {
if(furi_hal_bt_stack == FuriHalBtStackHciLayer) {
gap_stop_scan();
}
}
@@ -0,0 +1,236 @@
#include "furi_hal_bt_hid.h"
#include "dev_info_service.h"
#include "battery_service.h"
#include "hid_service.h"
#include <furi.h>
#define FURI_HAL_BT_INFO_BASE_USB_SPECIFICATION (0x0101)
#define FURI_HAL_BT_INFO_COUNTRY_CODE (0x00)
#define FURI_HAL_BT_HID_INFO_FLAG_REMOTE_WAKE_MSK (0x01)
#define FURI_HAL_BT_HID_INFO_FLAG_NORMALLY_CONNECTABLE_MSK (0x02)
#define FURI_HAL_BT_HID_KB_KEYS_MAX (6)
typedef struct {
// uint8_t report_id;
uint8_t mods;
uint8_t reserved;
uint8_t key[FURI_HAL_BT_HID_KB_KEYS_MAX];
} FuriHalBtHidKbReport;
typedef struct {
uint8_t report_id;
uint8_t key;
} FuriHalBtHidMediaReport;
// TODO make composite HID device
static uint8_t furi_hal_bt_hid_report_map_data[] = {
0x05,
0x01, // Usage Page (Generic Desktop)
0x09,
0x06, // Usage (Keyboard)
0xA1,
0x01, // Collection (Application)
// 0x85, 0x01, // Report ID (1)
0x05,
0x07, // Usage Page (Key Codes)
0x19,
0xe0, // Usage Minimum (224)
0x29,
0xe7, // Usage Maximum (231)
0x15,
0x00, // Logical Minimum (0)
0x25,
0x01, // Logical Maximum (1)
0x75,
0x01, // Report Size (1)
0x95,
0x08, // Report Count (8)
0x81,
0x02, // Input (Data, Variable, Absolute)
0x95,
0x01, // Report Count (1)
0x75,
0x08, // Report Size (8)
0x81,
0x01, // Input (Constant) reserved byte(1)
0x95,
0x05, // Report Count (5)
0x75,
0x01, // Report Size (1)
0x05,
0x08, // Usage Page (Page# for LEDs)
0x19,
0x01, // Usage Minimum (1)
0x29,
0x05, // Usage Maximum (5)
0x91,
0x02, // Output (Data, Variable, Absolute), Led report
0x95,
0x01, // Report Count (1)
0x75,
0x03, // Report Size (3)
0x91,
0x01, // Output (Data, Variable, Absolute), Led report padding
0x95,
0x06, // Report Count (6)
0x75,
0x08, // Report Size (8)
0x15,
0x00, // Logical Minimum (0)
0x25,
0x65, // Logical Maximum (101)
0x05,
0x07, // Usage Page (Key codes)
0x19,
0x00, // Usage Minimum (0)
0x29,
0x65, // Usage Maximum (101)
0x81,
0x00, // Input (Data, Array) Key array(6 bytes)
0x09,
0x05, // Usage (Vendor Defined)
0x15,
0x00, // Logical Minimum (0)
0x26,
0xFF,
0x00, // Logical Maximum (255)
0x75,
0x08, // Report Size (8 bit)
0x95,
0x02, // Report Count (2)
0xB1,
0x02, // Feature (Data, Variable, Absolute)
0xC0, // End Collection (Application)
// 0x05, 0x0C, // Usage Page (Consumer)
// 0x09, 0x01, // Usage (Consumer Control)
// 0xA1, 0x01, // Collection (Application)
// 0x85, 0x02, // Report ID (2)
// 0x05, 0x0C, // Usage Page (Consumer)
// 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, 0xB8, // Usage (Eject)
// 0x09, 0xCD, // Usage (Play/Pause)
// 0x09, 0xE2, // Usage (Mute)
// 0x09, 0xE9, // Usage (Volume Increment)
// 0x09, 0xEA, // Usage (Volume Decrement)
// 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
// 0xC0, // End Collection
};
FuriHalBtHidKbReport* kb_report = NULL;
FuriHalBtHidMediaReport* media_report = NULL;
void furi_hal_bt_hid_start() {
// Start device info
if(!dev_info_svc_is_started()) {
dev_info_svc_start();
}
// Start battery service
if(!battery_svc_is_started()) {
battery_svc_start();
}
// Start HID service
if(!hid_svc_is_started()) {
hid_svc_start();
}
// Configure HID Keyboard
kb_report = furi_alloc(sizeof(FuriHalBtHidKbReport));
media_report = furi_alloc(sizeof(FuriHalBtHidMediaReport));
// Configure Report Map characteristic
hid_svc_update_report_map(
furi_hal_bt_hid_report_map_data, sizeof(furi_hal_bt_hid_report_map_data));
// Configure HID Information characteristic
uint8_t hid_info_val[4] = {
FURI_HAL_BT_INFO_BASE_USB_SPECIFICATION & 0x00ff,
(FURI_HAL_BT_INFO_BASE_USB_SPECIFICATION & 0xff00) >> 8,
FURI_HAL_BT_INFO_COUNTRY_CODE,
FURI_HAL_BT_HID_INFO_FLAG_REMOTE_WAKE_MSK |
FURI_HAL_BT_HID_INFO_FLAG_NORMALLY_CONNECTABLE_MSK,
};
hid_svc_update_info(hid_info_val, sizeof(hid_info_val));
}
void furi_hal_bt_hid_stop() {
furi_assert(kb_report);
// Stop all services
if(dev_info_svc_is_started()) {
dev_info_svc_stop();
}
if(battery_svc_is_started()) {
battery_svc_stop();
}
if(hid_svc_is_started()) {
hid_svc_stop();
}
free(kb_report);
free(media_report);
media_report = NULL;
kb_report = NULL;
}
bool furi_hal_bt_hid_kb_press(uint16_t button) {
furi_assert(kb_report);
// kb_report->report_id = 0x01;
for(uint8_t i = 0; i < FURI_HAL_BT_HID_KB_KEYS_MAX; i++) {
if(kb_report->key[i] == 0) {
kb_report->key[i] = button & 0xFF;
break;
}
}
kb_report->mods |= (button >> 8);
return hid_svc_update_input_report((uint8_t*)kb_report, sizeof(FuriHalBtHidKbReport));
}
bool furi_hal_bt_hid_kb_release(uint16_t button) {
furi_assert(kb_report);
// kb_report->report_id = 0x01;
for(uint8_t i = 0; i < FURI_HAL_BT_HID_KB_KEYS_MAX; i++) {
if(kb_report->key[i] == (button & 0xFF)) {
kb_report->key[i] = 0;
break;
}
}
kb_report->mods &= ~(button >> 8);
return hid_svc_update_input_report((uint8_t*)kb_report, sizeof(FuriHalBtHidKbReport));
}
bool furi_hal_bt_hid_kb_release_all() {
furi_assert(kb_report);
// kb_report->report_id = 0x01;
memset(kb_report, 0, sizeof(FuriHalBtHidKbReport));
return hid_svc_update_input_report((uint8_t*)kb_report, sizeof(FuriHalBtHidKbReport));
}
bool furi_hal_bt_hid_media_press(uint8_t button) {
furi_assert(media_report);
media_report->report_id = 0x02;
media_report->key |= (0x01 << button);
return hid_svc_update_input_report((uint8_t*)media_report, sizeof(FuriHalBtHidMediaReport));
}
bool furi_hal_bt_hid_media_release(uint8_t button) {
furi_assert(media_report);
media_report->report_id = 0x02;
media_report->key &= ~(0x01 << button);
return hid_svc_update_input_report((uint8_t*)media_report, sizeof(FuriHalBtHidMediaReport));
}
bool furi_hal_bt_hid_media_release_all() {
furi_assert(media_report);
media_report->report_id = 0x02;
media_report->key = 0x00;
return hid_svc_update_input_report((uint8_t*)media_report, sizeof(FuriHalBtHidMediaReport));
}
@@ -0,0 +1,54 @@
#include "furi_hal_bt_serial.h"
#include "dev_info_service.h"
#include "battery_service.h"
#include "serial_service.h"
#include <furi.h>
void furi_hal_bt_serial_start() {
// Start device info
if(!dev_info_svc_is_started()) {
dev_info_svc_start();
}
// Start battery service
if(!battery_svc_is_started()) {
battery_svc_start();
}
// Start Serial service
if(!serial_svc_is_started()) {
serial_svc_start();
}
}
void furi_hal_bt_serial_set_event_callback(
uint16_t buff_size,
FuriHalBtSerialCallback callback,
void* context) {
serial_svc_set_callbacks(buff_size, callback, context);
}
void furi_hal_bt_serial_notify_buffer_is_empty() {
serial_svc_notify_buffer_is_empty();
}
bool furi_hal_bt_serial_tx(uint8_t* data, uint16_t size) {
if(size > FURI_HAL_BT_SERIAL_PACKET_SIZE_MAX) {
return false;
}
return serial_svc_update_tx(data, size);
}
void furi_hal_bt_serial_stop() {
// Stop all services
if(dev_info_svc_is_started()) {
dev_info_svc_stop();
}
// Start battery service
if(battery_svc_is_started()) {
battery_svc_stop();
}
// Start Serial service
if(serial_svc_is_started()) {
serial_svc_stop();
}
}
@@ -0,0 +1,159 @@
#include <furi_hal_clock.h>
#include <furi.h>
#include <stm32wbxx_ll_pwr.h>
#include <stm32wbxx_ll_rcc.h>
#include <stm32wbxx_ll_utils.h>
#define TAG "FuriHalClock"
#define HS_CLOCK_IS_READY() (LL_RCC_HSE_IsReady() && LL_RCC_HSI_IsReady())
#define LS_CLOCK_IS_READY() (LL_RCC_LSE_IsReady() && LL_RCC_LSI1_IsReady())
void furi_hal_clock_init() {
/* Prepare Flash memory for 64mHz system clock */
LL_FLASH_SetLatency(LL_FLASH_LATENCY_3);
while(LL_FLASH_GetLatency() != LL_FLASH_LATENCY_3)
;
/* HSE and HSI configuration and activation */
LL_RCC_HSE_SetCapacitorTuning(0x26);
LL_RCC_HSE_Enable();
LL_RCC_HSI_Enable();
while(!HS_CLOCK_IS_READY())
;
LL_RCC_HSE_EnableCSS();
/* LSE and LSI1 configuration and activation */
LL_PWR_EnableBkUpAccess();
LL_RCC_LSE_SetDriveCapability(LL_RCC_LSEDRIVE_HIGH);
LL_RCC_LSE_Enable();
LL_RCC_LSI1_Enable();
while(!LS_CLOCK_IS_READY())
;
LL_EXTI_EnableIT_0_31(
LL_EXTI_LINE_18); /* Why? Because that's why. See RM0434, Table 61. CPU1 vector table. */
LL_EXTI_EnableRisingTrig_0_31(LL_EXTI_LINE_18);
LL_RCC_EnableIT_LSECSS();
LL_RCC_LSE_EnableCSS();
/* Main PLL configuration and activation */
LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSE, LL_RCC_PLLM_DIV_2, 8, LL_RCC_PLLR_DIV_2);
LL_RCC_PLL_Enable();
LL_RCC_PLL_EnableDomain_SYS();
while(LL_RCC_PLL_IsReady() != 1)
;
LL_RCC_PLLSAI1_ConfigDomain_48M(
LL_RCC_PLLSOURCE_HSE, LL_RCC_PLLM_DIV_2, 6, LL_RCC_PLLSAI1Q_DIV_2);
LL_RCC_PLLSAI1_ConfigDomain_ADC(
LL_RCC_PLLSOURCE_HSE, LL_RCC_PLLM_DIV_2, 6, LL_RCC_PLLSAI1R_DIV_2);
LL_RCC_PLLSAI1_Enable();
LL_RCC_PLLSAI1_EnableDomain_48M();
LL_RCC_PLLSAI1_EnableDomain_ADC();
while(LL_RCC_PLLSAI1_IsReady() != 1)
;
/* Sysclk activation on the main PLL */
/* Set CPU1 prescaler*/
LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);
/* Set CPU2 prescaler*/
LL_C2_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_2);
LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL);
while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL)
;
/* Set AHB SHARED prescaler*/
LL_RCC_SetAHB4Prescaler(LL_RCC_SYSCLK_DIV_1);
/* Set APB1 prescaler*/
LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
/* Set APB2 prescaler*/
LL_RCC_SetAPB2Prescaler(LL_RCC_APB2_DIV_1);
/* Disable MSI */
LL_RCC_MSI_Disable();
while(LL_RCC_MSI_IsReady() != 0)
;
/* Update CMSIS variable (which can be updated also through SystemCoreClockUpdate function) */
LL_SetSystemCoreClock(64000000);
/* Update the time base */
if(HAL_InitTick(TICK_INT_PRIORITY) != HAL_OK) {
Error_Handler();
}
LL_RCC_SetUSARTClockSource(LL_RCC_USART1_CLKSOURCE_PCLK2);
LL_RCC_SetLPUARTClockSource(LL_RCC_LPUART1_CLKSOURCE_PCLK1);
LL_RCC_SetADCClockSource(LL_RCC_ADC_CLKSOURCE_PLLSAI1);
LL_RCC_SetI2CClockSource(LL_RCC_I2C1_CLKSOURCE_PCLK1);
LL_RCC_SetRNGClockSource(LL_RCC_RNG_CLKSOURCE_CLK48);
LL_RCC_SetUSBClockSource(LL_RCC_USB_CLKSOURCE_PLLSAI1);
LL_RCC_SetCLK48ClockSource(LL_RCC_CLK48_CLKSOURCE_PLLSAI1);
LL_RCC_SetSMPSClockSource(LL_RCC_SMPS_CLKSOURCE_HSE);
LL_RCC_SetSMPSPrescaler(LL_RCC_SMPS_DIV_1);
LL_RCC_SetRFWKPClockSource(LL_RCC_RFWKP_CLKSOURCE_LSE);
// AHB1
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMAMUX1);
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1);
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_I2C1);
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_SPI2);
// AHB2
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA);
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOB);
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOC);
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOD);
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOE);
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOH);
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SPI1);
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_AES1);
// AHB3
LL_AHB3_GRP1_EnableClock(LL_AHB3_GRP1_PERIPH_PKA);
LL_AHB3_GRP1_EnableClock(LL_AHB3_GRP1_PERIPH_RNG);
LL_AHB3_GRP1_EnableClock(LL_AHB3_GRP1_PERIPH_AES2);
// APB1
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2);
LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_LPUART1);
// APB2
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_USART1);
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_clock_switch_to_hsi() {
LL_RCC_HSI_Enable();
while(!LL_RCC_HSI_IsReady())
;
LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSI);
LL_RCC_SetSMPSClockSource(LL_RCC_SMPS_CLKSOURCE_HSI);
while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSI)
;
}
void furi_hal_clock_switch_to_pll() {
LL_RCC_HSE_Enable();
LL_RCC_PLL_Enable();
while(!LL_RCC_HSE_IsReady())
;
while(!LL_RCC_PLL_IsReady())
;
LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL);
LL_RCC_SetSMPSClockSource(LL_RCC_SMPS_CLKSOURCE_HSE);
while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL)
;
}
@@ -0,0 +1,10 @@
#pragma once
/** Initialize clocks */
void furi_hal_clock_init();
/** Switch to HSI clock */
void furi_hal_clock_switch_to_hsi();
/** Switch to PLL clock */
void furi_hal_clock_switch_to_pll();
@@ -0,0 +1,264 @@
#include <furi_hal_compress.h>
#include <furi.h>
#include <lib/heatshrink/heatshrink_encoder.h>
#include <lib/heatshrink/heatshrink_decoder.h>
#define TAG "FuriHalCompress"
#define FURI_HAL_COMPRESS_ICON_ENCODED_BUFF_SIZE (2 * 512)
#define FURI_HAL_COMPRESS_ICON_DECODED_BUFF_SIZE (1024)
#define FURI_HAL_COMPRESS_EXP_BUFF_SIZE (1 << FURI_HAL_COMPRESS_EXP_BUFF_SIZE_LOG)
typedef struct {
uint8_t is_compressed;
uint8_t reserved;
uint16_t compressed_buff_size;
} FuriHalCompressHeader;
typedef struct {
heatshrink_decoder* decoder;
uint8_t
compress_buff[FURI_HAL_COMPRESS_EXP_BUFF_SIZE + FURI_HAL_COMPRESS_ICON_ENCODED_BUFF_SIZE];
uint8_t decoded_buff[FURI_HAL_COMPRESS_ICON_DECODED_BUFF_SIZE];
} FuriHalCompressIcon;
struct FuriHalCompress {
heatshrink_encoder* encoder;
heatshrink_decoder* decoder;
uint8_t* compress_buff;
uint16_t compress_buff_size;
};
static FuriHalCompressIcon* icon_decoder;
static void furi_hal_compress_reset(FuriHalCompress* compress) {
furi_assert(compress);
heatshrink_encoder_reset(compress->encoder);
heatshrink_decoder_reset(compress->decoder);
memset(compress->compress_buff, 0, compress->compress_buff_size);
}
void furi_hal_compress_icon_init() {
icon_decoder = furi_alloc(sizeof(FuriHalCompressIcon));
icon_decoder->decoder = heatshrink_decoder_alloc(
icon_decoder->compress_buff,
FURI_HAL_COMPRESS_ICON_ENCODED_BUFF_SIZE,
FURI_HAL_COMPRESS_EXP_BUFF_SIZE_LOG,
FURI_HAL_COMPRESS_LOOKAHEAD_BUFF_SIZE_LOG);
heatshrink_decoder_reset(icon_decoder->decoder);
memset(icon_decoder->decoded_buff, 0, sizeof(icon_decoder->decoded_buff));
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_compress_icon_decode(const uint8_t* icon_data, uint8_t** decoded_buff) {
furi_assert(icon_data);
furi_assert(decoded_buff);
FuriHalCompressHeader* header = (FuriHalCompressHeader*)icon_data;
if(header->is_compressed) {
size_t data_processed = 0;
heatshrink_decoder_sink(
icon_decoder->decoder,
(uint8_t*)&icon_data[4],
header->compressed_buff_size,
&data_processed);
while(1) {
HSD_poll_res res = heatshrink_decoder_poll(
icon_decoder->decoder,
icon_decoder->decoded_buff,
sizeof(icon_decoder->decoded_buff),
&data_processed);
furi_assert((res == HSDR_POLL_EMPTY) || (res == HSDR_POLL_MORE));
if(res != HSDR_POLL_MORE) {
break;
}
}
heatshrink_decoder_reset(icon_decoder->decoder);
memset(icon_decoder->compress_buff, 0, sizeof(icon_decoder->compress_buff));
*decoded_buff = icon_decoder->decoded_buff;
} else {
*decoded_buff = (uint8_t*)&icon_data[1];
}
}
FuriHalCompress* furi_hal_compress_alloc(uint16_t compress_buff_size) {
FuriHalCompress* compress = furi_alloc(sizeof(FuriHalCompress));
compress->compress_buff = furi_alloc(compress_buff_size + FURI_HAL_COMPRESS_EXP_BUFF_SIZE);
compress->encoder = heatshrink_encoder_alloc(
compress->compress_buff,
FURI_HAL_COMPRESS_EXP_BUFF_SIZE_LOG,
FURI_HAL_COMPRESS_LOOKAHEAD_BUFF_SIZE_LOG);
compress->decoder = heatshrink_decoder_alloc(
compress->compress_buff,
compress_buff_size,
FURI_HAL_COMPRESS_EXP_BUFF_SIZE_LOG,
FURI_HAL_COMPRESS_LOOKAHEAD_BUFF_SIZE_LOG);
return compress;
}
void furi_hal_compress_free(FuriHalCompress* compress) {
furi_assert(compress);
heatshrink_encoder_free(compress->encoder);
heatshrink_decoder_free(compress->decoder);
free(compress->compress_buff);
free(compress);
}
bool furi_hal_compress_encode(
FuriHalCompress* compress,
uint8_t* data_in,
size_t data_in_size,
uint8_t* data_out,
size_t data_out_size,
size_t* data_res_size) {
furi_assert(compress);
furi_assert(data_in);
furi_assert(data_in_size);
size_t sink_size = 0;
size_t poll_size = 0;
HSE_sink_res sink_res;
HSE_poll_res poll_res;
HSE_finish_res finish_res;
bool encode_failed = false;
size_t sunk = 0;
size_t res_buff_size = sizeof(FuriHalCompressHeader);
// Sink data to encoding buffer
while((sunk < data_in_size) && !encode_failed) {
sink_res = heatshrink_encoder_sink(
compress->encoder, &data_in[sunk], data_in_size - sunk, &sink_size);
if(sink_res != HSER_SINK_OK) {
encode_failed = true;
break;
}
sunk += sink_size;
do {
poll_res = heatshrink_encoder_poll(
compress->encoder,
&data_out[res_buff_size],
data_out_size - res_buff_size,
&poll_size);
if(poll_res < 0) {
encode_failed = true;
break;
}
res_buff_size += poll_size;
} while(poll_res == HSER_POLL_MORE);
}
// Notify sinking complete and poll encoded data
finish_res = heatshrink_encoder_finish(compress->encoder);
if(finish_res < 0) {
encode_failed = true;
} else {
do {
poll_res = heatshrink_encoder_poll(
compress->encoder,
&data_out[res_buff_size],
data_out_size - 4 - res_buff_size,
&poll_size);
if(poll_res < 0) {
encode_failed = true;
break;
}
res_buff_size += poll_size;
finish_res = heatshrink_encoder_finish(compress->encoder);
} while(finish_res != HSER_FINISH_DONE);
}
bool result = true;
// Write encoded data to output buffer if compression is efficient. Else - write header and original data
if(!encode_failed && (res_buff_size < data_in_size + 1)) {
FuriHalCompressHeader header = {
.is_compressed = 0x01, .reserved = 0x00, .compressed_buff_size = res_buff_size};
memcpy(data_out, &header, sizeof(header));
*data_res_size = res_buff_size;
} else if(data_out_size > data_in_size) {
data_out[0] = 0x00;
memcpy(&data_out[1], data_in, data_in_size);
*data_res_size = data_in_size + 1;
} else {
*data_res_size = 0;
result = false;
}
furi_hal_compress_reset(compress);
return result;
}
bool furi_hal_compress_decode(
FuriHalCompress* compress,
uint8_t* data_in,
size_t data_in_size,
uint8_t* data_out,
size_t data_out_size,
size_t* data_res_size) {
furi_assert(compress);
furi_assert(data_in);
furi_assert(data_out);
furi_assert(data_res_size);
bool result = false;
bool decode_failed = false;
HSD_sink_res sink_res;
HSD_poll_res poll_res;
HSD_finish_res finish_res;
size_t sink_size = 0;
size_t res_buff_size = 0;
size_t poll_size = 0;
FuriHalCompressHeader* header = (FuriHalCompressHeader*)data_in;
if(header->is_compressed) {
// Sink data to decoding buffer
size_t compressed_size = header->compressed_buff_size;
size_t sunk = sizeof(FuriHalCompressHeader);
while(sunk < compressed_size && !decode_failed) {
sink_res = heatshrink_decoder_sink(
compress->decoder, &data_in[sunk], compressed_size - sunk, &sink_size);
if(sink_res < 0) {
decode_failed = true;
break;
}
sunk += sink_size;
do {
poll_res = heatshrink_decoder_poll(
compress->decoder, &data_out[res_buff_size], data_out_size, &poll_size);
if(poll_res < 0) {
decode_failed = true;
break;
}
res_buff_size += poll_size;
} while(poll_res == HSDR_POLL_MORE);
}
// Notify sinking complete and poll decoded data
if(!decode_failed) {
finish_res = heatshrink_decoder_finish(compress->decoder);
if(finish_res < 0) {
decode_failed = true;
} else {
do {
poll_res = heatshrink_decoder_poll(
compress->decoder, &data_out[res_buff_size], data_out_size, &poll_size);
res_buff_size += poll_size;
finish_res = heatshrink_decoder_finish(compress->decoder);
} while(finish_res != HSDR_FINISH_DONE);
}
}
*data_res_size = res_buff_size;
result = !decode_failed;
} else if(data_out_size >= data_in_size - 1) {
memcpy(data_out, &data_in[1], data_in_size);
*data_res_size = data_in_size - 1;
result = true;
} else {
result = false;
}
furi_hal_compress_reset(compress);
return result;
}
@@ -0,0 +1,78 @@
#include <furi_hal_console.h>
#include <furi_hal_uart.h>
#include <stdbool.h>
#include <stm32wbxx_ll_gpio.h>
#include <stm32wbxx_ll_usart.h>
#include <m-string.h>
#include <utilities_conf.h>
#include <furi.h>
#define TAG "FuriHalConsole"
#define CONSOLE_BAUDRATE 230400
volatile bool furi_hal_console_alive = false;
void furi_hal_console_init() {
furi_hal_uart_init(FuriHalUartIdUSART1, CONSOLE_BAUDRATE);
furi_hal_console_alive = true;
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_console_enable() {
furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, NULL, NULL);
while(!LL_USART_IsActiveFlag_TC(USART1))
;
furi_hal_uart_set_br(FuriHalUartIdUSART1, CONSOLE_BAUDRATE);
furi_hal_console_alive = true;
}
void furi_hal_console_disable() {
while(!LL_USART_IsActiveFlag_TC(USART1))
;
furi_hal_console_alive = false;
}
void furi_hal_console_tx(const uint8_t* buffer, size_t buffer_size) {
if(!furi_hal_console_alive) return;
FURI_CRITICAL_ENTER();
// Transmit data
furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t*)buffer, buffer_size);
// Wait for TC flag to be raised for last char
while(!LL_USART_IsActiveFlag_TC(USART1))
;
FURI_CRITICAL_EXIT();
}
void furi_hal_console_tx_with_new_line(const uint8_t* buffer, size_t buffer_size) {
if(!furi_hal_console_alive) return;
FURI_CRITICAL_ENTER();
// Transmit data
furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t*)buffer, buffer_size);
// Transmit new line symbols
furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t*)"\r\n", 2);
// Wait for TC flag to be raised for last char
while(!LL_USART_IsActiveFlag_TC(USART1))
;
FURI_CRITICAL_EXIT();
}
void furi_hal_console_printf(const char format[], ...) {
string_t string;
va_list args;
va_start(args, format);
string_init_vprintf(string, format, args);
va_end(args);
furi_hal_console_tx((const uint8_t*)string_get_cstr(string), string_size(string));
string_clear(string);
}
void furi_hal_console_puts(const char* data) {
furi_hal_console_tx((const uint8_t*)data, strlen(data));
}
@@ -0,0 +1,32 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
void furi_hal_console_init();
void furi_hal_console_enable();
void furi_hal_console_disable();
void furi_hal_console_tx(const uint8_t* buffer, size_t buffer_size);
void furi_hal_console_tx_with_new_line(const uint8_t* buffer, size_t buffer_size);
/**
* Printf-like plain uart interface
* @warning Will not work in ISR context
* @param format
* @param ...
*/
void furi_hal_console_printf(const char format[], ...);
void furi_hal_console_puts(const char* data);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,203 @@
#include <furi_hal_crypto.h>
#include <furi_hal_bt.h>
#include <furi_hal_random.h>
#include <furi.h>
#include <shci.h>
#define TAG "FuriHalCrypto"
CRYP_HandleTypeDef crypt;
#define ENCLAVE_FACTORY_KEY_SLOTS 10
#define ENCLAVE_SIGNATURE_SIZE 16
static const uint8_t enclave_signature_iv[ENCLAVE_FACTORY_KEY_SLOTS][16] = {
{0xac, 0x5d, 0x68, 0xb8, 0x79, 0x74, 0xfc, 0x7f, 0x45, 0x02, 0x82, 0xf1, 0x48, 0x7e, 0x75, 0x8a},
{0x38, 0xe6, 0x6a, 0x90, 0x5e, 0x5b, 0x8a, 0xa6, 0x70, 0x30, 0x04, 0x72, 0xc2, 0x42, 0xea, 0xaf},
{0x73, 0xd5, 0x8e, 0xfb, 0x0f, 0x4b, 0xa9, 0x79, 0x0f, 0xde, 0x0e, 0x53, 0x44, 0x7d, 0xaa, 0xfd},
{0x3c, 0x9a, 0xf4, 0x43, 0x2b, 0xfe, 0xea, 0xae, 0x8c, 0xc6, 0xd1, 0x60, 0xd2, 0x96, 0x64, 0xa9},
{0x10, 0xac, 0x7b, 0x63, 0x03, 0x7f, 0x43, 0x18, 0xec, 0x9d, 0x9c, 0xc4, 0x01, 0xdc, 0x35, 0xa7},
{0x26, 0x21, 0x64, 0xe6, 0xd0, 0xf2, 0x47, 0x49, 0xdc, 0x36, 0xcd, 0x68, 0x0c, 0x91, 0x03, 0x44},
{0x7a, 0xbd, 0xce, 0x9c, 0x24, 0x7a, 0x2a, 0xb1, 0x3c, 0x4f, 0x5a, 0x7d, 0x80, 0x3e, 0xfc, 0x0d},
{0xcd, 0xdd, 0xd3, 0x02, 0x85, 0x65, 0x43, 0x83, 0xf9, 0xac, 0x75, 0x2f, 0x21, 0xef, 0x28, 0x6b},
{0xab, 0x73, 0x70, 0xe8, 0xe2, 0x56, 0x0f, 0x58, 0xab, 0x29, 0xa5, 0xb1, 0x13, 0x47, 0x5e, 0xe8},
{0x4f, 0x3c, 0x43, 0x77, 0xde, 0xed, 0x79, 0xa1, 0x8d, 0x4c, 0x1f, 0xfd, 0xdb, 0x96, 0x87, 0x2e},
};
static const uint8_t enclave_signature_input[ENCLAVE_FACTORY_KEY_SLOTS][ENCLAVE_SIGNATURE_SIZE] = {
{0x9f, 0x5c, 0xb1, 0x43, 0x17, 0x53, 0x18, 0x8c, 0x66, 0x3d, 0x39, 0x45, 0x90, 0x13, 0xa9, 0xde},
{0xc5, 0x98, 0xe9, 0x17, 0xb8, 0x97, 0x9e, 0x03, 0x33, 0x14, 0x13, 0x8f, 0xce, 0x74, 0x0d, 0x54},
{0x34, 0xba, 0x99, 0x59, 0x9f, 0x70, 0x67, 0xe9, 0x09, 0xee, 0x64, 0x0e, 0xb3, 0xba, 0xfb, 0x75},
{0xdc, 0xfa, 0x6c, 0x9a, 0x6f, 0x0a, 0x3e, 0xdc, 0x42, 0xf6, 0xae, 0x0d, 0x3c, 0xf7, 0x83, 0xaf},
{0xea, 0x2d, 0xe3, 0x1f, 0x02, 0x99, 0x1a, 0x7e, 0x6d, 0x93, 0x4c, 0xb5, 0x42, 0xf0, 0x7a, 0x9b},
{0x53, 0x5e, 0x04, 0xa2, 0x49, 0xa0, 0x73, 0x49, 0x56, 0xb0, 0x88, 0x8c, 0x12, 0xa0, 0xe4, 0x18},
{0x7d, 0xa7, 0xc5, 0x21, 0x7f, 0x12, 0x95, 0xdd, 0x4d, 0x77, 0x01, 0xfa, 0x71, 0x88, 0x2b, 0x7f},
{0xdc, 0x9b, 0xc5, 0xa7, 0x6b, 0x84, 0x5c, 0x37, 0x7c, 0xec, 0x05, 0xa1, 0x9f, 0x91, 0x17, 0x3b},
{0xea, 0xcf, 0xd9, 0x9b, 0x86, 0xcd, 0x2b, 0x43, 0x54, 0x45, 0x82, 0xc6, 0xfe, 0x73, 0x1a, 0x1a},
{0x77, 0xb8, 0x1b, 0x90, 0xb4, 0xb7, 0x32, 0x76, 0x8f, 0x8a, 0x57, 0x06, 0xc7, 0xdd, 0x08, 0x90},
};
static const uint8_t enclave_signature_expected[ENCLAVE_FACTORY_KEY_SLOTS][ENCLAVE_SIGNATURE_SIZE] = {
{0xe9, 0x9a, 0xce, 0xe9, 0x4d, 0xe1, 0x7f, 0x55, 0xcb, 0x8a, 0xbf, 0xf2, 0x4d, 0x98, 0x27, 0x67},
{0x34, 0x27, 0xa7, 0xea, 0xa8, 0x98, 0x66, 0x9b, 0xed, 0x43, 0xd3, 0x93, 0xb5, 0xa2, 0x87, 0x8e},
{0x6c, 0xf3, 0x01, 0x78, 0x53, 0x1b, 0x11, 0x32, 0xf0, 0x27, 0x2f, 0xe3, 0x7d, 0xa6, 0xe2, 0xfd},
{0xdf, 0x7f, 0x37, 0x65, 0x2f, 0xdb, 0x7c, 0xcf, 0x5b, 0xb6, 0xe4, 0x9c, 0x63, 0xc5, 0x0f, 0xe0},
{0x9b, 0x5c, 0xee, 0x44, 0x0e, 0xd1, 0xcb, 0x5f, 0x28, 0x9f, 0x12, 0x17, 0x59, 0x64, 0x40, 0xbb},
{0x94, 0xc2, 0x09, 0x98, 0x62, 0xa7, 0x2b, 0x93, 0xed, 0x36, 0x1f, 0x10, 0xbc, 0x26, 0xbd, 0x41},
{0x4d, 0xb2, 0x2b, 0xc5, 0x96, 0x47, 0x61, 0xf4, 0x16, 0xe0, 0x81, 0xc3, 0x8e, 0xb9, 0x9c, 0x9b},
{0xc3, 0x6b, 0x83, 0x55, 0x90, 0x38, 0x0f, 0xea, 0xd1, 0x65, 0xbf, 0x32, 0x4f, 0x8e, 0x62, 0x5b},
{0x8d, 0x5e, 0x27, 0xbc, 0x14, 0x4f, 0x08, 0xa8, 0x2b, 0x14, 0x89, 0x5e, 0xdf, 0x77, 0x04, 0x31},
{0xc9, 0xf7, 0x03, 0xf1, 0x6c, 0x65, 0xad, 0x49, 0x74, 0xbe, 0x00, 0x54, 0xfd, 0xa6, 0x9c, 0x32},
};
void furi_hal_crypto_init() {
FURI_LOG_I(TAG, "Init OK");
}
static bool furi_hal_crypto_generate_unique_keys(uint8_t start_slot, uint8_t end_slot) {
FuriHalCryptoKey key;
uint8_t key_data[32];
FURI_LOG_I(TAG, "Generating keys %u..%u", start_slot, end_slot);
for(uint8_t slot = start_slot; slot <= end_slot; slot++) {
key.type = FuriHalCryptoKeyTypeSimple;
key.size = FuriHalCryptoKeySize256;
key.data = key_data;
furi_hal_random_fill_buf(key_data, 32);
if(!furi_hal_crypto_store_add_key(&key, &slot)) {
FURI_LOG_E(TAG, "Error writing key to slot %u", slot);
return false;
}
}
return true;
}
bool furi_hal_crypto_verify_key(uint8_t key_slot) {
uint8_t keys_nb = 0;
uint8_t valid_keys_nb = 0;
uint8_t last_valid_slot = ENCLAVE_FACTORY_KEY_SLOTS;
uint8_t empty_iv[16];
furi_hal_crypto_verify_enclave(&keys_nb, &valid_keys_nb);
if(key_slot <= ENCLAVE_FACTORY_KEY_SLOTS) { // It's a factory key
if(key_slot > keys_nb) return false;
} else { // Unique key
if(keys_nb < ENCLAVE_FACTORY_KEY_SLOTS) // Some factory keys are missing
return false;
for(uint8_t i = key_slot; i > ENCLAVE_FACTORY_KEY_SLOTS; i--) {
if(furi_hal_crypto_store_load_key(i, empty_iv)) {
last_valid_slot = i;
furi_hal_crypto_store_unload_key(i);
break;
}
}
if(last_valid_slot == key_slot)
return true;
else // Generate missing unique keys
return furi_hal_crypto_generate_unique_keys(last_valid_slot + 1, key_slot);
}
return true;
}
bool furi_hal_crypto_verify_enclave(uint8_t* keys_nb, uint8_t* valid_keys_nb) {
furi_assert(keys_nb);
furi_assert(valid_keys_nb);
uint8_t keys = 0;
uint8_t keys_valid = 0;
uint8_t buffer[ENCLAVE_SIGNATURE_SIZE];
for(size_t key_slot = 0; key_slot < ENCLAVE_FACTORY_KEY_SLOTS; key_slot++) {
if(furi_hal_crypto_store_load_key(key_slot + 1, enclave_signature_iv[key_slot])) {
keys++;
if(furi_hal_crypto_encrypt(
enclave_signature_input[key_slot], buffer, ENCLAVE_SIGNATURE_SIZE)) {
keys_valid +=
memcmp(buffer, enclave_signature_expected[key_slot], ENCLAVE_SIGNATURE_SIZE) ==
0;
}
furi_hal_crypto_store_unload_key(key_slot + 1);
}
}
*keys_nb = keys;
*valid_keys_nb = keys_valid;
if(*valid_keys_nb == ENCLAVE_FACTORY_KEY_SLOTS)
return true;
else
return false;
}
bool furi_hal_crypto_store_add_key(FuriHalCryptoKey* key, uint8_t* slot) {
furi_assert(key);
furi_assert(slot);
if(!furi_hal_bt_is_alive()) {
return false;
}
SHCI_C2_FUS_StoreUsrKey_Cmd_Param_t pParam;
size_t key_data_size = 0;
if(key->type == FuriHalCryptoKeyTypeMaster) {
pParam.KeyType = KEYTYPE_MASTER;
} else if(key->type == FuriHalCryptoKeyTypeSimple) {
pParam.KeyType = KEYTYPE_SIMPLE;
} else if(key->type == FuriHalCryptoKeyTypeEncrypted) {
pParam.KeyType = KEYTYPE_ENCRYPTED;
key_data_size += 12;
} else {
furi_crash("Incorrect key type");
}
if(key->size == FuriHalCryptoKeySize128) {
pParam.KeySize = KEYSIZE_16;
key_data_size += 16;
} else if(key->size == FuriHalCryptoKeySize256) {
pParam.KeySize = KEYSIZE_32;
key_data_size += 32;
} else {
furi_crash("Incorrect key size");
}
memcpy(pParam.KeyData, key->data, key_data_size);
return SHCI_C2_FUS_StoreUsrKey(&pParam, slot) == SHCI_Success;
}
bool furi_hal_crypto_store_load_key(uint8_t slot, const uint8_t* iv) {
furi_assert(slot > 0 && slot <= 100);
if(!furi_hal_bt_is_alive()) {
return false;
}
crypt.Instance = AES1;
crypt.Init.DataType = CRYP_DATATYPE_32B;
crypt.Init.KeySize = CRYP_KEYSIZE_256B;
crypt.Init.Algorithm = CRYP_AES_CBC;
crypt.Init.pInitVect = (uint32_t*)iv;
crypt.Init.KeyIVConfigSkip = CRYP_KEYIVCONFIG_ONCE;
crypt.Init.pKey = NULL;
furi_check(HAL_CRYP_Init(&crypt) == HAL_OK);
if(SHCI_C2_FUS_LoadUsrKey(slot) == SHCI_Success) {
return true;
} else {
furi_check(HAL_CRYP_DeInit(&crypt) == HAL_OK);
return false;
}
}
bool furi_hal_crypto_store_unload_key(uint8_t slot) {
if(!furi_hal_bt_is_alive()) {
return false;
}
furi_check(HAL_CRYP_DeInit(&crypt) == HAL_OK);
return SHCI_C2_FUS_UnloadUsrKey(slot) == SHCI_Success;
}
bool furi_hal_crypto_encrypt(const uint8_t* input, uint8_t* output, size_t size) {
return HAL_CRYP_Encrypt(&crypt, (uint32_t*)input, size / 4, (uint32_t*)output, 1000) == HAL_OK;
}
bool furi_hal_crypto_decrypt(const uint8_t* input, uint8_t* output, size_t size) {
return HAL_CRYP_Decrypt(&crypt, (uint32_t*)input, size / 4, (uint32_t*)output, 1000) == HAL_OK;
}
@@ -0,0 +1,36 @@
#include "furi_hal_delay.h"
#include <furi.h>
#include <cmsis_os2.h>
#define TAG "FuriHalDelay"
static uint32_t clk_per_microsecond;
void furi_hal_delay_init(void) {
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
DWT->CYCCNT = 0U;
clk_per_microsecond = SystemCoreClock / 1000000.0f;
FURI_LOG_I(TAG, "Init OK");
}
void delay_us(float microseconds) {
uint32_t start = DWT->CYCCNT;
uint32_t time_ticks = microseconds * clk_per_microsecond;
while((DWT->CYCCNT - start) < time_ticks) {
};
}
// cannot be used in ISR
// TODO add delay_ISR variant
void delay(float milliseconds) {
uint32_t ticks = milliseconds / (1000.0f / osKernelGetTickFreq());
osStatus_t result = osDelay(ticks);
(void)result;
furi_assert(result == osOK);
}
uint32_t millis(void) {
return HAL_GetTick();
}
@@ -0,0 +1,302 @@
#include <furi_hal_flash.h>
#include <furi_hal_bt.h>
#include <furi.h>
#include <ble.h>
#include <shci.h>
#include <stm32wbxx.h>
#define FURI_HAL_TAG "FuriHalFlash"
#define FURI_HAL_CRITICAL_MSG "Critical flash operation fail"
#define FURI_HAL_FLASH_READ_BLOCK 8
#define FURI_HAL_FLASH_WRITE_BLOCK 8
#define FURI_HAL_FLASH_PAGE_SIZE 4096
#define FURI_HAL_FLASH_CYCLES_COUNT 10000
/* Free flash space borders, exported by linker */
extern const void __free_flash_start__;
size_t furi_hal_flash_get_base() {
return FLASH_BASE;
}
size_t furi_hal_flash_get_read_block_size() {
return FURI_HAL_FLASH_READ_BLOCK;
}
size_t furi_hal_flash_get_write_block_size() {
return FURI_HAL_FLASH_WRITE_BLOCK;
}
size_t furi_hal_flash_get_page_size() {
return FURI_HAL_FLASH_PAGE_SIZE;
}
size_t furi_hal_flash_get_cycles_count() {
return FURI_HAL_FLASH_CYCLES_COUNT;
}
const void* furi_hal_flash_get_free_start_address() {
return &__free_flash_start__;
}
const void* furi_hal_flash_get_free_end_address() {
uint32_t sfr_reg_val = READ_REG(FLASH->SFR);
uint32_t sfsa = (READ_BIT(sfr_reg_val, FLASH_SFR_SFSA) >> FLASH_SFR_SFSA_Pos);
return (const void*)((sfsa * FLASH_PAGE_SIZE) + FLASH_BASE);
}
size_t furi_hal_flash_get_free_page_start_address() {
size_t start = (size_t)furi_hal_flash_get_free_start_address();
size_t page_start = start - start % FURI_HAL_FLASH_PAGE_SIZE;
if(page_start != start) {
page_start += FURI_HAL_FLASH_PAGE_SIZE;
}
return page_start;
}
size_t furi_hal_flash_get_free_page_count() {
size_t end = (size_t)furi_hal_flash_get_free_end_address();
size_t page_start = (size_t)furi_hal_flash_get_free_page_start_address();
return (end - page_start) / FURI_HAL_FLASH_PAGE_SIZE;
}
static void furi_hal_flash_unlock() {
/* verify Flash is locked */
furi_check(READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U);
/* Authorize the FLASH Registers access */
WRITE_REG(FLASH->KEYR, FLASH_KEY1);
WRITE_REG(FLASH->KEYR, FLASH_KEY2);
/* verify Flash is unlock */
furi_check(READ_BIT(FLASH->CR, FLASH_CR_LOCK) == 0U);
}
static void furi_hal_flash_lock(void) {
/* verify Flash is unlocked */
furi_check(READ_BIT(FLASH->CR, FLASH_CR_LOCK) == 0U);
/* Set the LOCK Bit to lock the FLASH Registers access */
/* @Note The lock and unlock procedure is done only using CR registers even from CPU2 */
SET_BIT(FLASH->CR, FLASH_CR_LOCK);
/* verify Flash is locked */
furi_check(READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U);
}
static void furi_hal_flash_begin_with_core2(bool erase_flag) {
// Take flash controller ownership
while(HAL_HSEM_FastTake(CFG_HW_FLASH_SEMID) != HAL_OK) {
taskYIELD();
}
// Unlock flash operation
furi_hal_flash_unlock();
// Erase activity notification
if(erase_flag) SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_ON);
while(true) {
// Wait till flash controller become usable
while(LL_FLASH_IsActiveFlag_OperationSuspended()) {
taskYIELD();
};
// Just a little more love
taskENTER_CRITICAL();
// Actually we already have mutex for it, but specification is specification
if(HAL_HSEM_IsSemTaken(CFG_HW_BLOCK_FLASH_REQ_BY_CPU1_SEMID)) {
taskEXIT_CRITICAL();
continue;
}
// Take sempahopre and prevent core2 from anyting funky
if(!HAL_HSEM_IsSemTaken(CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID)) {
if(HAL_HSEM_FastTake(CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID) != HAL_OK) {
taskEXIT_CRITICAL();
continue;
}
}
break;
}
}
static void furi_hal_flash_begin(bool erase_flag) {
// Acquire dangerous ops mutex
furi_hal_bt_lock_core2();
// If Core2 is running use IPC locking
if(furi_hal_bt_is_alive()) {
furi_hal_flash_begin_with_core2(erase_flag);
} else {
furi_hal_flash_unlock();
}
}
static void furi_hal_flash_end_with_core2(bool erase_flag) {
// Funky ops are ok at this point
HAL_HSEM_Release(CFG_HW_BLOCK_FLASH_REQ_BY_CPU2_SEMID, 0);
// Task switching is ok
taskEXIT_CRITICAL();
// Doesn't make much sense, does it?
while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY)) {
taskYIELD();
}
// Erase activity over, core2 can continue
if(erase_flag) SHCI_C2_FLASH_EraseActivity(ERASE_ACTIVITY_OFF);
// Lock flash controller
furi_hal_flash_lock();
// Release flash controller ownership
HAL_HSEM_Release(CFG_HW_FLASH_SEMID, 0);
}
static void furi_hal_flash_end(bool erase_flag) {
// If Core2 is running use IPC locking
if(furi_hal_bt_is_alive()) {
furi_hal_flash_end_with_core2(erase_flag);
} else {
furi_hal_flash_lock();
}
// Release dangerous ops mutex
furi_hal_bt_unlock_core2();
}
static void furi_hal_flush_cache(void) {
/* Flush instruction cache */
if(READ_BIT(FLASH->ACR, FLASH_ACR_ICEN) == FLASH_ACR_ICEN) {
/* Disable instruction cache */
__HAL_FLASH_INSTRUCTION_CACHE_DISABLE();
/* Reset instruction cache */
__HAL_FLASH_INSTRUCTION_CACHE_RESET();
/* Enable instruction cache */
__HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
}
/* Flush data cache */
if(READ_BIT(FLASH->ACR, FLASH_ACR_DCEN) == FLASH_ACR_DCEN) {
/* Disable data cache */
__HAL_FLASH_DATA_CACHE_DISABLE();
/* Reset data cache */
__HAL_FLASH_DATA_CACHE_RESET();
/* Enable data cache */
__HAL_FLASH_DATA_CACHE_ENABLE();
}
}
HAL_StatusTypeDef furi_hal_flash_wait_last_operation(uint32_t timeout) {
uint32_t error = 0;
uint32_t countdown = 0;
// Wait for the FLASH operation to complete by polling on BUSY flag to be reset.
// Even if the FLASH operation fails, the BUSY flag will be reset and an error
// flag will be set
countdown = timeout;
while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY)) {
if(LL_SYSTICK_IsActiveCounterFlag()) {
countdown--;
}
if(countdown == 0) {
return HAL_TIMEOUT;
}
}
/* Check FLASH operation error flags */
error = FLASH->SR;
/* Check FLASH End of Operation flag */
if((error & FLASH_FLAG_EOP) != 0U) {
/* Clear FLASH End of Operation pending bit */
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
}
/* Now update error variable to only error value */
error &= FLASH_FLAG_SR_ERRORS;
furi_check(error == 0);
/* clear error flags */
__HAL_FLASH_CLEAR_FLAG(error);
/* Wait for control register to be written */
countdown = timeout;
while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_CFGBSY)) {
if(LL_SYSTICK_IsActiveCounterFlag()) {
countdown--;
}
if(countdown == 0) {
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
bool furi_hal_flash_erase(uint8_t page) {
furi_hal_flash_begin(true);
// Ensure that controller state is valid
furi_check(FLASH->SR == 0);
/* Verify that next operation can be proceed */
furi_check(furi_hal_flash_wait_last_operation(FLASH_TIMEOUT_VALUE) == HAL_OK);
/* Select page and start operation */
MODIFY_REG(
FLASH->CR, FLASH_CR_PNB, ((page << FLASH_CR_PNB_Pos) | FLASH_CR_PER | FLASH_CR_STRT));
/* Wait for last operation to be completed */
furi_check(furi_hal_flash_wait_last_operation(FLASH_TIMEOUT_VALUE) == HAL_OK);
/* If operation is completed or interrupted, disable the Page Erase Bit */
CLEAR_BIT(FLASH->CR, (FLASH_CR_PER | FLASH_CR_PNB));
/* Flush the caches to be sure of the data consistency */
furi_hal_flush_cache();
furi_hal_flash_end(true);
return true;
}
bool furi_hal_flash_write_dword(size_t address, uint64_t data) {
furi_hal_flash_begin(false);
// Ensure that controller state is valid
furi_check(FLASH->SR == 0);
/* Check the parameters */
furi_check(IS_ADDR_ALIGNED_64BITS(address));
furi_check(IS_FLASH_PROGRAM_ADDRESS(address));
/* Set PG bit */
SET_BIT(FLASH->CR, FLASH_CR_PG);
/* Program first word */
*(uint32_t*)address = (uint32_t)data;
// Barrier to ensure programming is performed in 2 steps, in right order
// (independently of compiler optimization behavior)
__ISB();
/* Program second word */
*(uint32_t*)(address + 4U) = (uint32_t)(data >> 32U);
/* Wait for last operation to be completed */
furi_check(furi_hal_flash_wait_last_operation(FLASH_TIMEOUT_VALUE) == HAL_OK);
/* If the program operation is completed, disable the PG or FSTPG Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_PG);
furi_hal_flash_end(false);
return true;
}
@@ -0,0 +1,80 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
/** Get flash base address
*
* @return pointer to flash base
*/
size_t furi_hal_flash_get_base();
/** Get flash read block size
*
* @return size in bytes
*/
size_t furi_hal_flash_get_read_block_size();
/** Get flash write block size
*
* @return size in bytes
*/
size_t furi_hal_flash_get_write_block_size();
/** Get flash page size
*
* @return size in bytes
*/
size_t furi_hal_flash_get_page_size();
/** Get expected flash cycles count
*
* @return count of erase-write operations
*/
size_t furi_hal_flash_get_cycles_count();
/** Get free flash start address
*
* @return pointer to free region start
*/
const void* furi_hal_flash_get_free_start_address();
/** Get free flash end address
*
* @return pointer to free region end
*/
const void* furi_hal_flash_get_free_end_address();
/** Get first free page start address
*
* @return first free page memory address
*/
size_t furi_hal_flash_get_free_page_start_address();
/** Get free page count
*
* @return free page count
*/
size_t furi_hal_flash_get_free_page_count();
/** Erase Flash
*
* @warning locking operation with critical section, stales execution
*
* @param page The page to erase
*
* @return true on success
*/
bool furi_hal_flash_erase(uint8_t page);
/** Write double word (64 bits)
*
* @warning locking operation with critical section, stales execution
*
* @param address destination address, must be double word aligned.
* @param data data to write
*
* @return true on success
*/
bool furi_hal_flash_write_dword(size_t address, uint64_t data);
@@ -0,0 +1,299 @@
#include <furi.h>
#include <furi_hal_gpio.h>
#include <furi_hal_version.h>
#define GET_SYSCFG_EXTI_PORT(gpio) \
(((gpio) == (GPIOA)) ? LL_SYSCFG_EXTI_PORTA : \
((gpio) == (GPIOB)) ? LL_SYSCFG_EXTI_PORTB : \
((gpio) == (GPIOC)) ? LL_SYSCFG_EXTI_PORTC : \
((gpio) == (GPIOD)) ? LL_SYSCFG_EXTI_PORTD : \
((gpio) == (GPIOE)) ? LL_SYSCFG_EXTI_PORTE : \
LL_SYSCFG_EXTI_PORTH)
#define GPIO_PIN_MAP(pin, prefix) \
(((pin) == (LL_GPIO_PIN_0)) ? prefix##0 : \
((pin) == (LL_GPIO_PIN_1)) ? prefix##1 : \
((pin) == (LL_GPIO_PIN_2)) ? prefix##2 : \
((pin) == (LL_GPIO_PIN_3)) ? prefix##3 : \
((pin) == (LL_GPIO_PIN_4)) ? prefix##4 : \
((pin) == (LL_GPIO_PIN_5)) ? prefix##5 : \
((pin) == (LL_GPIO_PIN_6)) ? prefix##6 : \
((pin) == (LL_GPIO_PIN_7)) ? prefix##7 : \
((pin) == (LL_GPIO_PIN_8)) ? prefix##8 : \
((pin) == (LL_GPIO_PIN_9)) ? prefix##9 : \
((pin) == (LL_GPIO_PIN_10)) ? prefix##10 : \
((pin) == (LL_GPIO_PIN_11)) ? prefix##11 : \
((pin) == (LL_GPIO_PIN_12)) ? prefix##12 : \
((pin) == (LL_GPIO_PIN_13)) ? prefix##13 : \
((pin) == (LL_GPIO_PIN_14)) ? prefix##14 : \
prefix##15)
#define GET_SYSCFG_EXTI_LINE(pin) GPIO_PIN_MAP(pin, LL_SYSCFG_EXTI_LINE)
#define GET_EXTI_LINE(pin) GPIO_PIN_MAP(pin, LL_EXTI_LINE_)
static volatile GpioInterrupt gpio_interrupt[GPIO_NUMBER];
static uint8_t hal_gpio_get_pin_num(const GpioPin* gpio) {
uint8_t pin_num = 0;
for(pin_num = 0; pin_num < GPIO_NUMBER; pin_num++) {
if(gpio->pin & (1 << pin_num)) break;
}
return pin_num;
}
void hal_gpio_init_simple(const GpioPin* gpio, const GpioMode mode) {
hal_gpio_init(gpio, mode, GpioPullNo, GpioSpeedLow);
}
void hal_gpio_init(
const GpioPin* gpio,
const GpioMode mode,
const GpioPull pull,
const GpioSpeed speed) {
// we cannot set alternate mode in this function
furi_assert(mode != GpioModeAltFunctionPushPull);
furi_assert(mode != GpioModeAltFunctionOpenDrain);
hal_gpio_init_ex(gpio, mode, pull, speed, GpioAltFnUnused);
}
void hal_gpio_init_ex(
const GpioPin* gpio,
const GpioMode mode,
const GpioPull pull,
const GpioSpeed speed,
const GpioAltFn alt_fn) {
uint32_t sys_exti_port = GET_SYSCFG_EXTI_PORT(gpio->port);
uint32_t sys_exti_line = GET_SYSCFG_EXTI_LINE(gpio->pin);
uint32_t exti_line = GET_EXTI_LINE(gpio->pin);
// Configure gpio with interrupts disabled
__disable_irq();
// Set gpio speed
if(speed == GpioSpeedLow) {
LL_GPIO_SetPinSpeed(gpio->port, gpio->pin, LL_GPIO_SPEED_FREQ_LOW);
} else if(speed == GpioSpeedMedium) {
LL_GPIO_SetPinSpeed(gpio->port, gpio->pin, LL_GPIO_SPEED_FREQ_MEDIUM);
} else if(speed == GpioSpeedHigh) {
LL_GPIO_SetPinSpeed(gpio->port, gpio->pin, LL_GPIO_SPEED_FREQ_HIGH);
} else {
LL_GPIO_SetPinSpeed(gpio->port, gpio->pin, LL_GPIO_SPEED_FREQ_VERY_HIGH);
}
// Set gpio pull mode
if(pull == GpioPullNo) {
LL_GPIO_SetPinPull(gpio->port, gpio->pin, LL_GPIO_PULL_NO);
} else if(pull == GpioPullUp) {
LL_GPIO_SetPinPull(gpio->port, gpio->pin, LL_GPIO_PULL_UP);
} else {
LL_GPIO_SetPinPull(gpio->port, gpio->pin, LL_GPIO_PULL_DOWN);
}
// Set gpio mode
if(mode >= GpioModeInterruptRise) {
// Set pin in interrupt mode
LL_GPIO_SetPinMode(gpio->port, gpio->pin, LL_GPIO_MODE_INPUT);
LL_SYSCFG_SetEXTISource(sys_exti_port, sys_exti_line);
if(mode == GpioModeInterruptRise || mode == GpioModeInterruptRiseFall) {
LL_EXTI_EnableIT_0_31(exti_line);
LL_EXTI_EnableRisingTrig_0_31(exti_line);
}
if(mode == GpioModeInterruptFall || mode == GpioModeInterruptRiseFall) {
LL_EXTI_EnableIT_0_31(exti_line);
LL_EXTI_EnableFallingTrig_0_31(exti_line);
}
if(mode == GpioModeEventRise || mode == GpioModeInterruptRiseFall) {
LL_EXTI_EnableEvent_0_31(exti_line);
LL_EXTI_EnableRisingTrig_0_31(exti_line);
}
if(mode == GpioModeEventFall || mode == GpioModeInterruptRiseFall) {
LL_EXTI_EnableEvent_0_31(exti_line);
LL_EXTI_EnableFallingTrig_0_31(exti_line);
}
} else {
// Disable interrupt if it was set
if(LL_SYSCFG_GetEXTISource(sys_exti_line) == sys_exti_port &&
LL_EXTI_IsEnabledIT_0_31(exti_line)) {
LL_EXTI_DisableIT_0_31(exti_line);
LL_EXTI_DisableRisingTrig_0_31(exti_line);
LL_EXTI_DisableFallingTrig_0_31(exti_line);
}
// Set not interrupt pin modes
if(mode == GpioModeInput) {
LL_GPIO_SetPinMode(gpio->port, gpio->pin, LL_GPIO_MODE_INPUT);
} else if(mode == GpioModeOutputPushPull || mode == GpioModeAltFunctionPushPull) {
LL_GPIO_SetPinMode(gpio->port, gpio->pin, LL_GPIO_MODE_OUTPUT);
LL_GPIO_SetPinOutputType(gpio->port, gpio->pin, LL_GPIO_OUTPUT_PUSHPULL);
} else if(mode == GpioModeOutputOpenDrain || mode == GpioModeAltFunctionOpenDrain) {
LL_GPIO_SetPinMode(gpio->port, gpio->pin, LL_GPIO_MODE_OUTPUT);
LL_GPIO_SetPinOutputType(gpio->port, gpio->pin, LL_GPIO_OUTPUT_OPENDRAIN);
} else if(mode == GpioModeAnalog) {
LL_GPIO_SetPinMode(gpio->port, gpio->pin, LL_GPIO_MODE_ANALOG);
}
}
if(mode == GpioModeAltFunctionPushPull || mode == GpioModeAltFunctionOpenDrain) {
// enable alternate mode
LL_GPIO_SetPinMode(gpio->port, gpio->pin, LL_GPIO_MODE_ALTERNATE);
// set alternate function
if(hal_gpio_get_pin_num(gpio) < 8) {
LL_GPIO_SetAFPin_0_7(gpio->port, gpio->pin, alt_fn);
} else {
LL_GPIO_SetAFPin_8_15(gpio->port, gpio->pin, alt_fn);
}
}
__enable_irq();
}
void hal_gpio_add_int_callback(const GpioPin* gpio, GpioExtiCallback cb, void* ctx) {
furi_assert(gpio);
furi_assert(cb);
__disable_irq();
uint8_t pin_num = hal_gpio_get_pin_num(gpio);
furi_assert(gpio_interrupt[pin_num].callback == NULL);
gpio_interrupt[pin_num].callback = cb;
gpio_interrupt[pin_num].context = ctx;
gpio_interrupt[pin_num].ready = true;
__enable_irq();
}
void hal_gpio_enable_int_callback(const GpioPin* gpio) {
furi_assert(gpio);
__disable_irq();
uint8_t pin_num = hal_gpio_get_pin_num(gpio);
if(gpio_interrupt[pin_num].callback) {
gpio_interrupt[pin_num].ready = true;
}
__enable_irq();
}
void hal_gpio_disable_int_callback(const GpioPin* gpio) {
furi_assert(gpio);
__disable_irq();
uint8_t pin_num = hal_gpio_get_pin_num(gpio);
gpio_interrupt[pin_num].ready = false;
__enable_irq();
}
void hal_gpio_remove_int_callback(const GpioPin* gpio) {
furi_assert(gpio);
__disable_irq();
uint8_t pin_num = hal_gpio_get_pin_num(gpio);
gpio_interrupt[pin_num].callback = NULL;
gpio_interrupt[pin_num].context = NULL;
gpio_interrupt[pin_num].ready = false;
__enable_irq();
}
static void hal_gpio_int_call(uint16_t pin_num) {
if(gpio_interrupt[pin_num].callback && gpio_interrupt[pin_num].ready) {
gpio_interrupt[pin_num].callback(gpio_interrupt[pin_num].context);
}
}
/* Interrupt handlers */
void EXTI0_IRQHandler(void) {
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_0)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_0);
hal_gpio_int_call(0);
}
}
void EXTI1_IRQHandler(void) {
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_1)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_1);
hal_gpio_int_call(1);
}
}
void EXTI2_IRQHandler(void) {
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_2)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_2);
hal_gpio_int_call(2);
}
}
void EXTI3_IRQHandler(void) {
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_3)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_3);
hal_gpio_int_call(3);
}
}
void EXTI4_IRQHandler(void) {
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_4)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_4);
hal_gpio_int_call(4);
}
}
void EXTI9_5_IRQHandler(void) {
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_5)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_5);
hal_gpio_int_call(5);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_6)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_6);
hal_gpio_int_call(6);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_7)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_7);
hal_gpio_int_call(7);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_8)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_8);
hal_gpio_int_call(8);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_9)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_9);
hal_gpio_int_call(9);
}
}
void EXTI15_10_IRQHandler(void) {
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_10)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_10);
hal_gpio_int_call(10);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_11)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_11);
hal_gpio_int_call(11);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_12)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_12);
hal_gpio_int_call(12);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_13)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_13);
hal_gpio_int_call(13);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_14)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_14);
hal_gpio_int_call(14);
}
if(LL_EXTI_IsActiveFlag_0_31(LL_EXTI_LINE_15)) {
LL_EXTI_ClearFlag_0_31(LL_EXTI_LINE_15);
hal_gpio_int_call(15);
}
}
extern COMP_HandleTypeDef hcomp1;
bool hal_gpio_get_rfid_in_level() {
bool value = false;
if(furi_hal_version_get_hw_version() > 7) {
value = (HAL_COMP_GetOutputLevel(&hcomp1) == COMP_OUTPUT_LEVEL_LOW);
} else {
value = (HAL_COMP_GetOutputLevel(&hcomp1) == COMP_OUTPUT_LEVEL_HIGH);
}
#ifdef INVERT_RFID_IN
return !value;
#else
return value;
#endif
}
@@ -0,0 +1,264 @@
#pragma once
#include "main.h"
#include "stdbool.h"
#include <stm32wbxx_ll_gpio.h>
#include <stm32wbxx_ll_system.h>
#include <stm32wbxx_ll_exti.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Number of gpio on one port
*/
#define GPIO_NUMBER (16U)
/**
* Interrupt callback prototype
*/
typedef void (*GpioExtiCallback)(void* ctx);
/**
* Gpio interrupt type
*/
typedef struct {
GpioExtiCallback callback;
void* context;
volatile bool ready;
} GpioInterrupt;
/**
* Gpio modes
*/
typedef enum {
GpioModeInput,
GpioModeOutputPushPull,
GpioModeOutputOpenDrain,
GpioModeAltFunctionPushPull,
GpioModeAltFunctionOpenDrain,
GpioModeAnalog,
GpioModeInterruptRise,
GpioModeInterruptFall,
GpioModeInterruptRiseFall,
GpioModeEventRise,
GpioModeEventFall,
GpioModeEventRiseFall,
} GpioMode;
/**
* Gpio pull modes
*/
typedef enum {
GpioPullNo,
GpioPullUp,
GpioPullDown,
} GpioPull;
/**
* Gpio speed modes
*/
typedef enum {
GpioSpeedLow,
GpioSpeedMedium,
GpioSpeedHigh,
GpioSpeedVeryHigh,
} GpioSpeed;
/**
* Gpio alternate functions
*/
typedef enum {
GpioAltFn0MCO = 0, /*!< MCO Alternate Function mapping */
GpioAltFn0LSCO = 0, /*!< LSCO Alternate Function mapping */
GpioAltFn0JTMS_SWDIO = 0, /*!< JTMS-SWDIO Alternate Function mapping */
GpioAltFn0JTCK_SWCLK = 0, /*!< JTCK-SWCLK Alternate Function mapping */
GpioAltFn0JTDI = 0, /*!< JTDI Alternate Function mapping */
GpioAltFn0RTC_OUT = 0, /*!< RCT_OUT Alternate Function mapping */
GpioAltFn0JTD_TRACE = 0, /*!< JTDO-TRACESWO Alternate Function mapping */
GpioAltFn0NJTRST = 0, /*!< NJTRST Alternate Function mapping */
GpioAltFn0RTC_REFIN = 0, /*!< RTC_REFIN Alternate Function mapping */
GpioAltFn0TRACED0 = 0, /*!< TRACED0 Alternate Function mapping */
GpioAltFn0TRACED1 = 0, /*!< TRACED1 Alternate Function mapping */
GpioAltFn0TRACED2 = 0, /*!< TRACED2 Alternate Function mapping */
GpioAltFn0TRACED3 = 0, /*!< TRACED3 Alternate Function mapping */
GpioAltFn0TRIG_INOUT = 0, /*!< TRIG_INOUT Alternate Function mapping */
GpioAltFn0TRACECK = 0, /*!< TRACECK Alternate Function mapping */
GpioAltFn0SYS = 0, /*!< System Function mapping */
GpioAltFn1TIM1 = 1, /*!< TIM1 Alternate Function mapping */
GpioAltFn1TIM2 = 1, /*!< TIM2 Alternate Function mapping */
GpioAltFn1LPTIM1 = 1, /*!< LPTIM1 Alternate Function mapping */
GpioAltFn2TIM2 = 2, /*!< TIM2 Alternate Function mapping */
GpioAltFn2TIM1 = 2, /*!< TIM1 Alternate Function mapping */
GpioAltFn3SAI1 = 3, /*!< SAI1_CK1 Alternate Function mapping */
GpioAltFn3SPI2 = 3, /*!< SPI2 Alternate Function mapping */
GpioAltFn3TIM1 = 3, /*!< TIM1 Alternate Function mapping */
GpioAltFn4I2C1 = 4, /*!< I2C1 Alternate Function mapping */
GpioAltFn4I2C3 = 4, /*!< I2C3 Alternate Function mapping */
GpioAltFn5SPI1 = 5, /*!< SPI1 Alternate Function mapping */
GpioAltFn5SPI2 = 5, /*!< SPI2 Alternate Function mapping */
GpioAltFn6MCO = 6, /*!< MCO Alternate Function mapping */
GpioAltFn6LSCO = 6, /*!< LSCO Alternate Function mapping */
GpioAltFn6RF_DTB0 = 6, /*!< RF_DTB0 Alternate Function mapping */
GpioAltFn6RF_DTB1 = 6, /*!< RF_DTB1 Alternate Function mapping */
GpioAltFn6RF_DTB2 = 6, /*!< RF_DTB2 Alternate Function mapping */
GpioAltFn6RF_DTB3 = 6, /*!< RF_DTB3 Alternate Function mapping */
GpioAltFn6RF_DTB4 = 6, /*!< RF_DTB4 Alternate Function mapping */
GpioAltFn6RF_DTB5 = 6, /*!< RF_DTB5 Alternate Function mapping */
GpioAltFn6RF_DTB6 = 6, /*!< RF_DTB6 Alternate Function mapping */
GpioAltFn6RF_DTB7 = 6, /*!< RF_DTB7 Alternate Function mapping */
GpioAltFn6RF_DTB8 = 6, /*!< RF_DTB8 Alternate Function mapping */
GpioAltFn6RF_DTB9 = 6, /*!< RF_DTB9 Alternate Function mapping */
GpioAltFn6RF_DTB10 = 6, /*!< RF_DTB10 Alternate Function mapping */
GpioAltFn6RF_DTB11 = 6, /*!< RF_DTB11 Alternate Function mapping */
GpioAltFn6RF_DTB12 = 6, /*!< RF_DTB12 Alternate Function mapping */
GpioAltFn6RF_DTB13 = 6, /*!< RF_DTB13 Alternate Function mapping */
GpioAltFn6RF_DTB14 = 6, /*!< RF_DTB14 Alternate Function mapping */
GpioAltFn6RF_DTB15 = 6, /*!< RF_DTB15 Alternate Function mapping */
GpioAltFn6RF_DTB16 = 6, /*!< RF_DTB16 Alternate Function mapping */
GpioAltFn6RF_DTB17 = 6, /*!< RF_DTB17 Alternate Function mapping */
GpioAltFn6RF_DTB18 = 6, /*!< RF_DTB18 Alternate Function mapping */
GpioAltFn6RF_MISO = 6, /*!< RF_MISO Alternate Function mapping */
GpioAltFn6RF_MOSI = 6, /*!< RF_MOSI Alternate Function mapping */
GpioAltFn6RF_SCK = 6, /*!< RF_SCK Alternate Function mapping */
GpioAltFn6RF_NSS = 6, /*!< RF_NSS Alternate Function mapping */
GpioAltFn7USART1 = 7, /*!< USART1 Alternate Function mapping */
GpioAltFn8LPUART1 = 8, /*!< LPUART1 Alternate Function mapping */
GpioAltFn8IR = 8, /*!< IR Alternate Function mapping */
GpioAltFn9TSC = 9, /*!< TSC Alternate Function mapping */
GpioAltFn10QUADSPI = 10, /*!< QUADSPI Alternate Function mapping */
GpioAltFn10USB = 10, /*!< USB Alternate Function mapping */
GpioAltFn11LCD = 11, /*!< LCD Alternate Function mapping */
GpioAltFn12COMP1 = 12, /*!< COMP1 Alternate Function mapping */
GpioAltFn12COMP2 = 12, /*!< COMP2 Alternate Function mapping */
GpioAltFn12TIM1 = 12, /*!< TIM1 Alternate Function mapping */
GpioAltFn13SAI1 = 13, /*!< SAI1 Alternate Function mapping */
GpioAltFn14TIM2 = 14, /*!< TIM2 Alternate Function mapping */
GpioAltFn14TIM16 = 14, /*!< TIM16 Alternate Function mapping */
GpioAltFn14TIM17 = 14, /*!< TIM17 Alternate Function mapping */
GpioAltFn14LPTIM2 = 14, /*!< LPTIM2 Alternate Function mapping */
GpioAltFn15EVENTOUT = 15, /*!< EVENTOUT Alternate Function mapping */
GpioAltFnUnused = 16, /*!< just dummy value */
} GpioAltFn;
/**
* Gpio structure
*/
typedef struct {
GPIO_TypeDef* port;
uint16_t pin;
} GpioPin;
/**
* GPIO initialization function, simple version
* @param gpio GpioPin
* @param mode GpioMode
*/
void hal_gpio_init_simple(const GpioPin* gpio, const GpioMode mode);
/**
* GPIO initialization function, normal version
* @param gpio GpioPin
* @param mode GpioMode
* @param pull GpioPull
* @param speed GpioSpeed
*/
void hal_gpio_init(
const GpioPin* gpio,
const GpioMode mode,
const GpioPull pull,
const GpioSpeed speed);
/**
* GPIO initialization function, extended version
* @param gpio GpioPin
* @param mode GpioMode
* @param pull GpioPull
* @param speed GpioSpeed
* @param alt_fn GpioAltFn
*/
void hal_gpio_init_ex(
const GpioPin* gpio,
const GpioMode mode,
const GpioPull pull,
const GpioSpeed speed,
const GpioAltFn alt_fn);
/**
* Add and enable interrupt
* @param gpio GpioPin
* @param cb GpioExtiCallback
* @param ctx context for callback
*/
void hal_gpio_add_int_callback(const GpioPin* gpio, GpioExtiCallback cb, void* ctx);
/**
* Enable interrupt
* @param gpio GpioPin
*/
void hal_gpio_enable_int_callback(const GpioPin* gpio);
/**
* Disable interrupt
* @param gpio GpioPin
*/
void hal_gpio_disable_int_callback(const GpioPin* gpio);
/**
* Remove interrupt
* @param gpio GpioPin
*/
void hal_gpio_remove_int_callback(const GpioPin* gpio);
/**
* GPIO write pin
* @param gpio GpioPin
* @param state true / false
*/
static inline void hal_gpio_write(const GpioPin* gpio, const bool state) {
// writing to BSSR is an atomic operation
if(state == true) {
gpio->port->BSRR = gpio->pin;
} else {
gpio->port->BSRR = (uint32_t)gpio->pin << GPIO_NUMBER;
}
}
/**
* GPIO read pin
* @param gpio GpioPin
* @return true / false
*/
static inline bool hal_gpio_read(const GpioPin* gpio) {
if((gpio->port->IDR & gpio->pin) != 0x00U) {
return true;
} else {
return false;
}
}
/**
* Get RFID IN level
* @return false = LOW, true = HIGH
*/
bool hal_gpio_get_rfid_in_level();
#ifdef __cplusplus
}
#endif
+159
View File
@@ -0,0 +1,159 @@
#include <furi_hal_i2c.h>
#include <furi_hal_version.h>
#include <stm32wbxx_ll_i2c.h>
#include <stm32wbxx_ll_gpio.h>
#include <stm32wbxx_ll_cortex.h>
#include <furi.h>
#define TAG "FuriHalI2C"
void furi_hal_i2c_init() {
furi_hal_i2c_bus_power.callback(&furi_hal_i2c_bus_power, FuriHalI2cBusEventInit);
furi_hal_i2c_bus_external.callback(&furi_hal_i2c_bus_external, FuriHalI2cBusEventInit);
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_i2c_acquire(FuriHalI2cBusHandle* handle) {
// Lock bus access
handle->bus->callback(handle->bus, FuriHalI2cBusEventLock);
// Ensuree that no active handle set
furi_check(handle->bus->current_handle == NULL);
// Set current handle
handle->bus->current_handle = handle;
// Activate bus
handle->bus->callback(handle->bus, FuriHalI2cBusEventActivate);
// Activate handle
handle->callback(handle, FuriHalI2cBusHandleEventActivate);
}
void furi_hal_i2c_release(FuriHalI2cBusHandle* handle) {
// Ensure that current handle is our handle
furi_check(handle->bus->current_handle == handle);
// Deactivate handle
handle->callback(handle, FuriHalI2cBusHandleEventDeactivate);
// Deactivate bus
handle->bus->callback(handle->bus, FuriHalI2cBusEventDeactivate);
// Reset current handle
handle->bus->current_handle = NULL;
// Unlock bus
handle->bus->callback(handle->bus, FuriHalI2cBusEventUnlock);
}
bool furi_hal_i2c_tx(
FuriHalI2cBusHandle* handle,
uint8_t address,
const uint8_t* data,
uint8_t size,
uint32_t timeout) {
furi_check(handle->bus->current_handle == handle);
furi_assert(timeout > 0);
bool ret = true;
uint32_t timeout_tick = HAL_GetTick() + timeout;
do {
while(LL_I2C_IsActiveFlag_BUSY(handle->bus->i2c)) {
if(HAL_GetTick() >= timeout_tick) {
ret = false;
break;
}
}
if(!ret) {
break;
}
LL_I2C_HandleTransfer(
handle->bus->i2c,
address,
LL_I2C_ADDRSLAVE_7BIT,
size,
LL_I2C_MODE_AUTOEND,
LL_I2C_GENERATE_START_WRITE);
while(!LL_I2C_IsActiveFlag_STOP(handle->bus->i2c) || size > 0) {
if(LL_I2C_IsActiveFlag_TXIS(handle->bus->i2c)) {
LL_I2C_TransmitData8(handle->bus->i2c, (*data));
data++;
size--;
}
if(HAL_GetTick() >= timeout_tick) {
ret = false;
break;
}
}
LL_I2C_ClearFlag_STOP(handle->bus->i2c);
} while(0);
return ret;
}
bool furi_hal_i2c_rx(
FuriHalI2cBusHandle* handle,
uint8_t address,
uint8_t* data,
uint8_t size,
uint32_t timeout) {
furi_check(handle->bus->current_handle == handle);
furi_assert(timeout > 0);
bool ret = true;
uint32_t timeout_tick = HAL_GetTick() + timeout;
do {
while(LL_I2C_IsActiveFlag_BUSY(handle->bus->i2c)) {
if(HAL_GetTick() >= timeout_tick) {
ret = false;
break;
}
}
if(!ret) {
break;
}
LL_I2C_HandleTransfer(
handle->bus->i2c,
address,
LL_I2C_ADDRSLAVE_7BIT,
size,
LL_I2C_MODE_AUTOEND,
LL_I2C_GENERATE_START_READ);
while(!LL_I2C_IsActiveFlag_STOP(handle->bus->i2c) || size > 0) {
if(LL_I2C_IsActiveFlag_RXNE(handle->bus->i2c)) {
*data = LL_I2C_ReceiveData8(handle->bus->i2c);
data++;
size--;
}
if(HAL_GetTick() >= timeout_tick) {
ret = false;
break;
}
}
LL_I2C_ClearFlag_STOP(handle->bus->i2c);
} while(0);
return ret;
}
bool furi_hal_i2c_trx(
FuriHalI2cBusHandle* handle,
uint8_t address,
const uint8_t* tx_data,
uint8_t tx_size,
uint8_t* rx_data,
uint8_t rx_size,
uint32_t timeout) {
if(furi_hal_i2c_tx(handle, address, tx_data, tx_size, timeout) &&
furi_hal_i2c_rx(handle, address, rx_data, rx_size, timeout)) {
return true;
} else {
return false;
}
}
@@ -0,0 +1,159 @@
#include "furi_hal_i2c_config.h"
#include <furi_hal_resources.h>
#include <furi_hal_version.h>
/** Timing register value is computed with the STM32CubeMX Tool,
* Standard Mode @100kHz with I2CCLK = 64 MHz,
* rise time = 0ns, fall time = 0ns
*/
#define FURI_HAL_I2C_CONFIG_POWER_I2C_TIMINGS_100 0x10707DBC
/** Timing register value is computed with the STM32CubeMX Tool,
* Fast Mode @400kHz with I2CCLK = 64 MHz,
* rise time = 0ns, fall time = 0ns
*/
#define FURI_HAL_I2C_CONFIG_POWER_I2C_TIMINGS_400 0x00602173
osMutexId_t furi_hal_i2c_bus_power_mutex = NULL;
static void furi_hal_i2c_bus_power_event(FuriHalI2cBus* bus, FuriHalI2cBusEvent event) {
if(event == FuriHalI2cBusEventInit) {
furi_hal_i2c_bus_power_mutex = osMutexNew(NULL);
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_I2C1);
LL_RCC_SetI2CClockSource(LL_RCC_I2C1_CLKSOURCE_PCLK1);
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C1);
FURI_CRITICAL_EXIT();
bus->current_handle = NULL;
} else if(event == FuriHalI2cBusEventDeinit) {
osMutexDelete(furi_hal_i2c_bus_power_mutex);
} else if(event == FuriHalI2cBusEventLock) {
furi_check(osMutexAcquire(furi_hal_i2c_bus_power_mutex, osWaitForever) == osOK);
} else if(event == FuriHalI2cBusEventUnlock) {
furi_check(osMutexRelease(furi_hal_i2c_bus_power_mutex) == osOK);
} else if(event == FuriHalI2cBusEventActivate) {
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C1);
FURI_CRITICAL_EXIT();
} else if(event == FuriHalI2cBusEventDeactivate) {
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C1);
FURI_CRITICAL_EXIT();
}
}
FuriHalI2cBus furi_hal_i2c_bus_power = {
.i2c = I2C1,
.callback = furi_hal_i2c_bus_power_event,
};
osMutexId_t furi_hal_i2c_bus_external_mutex = NULL;
static void furi_hal_i2c_bus_external_event(FuriHalI2cBus* bus, FuriHalI2cBusEvent event) {
if(event == FuriHalI2cBusEventActivate) {
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_I2C3);
LL_RCC_SetI2CClockSource(LL_RCC_I2C3_CLKSOURCE_PCLK1);
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C3);
FURI_CRITICAL_EXIT();
} else if(event == FuriHalI2cBusEventDeactivate) {
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C3);
FURI_CRITICAL_EXIT();
}
}
FuriHalI2cBus furi_hal_i2c_bus_external = {
.i2c = I2C3,
.callback = furi_hal_i2c_bus_external_event,
};
void furi_hal_i2c_bus_handle_power_event(
FuriHalI2cBusHandle* handle,
FuriHalI2cBusHandleEvent event) {
if(event == FuriHalI2cBusHandleEventActivate) {
hal_gpio_init_ex(
&gpio_i2c_power_sda,
GpioModeAltFunctionOpenDrain,
GpioPullNo,
GpioSpeedLow,
GpioAltFn4I2C1);
hal_gpio_init_ex(
&gpio_i2c_power_scl,
GpioModeAltFunctionOpenDrain,
GpioPullNo,
GpioSpeedLow,
GpioAltFn4I2C1);
LL_I2C_InitTypeDef I2C_InitStruct = {0};
I2C_InitStruct.PeripheralMode = LL_I2C_MODE_I2C;
I2C_InitStruct.AnalogFilter = LL_I2C_ANALOGFILTER_ENABLE;
I2C_InitStruct.DigitalFilter = 0;
I2C_InitStruct.OwnAddress1 = 0;
I2C_InitStruct.TypeAcknowledge = LL_I2C_ACK;
I2C_InitStruct.OwnAddrSize = LL_I2C_OWNADDRESS1_7BIT;
if(furi_hal_version_get_hw_version() > 10) {
I2C_InitStruct.Timing = FURI_HAL_I2C_CONFIG_POWER_I2C_TIMINGS_400;
} else {
I2C_InitStruct.Timing = FURI_HAL_I2C_CONFIG_POWER_I2C_TIMINGS_100;
}
LL_I2C_Init(handle->bus->i2c, &I2C_InitStruct);
// I2C is enabled at this point
LL_I2C_EnableAutoEndMode(handle->bus->i2c);
LL_I2C_SetOwnAddress2(handle->bus->i2c, 0, LL_I2C_OWNADDRESS2_NOMASK);
LL_I2C_DisableOwnAddress2(handle->bus->i2c);
LL_I2C_DisableGeneralCall(handle->bus->i2c);
LL_I2C_EnableClockStretching(handle->bus->i2c);
} else if(event == FuriHalI2cBusHandleEventDeactivate) {
LL_I2C_Disable(handle->bus->i2c);
hal_gpio_write(&gpio_i2c_power_sda, 1);
hal_gpio_write(&gpio_i2c_power_scl, 1);
hal_gpio_init_ex(
&gpio_i2c_power_sda, GpioModeAnalog, GpioPullNo, GpioSpeedLow, GpioAltFnUnused);
hal_gpio_init_ex(
&gpio_i2c_power_scl, GpioModeAnalog, GpioPullNo, GpioSpeedLow, GpioAltFnUnused);
}
}
FuriHalI2cBusHandle furi_hal_i2c_handle_power = {
.bus = &furi_hal_i2c_bus_power,
.callback = furi_hal_i2c_bus_handle_power_event,
};
void furi_hal_i2c_bus_handle_external_event(
FuriHalI2cBusHandle* handle,
FuriHalI2cBusHandleEvent event) {
if(event == FuriHalI2cBusHandleEventActivate) {
hal_gpio_init_ex(
&gpio_ext_pc0, GpioModeAltFunctionOpenDrain, GpioPullNo, GpioSpeedLow, GpioAltFn4I2C3);
hal_gpio_init_ex(
&gpio_ext_pc1, GpioModeAltFunctionOpenDrain, GpioPullNo, GpioSpeedLow, GpioAltFn4I2C3);
LL_I2C_InitTypeDef I2C_InitStruct = {0};
I2C_InitStruct.PeripheralMode = LL_I2C_MODE_I2C;
I2C_InitStruct.AnalogFilter = LL_I2C_ANALOGFILTER_ENABLE;
I2C_InitStruct.DigitalFilter = 0;
I2C_InitStruct.OwnAddress1 = 0;
I2C_InitStruct.TypeAcknowledge = LL_I2C_ACK;
I2C_InitStruct.OwnAddrSize = LL_I2C_OWNADDRESS1_7BIT;
I2C_InitStruct.Timing = FURI_HAL_I2C_CONFIG_POWER_I2C_TIMINGS_100;
LL_I2C_Init(handle->bus->i2c, &I2C_InitStruct);
// I2C is enabled at this point
LL_I2C_EnableAutoEndMode(handle->bus->i2c);
LL_I2C_SetOwnAddress2(handle->bus->i2c, 0, LL_I2C_OWNADDRESS2_NOMASK);
LL_I2C_DisableOwnAddress2(handle->bus->i2c);
LL_I2C_DisableGeneralCall(handle->bus->i2c);
LL_I2C_EnableClockStretching(handle->bus->i2c);
} else if(event == FuriHalI2cBusHandleEventDeactivate) {
LL_I2C_Disable(handle->bus->i2c);
hal_gpio_write(&gpio_ext_pc0, 1);
hal_gpio_write(&gpio_ext_pc1, 1);
hal_gpio_init_ex(&gpio_ext_pc0, GpioModeAnalog, GpioPullNo, GpioSpeedLow, GpioAltFnUnused);
hal_gpio_init_ex(&gpio_ext_pc1, GpioModeAnalog, GpioPullNo, GpioSpeedLow, GpioAltFnUnused);
}
}
FuriHalI2cBusHandle furi_hal_i2c_handle_external = {
.bus = &furi_hal_i2c_bus_external,
.callback = furi_hal_i2c_bus_handle_external_event,
};
@@ -0,0 +1,31 @@
#pragma once
#include <furi_hal_i2c_types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Internal(power) i2c bus, I2C1, under reset when not used */
extern FuriHalI2cBus furi_hal_i2c_bus_power;
/** External i2c bus, I2C3, under reset when not used */
extern FuriHalI2cBus furi_hal_i2c_bus_external;
/** Handle for internal(power) i2c bus
* Bus: furi_hal_i2c_bus_external
* Pins: PA9(SCL) / PA10(SDA), float on release
* Params: 400khz
*/
extern FuriHalI2cBusHandle furi_hal_i2c_handle_power;
/** Handle for external i2c bus
* Bus: furi_hal_i2c_bus_external
* Pins: PC0(SCL) / PC1(SDA), float on release
* Params: 100khz
*/
extern FuriHalI2cBusHandle furi_hal_i2c_handle_external;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,51 @@
#pragma once
#include <stm32wbxx_ll_i2c.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct FuriHalI2cBus FuriHalI2cBus;
typedef struct FuriHalI2cBusHandle FuriHalI2cBusHandle;
/** FuriHal i2c bus states */
typedef enum {
FuriHalI2cBusEventInit, /**< Bus initialization event, called on system start */
FuriHalI2cBusEventDeinit, /**< Bus deinitialization event, called on system stop */
FuriHalI2cBusEventLock, /**< Bus lock event, called before activation */
FuriHalI2cBusEventUnlock, /**< Bus unlock event, called after deactivation */
FuriHalI2cBusEventActivate, /**< Bus activation event, called before handle activation */
FuriHalI2cBusEventDeactivate, /**< Bus deactivation event, called after handle deactivation */
} FuriHalI2cBusEvent;
/** FuriHal i2c bus event callback */
typedef void (*FuriHalI2cBusEventCallback)(FuriHalI2cBus* bus, FuriHalI2cBusEvent event);
/** FuriHal i2c bus */
struct FuriHalI2cBus {
I2C_TypeDef* i2c;
FuriHalI2cBusHandle* current_handle;
FuriHalI2cBusEventCallback callback;
};
/** FuriHal i2c handle states */
typedef enum {
FuriHalI2cBusHandleEventActivate, /**< Handle activate: connect gpio and apply bus config */
FuriHalI2cBusHandleEventDeactivate, /**< Handle deactivate: disconnect gpio and reset bus config */
} FuriHalI2cBusHandleEvent;
/** FuriHal i2c handle event callback */
typedef void (*FuriHalI2cBusHandleEventCallback)(
FuriHalI2cBusHandle* handle,
FuriHalI2cBusHandleEvent event);
/** FuriHal i2c handle */
struct FuriHalI2cBusHandle {
FuriHalI2cBus* bus;
FuriHalI2cBusHandleEventCallback callback;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,24 @@
#include <furi_hal_ibutton.h>
#include <furi_hal_resources.h>
void furi_hal_ibutton_start() {
furi_hal_ibutton_pin_high();
hal_gpio_init(&ibutton_gpio, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow);
}
void furi_hal_ibutton_stop() {
furi_hal_ibutton_pin_high();
hal_gpio_init(&ibutton_gpio, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
}
void furi_hal_ibutton_pin_low() {
hal_gpio_write(&ibutton_gpio, false);
}
void furi_hal_ibutton_pin_high() {
hal_gpio_write(&ibutton_gpio, true);
}
bool furi_hal_ibutton_pin_get_level() {
return hal_gpio_read(&ibutton_gpio);
}
@@ -0,0 +1,136 @@
#include <furi_hal_info.h>
#include <furi_hal.h>
#include <shci.h>
void furi_hal_info_get(FuriHalInfoValueCallback out, void* context) {
string_t value;
string_init(value);
// Device Info version
out("device_info_major", "2", false, context);
out("device_info_minor", "0", false, context);
// Model name
out("hardware_model", furi_hal_version_get_model_name(), false, context);
// Unique ID
string_reset(value);
const uint8_t* uid = furi_hal_version_uid();
for(size_t i = 0; i < furi_hal_version_uid_size(); i++) {
string_cat_printf(value, "%02X", uid[i]);
}
out("hardware_uid", string_get_cstr(value), false, context);
// OTP Revision
string_printf(value, "%d", furi_hal_version_get_otp_version());
out("hardware_otp_ver", string_get_cstr(value), false, context);
string_printf(value, "%lu", furi_hal_version_get_hw_timestamp());
out("hardware_timestamp", string_get_cstr(value), false, context);
// Board Revision
string_printf(value, "%d", furi_hal_version_get_hw_version());
out("hardware_ver", string_get_cstr(value), false, context);
string_printf(value, "%d", furi_hal_version_get_hw_target());
out("hardware_target", string_get_cstr(value), false, context);
string_printf(value, "%d", furi_hal_version_get_hw_body());
out("hardware_body", string_get_cstr(value), false, context);
string_printf(value, "%d", furi_hal_version_get_hw_connect());
out("hardware_connect", string_get_cstr(value), false, context);
string_printf(value, "%d", furi_hal_version_get_hw_display());
out("hardware_display", string_get_cstr(value), false, context);
// Board Personification
string_printf(value, "%d", furi_hal_version_get_hw_color());
out("hardware_color", string_get_cstr(value), false, context);
string_printf(value, "%d", furi_hal_version_get_hw_region());
out("hardware_region", string_get_cstr(value), false, context);
const char* name = furi_hal_version_get_name_ptr();
if(name) {
out("hardware_name", name, false, context);
}
// Bootloader Version
const Version* bootloader_version = furi_hal_version_get_bootloader_version();
if(bootloader_version) {
out("bootloader_commit", version_get_githash(bootloader_version), false, context);
out("bootloader_branch", version_get_gitbranch(bootloader_version), false, context);
out("bootloader_branch_num", version_get_gitbranchnum(bootloader_version), false, context);
out("bootloader_version", version_get_version(bootloader_version), false, context);
out("bootloader_build_date", version_get_builddate(bootloader_version), false, context);
string_printf(value, "%d", version_get_target(bootloader_version));
out("bootloader_target", string_get_cstr(value), false, context);
}
// Firmware version
const Version* firmware_version = furi_hal_version_get_firmware_version();
if(firmware_version) {
out("firmware_commit", version_get_githash(firmware_version), false, context);
out("firmware_branch", version_get_gitbranch(firmware_version), false, context);
out("firmware_branch_num", version_get_gitbranchnum(firmware_version), false, context);
out("firmware_version", version_get_version(firmware_version), false, context);
out("firmware_build_date", version_get_builddate(firmware_version), false, context);
string_printf(value, "%d", version_get_target(firmware_version));
out("firmware_target", string_get_cstr(value), false, context);
}
WirelessFwInfo_t pWirelessInfo;
if(furi_hal_bt_is_alive() && SHCI_GetWirelessFwInfo(&pWirelessInfo) == SHCI_Success) {
out("radio_alive", "true", false, context);
// FUS Info
string_printf(value, "%d", pWirelessInfo.FusVersionMajor);
out("radio_fus_major", string_get_cstr(value), false, context);
string_printf(value, "%d", pWirelessInfo.FusVersionMinor);
out("radio_fus_minor", string_get_cstr(value), false, context);
string_printf(value, "%d", pWirelessInfo.FusVersionSub);
out("radio_fus_sub", string_get_cstr(value), false, context);
string_printf(value, "%dK", pWirelessInfo.FusMemorySizeSram2B);
out("radio_fus_sram2b", string_get_cstr(value), false, context);
string_printf(value, "%dK", pWirelessInfo.FusMemorySizeSram2A);
out("radio_fus_sram2a", string_get_cstr(value), false, context);
string_printf(value, "%dK", pWirelessInfo.FusMemorySizeFlash * 4);
out("radio_fus_flash", string_get_cstr(value), false, context);
// Stack Info
string_printf(value, "%d", pWirelessInfo.StackType);
out("radio_stack_type", string_get_cstr(value), false, context);
string_printf(value, "%d", pWirelessInfo.VersionMajor);
out("radio_stack_major", string_get_cstr(value), false, context);
string_printf(value, "%d", pWirelessInfo.VersionMinor);
out("radio_stack_minor", string_get_cstr(value), false, context);
string_printf(value, "%d", pWirelessInfo.VersionSub);
out("radio_stack_sub", string_get_cstr(value), false, context);
string_printf(value, "%d", pWirelessInfo.VersionBranch);
out("radio_stack_branch", string_get_cstr(value), false, context);
string_printf(value, "%d", pWirelessInfo.VersionReleaseType);
out("radio_stack_release", string_get_cstr(value), false, context);
string_printf(value, "%dK", pWirelessInfo.MemorySizeSram2B);
out("radio_stack_sram2b", string_get_cstr(value), false, context);
string_printf(value, "%dK", pWirelessInfo.MemorySizeSram2A);
out("radio_stack_sram2a", string_get_cstr(value), false, context);
string_printf(value, "%dK", pWirelessInfo.MemorySizeSram1);
out("radio_stack_sram1", string_get_cstr(value), false, context);
string_printf(value, "%dK", pWirelessInfo.MemorySizeFlash * 4);
out("radio_stack_flash", string_get_cstr(value), false, context);
// Mac address
string_reset(value);
const uint8_t* ble_mac = furi_hal_version_get_ble_mac();
for(size_t i = 0; i < 6; i++) {
string_cat_printf(value, "%02X", ble_mac[i]);
}
out("radio_ble_mac", string_get_cstr(value), false, context);
// Signature verification
uint8_t enclave_keys = 0;
uint8_t enclave_valid_keys = 0;
bool enclave_valid = furi_hal_crypto_verify_enclave(&enclave_keys, &enclave_valid_keys);
string_printf(value, "%d", enclave_valid_keys);
out("enclave_valid_keys", string_get_cstr(value), false, context);
out("enclave_valid", enclave_valid ? "true" : "false", true, context);
} else {
out("radio_alive", "false", true, context);
}
string_clear(value);
}
@@ -0,0 +1,206 @@
#include "furi_hal_interrupt.h"
#include <furi.h>
#include <main.h>
#include <stm32wbxx_ll_tim.h>
#define TAG "FuriHalInterrupt"
volatile FuriHalInterruptISR furi_hal_tim_tim2_isr = NULL;
volatile FuriHalInterruptISR furi_hal_tim_tim1_isr = NULL;
#define FURI_HAL_INTERRUPT_DMA_COUNT 2
#define FURI_HAL_INTERRUPT_DMA_CHANNELS_COUNT 8
volatile FuriHalInterruptISR furi_hal_dma_channel_isr[FURI_HAL_INTERRUPT_DMA_COUNT]
[FURI_HAL_INTERRUPT_DMA_CHANNELS_COUNT] = {0};
void furi_hal_interrupt_init() {
NVIC_SetPriority(RCC_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 0, 0));
NVIC_EnableIRQ(RCC_IRQn);
NVIC_SetPriority(
TAMP_STAMP_LSECSS_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 0, 0));
NVIC_EnableIRQ(TAMP_STAMP_LSECSS_IRQn);
NVIC_SetPriority(DMA1_Channel1_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(DMA1_Channel1_IRQn);
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_interrupt_set_timer_isr(TIM_TypeDef* timer, FuriHalInterruptISR isr) {
if(timer == TIM2) {
if(isr) {
furi_assert(furi_hal_tim_tim2_isr == NULL);
} else {
furi_assert(furi_hal_tim_tim2_isr != NULL);
}
furi_hal_tim_tim2_isr = isr;
} else if(timer == TIM1) {
if(isr) {
furi_assert(furi_hal_tim_tim1_isr == NULL);
} else {
furi_assert(furi_hal_tim_tim1_isr != NULL);
}
furi_hal_tim_tim1_isr = isr;
} else {
furi_crash(NULL);
}
}
void furi_hal_interrupt_set_dma_channel_isr(
DMA_TypeDef* dma,
uint32_t channel,
FuriHalInterruptISR isr) {
--channel; // Pascal
furi_check(dma);
furi_check(channel < FURI_HAL_INTERRUPT_DMA_CHANNELS_COUNT);
if(dma == DMA1) {
furi_hal_dma_channel_isr[0][channel] = isr;
} else if(dma == DMA2) {
furi_hal_dma_channel_isr[1][channel] = isr;
} else {
furi_crash(NULL);
}
}
extern void api_interrupt_call(InterruptType type, void* hw);
/* ST HAL symbols */
/* Comparator trigger event */
void HAL_COMP_TriggerCallback(COMP_HandleTypeDef* hcomp) {
api_interrupt_call(InterruptTypeComparatorTrigger, hcomp);
}
/* Timer update event */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef* htim) {
api_interrupt_call(InterruptTypeTimerUpdate, htim);
}
/* Timer 2 */
void TIM2_IRQHandler(void) {
if(furi_hal_tim_tim2_isr) {
furi_hal_tim_tim2_isr();
} else {
HAL_TIM_IRQHandler(&htim2);
}
}
/* Timer 1 Update */
void TIM1_UP_TIM16_IRQHandler(void) {
if(furi_hal_tim_tim1_isr) {
furi_hal_tim_tim1_isr();
} else {
HAL_TIM_IRQHandler(&htim1);
}
}
/* DMA 1 */
void DMA1_Channel1_IRQHandler(void) {
if(furi_hal_dma_channel_isr[0][0]) furi_hal_dma_channel_isr[0][0]();
}
void DMA1_Channel2_IRQHandler(void) {
if(furi_hal_dma_channel_isr[0][1]) furi_hal_dma_channel_isr[0][1]();
}
void DMA1_Channel3_IRQHandler(void) {
if(furi_hal_dma_channel_isr[0][2]) furi_hal_dma_channel_isr[0][2]();
}
void DMA1_Channel4_IRQHandler(void) {
if(furi_hal_dma_channel_isr[0][3]) furi_hal_dma_channel_isr[0][3]();
}
void DMA1_Channel5_IRQHandler(void) {
if(furi_hal_dma_channel_isr[0][4]) furi_hal_dma_channel_isr[0][4]();
}
void DMA1_Channel6_IRQHandler(void) {
if(furi_hal_dma_channel_isr[0][5]) furi_hal_dma_channel_isr[0][5]();
}
void DMA1_Channel7_IRQHandler(void) {
if(furi_hal_dma_channel_isr[0][6]) furi_hal_dma_channel_isr[0][6]();
}
void DMA1_Channel8_IRQHandler(void) {
if(furi_hal_dma_channel_isr[0][7]) furi_hal_dma_channel_isr[0][7]();
}
/* DMA 2 */
void DMA2_Channel1_IRQHandler(void) {
if(furi_hal_dma_channel_isr[1][0]) furi_hal_dma_channel_isr[1][0]();
}
void DMA2_Channel2_IRQHandler(void) {
if(furi_hal_dma_channel_isr[1][1]) furi_hal_dma_channel_isr[1][1]();
}
void DMA2_Channel3_IRQHandler(void) {
if(furi_hal_dma_channel_isr[1][2]) furi_hal_dma_channel_isr[1][2]();
}
void DMA2_Channel4_IRQHandler(void) {
if(furi_hal_dma_channel_isr[1][3]) furi_hal_dma_channel_isr[1][3]();
}
void DMA2_Channel5_IRQHandler(void) {
if(furi_hal_dma_channel_isr[1][4]) furi_hal_dma_channel_isr[1][4]();
}
void DMA2_Channel6_IRQHandler(void) {
if(furi_hal_dma_channel_isr[1][5]) furi_hal_dma_channel_isr[1][5]();
}
void DMA2_Channel7_IRQHandler(void) {
if(furi_hal_dma_channel_isr[1][6]) furi_hal_dma_channel_isr[1][6]();
}
void DMA2_Channel8_IRQHandler(void) {
if(furi_hal_dma_channel_isr[1][7]) furi_hal_dma_channel_isr[1][7]();
}
void TAMP_STAMP_LSECSS_IRQHandler(void) {
if(LL_RCC_IsActiveFlag_LSECSS()) {
LL_RCC_ClearFlag_LSECSS();
if(!LL_RCC_LSE_IsReady()) {
FURI_LOG_E(TAG, "LSE CSS fired: resetting system");
NVIC_SystemReset();
} else {
FURI_LOG_E(TAG, "LSE CSS fired: but LSE is alive");
}
}
}
void RCC_IRQHandler(void) {
}
void NMI_Handler(void) {
if(LL_RCC_IsActiveFlag_HSECSS()) {
LL_RCC_ClearFlag_HSECSS();
FURI_LOG_E(TAG, "HSE CSS fired: resetting system");
NVIC_SystemReset();
}
}
void HardFault_Handler(void) {
furi_crash("HardFault");
}
void MemManage_Handler(void) {
furi_crash("MemManage");
}
void BusFault_Handler(void) {
furi_crash("BusFault");
}
void UsageFault_Handler(void) {
furi_crash("UsageFault");
}
void DebugMon_Handler(void) {
}
@@ -0,0 +1,36 @@
#pragma once
#include <stm32wbxx_ll_tim.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Timer ISR */
typedef void (*FuriHalInterruptISR)();
/** Initialize interrupt subsystem */
void furi_hal_interrupt_init();
/** Set DMA Channel ISR
* We don't clear interrupt flags for you, do it by your self.
* @param dma - DMA instance
* @param channel - DMA channel
* @param isr - your interrupt service routine or use NULL to clear
*/
void furi_hal_interrupt_set_dma_channel_isr(
DMA_TypeDef* dma,
uint32_t channel,
FuriHalInterruptISR isr);
/** Set Timer ISR
* By default ISR is serviced by ST HAL. Use this function to override it.
* We don't clear interrupt flags for you, do it by your self.
* @param timer - timer instance
* @param isr - your interrupt service routine or use NULL to clear
*/
void furi_hal_interrupt_set_timer_isr(TIM_TypeDef* timer, FuriHalInterruptISR isr);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,665 @@
#include "furi_hal_irda.h"
#include "furi_hal_delay.h"
#include "furi/check.h"
#include "stm32wbxx_ll_dma.h"
#include "sys/_stdint.h"
#include <cmsis_os2.h>
#include <furi_hal_interrupt.h>
#include <furi_hal_resources.h>
#include <stdint.h>
#include <stm32wbxx_ll_tim.h>
#include <stm32wbxx_ll_gpio.h>
#include <stdio.h>
#include <furi.h>
#include <math.h>
#include <main.h>
#include <furi_hal_pwm.h>
#define IRDA_TX_DEBUG 0
#if IRDA_TX_DEBUG == 1
#define gpio_irda_tx gpio_irda_tx_debug
const GpioPin gpio_irda_tx_debug = {.port = GPIOA, .pin = GPIO_PIN_7};
#endif
#define IRDA_TIM_TX_DMA_BUFFER_SIZE 200
#define IRDA_POLARITY_SHIFT 1
#define IRDA_TX_CCMR_HIGH (TIM_CCMR2_OC3PE | LL_TIM_OCMODE_PWM2) /* Mark time - enable PWM2 mode */
#define IRDA_TX_CCMR_LOW \
(TIM_CCMR2_OC3PE | LL_TIM_OCMODE_FORCED_INACTIVE) /* Space time - force low */
typedef struct {
FuriHalIrdaRxCaptureCallback capture_callback;
void* capture_context;
FuriHalIrdaRxTimeoutCallback timeout_callback;
void* timeout_context;
} IrdaTimRx;
typedef struct {
uint8_t* polarity;
uint16_t* data;
size_t size;
bool packet_end;
bool last_packet_end;
} IrdaTxBuf;
typedef struct {
float cycle_duration;
FuriHalIrdaTxGetDataISRCallback data_callback;
FuriHalIrdaTxSignalSentISRCallback signal_sent_callback;
void* data_context;
void* signal_sent_context;
IrdaTxBuf buffer[2];
osSemaphoreId_t stop_semaphore;
uint32_t
tx_timing_rest_duration; /** if timing is too long (> 0xFFFF), send it in few iterations */
bool tx_timing_rest_level;
FuriHalIrdaTxGetDataState tx_timing_rest_status;
} IrdaTimTx;
typedef enum {
IrdaStateIdle, /** Furi Hal Irda is ready to start RX or TX */
IrdaStateAsyncRx, /** Async RX started */
IrdaStateAsyncTx, /** Async TX started, DMA and timer is on */
IrdaStateAsyncTxStopReq, /** Async TX started, async stop request received */
IrdaStateAsyncTxStopInProgress, /** Async TX started, stop request is processed and we wait for last data to be sent */
IrdaStateAsyncTxStopped, /** Async TX complete, cleanup needed */
IrdaStateMAX,
} IrdaState;
static volatile IrdaState furi_hal_irda_state = IrdaStateIdle;
static IrdaTimTx irda_tim_tx;
static IrdaTimRx irda_tim_rx;
static void furi_hal_irda_tx_fill_buffer(uint8_t buf_num, uint8_t polarity_shift);
static void furi_hal_irda_async_tx_free_resources(void);
static void furi_hal_irda_tx_dma_set_polarity(uint8_t buf_num, uint8_t polarity_shift);
static void furi_hal_irda_tx_dma_set_buffer(uint8_t buf_num);
static void furi_hal_irda_tx_fill_buffer_last(uint8_t buf_num);
static uint8_t furi_hal_irda_get_current_dma_tx_buffer(void);
static void furi_hal_irda_tx_dma_polarity_isr();
static void furi_hal_irda_tx_dma_isr();
static void furi_hal_irda_tim_rx_isr() {
static uint32_t previous_captured_ch2 = 0;
/* Timeout */
if(LL_TIM_IsActiveFlag_CC3(TIM2)) {
LL_TIM_ClearFlag_CC3(TIM2);
furi_assert(furi_hal_irda_state == IrdaStateAsyncRx);
/* Timers CNT register starts to counting from 0 to ARR, but it is
* reseted when Channel 1 catches interrupt. It is not reseted by
* channel 2, though, so we have to distract it's values (see TimerIRQSourceCCI1 ISR).
* This can cause false timeout: when time is over, but we started
* receiving new signal few microseconds ago, because CNT register
* is reseted once per period, not per sample. */
if(LL_GPIO_IsInputPinSet(gpio_irda_rx.port, gpio_irda_rx.pin) != 0) {
if(irda_tim_rx.timeout_callback)
irda_tim_rx.timeout_callback(irda_tim_rx.timeout_context);
}
}
/* Rising Edge */
if(LL_TIM_IsActiveFlag_CC1(TIM2)) {
LL_TIM_ClearFlag_CC1(TIM2);
furi_assert(furi_hal_irda_state == IrdaStateAsyncRx);
if(READ_BIT(TIM2->CCMR1, TIM_CCMR1_CC1S)) {
/* Low pin level is a Mark state of IRDA signal. Invert level for further processing. */
uint32_t duration = LL_TIM_IC_GetCaptureCH1(TIM2) - previous_captured_ch2;
if(irda_tim_rx.capture_callback)
irda_tim_rx.capture_callback(irda_tim_rx.capture_context, 1, duration);
} else {
furi_assert(0);
}
}
/* Falling Edge */
if(LL_TIM_IsActiveFlag_CC2(TIM2)) {
LL_TIM_ClearFlag_CC2(TIM2);
furi_assert(furi_hal_irda_state == IrdaStateAsyncRx);
if(READ_BIT(TIM2->CCMR1, TIM_CCMR1_CC2S)) {
/* High pin level is a Space state of IRDA signal. Invert level for further processing. */
uint32_t duration = LL_TIM_IC_GetCaptureCH2(TIM2);
previous_captured_ch2 = duration;
if(irda_tim_rx.capture_callback)
irda_tim_rx.capture_callback(irda_tim_rx.capture_context, 0, duration);
} else {
furi_assert(0);
}
}
}
void furi_hal_irda_async_rx_start(void) {
furi_assert(furi_hal_irda_state == IrdaStateIdle);
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2);
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA);
FURI_CRITICAL_EXIT();
hal_gpio_init_ex(
&gpio_irda_rx, GpioModeAltFunctionPushPull, GpioPullNo, GpioSpeedLow, GpioAltFn1TIM2);
LL_TIM_InitTypeDef TIM_InitStruct = {0};
TIM_InitStruct.Prescaler = 64 - 1;
TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
TIM_InitStruct.Autoreload = 0x7FFFFFFE;
TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
LL_TIM_Init(TIM2, &TIM_InitStruct);
LL_TIM_SetClockSource(TIM2, LL_TIM_CLOCKSOURCE_INTERNAL);
LL_TIM_DisableARRPreload(TIM2);
LL_TIM_SetTriggerInput(TIM2, LL_TIM_TS_TI1FP1);
LL_TIM_SetSlaveMode(TIM2, LL_TIM_SLAVEMODE_RESET);
LL_TIM_CC_DisableChannel(TIM2, LL_TIM_CHANNEL_CH2);
LL_TIM_IC_SetFilter(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_IC_FILTER_FDIV1);
LL_TIM_IC_SetPolarity(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_IC_POLARITY_FALLING);
LL_TIM_DisableIT_TRIG(TIM2);
LL_TIM_DisableDMAReq_TRIG(TIM2);
LL_TIM_SetTriggerOutput(TIM2, LL_TIM_TRGO_RESET);
LL_TIM_EnableMasterSlaveMode(TIM2);
LL_TIM_IC_SetActiveInput(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_ACTIVEINPUT_DIRECTTI);
LL_TIM_IC_SetPrescaler(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_ICPSC_DIV1);
LL_TIM_IC_SetFilter(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_IC_FILTER_FDIV1);
LL_TIM_IC_SetPolarity(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_IC_POLARITY_RISING);
LL_TIM_IC_SetActiveInput(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_ACTIVEINPUT_INDIRECTTI);
LL_TIM_IC_SetPrescaler(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_ICPSC_DIV1);
furi_hal_interrupt_set_timer_isr(TIM2, furi_hal_irda_tim_rx_isr);
furi_hal_irda_state = IrdaStateAsyncRx;
LL_TIM_EnableIT_CC1(TIM2);
LL_TIM_EnableIT_CC2(TIM2);
LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH1);
LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH2);
LL_TIM_SetCounter(TIM2, 0);
LL_TIM_EnableCounter(TIM2);
NVIC_SetPriority(TIM2_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(TIM2_IRQn);
}
void furi_hal_irda_async_rx_stop(void) {
furi_assert(furi_hal_irda_state == IrdaStateAsyncRx);
LL_TIM_DeInit(TIM2);
furi_hal_interrupt_set_timer_isr(TIM2, NULL);
LL_APB1_GRP1_DisableClock(LL_APB1_GRP1_PERIPH_TIM2);
furi_hal_irda_state = IrdaStateIdle;
}
void furi_hal_irda_async_rx_set_timeout(uint32_t timeout_us) {
furi_assert(LL_APB1_GRP1_IsEnabledClock(LL_APB1_GRP1_PERIPH_TIM2));
LL_TIM_OC_SetCompareCH3(TIM2, timeout_us);
LL_TIM_OC_SetMode(TIM2, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_ACTIVE);
LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH3);
LL_TIM_EnableIT_CC3(TIM2);
}
bool furi_hal_irda_is_busy(void) {
return furi_hal_irda_state != IrdaStateIdle;
}
void furi_hal_irda_async_rx_set_capture_isr_callback(
FuriHalIrdaRxCaptureCallback callback,
void* ctx) {
irda_tim_rx.capture_callback = callback;
irda_tim_rx.capture_context = ctx;
}
void furi_hal_irda_async_rx_set_timeout_isr_callback(
FuriHalIrdaRxTimeoutCallback callback,
void* ctx) {
irda_tim_rx.timeout_callback = callback;
irda_tim_rx.timeout_context = ctx;
}
static void furi_hal_irda_tx_dma_terminate(void) {
LL_DMA_DisableIT_TC(DMA1, LL_DMA_CHANNEL_1);
LL_DMA_DisableIT_HT(DMA1, LL_DMA_CHANNEL_2);
LL_DMA_DisableIT_TC(DMA1, LL_DMA_CHANNEL_2);
furi_assert(furi_hal_irda_state == IrdaStateAsyncTxStopInProgress);
LL_DMA_DisableIT_TC(DMA1, LL_DMA_CHANNEL_1);
LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_2);
LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1);
LL_TIM_DisableCounter(TIM1);
osStatus_t status = osSemaphoreRelease(irda_tim_tx.stop_semaphore);
furi_check(status == osOK);
furi_hal_irda_state = IrdaStateAsyncTxStopped;
}
static uint8_t furi_hal_irda_get_current_dma_tx_buffer(void) {
uint8_t buf_num = 0;
uint32_t buffer_adr = LL_DMA_GetMemoryAddress(DMA1, LL_DMA_CHANNEL_2);
if(buffer_adr == (uint32_t)irda_tim_tx.buffer[0].data) {
buf_num = 0;
} else if(buffer_adr == (uint32_t)irda_tim_tx.buffer[1].data) {
buf_num = 1;
} else {
furi_assert(0);
}
return buf_num;
}
static void furi_hal_irda_tx_dma_polarity_isr() {
if(LL_DMA_IsActiveFlag_TE1(DMA1)) {
LL_DMA_ClearFlag_TE1(DMA1);
furi_crash(NULL);
}
if(LL_DMA_IsActiveFlag_TC1(DMA1) && LL_DMA_IsEnabledIT_TC(DMA1, LL_DMA_CHANNEL_1)) {
LL_DMA_ClearFlag_TC1(DMA1);
furi_check(
(furi_hal_irda_state == IrdaStateAsyncTx) ||
(furi_hal_irda_state == IrdaStateAsyncTxStopReq) ||
(furi_hal_irda_state == IrdaStateAsyncTxStopInProgress));
/* actually TC2 is processed and buffer is next buffer */
uint8_t next_buf_num = furi_hal_irda_get_current_dma_tx_buffer();
furi_hal_irda_tx_dma_set_polarity(next_buf_num, 0);
}
}
static void furi_hal_irda_tx_dma_isr() {
if(LL_DMA_IsActiveFlag_TE2(DMA1)) {
LL_DMA_ClearFlag_TE2(DMA1);
furi_crash(NULL);
}
if(LL_DMA_IsActiveFlag_HT2(DMA1) && LL_DMA_IsEnabledIT_HT(DMA1, LL_DMA_CHANNEL_2)) {
LL_DMA_ClearFlag_HT2(DMA1);
uint8_t buf_num = furi_hal_irda_get_current_dma_tx_buffer();
uint8_t next_buf_num = !buf_num;
if(irda_tim_tx.buffer[buf_num].last_packet_end) {
LL_DMA_DisableIT_HT(DMA1, LL_DMA_CHANNEL_2);
} else if(
!irda_tim_tx.buffer[buf_num].packet_end || (furi_hal_irda_state == IrdaStateAsyncTx)) {
furi_hal_irda_tx_fill_buffer(next_buf_num, 0);
if(irda_tim_tx.buffer[next_buf_num].last_packet_end) {
LL_DMA_DisableIT_HT(DMA1, LL_DMA_CHANNEL_2);
}
} else if(furi_hal_irda_state == IrdaStateAsyncTxStopReq) {
/* fallthrough */
} else {
furi_crash(NULL);
}
}
if(LL_DMA_IsActiveFlag_TC2(DMA1) && LL_DMA_IsEnabledIT_TC(DMA1, LL_DMA_CHANNEL_2)) {
LL_DMA_ClearFlag_TC2(DMA1);
furi_check(
(furi_hal_irda_state == IrdaStateAsyncTxStopInProgress) ||
(furi_hal_irda_state == IrdaStateAsyncTxStopReq) ||
(furi_hal_irda_state == IrdaStateAsyncTx));
uint8_t buf_num = furi_hal_irda_get_current_dma_tx_buffer();
uint8_t next_buf_num = !buf_num;
if(furi_hal_irda_state == IrdaStateAsyncTxStopInProgress) {
furi_hal_irda_tx_dma_terminate();
} else if(
irda_tim_tx.buffer[buf_num].last_packet_end ||
(irda_tim_tx.buffer[buf_num].packet_end &&
(furi_hal_irda_state == IrdaStateAsyncTxStopReq))) {
furi_hal_irda_state = IrdaStateAsyncTxStopInProgress;
furi_hal_irda_tx_fill_buffer_last(next_buf_num);
furi_hal_irda_tx_dma_set_buffer(next_buf_num);
} else {
/* if it's not end of the packet - continue receiving */
furi_hal_irda_tx_dma_set_buffer(next_buf_num);
}
if(irda_tim_tx.signal_sent_callback && irda_tim_tx.buffer[buf_num].packet_end &&
(furi_hal_irda_state != IrdaStateAsyncTxStopped)) {
irda_tim_tx.signal_sent_callback(irda_tim_tx.signal_sent_context);
}
}
}
static void furi_hal_irda_configure_tim_pwm_tx(uint32_t freq, float duty_cycle) {
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_TIM1);
/* LL_DBGMCU_APB2_GRP1_FreezePeriph(LL_DBGMCU_APB2_GRP1_TIM1_STOP); */
LL_TIM_DisableCounter(TIM1);
LL_TIM_SetRepetitionCounter(TIM1, 0);
LL_TIM_SetCounter(TIM1, 0);
LL_TIM_SetPrescaler(TIM1, 0);
LL_TIM_SetCounterMode(TIM1, LL_TIM_COUNTERMODE_UP);
LL_TIM_EnableARRPreload(TIM1);
LL_TIM_SetAutoReload(
TIM1, __LL_TIM_CALC_ARR(SystemCoreClock, LL_TIM_GetPrescaler(TIM1), freq));
#if IRDA_TX_DEBUG == 1
LL_TIM_OC_SetCompareCH1(TIM1, ((LL_TIM_GetAutoReload(TIM1) + 1) * (1 - duty_cycle)));
LL_TIM_OC_EnablePreload(TIM1, LL_TIM_CHANNEL_CH1);
/* LL_TIM_OCMODE_PWM2 set by DMA */
LL_TIM_OC_SetMode(TIM1, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_FORCED_INACTIVE);
LL_TIM_OC_SetPolarity(TIM1, LL_TIM_CHANNEL_CH1N, LL_TIM_OCPOLARITY_HIGH);
LL_TIM_OC_DisableFast(TIM1, LL_TIM_CHANNEL_CH1);
LL_TIM_CC_EnableChannel(TIM1, LL_TIM_CHANNEL_CH1N);
LL_TIM_DisableIT_CC1(TIM1);
#else
LL_TIM_OC_SetCompareCH3(TIM1, ((LL_TIM_GetAutoReload(TIM1) + 1) * (1 - duty_cycle)));
LL_TIM_OC_EnablePreload(TIM1, LL_TIM_CHANNEL_CH3);
/* LL_TIM_OCMODE_PWM2 set by DMA */
LL_TIM_OC_SetMode(TIM1, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_FORCED_INACTIVE);
LL_TIM_OC_SetPolarity(TIM1, LL_TIM_CHANNEL_CH3N, LL_TIM_OCPOLARITY_HIGH);
LL_TIM_OC_DisableFast(TIM1, LL_TIM_CHANNEL_CH3);
LL_TIM_CC_EnableChannel(TIM1, LL_TIM_CHANNEL_CH3N);
LL_TIM_DisableIT_CC3(TIM1);
#endif
LL_TIM_DisableMasterSlaveMode(TIM1);
LL_TIM_EnableAllOutputs(TIM1);
LL_TIM_DisableIT_UPDATE(TIM1);
LL_TIM_EnableDMAReq_UPDATE(TIM1);
NVIC_SetPriority(TIM1_UP_TIM16_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(TIM1_UP_TIM16_IRQn);
}
static void furi_hal_irda_configure_tim_cmgr2_dma_tx(void) {
LL_C2_AHB1_GRP1_EnableClock(LL_C2_AHB1_GRP1_PERIPH_DMA1);
LL_DMA_InitTypeDef dma_config = {0};
#if IRDA_TX_DEBUG == 1
dma_config.PeriphOrM2MSrcAddress = (uint32_t) & (TIM1->CCMR1);
#else
dma_config.PeriphOrM2MSrcAddress = (uint32_t) & (TIM1->CCMR2);
#endif
dma_config.MemoryOrM2MDstAddress = (uint32_t)NULL;
dma_config.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH;
dma_config.Mode = LL_DMA_MODE_NORMAL;
dma_config.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT;
dma_config.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT;
/* fill word to have other bits set to 0 */
dma_config.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD;
dma_config.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_BYTE;
dma_config.NbData = 0;
dma_config.PeriphRequest = LL_DMAMUX_REQ_TIM1_UP;
dma_config.Priority = LL_DMA_PRIORITY_VERYHIGH;
LL_DMA_Init(DMA1, LL_DMA_CHANNEL_1, &dma_config);
furi_hal_interrupt_set_dma_channel_isr(
DMA1, LL_DMA_CHANNEL_1, furi_hal_irda_tx_dma_polarity_isr);
LL_DMA_ClearFlag_TE1(DMA1);
LL_DMA_ClearFlag_TC1(DMA1);
LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_1);
LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_1);
NVIC_SetPriority(DMA1_Channel1_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 4, 0));
NVIC_EnableIRQ(DMA1_Channel1_IRQn);
}
static void furi_hal_irda_configure_tim_rcr_dma_tx(void) {
LL_C2_AHB1_GRP1_EnableClock(LL_C2_AHB1_GRP1_PERIPH_DMA1);
LL_DMA_InitTypeDef dma_config = {0};
dma_config.PeriphOrM2MSrcAddress = (uint32_t) & (TIM1->RCR);
dma_config.MemoryOrM2MDstAddress = (uint32_t)NULL;
dma_config.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH;
dma_config.Mode = LL_DMA_MODE_NORMAL;
dma_config.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT;
dma_config.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT;
dma_config.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_HALFWORD;
dma_config.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_HALFWORD;
dma_config.NbData = 0;
dma_config.PeriphRequest = LL_DMAMUX_REQ_TIM1_UP;
dma_config.Priority = LL_DMA_PRIORITY_MEDIUM;
LL_DMA_Init(DMA1, LL_DMA_CHANNEL_2, &dma_config);
furi_hal_interrupt_set_dma_channel_isr(DMA1, LL_DMA_CHANNEL_2, furi_hal_irda_tx_dma_isr);
LL_DMA_ClearFlag_TC2(DMA1);
LL_DMA_ClearFlag_HT2(DMA1);
LL_DMA_ClearFlag_TE2(DMA1);
LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_2);
LL_DMA_EnableIT_HT(DMA1, LL_DMA_CHANNEL_2);
LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_2);
NVIC_SetPriority(DMA1_Channel2_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(DMA1_Channel2_IRQn);
}
static void furi_hal_irda_tx_fill_buffer_last(uint8_t buf_num) {
furi_assert(buf_num < 2);
furi_assert(furi_hal_irda_state != IrdaStateAsyncRx);
furi_assert(furi_hal_irda_state < IrdaStateMAX);
furi_assert(irda_tim_tx.data_callback);
IrdaTxBuf* buffer = &irda_tim_tx.buffer[buf_num];
furi_assert(buffer->data != NULL);
(void)buffer->data;
furi_assert(buffer->polarity != NULL);
(void)buffer->polarity;
irda_tim_tx.buffer[buf_num].data[0] = 0; // 1 pulse
irda_tim_tx.buffer[buf_num].polarity[0] = IRDA_TX_CCMR_LOW;
irda_tim_tx.buffer[buf_num].data[1] = 0; // 1 pulse
irda_tim_tx.buffer[buf_num].polarity[1] = IRDA_TX_CCMR_LOW;
irda_tim_tx.buffer[buf_num].size = 2;
irda_tim_tx.buffer[buf_num].last_packet_end = true;
irda_tim_tx.buffer[buf_num].packet_end = true;
}
static void furi_hal_irda_tx_fill_buffer(uint8_t buf_num, uint8_t polarity_shift) {
furi_assert(buf_num < 2);
furi_assert(furi_hal_irda_state != IrdaStateAsyncRx);
furi_assert(furi_hal_irda_state < IrdaStateMAX);
furi_assert(irda_tim_tx.data_callback);
IrdaTxBuf* buffer = &irda_tim_tx.buffer[buf_num];
furi_assert(buffer->data != NULL);
furi_assert(buffer->polarity != NULL);
FuriHalIrdaTxGetDataState status = FuriHalIrdaTxGetDataStateOk;
uint32_t duration = 0;
bool level = 0;
size_t* size = &buffer->size;
size_t polarity_counter = 0;
while(polarity_shift--) {
buffer->polarity[polarity_counter++] = IRDA_TX_CCMR_LOW;
}
for(*size = 0;
(*size < IRDA_TIM_TX_DMA_BUFFER_SIZE) && (status == FuriHalIrdaTxGetDataStateOk);) {
if(irda_tim_tx.tx_timing_rest_duration > 0) {
if(irda_tim_tx.tx_timing_rest_duration > 0xFFFF) {
buffer->data[*size] = 0xFFFF;
status = FuriHalIrdaTxGetDataStateOk;
} else {
buffer->data[*size] = irda_tim_tx.tx_timing_rest_duration;
status = irda_tim_tx.tx_timing_rest_status;
}
irda_tim_tx.tx_timing_rest_duration -= buffer->data[*size];
buffer->polarity[polarity_counter] =
irda_tim_tx.tx_timing_rest_level ? IRDA_TX_CCMR_HIGH : IRDA_TX_CCMR_LOW;
++(*size);
++polarity_counter;
continue;
}
status = irda_tim_tx.data_callback(irda_tim_tx.data_context, &duration, &level);
uint32_t num_of_impulses = roundf(duration / irda_tim_tx.cycle_duration);
if(num_of_impulses == 0) {
if((*size == 0) && (status == FuriHalIrdaTxGetDataStateDone)) {
/* if this is one sample in current buffer, but we
* have more to send - continue
*/
status = FuriHalIrdaTxGetDataStateOk;
}
} else if((num_of_impulses - 1) > 0xFFFF) {
irda_tim_tx.tx_timing_rest_duration = num_of_impulses - 1;
irda_tim_tx.tx_timing_rest_status = status;
irda_tim_tx.tx_timing_rest_level = level;
status = FuriHalIrdaTxGetDataStateOk;
} else {
buffer->polarity[polarity_counter] = level ? IRDA_TX_CCMR_HIGH : IRDA_TX_CCMR_LOW;
buffer->data[*size] = num_of_impulses - 1;
++(*size);
++polarity_counter;
}
}
buffer->last_packet_end = (status == FuriHalIrdaTxGetDataStateLastDone);
buffer->packet_end = buffer->last_packet_end || (status == FuriHalIrdaTxGetDataStateDone);
if(*size == 0) {
buffer->data[0] = 0; // 1 pulse
buffer->polarity[0] = IRDA_TX_CCMR_LOW;
buffer->size = 1;
}
}
static void furi_hal_irda_tx_dma_set_polarity(uint8_t buf_num, uint8_t polarity_shift) {
furi_assert(buf_num < 2);
furi_assert(furi_hal_irda_state < IrdaStateMAX);
IrdaTxBuf* buffer = &irda_tim_tx.buffer[buf_num];
furi_assert(buffer->polarity != NULL);
__disable_irq();
bool channel_enabled = LL_DMA_IsEnabledChannel(DMA1, LL_DMA_CHANNEL_1);
if(channel_enabled) {
LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1);
}
LL_DMA_SetMemoryAddress(DMA1, LL_DMA_CHANNEL_1, (uint32_t)buffer->polarity);
LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_1, buffer->size + polarity_shift);
if(channel_enabled) {
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1);
}
__enable_irq();
}
static void furi_hal_irda_tx_dma_set_buffer(uint8_t buf_num) {
furi_assert(buf_num < 2);
furi_assert(furi_hal_irda_state < IrdaStateMAX);
IrdaTxBuf* buffer = &irda_tim_tx.buffer[buf_num];
furi_assert(buffer->data != NULL);
/* non-circular mode requires disabled channel before setup */
__disable_irq();
bool channel_enabled = LL_DMA_IsEnabledChannel(DMA1, LL_DMA_CHANNEL_2);
if(channel_enabled) {
LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_2);
}
LL_DMA_SetMemoryAddress(DMA1, LL_DMA_CHANNEL_2, (uint32_t)buffer->data);
LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_2, buffer->size);
if(channel_enabled) {
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_2);
}
__enable_irq();
}
static void furi_hal_irda_async_tx_free_resources(void) {
furi_assert(
(furi_hal_irda_state == IrdaStateIdle) ||
(furi_hal_irda_state == IrdaStateAsyncTxStopped));
osStatus_t status;
hal_gpio_init(&gpio_irda_tx, GpioModeOutputOpenDrain, GpioPullDown, GpioSpeedLow);
furi_hal_interrupt_set_dma_channel_isr(DMA1, LL_DMA_CHANNEL_1, NULL);
furi_hal_interrupt_set_dma_channel_isr(DMA1, LL_DMA_CHANNEL_2, NULL);
LL_TIM_DeInit(TIM1);
LL_APB2_GRP1_DisableClock(LL_APB2_GRP1_PERIPH_TIM1);
LL_C2_AHB1_GRP1_DisableClock(LL_C2_AHB1_GRP1_PERIPH_DMA1);
status = osSemaphoreDelete(irda_tim_tx.stop_semaphore);
furi_check(status == osOK);
free(irda_tim_tx.buffer[0].data);
free(irda_tim_tx.buffer[1].data);
free(irda_tim_tx.buffer[0].polarity);
free(irda_tim_tx.buffer[1].polarity);
irda_tim_tx.buffer[0].data = NULL;
irda_tim_tx.buffer[1].data = NULL;
irda_tim_tx.buffer[0].polarity = NULL;
irda_tim_tx.buffer[1].polarity = NULL;
}
void furi_hal_irda_async_tx_start(uint32_t freq, float duty_cycle) {
if((duty_cycle > 1) || (duty_cycle <= 0) || (freq > IRDA_MAX_FREQUENCY) ||
(freq < IRDA_MIN_FREQUENCY) || (irda_tim_tx.data_callback == NULL)) {
furi_crash(NULL);
}
furi_assert(furi_hal_irda_state == IrdaStateIdle);
furi_assert(irda_tim_tx.buffer[0].data == NULL);
furi_assert(irda_tim_tx.buffer[1].data == NULL);
furi_assert(irda_tim_tx.buffer[0].polarity == NULL);
furi_assert(irda_tim_tx.buffer[1].polarity == NULL);
size_t alloc_size_data = IRDA_TIM_TX_DMA_BUFFER_SIZE * sizeof(uint16_t);
irda_tim_tx.buffer[0].data = furi_alloc(alloc_size_data);
irda_tim_tx.buffer[1].data = furi_alloc(alloc_size_data);
size_t alloc_size_polarity =
(IRDA_TIM_TX_DMA_BUFFER_SIZE + IRDA_POLARITY_SHIFT) * sizeof(uint8_t);
irda_tim_tx.buffer[0].polarity = furi_alloc(alloc_size_polarity);
irda_tim_tx.buffer[1].polarity = furi_alloc(alloc_size_polarity);
irda_tim_tx.stop_semaphore = osSemaphoreNew(1, 0, NULL);
irda_tim_tx.cycle_duration = 1000000.0 / freq;
irda_tim_tx.tx_timing_rest_duration = 0;
furi_hal_irda_tx_fill_buffer(0, IRDA_POLARITY_SHIFT);
furi_hal_irda_configure_tim_pwm_tx(freq, duty_cycle);
furi_hal_irda_configure_tim_cmgr2_dma_tx();
furi_hal_irda_configure_tim_rcr_dma_tx();
furi_hal_irda_tx_dma_set_polarity(0, IRDA_POLARITY_SHIFT);
furi_hal_irda_tx_dma_set_buffer(0);
furi_hal_irda_state = IrdaStateAsyncTx;
LL_TIM_ClearFlag_UPDATE(TIM1);
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1);
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_2);
delay_us(5);
LL_TIM_GenerateEvent_UPDATE(TIM1); /* DMA -> TIMx_RCR */
delay_us(5);
LL_GPIO_ResetOutputPin(
gpio_irda_tx.port, gpio_irda_tx.pin); /* when disable it prevents false pulse */
hal_gpio_init_ex(
&gpio_irda_tx, GpioModeAltFunctionPushPull, GpioPullUp, GpioSpeedHigh, GpioAltFn1TIM1);
__disable_irq();
LL_TIM_GenerateEvent_UPDATE(TIM1); /* TIMx_RCR -> Repetition counter */
LL_TIM_EnableCounter(TIM1);
__enable_irq();
}
void furi_hal_irda_async_tx_wait_termination(void) {
furi_assert(furi_hal_irda_state >= IrdaStateAsyncTx);
furi_assert(furi_hal_irda_state < IrdaStateMAX);
osStatus_t status;
status = osSemaphoreAcquire(irda_tim_tx.stop_semaphore, osWaitForever);
furi_check(status == osOK);
furi_hal_irda_async_tx_free_resources();
furi_hal_irda_state = IrdaStateIdle;
}
void furi_hal_irda_async_tx_stop(void) {
furi_assert(furi_hal_irda_state >= IrdaStateAsyncTx);
furi_assert(furi_hal_irda_state < IrdaStateMAX);
__disable_irq();
if(furi_hal_irda_state == IrdaStateAsyncTx) furi_hal_irda_state = IrdaStateAsyncTxStopReq;
__enable_irq();
furi_hal_irda_async_tx_wait_termination();
}
void furi_hal_irda_async_tx_set_data_isr_callback(
FuriHalIrdaTxGetDataISRCallback callback,
void* context) {
furi_assert(furi_hal_irda_state == IrdaStateIdle);
irda_tim_tx.data_callback = callback;
irda_tim_tx.data_context = context;
}
void furi_hal_irda_async_tx_set_signal_sent_isr_callback(
FuriHalIrdaTxSignalSentISRCallback callback,
void* context) {
irda_tim_tx.signal_sent_callback = callback;
irda_tim_tx.signal_sent_context = context;
}
@@ -0,0 +1,49 @@
#include <furi_hal_light.h>
#include <lp5562.h>
#define LED_CURRENT_RED 50
#define LED_CURRENT_GREEN 50
#define LED_CURRENT_BLUE 50
#define LED_CURRENT_WHITE 150
void furi_hal_light_init() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
lp5562_reset(&furi_hal_i2c_handle_power);
lp5562_set_channel_current(&furi_hal_i2c_handle_power, LP5562ChannelRed, LED_CURRENT_RED);
lp5562_set_channel_current(&furi_hal_i2c_handle_power, LP5562ChannelGreen, LED_CURRENT_GREEN);
lp5562_set_channel_current(&furi_hal_i2c_handle_power, LP5562ChannelBlue, LED_CURRENT_BLUE);
lp5562_set_channel_current(&furi_hal_i2c_handle_power, LP5562ChannelWhite, LED_CURRENT_WHITE);
lp5562_set_channel_value(&furi_hal_i2c_handle_power, LP5562ChannelRed, 0x00);
lp5562_set_channel_value(&furi_hal_i2c_handle_power, LP5562ChannelGreen, 0x00);
lp5562_set_channel_value(&furi_hal_i2c_handle_power, LP5562ChannelBlue, 0x00);
lp5562_set_channel_value(&furi_hal_i2c_handle_power, LP5562ChannelWhite, 0x00);
lp5562_enable(&furi_hal_i2c_handle_power);
lp5562_configure(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
}
void furi_hal_light_set(Light light, uint8_t value) {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
switch(light) {
case LightRed:
lp5562_set_channel_value(&furi_hal_i2c_handle_power, LP5562ChannelRed, value);
break;
case LightGreen:
lp5562_set_channel_value(&furi_hal_i2c_handle_power, LP5562ChannelGreen, value);
break;
case LightBlue:
lp5562_set_channel_value(&furi_hal_i2c_handle_power, LP5562ChannelBlue, value);
break;
case LightBacklight:
lp5562_set_channel_value(&furi_hal_i2c_handle_power, LP5562ChannelWhite, value);
break;
default:
break;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
}
+233
View File
@@ -0,0 +1,233 @@
#include "furi_hal_nfc.h"
#include <st25r3916.h>
#define TAG "FuriHalNfc"
static const uint32_t clocks_in_ms = 64 * 1000;
void furi_hal_nfc_init() {
ReturnCode ret = rfalNfcInitialize();
if(ret == ERR_NONE) {
furi_hal_nfc_start_sleep();
FURI_LOG_I(TAG, "Init OK");
} else {
FURI_LOG_W(TAG, "Initialization failed, RFAL returned: %d", ret);
}
}
bool furi_hal_nfc_is_busy() {
return rfalNfcGetState() != RFAL_NFC_STATE_IDLE;
}
void furi_hal_nfc_field_on() {
furi_hal_nfc_exit_sleep();
st25r3916TxRxOn();
}
void furi_hal_nfc_field_off() {
st25r3916TxRxOff();
furi_hal_nfc_start_sleep();
}
void furi_hal_nfc_start_sleep() {
rfalLowPowerModeStart();
}
void furi_hal_nfc_exit_sleep() {
rfalLowPowerModeStop();
}
bool furi_hal_nfc_detect(
rfalNfcDevice** dev_list,
uint8_t* dev_cnt,
uint32_t timeout,
bool deactivate) {
furi_assert(dev_list);
furi_assert(dev_cnt);
rfalLowPowerModeStop();
rfalNfcState state = rfalNfcGetState();
if(state == RFAL_NFC_STATE_NOTINIT) {
rfalNfcInitialize();
}
rfalNfcDiscoverParam params;
params.compMode = RFAL_COMPLIANCE_MODE_EMV;
params.techs2Find = RFAL_NFC_POLL_TECH_A | RFAL_NFC_POLL_TECH_B | RFAL_NFC_POLL_TECH_F |
RFAL_NFC_POLL_TECH_V | RFAL_NFC_POLL_TECH_AP2P | RFAL_NFC_POLL_TECH_ST25TB;
params.totalDuration = 1000;
params.devLimit = 3;
params.wakeupEnabled = false;
params.wakeupConfigDefault = true;
params.nfcfBR = RFAL_BR_212;
params.ap2pBR = RFAL_BR_424;
params.maxBR = RFAL_BR_KEEP;
params.GBLen = RFAL_NFCDEP_GB_MAX_LEN;
params.notifyCb = NULL;
uint32_t start = DWT->CYCCNT;
rfalNfcDiscover(&params);
while(state != RFAL_NFC_STATE_ACTIVATED) {
rfalNfcWorker();
state = rfalNfcGetState();
FURI_LOG_T(TAG, "Current state %d", state);
if(state == RFAL_NFC_STATE_POLL_ACTIVATION) {
start = DWT->CYCCNT;
continue;
}
if(state == RFAL_NFC_STATE_POLL_SELECT) {
rfalNfcSelect(0);
}
if(DWT->CYCCNT - start > timeout * clocks_in_ms) {
rfalNfcDeactivate(true);
FURI_LOG_T(TAG, "Timeout");
return false;
}
osThreadYield();
}
rfalNfcGetDevicesFound(dev_list, dev_cnt);
if(deactivate) {
rfalNfcDeactivate(false);
rfalLowPowerModeStart();
}
return true;
}
bool furi_hal_nfc_listen(
uint8_t* uid,
uint8_t uid_len,
uint8_t* atqa,
uint8_t sak,
bool activate_after_sak,
uint32_t timeout) {
rfalNfcState state = rfalNfcGetState();
if(state == RFAL_NFC_STATE_NOTINIT) {
rfalNfcInitialize();
} else if(state >= RFAL_NFC_STATE_ACTIVATED) {
rfalNfcDeactivate(false);
}
rfalLowPowerModeStop();
rfalNfcDiscoverParam params = {
.compMode = RFAL_COMPLIANCE_MODE_NFC,
.techs2Find = RFAL_NFC_LISTEN_TECH_A,
.totalDuration = 1000,
.devLimit = 1,
.wakeupEnabled = false,
.wakeupConfigDefault = true,
.nfcfBR = RFAL_BR_212,
.ap2pBR = RFAL_BR_424,
.maxBR = RFAL_BR_KEEP,
.GBLen = RFAL_NFCDEP_GB_MAX_LEN,
.notifyCb = NULL,
.activate_after_sak = activate_after_sak,
};
params.lmConfigPA.nfcidLen = uid_len;
memcpy(params.lmConfigPA.nfcid, uid, uid_len);
params.lmConfigPA.SENS_RES[0] = atqa[0];
params.lmConfigPA.SENS_RES[1] = atqa[1];
params.lmConfigPA.SEL_RES = sak;
rfalNfcDiscover(&params);
uint32_t start = DWT->CYCCNT;
while(state != RFAL_NFC_STATE_ACTIVATED) {
rfalNfcWorker();
state = rfalNfcGetState();
if(DWT->CYCCNT - start > timeout * clocks_in_ms) {
rfalNfcDeactivate(true);
return false;
}
osThreadYield();
}
return true;
}
bool furi_hal_nfc_get_first_frame(uint8_t** rx_buff, uint16_t** rx_len) {
ReturnCode ret =
rfalNfcDataExchangeStart(NULL, 0, rx_buff, rx_len, 0, RFAL_TXRX_FLAGS_DEFAULT);
return ret == ERR_NONE;
}
ReturnCode furi_hal_nfc_data_exchange(
uint8_t* tx_buff,
uint16_t tx_len,
uint8_t** rx_buff,
uint16_t** rx_len,
bool deactivate) {
furi_assert(rx_buff);
furi_assert(rx_len);
ReturnCode ret;
rfalNfcState state = RFAL_NFC_STATE_ACTIVATED;
ret = rfalNfcDataExchangeStart(tx_buff, tx_len, rx_buff, rx_len, 0, RFAL_TXRX_FLAGS_DEFAULT);
if(ret != ERR_NONE) {
return ret;
}
uint32_t start = DWT->CYCCNT;
while(state != RFAL_NFC_STATE_DATAEXCHANGE_DONE) {
rfalNfcWorker();
state = rfalNfcGetState();
ret = rfalNfcDataExchangeGetStatus();
if(ret > ERR_SLEEP_REQ) {
return ret;
}
if(ret == ERR_BUSY) {
if(DWT->CYCCNT - start > 1000 * clocks_in_ms) {
return ERR_TIMEOUT;
}
continue;
} else {
start = DWT->CYCCNT;
}
taskYIELD();
}
if(deactivate) {
rfalNfcDeactivate(false);
rfalLowPowerModeStart();
}
return ERR_NONE;
}
ReturnCode furi_hal_nfc_raw_bitstream_exchange(
uint8_t* tx_buff,
uint16_t tx_bit_len,
uint8_t** rx_buff,
uint16_t** rx_bit_len,
bool deactivate) {
furi_assert(rx_buff);
furi_assert(rx_bit_len);
ReturnCode ret;
rfalNfcState state = RFAL_NFC_STATE_ACTIVATED;
ret =
rfalNfcDataExchangeStart(tx_buff, tx_bit_len, rx_buff, rx_bit_len, 0, RFAL_TXRX_FLAGS_RAW);
if(ret != ERR_NONE) {
return ret;
}
uint32_t start = DWT->CYCCNT;
while(state != RFAL_NFC_STATE_DATAEXCHANGE_DONE) {
rfalNfcWorker();
state = rfalNfcGetState();
ret = rfalNfcDataExchangeGetStatus();
if(ret > ERR_SLEEP_REQ) {
return ret;
}
if(ret == ERR_BUSY) {
if(DWT->CYCCNT - start > 1000 * clocks_in_ms) {
return ERR_TIMEOUT;
}
continue;
} else {
start = DWT->CYCCNT;
}
taskYIELD();
}
if(deactivate) {
rfalNfcDeactivate(false);
rfalLowPowerModeStart();
}
return ERR_NONE;
}
void furi_hal_nfc_deactivate() {
rfalNfcDeactivate(false);
rfalLowPowerModeStart();
}
+144
View File
@@ -0,0 +1,144 @@
#include <furi_hal_os.h>
#include <furi_hal_os_timer.h>
#include <furi_hal_power.h>
#include <stm32wbxx_ll_cortex.h>
#include <furi.h>
#define TAG "FuriHalOs"
#define FURI_HAL_OS_CLK_FREQUENCY 32768
#define FURI_HAL_OS_TICK_PER_SECOND 1024
#define FURI_HAL_OS_CLK_PER_TICK (FURI_HAL_OS_CLK_FREQUENCY / FURI_HAL_OS_TICK_PER_SECOND)
#define FURI_HAL_OS_TICK_PER_EPOCH (FURI_HAL_OS_TIMER_MAX / FURI_HAL_OS_CLK_PER_TICK)
#define FURI_HAL_OS_MAX_SLEEP (FURI_HAL_OS_TICK_PER_EPOCH - 1)
#ifdef FURI_HAL_OS_DEBUG
#include <stm32wbxx_ll_gpio.h>
#define LED_SLEEP_PORT GPIOA
#define LED_SLEEP_PIN LL_GPIO_PIN_7
#define LED_TICK_PORT GPIOA
#define LED_TICK_PIN LL_GPIO_PIN_6
#define LED_SECOND_PORT GPIOA
#define LED_SECOND_PIN LL_GPIO_PIN_4
void furi_hal_os_timer_callback() {
LL_GPIO_TogglePin(LED_SECOND_PORT, LED_SECOND_PIN);
}
#endif
extern void xPortSysTickHandler();
volatile uint32_t furi_hal_os_skew = 0;
void furi_hal_os_init() {
LL_DBGMCU_APB1_GRP2_FreezePeriph(LL_DBGMCU_APB1_GRP2_LPTIM2_STOP);
furi_hal_os_timer_init();
furi_hal_os_timer_continuous(FURI_HAL_OS_CLK_PER_TICK);
#ifdef FURI_HAL_OS_DEBUG
LL_GPIO_SetPinMode(LED_SLEEP_PORT, LED_SLEEP_PIN, LL_GPIO_MODE_OUTPUT);
LL_GPIO_SetPinMode(LED_TICK_PORT, LED_TICK_PIN, LL_GPIO_MODE_OUTPUT);
LL_GPIO_SetPinMode(LED_SECOND_PORT, LED_SECOND_PIN, LL_GPIO_MODE_OUTPUT);
osTimerId_t second_timer = osTimerNew(furi_hal_os_timer_callback, osTimerPeriodic, NULL, NULL);
osTimerStart(second_timer, FURI_HAL_OS_TICK_PER_SECOND);
#endif
FURI_LOG_I(TAG, "Init OK");
}
void LPTIM2_IRQHandler(void) {
// Autoreload
if(LL_LPTIM_IsActiveFlag_ARRM(FURI_HAL_OS_TIMER)) {
LL_LPTIM_ClearFLAG_ARRM(FURI_HAL_OS_TIMER);
if(xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
#ifdef FURI_HAL_OS_DEBUG
LL_GPIO_TogglePin(LED_TICK_PORT, LED_TICK_PIN);
#endif
xPortSysTickHandler();
}
}
if(LL_LPTIM_IsActiveFlag_CMPM(FURI_HAL_OS_TIMER)) {
LL_LPTIM_ClearFLAG_CMPM(FURI_HAL_OS_TIMER);
}
}
static inline uint32_t furi_hal_os_sleep(TickType_t expected_idle_ticks) {
// Stop ticks
furi_hal_os_timer_reset();
LL_SYSTICK_DisableIT();
// Start wakeup timer
furi_hal_os_timer_single(expected_idle_ticks * FURI_HAL_OS_CLK_PER_TICK);
#ifdef FURI_HAL_OS_DEBUG
LL_GPIO_ResetOutputPin(LED_SLEEP_PORT, LED_SLEEP_PIN);
#endif
// Go to sleep mode
furi_hal_power_sleep();
#ifdef FURI_HAL_OS_DEBUG
LL_GPIO_SetOutputPin(LED_SLEEP_PORT, LED_SLEEP_PIN);
#endif
// Calculate how much time we spent in the sleep
uint32_t after_cnt = furi_hal_os_timer_get_cnt() + furi_hal_os_skew;
uint32_t after_tick = after_cnt / FURI_HAL_OS_CLK_PER_TICK;
furi_hal_os_skew = after_cnt % FURI_HAL_OS_CLK_PER_TICK;
bool cmpm = LL_LPTIM_IsActiveFlag_CMPM(FURI_HAL_OS_TIMER);
bool arrm = LL_LPTIM_IsActiveFlag_ARRM(FURI_HAL_OS_TIMER);
if(cmpm && arrm) after_tick += expected_idle_ticks;
// Prepare tick timer for new round
furi_hal_os_timer_reset();
// Resume ticks
LL_SYSTICK_EnableIT();
furi_hal_os_timer_continuous(FURI_HAL_OS_CLK_PER_TICK);
return after_tick;
}
void vPortSuppressTicksAndSleep(TickType_t expected_idle_ticks) {
if(!furi_hal_power_sleep_available()) {
__WFI();
return;
}
// Limit mount of ticks to maximum that timer can count
if(expected_idle_ticks > FURI_HAL_OS_MAX_SLEEP) {
expected_idle_ticks = FURI_HAL_OS_MAX_SLEEP;
}
// Stop IRQ handling, no one should disturb us till we finish
__disable_irq();
// Confirm OS that sleep is still possible
if(eTaskConfirmSleepModeStatus() == eAbortSleep) {
__enable_irq();
return;
}
// Sleep and track how much ticks we spent sleeping
uint32_t completed_ticks = furi_hal_os_sleep(expected_idle_ticks);
// Notify system about time spent in sleep
if(completed_ticks > 0) {
if(completed_ticks > expected_idle_ticks) {
vTaskStepTick(expected_idle_ticks);
} else {
vTaskStepTick(completed_ticks);
}
}
// Reenable IRQ
__enable_irq();
}
void vApplicationStackOverflowHook(TaskHandle_t xTask, char* pcTaskName) {
furi_crash("StackOverflow");
}
@@ -0,0 +1,16 @@
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Initialize OS helpers
* Configure and start tick timer
*/
void furi_hal_os_init();
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,69 @@
#pragma once
#include <stm32wbxx_ll_lptim.h>
#include <stm32wbxx_ll_bus.h>
#include <stdint.h>
// Timer used for system ticks
#define FURI_HAL_OS_TIMER_MAX 0xFFFF
#define FURI_HAL_OS_TIMER_REG_LOAD_DLY 0x1
#define FURI_HAL_OS_TIMER LPTIM2
#define FURI_HAL_OS_TIMER_IRQ LPTIM2_IRQn
static inline void furi_hal_os_timer_init() {
// Configure clock source
LL_RCC_SetLPTIMClockSource(LL_RCC_LPTIM2_CLKSOURCE_LSE);
LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_LPTIM2);
// Set interrupt priority and enable them
NVIC_SetPriority(
FURI_HAL_OS_TIMER_IRQ, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 15, 0));
NVIC_EnableIRQ(FURI_HAL_OS_TIMER_IRQ);
}
static inline void furi_hal_os_timer_continuous(uint32_t count) {
count--;
// Enable timer
LL_LPTIM_Enable(FURI_HAL_OS_TIMER);
while(!LL_LPTIM_IsEnabled(FURI_HAL_OS_TIMER))
;
// Enable rutoreload match interrupt
LL_LPTIM_EnableIT_ARRM(FURI_HAL_OS_TIMER);
// Set autoreload and start counter
LL_LPTIM_SetAutoReload(FURI_HAL_OS_TIMER, count);
LL_LPTIM_StartCounter(FURI_HAL_OS_TIMER, LL_LPTIM_OPERATING_MODE_CONTINUOUS);
}
static inline void furi_hal_os_timer_single(uint32_t count) {
count--;
// Enable timer
LL_LPTIM_Enable(FURI_HAL_OS_TIMER);
while(!LL_LPTIM_IsEnabled(FURI_HAL_OS_TIMER))
;
// Enable compare match interrupt
LL_LPTIM_EnableIT_CMPM(FURI_HAL_OS_TIMER);
// Set compare, autoreload and start counter
// Include some marging to workaround ARRM behaviour
LL_LPTIM_SetCompare(FURI_HAL_OS_TIMER, count - 3);
LL_LPTIM_SetAutoReload(FURI_HAL_OS_TIMER, count);
LL_LPTIM_StartCounter(FURI_HAL_OS_TIMER, LL_LPTIM_OPERATING_MODE_ONESHOT);
}
static inline void furi_hal_os_timer_reset() {
// Hard reset timer
// THE ONLY RELIABLEWAY to stop it according to errata
LL_LPTIM_DeInit(FURI_HAL_OS_TIMER);
}
static inline uint32_t furi_hal_os_timer_get_cnt() {
uint32_t counter = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
uint32_t counter_shadow = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
while(counter != counter_shadow) {
counter = counter_shadow;
counter_shadow = LL_LPTIM_GetCounter(FURI_HAL_OS_TIMER);
}
return counter;
}
@@ -0,0 +1,391 @@
#include <furi_hal_power.h>
#include <furi_hal_clock.h>
#include <furi_hal_bt.h>
#include <stm32wbxx_ll_rcc.h>
#include <stm32wbxx_ll_pwr.h>
#include <stm32wbxx_ll_hsem.h>
#include <stm32wbxx_ll_cortex.h>
#include <stm32wbxx_ll_gpio.h>
#include <main.h>
#include <hw_conf.h>
#include <bq27220.h>
#include <bq25896.h>
#include <furi.h>
#define TAG "FuriHalPower"
typedef struct {
volatile uint8_t insomnia;
volatile uint8_t deep_insomnia;
volatile uint8_t suppress_charge;
} FuriHalPower;
static volatile FuriHalPower furi_hal_power = {
.insomnia = 0,
.deep_insomnia = 1,
.suppress_charge = 0,
};
const ParamCEDV cedv = {
.cedv_conf.gauge_conf =
{
.CCT = 1,
.CSYNC = 0,
.EDV_CMP = 0,
.SC = 1,
.FIXED_EDV0 = 1,
.FCC_LIM = 1,
.FC_FOR_VDQ = 1,
.IGNORE_SD = 1,
.SME0 = 0,
},
.full_charge_cap = 2100,
.design_cap = 2100,
.EDV0 = 3300,
.EDV1 = 3321,
.EDV2 = 3355,
.EMF = 3679,
.C0 = 430,
.C1 = 0,
.R1 = 408,
.R0 = 334,
.T0 = 4626,
.TC = 11,
.DOD0 = 4044,
.DOD10 = 3905,
.DOD20 = 3807,
.DOD30 = 3718,
.DOD40 = 3642,
.DOD50 = 3585,
.DOD60 = 3546,
.DOD70 = 3514,
.DOD80 = 3477,
.DOD90 = 3411,
.DOD100 = 3299,
};
void HAL_RCC_CSSCallback(void) {
// TODO: notify user about issue with HSE
furi_hal_power_reset();
}
void furi_hal_power_init() {
LL_PWR_SetRegulVoltageScaling(LL_PWR_REGU_VOLTAGE_SCALE1);
LL_PWR_SMPS_SetMode(LL_PWR_SMPS_STEP_DOWN);
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
bq27220_init(&furi_hal_i2c_handle_power, &cedv);
bq25896_init(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
FURI_LOG_I(TAG, "Init OK");
}
uint16_t furi_hal_power_insomnia_level() {
return furi_hal_power.insomnia;
}
void furi_hal_power_insomnia_enter() {
vTaskSuspendAll();
furi_hal_power.insomnia++;
xTaskResumeAll();
}
void furi_hal_power_insomnia_exit() {
vTaskSuspendAll();
furi_hal_power.insomnia--;
xTaskResumeAll();
}
bool furi_hal_power_sleep_available() {
return furi_hal_power.insomnia == 0;
}
bool furi_hal_power_deep_sleep_available() {
return furi_hal_bt_is_alive() && furi_hal_power.deep_insomnia == 0;
}
void furi_hal_power_light_sleep() {
__WFI();
}
void furi_hal_power_deep_sleep() {
while(LL_HSEM_1StepLock(HSEM, CFG_HW_RCC_SEMID))
;
if(!LL_HSEM_1StepLock(HSEM, CFG_HW_ENTRY_STOP_MODE_SEMID)) {
if(LL_PWR_IsActiveFlag_C2DS()) {
// Release ENTRY_STOP_MODE semaphore
LL_HSEM_ReleaseLock(HSEM, CFG_HW_ENTRY_STOP_MODE_SEMID, 0);
// The switch on HSI before entering Stop Mode is required
furi_hal_clock_switch_to_hsi();
}
} else {
/**
* The switch on HSI before entering Stop Mode is required
*/
furi_hal_clock_switch_to_hsi();
}
/* Release RCC semaphore */
LL_HSEM_ReleaseLock(HSEM, CFG_HW_RCC_SEMID, 0);
// Prepare deep sleep
LL_PWR_SetPowerMode(LL_PWR_MODE_STOP1);
LL_LPM_EnableDeepSleep();
#if defined(__CC_ARM)
// Force store operations
__force_stores();
#endif
__WFI();
/* Release ENTRY_STOP_MODE semaphore */
LL_HSEM_ReleaseLock(HSEM, CFG_HW_ENTRY_STOP_MODE_SEMID, 0);
while(LL_HSEM_1StepLock(HSEM, CFG_HW_RCC_SEMID))
;
if(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL) {
furi_hal_clock_switch_to_pll();
}
LL_HSEM_ReleaseLock(HSEM, CFG_HW_RCC_SEMID, 0);
}
void furi_hal_power_sleep() {
if(furi_hal_power_deep_sleep_available()) {
furi_hal_power_deep_sleep();
} else {
furi_hal_power_light_sleep();
}
}
uint8_t furi_hal_power_get_pct() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
uint8_t ret = bq27220_get_state_of_charge(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
uint8_t furi_hal_power_get_bat_health_pct() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
uint8_t ret = bq27220_get_state_of_health(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
bool furi_hal_power_is_charging() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
bool ret = bq25896_is_charging(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
void furi_hal_power_off() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
bq25896_poweroff(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
}
void furi_hal_power_reset() {
NVIC_SystemReset();
}
void furi_hal_power_enable_otg() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
bq25896_enable_otg(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
}
void furi_hal_power_disable_otg() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
bq25896_disable_otg(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
}
bool furi_hal_power_is_otg_enabled() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
bool ret = bq25896_is_otg_enabled(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
uint32_t furi_hal_power_get_battery_remaining_capacity() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
uint32_t ret = bq27220_get_remaining_capacity(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
uint32_t furi_hal_power_get_battery_full_capacity() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
uint32_t ret = bq27220_get_full_charge_capacity(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
float furi_hal_power_get_battery_voltage(FuriHalPowerIC ic) {
float ret = 0.0f;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
if(ic == FuriHalPowerICCharger) {
ret = (float)bq25896_get_vbat_voltage(&furi_hal_i2c_handle_power) / 1000.0f;
} else if(ic == FuriHalPowerICFuelGauge) {
ret = (float)bq27220_get_voltage(&furi_hal_i2c_handle_power) / 1000.0f;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
float furi_hal_power_get_battery_current(FuriHalPowerIC ic) {
float ret = 0.0f;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
if(ic == FuriHalPowerICCharger) {
ret = (float)bq25896_get_vbat_current(&furi_hal_i2c_handle_power) / 1000.0f;
} else if(ic == FuriHalPowerICFuelGauge) {
ret = (float)bq27220_get_current(&furi_hal_i2c_handle_power) / 1000.0f;
}
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
static float furi_hal_power_get_battery_temperature_internal(FuriHalPowerIC ic) {
float ret = 0.0f;
if(ic == FuriHalPowerICCharger) {
// Linear approximation, +/- 5 C
ret = (71.0f - (float)bq25896_get_ntc_mpct(&furi_hal_i2c_handle_power) / 1000) / 0.6f;
} else if(ic == FuriHalPowerICFuelGauge) {
ret = ((float)bq27220_get_temperature(&furi_hal_i2c_handle_power) - 2731.0f) / 10.0f;
}
return ret;
}
float furi_hal_power_get_battery_temperature(FuriHalPowerIC ic) {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
float ret = furi_hal_power_get_battery_temperature_internal(ic);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
float furi_hal_power_get_usb_voltage() {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
float ret = (float)bq25896_get_vbus_voltage(&furi_hal_i2c_handle_power) / 1000.0f;
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
return ret;
}
void furi_hal_power_dump_state() {
BatteryStatus battery_status;
OperationStatus operation_status;
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
if(bq27220_get_battery_status(&furi_hal_i2c_handle_power, &battery_status) == BQ27220_ERROR ||
bq27220_get_operation_status(&furi_hal_i2c_handle_power, &operation_status) ==
BQ27220_ERROR) {
printf("Failed to get bq27220 status. Communication error.\r\n");
} else {
printf(
"bq27220: CALMD: %d, SEC0: %d, SEC1: %d, EDV2: %d, VDQ: %d, INITCOMP: %d, SMTH: %d, BTPINT: %d, CFGUPDATE: %d\r\n",
operation_status.CALMD,
operation_status.SEC0,
operation_status.SEC1,
operation_status.EDV2,
operation_status.VDQ,
operation_status.INITCOMP,
operation_status.SMTH,
operation_status.BTPINT,
operation_status.CFGUPDATE);
// Battery status register, part 1
printf(
"bq27220: CHGINH: %d, FC: %d, OTD: %d, OTC: %d, SLEEP: %d, OCVFAIL: %d, OCVCOMP: %d, FD: %d\r\n",
battery_status.CHGINH,
battery_status.FC,
battery_status.OTD,
battery_status.OTC,
battery_status.SLEEP,
battery_status.OCVFAIL,
battery_status.OCVCOMP,
battery_status.FD);
// Battery status register, part 2
printf(
"bq27220: DSG: %d, SYSDWN: %d, TDA: %d, BATTPRES: %d, AUTH_GD: %d, OCVGD: %d, TCA: %d, RSVD: %d\r\n",
battery_status.DSG,
battery_status.SYSDWN,
battery_status.TDA,
battery_status.BATTPRES,
battery_status.AUTH_GD,
battery_status.OCVGD,
battery_status.TCA,
battery_status.RSVD);
// Voltage and current info
printf(
"bq27220: Full capacity: %dmAh, Design capacity: %dmAh, Remaining capacity: %dmAh, State of Charge: %d%%, State of health: %d%%\r\n",
bq27220_get_full_charge_capacity(&furi_hal_i2c_handle_power),
bq27220_get_design_capacity(&furi_hal_i2c_handle_power),
bq27220_get_remaining_capacity(&furi_hal_i2c_handle_power),
bq27220_get_state_of_charge(&furi_hal_i2c_handle_power),
bq27220_get_state_of_health(&furi_hal_i2c_handle_power));
printf(
"bq27220: Voltage: %dmV, Current: %dmA, Temperature: %dC\r\n",
bq27220_get_voltage(&furi_hal_i2c_handle_power),
bq27220_get_current(&furi_hal_i2c_handle_power),
(int)furi_hal_power_get_battery_temperature_internal(FuriHalPowerICFuelGauge));
}
printf(
"bq25896: VBUS: %d, VSYS: %d, VBAT: %d, Current: %d, NTC: %ldm%%\r\n",
bq25896_get_vbus_voltage(&furi_hal_i2c_handle_power),
bq25896_get_vsys_voltage(&furi_hal_i2c_handle_power),
bq25896_get_vbat_voltage(&furi_hal_i2c_handle_power),
bq25896_get_vbat_current(&furi_hal_i2c_handle_power),
bq25896_get_ntc_mpct(&furi_hal_i2c_handle_power));
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
}
void furi_hal_power_enable_external_3_3v() {
LL_GPIO_SetOutputPin(PERIPH_POWER_GPIO_Port, PERIPH_POWER_Pin);
}
void furi_hal_power_disable_external_3_3v() {
LL_GPIO_ResetOutputPin(PERIPH_POWER_GPIO_Port, PERIPH_POWER_Pin);
}
void furi_hal_power_suppress_charge_enter() {
vTaskSuspendAll();
bool disable_charging = furi_hal_power.suppress_charge == 0;
furi_hal_power.suppress_charge++;
xTaskResumeAll();
if(disable_charging) {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
bq25896_disable_charging(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
}
}
void furi_hal_power_suppress_charge_exit() {
vTaskSuspendAll();
furi_hal_power.suppress_charge--;
bool enable_charging = furi_hal_power.suppress_charge == 0;
xTaskResumeAll();
if(enable_charging) {
furi_hal_i2c_acquire(&furi_hal_i2c_handle_power);
bq25896_enable_charging(&furi_hal_i2c_handle_power);
furi_hal_i2c_release(&furi_hal_i2c_handle_power);
}
}
@@ -0,0 +1,49 @@
#include "furi_hal_pwm.h"
void hal_pwm_set(float value, float freq, TIM_HandleTypeDef* tim, uint32_t channel) {
tim->Init.CounterMode = TIM_COUNTERMODE_UP;
tim->Init.Period = (uint32_t)((SystemCoreClock / (tim->Init.Prescaler + 1)) / freq) - 1;
tim->Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim->Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
HAL_TIM_PWM_Init(tim);
TIM_OC_InitTypeDef sConfigOC;
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = (uint16_t)(tim->Init.Period * value);
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
HAL_TIM_PWM_ConfigChannel(tim, &sConfigOC, channel);
HAL_TIM_PWM_Start(tim, channel);
}
void hal_pwmn_set(float value, float freq, TIM_HandleTypeDef* tim, uint32_t channel) {
tim->Init.CounterMode = TIM_COUNTERMODE_UP;
tim->Init.Period = (uint32_t)((SystemCoreClock / (tim->Init.Prescaler + 1)) / freq) - 1;
tim->Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
tim->Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
HAL_TIM_PWM_Init(tim);
TIM_OC_InitTypeDef sConfigOC;
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = (uint16_t)(tim->Init.Period * value);
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
HAL_TIM_PWM_ConfigChannel(tim, &sConfigOC, channel);
HAL_TIMEx_PWMN_Start(tim, channel);
}
void hal_pwm_stop(TIM_HandleTypeDef* tim, uint32_t channel) {
HAL_TIM_PWM_Stop(tim, channel);
}
void hal_pwmn_stop(TIM_HandleTypeDef* tim, uint32_t channel) {
HAL_TIMEx_PWMN_Stop(tim, channel);
}
@@ -0,0 +1,16 @@
#pragma once
#include "main.h"
#include "stdbool.h"
#ifdef __cplusplus
extern "C" {
#endif
void hal_pwm_set(float value, float freq, TIM_HandleTypeDef* tim, uint32_t channel);
void hal_pwmn_set(float value, float freq, TIM_HandleTypeDef* tim, uint32_t channel);
void hal_pwm_stop(TIM_HandleTypeDef* tim, uint32_t channel);
void hal_pwmn_stop(TIM_HandleTypeDef* tim, uint32_t channel);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,58 @@
#include "furi_hal_random.h"
#include <furi.h>
#include <furi_hal.h>
#include <stm32wbxx_ll_rng.h>
#include <stm32wbxx_ll_hsem.h>
#include <hw_conf.h>
uint32_t furi_hal_random_get() {
while(LL_HSEM_1StepLock(HSEM, CFG_HW_RNG_SEMID))
;
LL_RNG_Enable(RNG);
while(!LL_RNG_IsActiveFlag_DRDY(RNG))
;
if((LL_RNG_IsActiveFlag_CECS(RNG)) || (LL_RNG_IsActiveFlag_SECS(RNG))) {
furi_crash("TRNG error");
}
uint32_t random_val = LL_RNG_ReadRandData32(RNG);
LL_RNG_Disable(RNG);
LL_HSEM_ReleaseLock(HSEM, CFG_HW_RNG_SEMID, 0);
return random_val;
}
void furi_hal_random_fill_buf(uint8_t* buf, uint32_t len) {
while(LL_HSEM_1StepLock(HSEM, CFG_HW_RNG_SEMID))
;
LL_RNG_Enable(RNG);
for(uint32_t i = 0; i < len; i += 4) {
while(!LL_RNG_IsActiveFlag_DRDY(RNG))
;
if((LL_RNG_IsActiveFlag_CECS(RNG)) || (LL_RNG_IsActiveFlag_SECS(RNG))) {
furi_crash("TRNG error");
}
uint32_t random_val = LL_RNG_ReadRandData32(RNG);
uint8_t len_cur = ((i + 4) < len) ? (4) : (len - i);
memcpy(&buf[i], &random_val, len_cur);
}
LL_RNG_Disable(RNG);
LL_HSEM_ReleaseLock(HSEM, CFG_HW_RNG_SEMID, 0);
}
void srand(unsigned seed) {
}
int rand() {
return (furi_hal_random_get() & RAND_MAX);
}
@@ -0,0 +1,81 @@
#include <furi_hal_resources.h>
#include "main.h"
#include <furi.h>
const InputPin input_pins[] = {
{.port = BUTTON_UP_GPIO_Port,
.pin = BUTTON_UP_Pin,
.key = InputKeyUp,
.inverted = true,
.name = "Up"},
{.port = BUTTON_DOWN_GPIO_Port,
.pin = BUTTON_DOWN_Pin,
.key = InputKeyDown,
.inverted = true,
.name = "Down"},
{.port = BUTTON_RIGHT_GPIO_Port,
.pin = BUTTON_RIGHT_Pin,
.key = InputKeyRight,
.inverted = true,
.name = "Right"},
{.port = BUTTON_LEFT_GPIO_Port,
.pin = BUTTON_LEFT_Pin,
.key = InputKeyLeft,
.inverted = true,
.name = "Left"},
{.port = BUTTON_OK_GPIO_Port,
.pin = BUTTON_OK_Pin,
.key = InputKeyOk,
.inverted = false,
.name = "Ok"},
{.port = BUTTON_BACK_GPIO_Port,
.pin = BUTTON_BACK_Pin,
.key = InputKeyBack,
.inverted = true,
.name = "Back"},
};
const size_t input_pins_count = sizeof(input_pins) / sizeof(InputPin);
const GpioPin vibro_gpio = {.port = VIBRO_GPIO_Port, .pin = VIBRO_Pin};
const GpioPin ibutton_gpio = {.port = iBTN_GPIO_Port, .pin = iBTN_Pin};
const GpioPin gpio_cc1101_g0 = {.port = CC1101_G0_GPIO_Port, .pin = CC1101_G0_Pin};
const GpioPin gpio_rf_sw_0 = {.port = RF_SW_0_GPIO_Port, .pin = RF_SW_0_Pin};
const GpioPin gpio_subghz_cs = {.port = CC1101_CS_GPIO_Port, .pin = CC1101_CS_Pin};
const GpioPin gpio_display_cs = {.port = DISPLAY_CS_GPIO_Port, .pin = DISPLAY_CS_Pin};
const GpioPin gpio_display_rst = {.port = DISPLAY_RST_GPIO_Port, .pin = DISPLAY_RST_Pin};
const GpioPin gpio_display_di = {.port = DISPLAY_DI_GPIO_Port, .pin = DISPLAY_DI_Pin};
const GpioPin gpio_sdcard_cs = {.port = SD_CS_GPIO_Port, .pin = SD_CS_Pin};
const GpioPin gpio_nfc_cs = {.port = NFC_CS_GPIO_Port, .pin = NFC_CS_Pin};
const GpioPin gpio_spi_d_miso = {.port = SPI_D_MISO_GPIO_Port, .pin = SPI_D_MISO_Pin};
const GpioPin gpio_spi_d_mosi = {.port = SPI_D_MOSI_GPIO_Port, .pin = SPI_D_MOSI_Pin};
const GpioPin gpio_spi_d_sck = {.port = SPI_D_SCK_GPIO_Port, .pin = SPI_D_SCK_Pin};
const GpioPin gpio_spi_r_miso = {.port = SPI_R_MISO_GPIO_Port, .pin = SPI_R_MISO_Pin};
const GpioPin gpio_spi_r_mosi = {.port = SPI_R_MOSI_GPIO_Port, .pin = SPI_R_MOSI_Pin};
const GpioPin gpio_spi_r_sck = {.port = SPI_R_SCK_GPIO_Port, .pin = SPI_R_SCK_Pin};
const GpioPin gpio_ext_pc0 = {.port = GPIOC, .pin = GPIO_PIN_0};
const GpioPin gpio_ext_pc1 = {.port = GPIOC, .pin = GPIO_PIN_1};
const GpioPin gpio_ext_pc3 = {.port = GPIOC, .pin = GPIO_PIN_3};
const GpioPin gpio_ext_pb2 = {.port = GPIOB, .pin = GPIO_PIN_2};
const GpioPin gpio_ext_pb3 = {.port = GPIOB, .pin = GPIO_PIN_3};
const GpioPin gpio_ext_pa4 = {.port = GPIOA, .pin = GPIO_PIN_4};
const GpioPin gpio_ext_pa6 = {.port = GPIOA, .pin = GPIO_PIN_6};
const GpioPin gpio_ext_pa7 = {.port = GPIOA, .pin = GPIO_PIN_7};
const GpioPin gpio_rfid_pull = {.port = RFID_PULL_GPIO_Port, .pin = RFID_PULL_Pin};
const GpioPin gpio_rfid_carrier_out = {.port = RFID_OUT_GPIO_Port, .pin = RFID_OUT_Pin};
const GpioPin gpio_rfid_data_in = {.port = RFID_RF_IN_GPIO_Port, .pin = RFID_RF_IN_Pin};
const GpioPin gpio_rfid_carrier = {.port = RFID_CARRIER_GPIO_Port, .pin = RFID_CARRIER_Pin};
const GpioPin gpio_irda_rx = {.port = IR_RX_GPIO_Port, .pin = IR_RX_Pin};
const GpioPin gpio_irda_tx = {.port = IR_TX_GPIO_Port, .pin = IR_TX_Pin};
const GpioPin gpio_usart_tx = {.port = USART1_TX_Port, .pin = USART1_TX_Pin};
const GpioPin gpio_usart_rx = {.port = USART1_RX_Port, .pin = USART1_RX_Pin};
const GpioPin gpio_i2c_power_sda = {.port = GPIOA, .pin = LL_GPIO_PIN_10};
const GpioPin gpio_i2c_power_scl = {.port = GPIOA, .pin = LL_GPIO_PIN_9};
@@ -0,0 +1,89 @@
#pragma once
#include "main.h"
#include <furi.h>
#include <stm32wbxx.h>
#include <stm32wbxx_ll_gpio.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Input Related Constants */
#define INPUT_DEBOUNCE_TICKS 20
/* Input Keys */
typedef enum {
InputKeyUp,
InputKeyDown,
InputKeyRight,
InputKeyLeft,
InputKeyOk,
InputKeyBack,
} InputKey;
/* Light */
typedef enum {
LightRed,
LightGreen,
LightBlue,
LightBacklight,
} Light;
typedef struct {
const GPIO_TypeDef* port;
const uint16_t pin;
const InputKey key;
const bool inverted;
const char* name;
} InputPin;
extern const InputPin input_pins[];
extern const size_t input_pins_count;
extern const GpioPin vibro_gpio;
extern const GpioPin ibutton_gpio;
extern const GpioPin gpio_cc1101_g0;
extern const GpioPin gpio_rf_sw_0;
extern const GpioPin gpio_subghz_cs;
extern const GpioPin gpio_display_cs;
extern const GpioPin gpio_display_rst;
extern const GpioPin gpio_display_di;
extern const GpioPin gpio_sdcard_cs;
extern const GpioPin gpio_nfc_cs;
extern const GpioPin gpio_spi_d_miso;
extern const GpioPin gpio_spi_d_mosi;
extern const GpioPin gpio_spi_d_sck;
extern const GpioPin gpio_spi_r_miso;
extern const GpioPin gpio_spi_r_mosi;
extern const GpioPin gpio_spi_r_sck;
extern const GpioPin gpio_ext_pc0;
extern const GpioPin gpio_ext_pc1;
extern const GpioPin gpio_ext_pc3;
extern const GpioPin gpio_ext_pb2;
extern const GpioPin gpio_ext_pb3;
extern const GpioPin gpio_ext_pa4;
extern const GpioPin gpio_ext_pa6;
extern const GpioPin gpio_ext_pa7;
extern const GpioPin gpio_rfid_pull;
extern const GpioPin gpio_rfid_carrier_out;
extern const GpioPin gpio_rfid_data_in;
extern const GpioPin gpio_rfid_carrier;
extern const GpioPin gpio_irda_rx;
extern const GpioPin gpio_irda_tx;
extern const GpioPin gpio_usart_tx;
extern const GpioPin gpio_usart_rx;
extern const GpioPin gpio_i2c_power_sda;
extern const GpioPin gpio_i2c_power_scl;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,286 @@
#include <furi_hal_rfid.h>
#include <furi_hal_ibutton.h>
#include <furi_hal_resources.h>
#include <stm32wbxx_ll_tim.h>
#define LFRFID_READ_TIM htim1
#define LFRFID_READ_CHANNEL TIM_CHANNEL_1
#define LFRFID_EMULATE_TIM htim2
#define LFRFID_EMULATE_CHANNEL TIM_CHANNEL_3
void furi_hal_rfid_init() {
furi_hal_rfid_pins_reset();
}
void furi_hal_rfid_pins_reset() {
// ibutton bus disable
furi_hal_ibutton_stop();
// pulldown rfid antenna
hal_gpio_init(&gpio_rfid_carrier_out, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow);
hal_gpio_write(&gpio_rfid_carrier_out, false);
// from both sides
hal_gpio_init(&gpio_rfid_pull, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow);
hal_gpio_write(&gpio_rfid_pull, true);
hal_gpio_init_simple(&gpio_rfid_carrier, GpioModeAnalog);
}
void furi_hal_rfid_pins_emulate() {
// ibutton low
furi_hal_ibutton_start();
furi_hal_ibutton_pin_low();
// pull pin to timer out
hal_gpio_init_ex(
&gpio_rfid_pull, GpioModeAltFunctionPushPull, GpioPullNo, GpioSpeedLow, GpioAltFn1TIM2);
// pull rfid antenna from carrier side
hal_gpio_init(&gpio_rfid_carrier_out, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow);
hal_gpio_write(&gpio_rfid_carrier_out, false);
hal_gpio_init_ex(
&gpio_rfid_carrier, GpioModeAltFunctionPushPull, GpioPullNo, GpioSpeedLow, GpioAltFn2TIM2);
}
void furi_hal_rfid_pins_read() {
// ibutton low
furi_hal_ibutton_start();
furi_hal_ibutton_pin_low();
// dont pull rfid antenna
hal_gpio_init(&gpio_rfid_pull, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow);
hal_gpio_write(&gpio_rfid_pull, false);
// carrier pin to timer out
hal_gpio_init_ex(
&gpio_rfid_carrier_out,
GpioModeAltFunctionPushPull,
GpioPullNo,
GpioSpeedLow,
GpioAltFn1TIM1);
// comparator in
hal_gpio_init(&gpio_rfid_data_in, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
}
void furi_hal_rfid_pin_pull_release() {
hal_gpio_write(&gpio_rfid_pull, true);
}
void furi_hal_rfid_pin_pull_pulldown() {
hal_gpio_write(&gpio_rfid_pull, false);
}
void furi_hal_rfid_tim_read(float freq, float duty_cycle) {
// TODO LL init
uint32_t period = (uint32_t)((SystemCoreClock) / freq) - 1;
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};
// basic PWM setup with needed freq and internal clock
LFRFID_READ_TIM.Init.Prescaler = 0;
LFRFID_READ_TIM.Init.CounterMode = TIM_COUNTERMODE_UP;
LFRFID_READ_TIM.Init.Period = period;
LFRFID_READ_TIM.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
LFRFID_READ_TIM.Init.RepetitionCounter = 0;
LFRFID_READ_TIM.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if(HAL_TIM_Base_Init(&LFRFID_READ_TIM) != HAL_OK) {
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if(HAL_TIM_ConfigClockSource(&LFRFID_READ_TIM, &sClockSourceConfig) != HAL_OK) {
Error_Handler();
}
if(HAL_TIM_PWM_Init(&LFRFID_READ_TIM) != HAL_OK) {
Error_Handler();
}
// no master-slave mode
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterOutputTrigger2 = TIM_TRGO2_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if(HAL_TIMEx_MasterConfigSynchronization(&LFRFID_READ_TIM, &sMasterConfig) != HAL_OK) {
Error_Handler();
}
// pwm config
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = (uint32_t)(LFRFID_READ_TIM.Init.Period * duty_cycle);
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if(HAL_TIM_PWM_ConfigChannel(&LFRFID_READ_TIM, &sConfigOC, LFRFID_READ_CHANNEL) != HAL_OK) {
Error_Handler();
}
// no deadtime
sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
sBreakDeadTimeConfig.DeadTime = 0;
sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
sBreakDeadTimeConfig.BreakFilter = 0;
sBreakDeadTimeConfig.BreakAFMode = TIM_BREAK_AFMODE_INPUT;
sBreakDeadTimeConfig.Break2State = TIM_BREAK2_DISABLE;
sBreakDeadTimeConfig.Break2Polarity = TIM_BREAK2POLARITY_HIGH;
sBreakDeadTimeConfig.Break2Filter = 0;
sBreakDeadTimeConfig.Break2AFMode = TIM_BREAK_AFMODE_INPUT;
sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
if(HAL_TIMEx_ConfigBreakDeadTime(&LFRFID_READ_TIM, &sBreakDeadTimeConfig) != HAL_OK) {
Error_Handler();
}
}
void furi_hal_rfid_tim_read_start() {
HAL_TIMEx_PWMN_Start(&LFRFID_READ_TIM, LFRFID_READ_CHANNEL);
}
void furi_hal_rfid_tim_read_stop() {
HAL_TIMEx_PWMN_Stop(&LFRFID_READ_TIM, LFRFID_READ_CHANNEL);
}
void furi_hal_rfid_tim_emulate(float freq) {
// TODO LL init
// uint32_t prescaler = (uint32_t)((SystemCoreClock) / freq) - 1;
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
// basic PWM setup with needed freq and internal clock
LFRFID_EMULATE_TIM.Init.Prescaler = 0;
LFRFID_EMULATE_TIM.Init.CounterMode = TIM_COUNTERMODE_UP;
LFRFID_EMULATE_TIM.Init.Period = 1;
LFRFID_EMULATE_TIM.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
LFRFID_EMULATE_TIM.Init.RepetitionCounter = 0;
LFRFID_EMULATE_TIM.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if(HAL_TIM_Base_Init(&LFRFID_EMULATE_TIM) != HAL_OK) {
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_ETRMODE2;
sClockSourceConfig.ClockPolarity = TIM_ETRPOLARITY_INVERTED;
sClockSourceConfig.ClockPrescaler = TIM_CLOCKPRESCALER_DIV1;
sClockSourceConfig.ClockFilter = 0;
if(HAL_TIM_ConfigClockSource(&LFRFID_EMULATE_TIM, &sClockSourceConfig) != HAL_OK) {
Error_Handler();
}
if(HAL_TIM_PWM_Init(&LFRFID_EMULATE_TIM) != HAL_OK) {
Error_Handler();
}
// no master-slave mode
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterOutputTrigger2 = TIM_TRGO2_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if(HAL_TIMEx_MasterConfigSynchronization(&LFRFID_EMULATE_TIM, &sMasterConfig) != HAL_OK) {
Error_Handler();
}
// pwm config
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 1;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
if(HAL_TIM_PWM_ConfigChannel(&LFRFID_EMULATE_TIM, &sConfigOC, LFRFID_EMULATE_CHANNEL) !=
HAL_OK) {
Error_Handler();
}
}
void furi_hal_rfid_tim_emulate_start() {
// TODO make api for interrupts priority
for(size_t i = WWDG_IRQn; i <= DMAMUX1_OVR_IRQn; i++) {
HAL_NVIC_SetPriority(i, 15, 0);
}
HAL_NVIC_SetPriority(TIM2_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(TIM2_IRQn);
HAL_TIM_PWM_Start_IT(&LFRFID_EMULATE_TIM, LFRFID_EMULATE_CHANNEL);
HAL_TIM_Base_Start_IT(&LFRFID_EMULATE_TIM);
}
void furi_hal_rfid_tim_emulate_stop() {
HAL_TIM_Base_Stop(&LFRFID_EMULATE_TIM);
HAL_TIM_PWM_Stop(&LFRFID_EMULATE_TIM, LFRFID_EMULATE_CHANNEL);
}
void furi_hal_rfid_tim_reset() {
HAL_TIM_Base_DeInit(&LFRFID_READ_TIM);
LL_TIM_DeInit(TIM1);
LL_APB2_GRP1_DisableClock(LL_APB2_GRP1_PERIPH_TIM1);
HAL_TIM_Base_DeInit(&LFRFID_EMULATE_TIM);
LL_TIM_DeInit(TIM2);
LL_APB1_GRP1_DisableClock(LL_APB1_GRP1_PERIPH_TIM2);
}
bool furi_hal_rfid_is_tim_emulate(TIM_HandleTypeDef* hw) {
return (hw == &LFRFID_EMULATE_TIM);
}
void furi_hal_rfid_set_emulate_period(uint32_t period) {
LFRFID_EMULATE_TIM.Instance->ARR = period;
}
void furi_hal_rfid_set_emulate_pulse(uint32_t pulse) {
switch(LFRFID_EMULATE_CHANNEL) {
case TIM_CHANNEL_1:
LFRFID_EMULATE_TIM.Instance->CCR1 = pulse;
break;
case TIM_CHANNEL_2:
LFRFID_EMULATE_TIM.Instance->CCR2 = pulse;
break;
case TIM_CHANNEL_3:
LFRFID_EMULATE_TIM.Instance->CCR3 = pulse;
break;
case TIM_CHANNEL_4:
LFRFID_EMULATE_TIM.Instance->CCR4 = pulse;
break;
default:
furi_crash(NULL);
break;
}
}
void furi_hal_rfid_set_read_period(uint32_t period) {
LFRFID_TIM.Instance->ARR = period;
}
void furi_hal_rfid_set_read_pulse(uint32_t pulse) {
switch(LFRFID_READ_CHANNEL) {
case TIM_CHANNEL_1:
LFRFID_TIM.Instance->CCR1 = pulse;
break;
case TIM_CHANNEL_2:
LFRFID_TIM.Instance->CCR2 = pulse;
break;
case TIM_CHANNEL_3:
LFRFID_TIM.Instance->CCR3 = pulse;
break;
case TIM_CHANNEL_4:
LFRFID_TIM.Instance->CCR4 = pulse;
break;
default:
furi_crash(NULL);
break;
}
}
void furi_hal_rfid_change_read_config(float freq, float duty_cycle) {
uint32_t period = (uint32_t)((SystemCoreClock) / freq) - 1;
furi_hal_rfid_set_read_period(period);
furi_hal_rfid_set_read_pulse(period * duty_cycle);
}
+165
View File
@@ -0,0 +1,165 @@
#include <furi_hal_rtc.h>
#include <stm32wbxx_ll_rcc.h>
#include <stm32wbxx_ll_rtc.h>
#include <furi.h>
#define TAG "FuriHalRtc"
typedef struct {
uint8_t log_level : 4;
uint8_t log_reserved : 4;
uint8_t flags;
uint16_t reserved;
} DeveloperReg;
_Static_assert(sizeof(DeveloperReg) == 4, "DeveloperReg size mismatch");
void furi_hal_rtc_init() {
if(LL_RCC_GetRTCClockSource() != LL_RCC_RTC_CLKSOURCE_LSE) {
LL_RCC_ForceBackupDomainReset();
LL_RCC_ReleaseBackupDomainReset();
LL_RCC_SetRTCClockSource(LL_RCC_RTC_CLKSOURCE_LSE);
}
LL_RCC_EnableRTC();
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_RTCAPB);
LL_RTC_InitTypeDef RTC_InitStruct = {0};
RTC_InitStruct.HourFormat = LL_RTC_HOURFORMAT_24HOUR;
RTC_InitStruct.AsynchPrescaler = 127;
RTC_InitStruct.SynchPrescaler = 255;
LL_RTC_Init(RTC, &RTC_InitStruct);
furi_log_set_level(furi_hal_rtc_get_log_level());
FURI_LOG_I(TAG, "Init OK");
}
uint32_t furi_hal_rtc_get_register(FuriHalRtcRegister reg) {
return LL_RTC_BAK_GetRegister(RTC, reg);
}
void furi_hal_rtc_set_register(FuriHalRtcRegister reg, uint32_t value) {
LL_RTC_BAK_SetRegister(RTC, reg, value);
}
void furi_hal_rtc_set_log_level(uint8_t level) {
uint32_t data_reg = furi_hal_rtc_get_register(FuriHalRtcRegisterSystem);
DeveloperReg* data = (DeveloperReg*)&data_reg;
data->log_level = level;
furi_hal_rtc_set_register(FuriHalRtcRegisterSystem, data_reg);
furi_log_set_level(level);
}
uint8_t furi_hal_rtc_get_log_level() {
uint32_t data_reg = furi_hal_rtc_get_register(FuriHalRtcRegisterSystem);
DeveloperReg* data = (DeveloperReg*)&data_reg;
return data->log_level;
}
void furi_hal_rtc_set_flag(FuriHalRtcFlag flag) {
uint32_t data_reg = furi_hal_rtc_get_register(FuriHalRtcRegisterSystem);
DeveloperReg* data = (DeveloperReg*)&data_reg;
data->flags |= flag;
furi_hal_rtc_set_register(FuriHalRtcRegisterSystem, data_reg);
}
void furi_hal_rtc_reset_flag(FuriHalRtcFlag flag) {
uint32_t data_reg = furi_hal_rtc_get_register(FuriHalRtcRegisterSystem);
DeveloperReg* data = (DeveloperReg*)&data_reg;
data->flags &= ~flag;
furi_hal_rtc_set_register(FuriHalRtcRegisterSystem, data_reg);
}
bool furi_hal_rtc_is_flag_set(FuriHalRtcFlag flag) {
uint32_t data_reg = furi_hal_rtc_get_register(FuriHalRtcRegisterSystem);
DeveloperReg* data = (DeveloperReg*)&data_reg;
return data->flags & flag;
}
void furi_hal_rtc_set_datetime(FuriHalRtcDateTime* datetime) {
furi_assert(datetime);
/* Disable write protection */
LL_RTC_DisableWriteProtection(RTC);
/* Enter Initialization mode and wait for INIT flag to be set */
LL_RTC_EnableInitMode(RTC);
while(!LL_RTC_IsActiveFlag_INIT(RTC)) {
}
/* Set time */
LL_RTC_TIME_Config(
RTC,
LL_RTC_TIME_FORMAT_AM_OR_24,
__LL_RTC_CONVERT_BIN2BCD(datetime->hour),
__LL_RTC_CONVERT_BIN2BCD(datetime->minute),
__LL_RTC_CONVERT_BIN2BCD(datetime->second));
/* Set date */
LL_RTC_DATE_Config(
RTC,
datetime->weekday,
__LL_RTC_CONVERT_BIN2BCD(datetime->day),
__LL_RTC_CONVERT_BIN2BCD(datetime->month),
__LL_RTC_CONVERT_BIN2BCD(datetime->year - 2000));
/* Exit Initialization mode */
LL_RTC_DisableInitMode(RTC);
/* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
if(!LL_RTC_IsShadowRegBypassEnabled(RTC)) {
LL_RTC_ClearFlag_RS(RTC);
while(!LL_RTC_IsActiveFlag_RS(RTC)) {
};
}
/* Enable write protection */
LL_RTC_EnableWriteProtection(RTC);
}
void furi_hal_rtc_get_datetime(FuriHalRtcDateTime* datetime) {
furi_assert(datetime);
uint32_t time = LL_RTC_TIME_Get(RTC); // 0x00HHMMSS
uint32_t date = LL_RTC_DATE_Get(RTC); // 0xWWDDMMYY
datetime->second = __LL_RTC_CONVERT_BCD2BIN((time >> 0) & 0xFF);
datetime->minute = __LL_RTC_CONVERT_BCD2BIN((time >> 8) & 0xFF);
datetime->hour = __LL_RTC_CONVERT_BCD2BIN((time >> 16) & 0xFF);
datetime->year = __LL_RTC_CONVERT_BCD2BIN((date >> 0) & 0xFF) + 2000;
datetime->month = __LL_RTC_CONVERT_BCD2BIN((date >> 8) & 0xFF);
datetime->day = __LL_RTC_CONVERT_BCD2BIN((date >> 16) & 0xFF);
datetime->weekday = __LL_RTC_CONVERT_BCD2BIN((date >> 24) & 0xFF);
}
bool furi_hal_rtc_validate_datetime(FuriHalRtcDateTime* datetime) {
bool invalid = false;
invalid |= (datetime->second > 59);
invalid |= (datetime->minute > 59);
invalid |= (datetime->hour > 23);
invalid |= (datetime->year < 2000);
invalid |= (datetime->year > 2099);
invalid |= (datetime->month == 0);
invalid |= (datetime->month > 12);
invalid |= (datetime->day == 0);
invalid |= (datetime->day > 31);
invalid |= (datetime->weekday == 0);
invalid |= (datetime->weekday > 7);
return !invalid;
}
void furi_hal_rtc_set_fault_data(uint32_t value) {
furi_hal_rtc_set_register(FuriHalRtcRegisterFaultData, value);
}
uint32_t furi_hal_rtc_get_fault_data() {
return furi_hal_rtc_get_register(FuriHalRtcRegisterFaultData);
}
@@ -0,0 +1,24 @@
#include "furi_hal_sd.h"
#include <stm32wbxx_ll_gpio.h>
#include <furi.h>
void hal_sd_detect_init(void) {
// low speed input with pullup
LL_GPIO_SetPinMode(SD_CD_GPIO_Port, SD_CD_Pin, LL_GPIO_MODE_INPUT);
LL_GPIO_SetPinSpeed(SD_CD_GPIO_Port, SD_CD_Pin, LL_GPIO_SPEED_FREQ_LOW);
LL_GPIO_SetPinPull(SD_CD_GPIO_Port, SD_CD_Pin, LL_GPIO_PULL_UP);
}
void hal_sd_detect_set_low(void) {
// low speed input with pullup
LL_GPIO_SetPinMode(SD_CD_GPIO_Port, SD_CD_Pin, LL_GPIO_MODE_OUTPUT);
LL_GPIO_SetPinOutputType(SD_CD_GPIO_Port, SD_CD_Pin, LL_GPIO_OUTPUT_OPENDRAIN);
LL_GPIO_ResetOutputPin(SD_CD_GPIO_Port, SD_CD_Pin);
}
bool hal_sd_detect(void) {
bool result = !(LL_GPIO_IsInputPinSet(SD_CD_GPIO_Port, SD_CD_Pin));
return result;
}
FuriHalSpiBusHandle* furi_hal_sd_spi_handle = NULL;
+155
View File
@@ -0,0 +1,155 @@
#include "furi_hal_spi.h"
#include "furi_hal_resources.h"
#include <stdbool.h>
#include <string.h>
#include <furi.h>
#include <stm32wbxx_ll_spi.h>
#include <stm32wbxx_ll_utils.h>
#include <stm32wbxx_ll_cortex.h>
#define TAG "FuriHalSpi"
void furi_hal_spi_init() {
furi_hal_spi_bus_init(&furi_hal_spi_bus_r);
furi_hal_spi_bus_init(&furi_hal_spi_bus_d);
furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_nfc);
furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_display);
furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_sd_fast);
furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_sd_slow);
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_spi_bus_init(FuriHalSpiBus* bus) {
furi_assert(bus);
bus->callback(bus, FuriHalSpiBusEventInit);
}
void furi_hal_spi_bus_deinit(FuriHalSpiBus* bus) {
furi_assert(bus);
bus->callback(bus, FuriHalSpiBusEventDeinit);
}
void furi_hal_spi_bus_handle_init(FuriHalSpiBusHandle* handle) {
furi_assert(handle);
handle->callback(handle, FuriHalSpiBusHandleEventInit);
}
void furi_hal_spi_bus_handle_deinit(FuriHalSpiBusHandle* handle) {
furi_assert(handle);
handle->callback(handle, FuriHalSpiBusHandleEventDeinit);
}
void furi_hal_spi_acquire(FuriHalSpiBusHandle* handle) {
furi_assert(handle);
handle->bus->callback(handle->bus, FuriHalSpiBusEventLock);
handle->bus->callback(handle->bus, FuriHalSpiBusEventActivate);
furi_assert(handle->bus->current_handle == NULL);
handle->bus->current_handle = handle;
handle->callback(handle, FuriHalSpiBusHandleEventActivate);
}
void furi_hal_spi_release(FuriHalSpiBusHandle* handle) {
furi_assert(handle);
furi_assert(handle->bus->current_handle == handle);
// Handle event and unset handle
handle->callback(handle, FuriHalSpiBusHandleEventDeactivate);
handle->bus->current_handle = NULL;
// Bus events
handle->bus->callback(handle->bus, FuriHalSpiBusEventDeactivate);
handle->bus->callback(handle->bus, FuriHalSpiBusEventUnlock);
}
static void furi_hal_spi_bus_end_txrx(FuriHalSpiBusHandle* handle, uint32_t timeout) {
while(LL_SPI_GetTxFIFOLevel(handle->bus->spi) != LL_SPI_TX_FIFO_EMPTY)
;
while(LL_SPI_IsActiveFlag_BSY(handle->bus->spi))
;
while(LL_SPI_GetRxFIFOLevel(handle->bus->spi) != LL_SPI_RX_FIFO_EMPTY) {
LL_SPI_ReceiveData8(handle->bus->spi);
}
}
bool furi_hal_spi_bus_rx(
FuriHalSpiBusHandle* handle,
uint8_t* buffer,
size_t size,
uint32_t timeout) {
furi_assert(handle);
furi_assert(handle->bus->current_handle == handle);
furi_assert(buffer);
furi_assert(size > 0);
return furi_hal_spi_bus_trx(handle, buffer, buffer, size, timeout);
}
bool furi_hal_spi_bus_tx(
FuriHalSpiBusHandle* handle,
uint8_t* buffer,
size_t size,
uint32_t timeout) {
furi_assert(handle);
furi_assert(handle->bus->current_handle == handle);
furi_assert(buffer);
furi_assert(size > 0);
bool ret = true;
while(size > 0) {
if(LL_SPI_IsActiveFlag_TXE(handle->bus->spi)) {
LL_SPI_TransmitData8(handle->bus->spi, *buffer);
buffer++;
size--;
}
}
furi_hal_spi_bus_end_txrx(handle, timeout);
LL_SPI_ClearFlag_OVR(handle->bus->spi);
return ret;
}
bool furi_hal_spi_bus_trx(
FuriHalSpiBusHandle* handle,
uint8_t* tx_buffer,
uint8_t* rx_buffer,
size_t size,
uint32_t timeout) {
furi_assert(handle);
furi_assert(handle->bus->current_handle == handle);
furi_assert(tx_buffer);
furi_assert(rx_buffer);
furi_assert(size > 0);
bool ret = true;
size_t tx_size = size;
bool tx_allowed = true;
while(size > 0) {
if(tx_size > 0 && LL_SPI_IsActiveFlag_TXE(handle->bus->spi) && tx_allowed) {
LL_SPI_TransmitData8(handle->bus->spi, *tx_buffer);
tx_buffer++;
tx_size--;
tx_allowed = false;
}
if(LL_SPI_IsActiveFlag_RXNE(handle->bus->spi)) {
*rx_buffer = LL_SPI_ReceiveData8(handle->bus->spi);
rx_buffer++;
size--;
tx_allowed = true;
}
}
furi_hal_spi_bus_end_txrx(handle, timeout);
return ret;
}
@@ -0,0 +1,314 @@
#include <furi_hal_spi_config.h>
#include <furi_hal_resources.h>
/* SPI Presets */
const LL_SPI_InitTypeDef furi_hal_spi_preset_2edge_low_8m = {
.Mode = LL_SPI_MODE_MASTER,
.TransferDirection = LL_SPI_FULL_DUPLEX,
.DataWidth = LL_SPI_DATAWIDTH_8BIT,
.ClockPolarity = LL_SPI_POLARITY_LOW,
.ClockPhase = LL_SPI_PHASE_2EDGE,
.NSS = LL_SPI_NSS_SOFT,
.BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV8,
.BitOrder = LL_SPI_MSB_FIRST,
.CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE,
.CRCPoly = 7,
};
const LL_SPI_InitTypeDef furi_hal_spi_preset_1edge_low_8m = {
.Mode = LL_SPI_MODE_MASTER,
.TransferDirection = LL_SPI_FULL_DUPLEX,
.DataWidth = LL_SPI_DATAWIDTH_8BIT,
.ClockPolarity = LL_SPI_POLARITY_LOW,
.ClockPhase = LL_SPI_PHASE_1EDGE,
.NSS = LL_SPI_NSS_SOFT,
.BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV8,
.BitOrder = LL_SPI_MSB_FIRST,
.CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE,
.CRCPoly = 7,
};
const LL_SPI_InitTypeDef furi_hal_spi_preset_1edge_low_4m = {
.Mode = LL_SPI_MODE_MASTER,
.TransferDirection = LL_SPI_FULL_DUPLEX,
.DataWidth = LL_SPI_DATAWIDTH_8BIT,
.ClockPolarity = LL_SPI_POLARITY_LOW,
.ClockPhase = LL_SPI_PHASE_1EDGE,
.NSS = LL_SPI_NSS_SOFT,
.BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV16,
.BitOrder = LL_SPI_MSB_FIRST,
.CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE,
.CRCPoly = 7,
};
const LL_SPI_InitTypeDef furi_hal_spi_preset_1edge_low_16m = {
.Mode = LL_SPI_MODE_MASTER,
.TransferDirection = LL_SPI_FULL_DUPLEX,
.DataWidth = LL_SPI_DATAWIDTH_8BIT,
.ClockPolarity = LL_SPI_POLARITY_LOW,
.ClockPhase = LL_SPI_PHASE_1EDGE,
.NSS = LL_SPI_NSS_SOFT,
.BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV2,
.BitOrder = LL_SPI_MSB_FIRST,
.CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE,
.CRCPoly = 7,
};
const LL_SPI_InitTypeDef furi_hal_spi_preset_1edge_low_2m = {
.Mode = LL_SPI_MODE_MASTER,
.TransferDirection = LL_SPI_FULL_DUPLEX,
.DataWidth = LL_SPI_DATAWIDTH_8BIT,
.ClockPolarity = LL_SPI_POLARITY_LOW,
.ClockPhase = LL_SPI_PHASE_1EDGE,
.NSS = LL_SPI_NSS_SOFT,
.BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV32,
.BitOrder = LL_SPI_MSB_FIRST,
.CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE,
.CRCPoly = 7,
};
/* SPI Buses */
osMutexId_t furi_hal_spi_bus_r_mutex = NULL;
static void furi_hal_spi_bus_r_event_callback(FuriHalSpiBus* bus, FuriHalSpiBusEvent event) {
if(event == FuriHalSpiBusEventInit) {
furi_hal_spi_bus_r_mutex = osMutexNew(NULL);
FURI_CRITICAL_ENTER();
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SPI1);
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1);
FURI_CRITICAL_EXIT();
bus->current_handle = NULL;
} else if(event == FuriHalSpiBusEventDeinit) {
furi_check(osMutexDelete(furi_hal_spi_bus_r_mutex));
} else if(event == FuriHalSpiBusEventLock) {
furi_check(osMutexAcquire(furi_hal_spi_bus_r_mutex, osWaitForever) == osOK);
} else if(event == FuriHalSpiBusEventUnlock) {
furi_check(osMutexRelease(furi_hal_spi_bus_r_mutex) == osOK);
} else if(event == FuriHalSpiBusEventActivate) {
FURI_CRITICAL_ENTER();
LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI1);
FURI_CRITICAL_EXIT();
} else if(event == FuriHalSpiBusEventDeactivate) {
FURI_CRITICAL_ENTER();
LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1);
FURI_CRITICAL_EXIT();
}
}
FuriHalSpiBus furi_hal_spi_bus_r = {
.spi = SPI1,
.callback = furi_hal_spi_bus_r_event_callback,
};
osMutexId_t furi_hal_spi_bus_d_mutex = NULL;
static void furi_hal_spi_bus_d_event_callback(FuriHalSpiBus* bus, FuriHalSpiBusEvent event) {
if(event == FuriHalSpiBusEventInit) {
furi_hal_spi_bus_d_mutex = osMutexNew(NULL);
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_SPI2);
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2);
FURI_CRITICAL_EXIT();
bus->current_handle = NULL;
} else if(event == FuriHalSpiBusEventDeinit) {
furi_check(osMutexDelete(furi_hal_spi_bus_d_mutex));
} else if(event == FuriHalSpiBusEventLock) {
furi_check(osMutexAcquire(furi_hal_spi_bus_d_mutex, osWaitForever) == osOK);
} else if(event == FuriHalSpiBusEventUnlock) {
furi_check(osMutexRelease(furi_hal_spi_bus_d_mutex) == osOK);
} else if(event == FuriHalSpiBusEventActivate) {
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2);
FURI_CRITICAL_EXIT();
} else if(event == FuriHalSpiBusEventDeactivate) {
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2);
FURI_CRITICAL_EXIT();
}
}
FuriHalSpiBus furi_hal_spi_bus_d = {
.spi = SPI2,
.callback = furi_hal_spi_bus_d_event_callback,
};
/* SPI Bus Handles */
inline static void furi_hal_spi_bus_r_handle_event_callback(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event,
const LL_SPI_InitTypeDef* preset) {
if(event == FuriHalSpiBusHandleEventInit) {
hal_gpio_write(handle->cs, true);
hal_gpio_init(handle->cs, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh);
} else if(event == FuriHalSpiBusHandleEventDeinit) {
hal_gpio_write(handle->cs, true);
hal_gpio_init(handle->cs, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
} else if(event == FuriHalSpiBusHandleEventActivate) {
LL_SPI_Init(handle->bus->spi, (LL_SPI_InitTypeDef*)preset);
LL_SPI_SetRxFIFOThreshold(handle->bus->spi, LL_SPI_RX_FIFO_TH_QUARTER);
LL_SPI_Enable(handle->bus->spi);
hal_gpio_init_ex(
handle->miso,
GpioModeAltFunctionPushPull,
GpioPullNo,
GpioSpeedVeryHigh,
GpioAltFn5SPI1);
hal_gpio_init_ex(
handle->mosi,
GpioModeAltFunctionPushPull,
GpioPullNo,
GpioSpeedVeryHigh,
GpioAltFn5SPI1);
hal_gpio_init_ex(
handle->sck,
GpioModeAltFunctionPushPull,
GpioPullNo,
GpioSpeedVeryHigh,
GpioAltFn5SPI1);
hal_gpio_write(handle->cs, false);
} else if(event == FuriHalSpiBusHandleEventDeactivate) {
hal_gpio_write(handle->cs, true);
hal_gpio_init(handle->miso, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
hal_gpio_init(handle->mosi, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
hal_gpio_init(handle->sck, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
LL_SPI_Disable(handle->bus->spi);
}
}
static void furi_hal_spi_bus_handle_subghz_event_callback(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event) {
furi_hal_spi_bus_r_handle_event_callback(handle, event, &furi_hal_spi_preset_1edge_low_8m);
}
FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz = {
.bus = &furi_hal_spi_bus_r,
.callback = furi_hal_spi_bus_handle_subghz_event_callback,
.miso = &gpio_spi_r_miso,
.mosi = &gpio_spi_r_mosi,
.sck = &gpio_spi_r_sck,
.cs = &gpio_subghz_cs,
};
static void furi_hal_spi_bus_handle_nfc_event_callback(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event) {
furi_hal_spi_bus_r_handle_event_callback(handle, event, &furi_hal_spi_preset_2edge_low_8m);
}
FuriHalSpiBusHandle furi_hal_spi_bus_handle_nfc = {
.bus = &furi_hal_spi_bus_r,
.callback = furi_hal_spi_bus_handle_nfc_event_callback,
.miso = &gpio_spi_r_miso,
.mosi = &gpio_spi_r_mosi,
.sck = &gpio_spi_r_sck,
.cs = &gpio_nfc_cs,
};
static void furi_hal_spi_bus_handle_external_event_callback(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event) {
furi_hal_spi_bus_r_handle_event_callback(handle, event, &furi_hal_spi_preset_1edge_low_2m);
}
FuriHalSpiBusHandle furi_hal_spi_bus_handle_external = {
.bus = &furi_hal_spi_bus_r,
.callback = furi_hal_spi_bus_handle_external_event_callback,
.miso = &gpio_ext_pa6,
.mosi = &gpio_ext_pa7,
.sck = &gpio_ext_pb3,
.cs = &gpio_ext_pa4,
};
inline static void furi_hal_spi_bus_d_handle_event_callback(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event,
const LL_SPI_InitTypeDef* preset) {
if(event == FuriHalSpiBusHandleEventInit) {
hal_gpio_write(handle->cs, true);
hal_gpio_init(handle->cs, GpioModeOutputPushPull, GpioPullUp, GpioSpeedVeryHigh);
hal_gpio_init_ex(
handle->miso,
GpioModeAltFunctionPushPull,
GpioPullNo,
GpioSpeedVeryHigh,
GpioAltFn5SPI2);
hal_gpio_init_ex(
handle->mosi,
GpioModeAltFunctionPushPull,
GpioPullNo,
GpioSpeedVeryHigh,
GpioAltFn5SPI2);
hal_gpio_init_ex(
handle->sck,
GpioModeAltFunctionPushPull,
GpioPullNo,
GpioSpeedVeryHigh,
GpioAltFn5SPI2);
} else if(event == FuriHalSpiBusHandleEventDeinit) {
hal_gpio_write(handle->cs, true);
hal_gpio_init(handle->cs, GpioModeAnalog, GpioPullUp, GpioSpeedLow);
} else if(event == FuriHalSpiBusHandleEventActivate) {
LL_SPI_Init(handle->bus->spi, (LL_SPI_InitTypeDef*)preset);
LL_SPI_SetRxFIFOThreshold(handle->bus->spi, LL_SPI_RX_FIFO_TH_QUARTER);
LL_SPI_Enable(handle->bus->spi);
hal_gpio_write(handle->cs, false);
} else if(event == FuriHalSpiBusHandleEventDeactivate) {
hal_gpio_write(handle->cs, true);
LL_SPI_Disable(handle->bus->spi);
}
}
static void furi_hal_spi_bus_handle_display_event_callback(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event) {
furi_hal_spi_bus_d_handle_event_callback(handle, event, &furi_hal_spi_preset_1edge_low_4m);
}
FuriHalSpiBusHandle furi_hal_spi_bus_handle_display = {
.bus = &furi_hal_spi_bus_d,
.callback = furi_hal_spi_bus_handle_display_event_callback,
.miso = &gpio_spi_d_miso,
.mosi = &gpio_spi_d_mosi,
.sck = &gpio_spi_d_sck,
.cs = &gpio_display_cs,
};
static void furi_hal_spi_bus_handle_sd_fast_event_callback(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event) {
furi_hal_spi_bus_d_handle_event_callback(handle, event, &furi_hal_spi_preset_1edge_low_16m);
}
FuriHalSpiBusHandle furi_hal_spi_bus_handle_sd_fast = {
.bus = &furi_hal_spi_bus_d,
.callback = furi_hal_spi_bus_handle_sd_fast_event_callback,
.miso = &gpio_spi_d_miso,
.mosi = &gpio_spi_d_mosi,
.sck = &gpio_spi_d_sck,
.cs = &gpio_sdcard_cs,
};
static void furi_hal_spi_bus_handle_sd_slow_event_callback(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event) {
furi_hal_spi_bus_d_handle_event_callback(handle, event, &furi_hal_spi_preset_1edge_low_2m);
}
FuriHalSpiBusHandle furi_hal_spi_bus_handle_sd_slow = {
.bus = &furi_hal_spi_bus_d,
.callback = furi_hal_spi_bus_handle_sd_slow_event_callback,
.miso = &gpio_spi_d_miso,
.mosi = &gpio_spi_d_mosi,
.sck = &gpio_spi_d_sck,
.cs = &gpio_sdcard_cs,
};
@@ -0,0 +1,61 @@
#pragma once
#include <furi_hal_spi_types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Preset for ST25R916 */
extern const LL_SPI_InitTypeDef furi_hal_spi_preset_2edge_low_8m;
/** Preset for CC1101 */
extern const LL_SPI_InitTypeDef furi_hal_spi_preset_1edge_low_8m;
/** Preset for ST7567 (Display) */
extern const LL_SPI_InitTypeDef furi_hal_spi_preset_1edge_low_4m;
/** Preset for SdCard in fast mode */
extern const LL_SPI_InitTypeDef furi_hal_spi_preset_1edge_low_16m;
/** Preset for SdCard in slow mode */
extern const LL_SPI_InitTypeDef furi_hal_spi_preset_1edge_low_2m;
/** Furi Hal Spi Bus R (Radio: CC1101, Nfc, External)*/
extern FuriHalSpiBus furi_hal_spi_bus_r;
/** Furi Hal Spi Bus D (Display, SdCard) */
extern FuriHalSpiBus furi_hal_spi_bus_d;
/** CC1101 on `furi_hal_spi_bus_r` */
extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz;
/** ST25R3916 on `furi_hal_spi_bus_r` */
extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_nfc;
/** External on `furi_hal_spi_bus_r`
* Preset: `furi_hal_spi_preset_1edge_low_2m`
*
* miso: pa6
* mosi: pa7
* sck: pb3
* cs: pa4 (software controlled)
*
* @warning not initialized by default, call `furi_hal_spi_bus_handle_init` to initialize
* Bus pins are floating on inactive state, CS high after initialization
*
*/
extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_external;
/** ST7567(Display) on `furi_hal_spi_bus_d` */
extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_display;
/** SdCard in fast mode on `furi_hal_spi_bus_d` */
extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_sd_fast;
/** SdCard in slow mode on `furi_hal_spi_bus_d` */
extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_sd_slow;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,64 @@
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <furi_hal_gpio.h>
#include <stm32wbxx_ll_spi.h>
#include <stm32wbxx_ll_rcc.h>
#include <stm32wbxx_ll_bus.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct FuriHalSpiBus FuriHalSpiBus;
typedef struct FuriHalSpiBusHandle FuriHalSpiBusHandle;
/** FuriHal spi bus states */
typedef enum {
FuriHalSpiBusEventInit, /**< Bus initialization event, called on system start */
FuriHalSpiBusEventDeinit, /**< Bus deinitialization event, called on system stop */
FuriHalSpiBusEventLock, /**< Bus lock event, called before activation */
FuriHalSpiBusEventUnlock, /**< Bus unlock event, called after deactivation */
FuriHalSpiBusEventActivate, /**< Bus activation event, called before handle activation */
FuriHalSpiBusEventDeactivate, /**< Bus deactivation event, called after handle deactivation */
} FuriHalSpiBusEvent;
/** FuriHal spi bus event callback */
typedef void (*FuriHalSpiBusEventCallback)(FuriHalSpiBus* bus, FuriHalSpiBusEvent event);
/** FuriHal spi bus */
struct FuriHalSpiBus {
SPI_TypeDef* spi;
FuriHalSpiBusEventCallback callback;
FuriHalSpiBusHandle* current_handle;
};
/** FuriHal spi handle states */
typedef enum {
FuriHalSpiBusHandleEventInit, /**< Handle init, called on system start, initialize gpio for idle state */
FuriHalSpiBusHandleEventDeinit, /**< Handle deinit, called on system stop, deinitialize gpio for default state */
FuriHalSpiBusHandleEventActivate, /**< Handle activate: connect gpio and apply bus config */
FuriHalSpiBusHandleEventDeactivate, /**< Handle deactivate: disconnect gpio and reset bus config */
} FuriHalSpiBusHandleEvent;
/** FuriHal spi handle event callback */
typedef void (*FuriHalSpiBusHandleEventCallback)(
FuriHalSpiBusHandle* handle,
FuriHalSpiBusHandleEvent event);
/** FuriHal spi handle */
struct FuriHalSpiBusHandle {
FuriHalSpiBus* bus;
FuriHalSpiBusHandleEventCallback callback;
const GpioPin* miso;
const GpioPin* mosi;
const GpioPin* sck;
const GpioPin* cs;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,993 @@
#include "furi_hal_subghz.h"
#include "furi_hal_version.h"
#include "furi_hal_rtc.h"
#include <furi_hal_gpio.h>
#include <furi_hal_spi.h>
#include <furi_hal_interrupt.h>
#include <furi_hal_resources.h>
#include <furi.h>
#include <cc1101.h>
#include <stdio.h>
#define TAG "FuriHalSubGhz"
static volatile SubGhzState furi_hal_subghz_state = SubGhzStateInit;
static volatile SubGhzRegulation furi_hal_subghz_regulation = SubGhzRegulationTxRx;
static volatile FuriHalSubGhzPreset furi_hal_subghz_preset = FuriHalSubGhzPresetIDLE;
static const uint8_t furi_hal_subghz_preset_ook_270khz_async_regs[][2] = {
// https://e2e.ti.com/support/wireless-connectivity/sub-1-ghz-group/sub-1-ghz/f/sub-1-ghz-forum/382066/cc1101---don-t-know-the-correct-registers-configuration
/* GPIO GD0 */
{CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input
/* FIFO and internals */
{CC1101_FIFOTHR, 0x47}, // The only important bit is ADC_RETENTION, FIFO Tx=33 Rx=32
/* Packet engine */
{CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening
/* Frequency Synthesizer Control */
{CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz
// Modem Configuration
{CC1101_MDMCFG0, 0x00}, // Channel spacing is 25kHz
{CC1101_MDMCFG1, 0x00}, // Channel spacing is 25kHz
{CC1101_MDMCFG2, 0x30}, // Format ASK/OOK, No preamble/sync
{CC1101_MDMCFG3, 0x32}, // Data rate is 3.79372 kBaud
{CC1101_MDMCFG4, 0x67}, // Rx BW filter is 270.833333kHz
/* Main Radio Control State Machine */
{CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us)
/* Frequency Offset Compensation Configuration */
{CC1101_FOCCFG,
0x18}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off
/* Automatic Gain Control */
{CC1101_AGCCTRL0,
0x40}, // 01 - Low hysteresis, small asymmetric dead zone, medium gain; 00 - 8 samples agc; 00 - Normal AGC, 00 - 4dB boundary
{CC1101_AGCCTRL1,
0x00}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET
{CC1101_AGCCTRL2, 0x03}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 011 - MAIN_TARGET 24 dB
/* Wake on radio and timeouts control */
{CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours
/* Frontend configuration */
{CC1101_FREND0, 0x11}, // Adjusts current TX LO buffer + high is PATABLE[1]
{CC1101_FREND1, 0xB6}, //
/* End */
{0, 0},
};
static const uint8_t furi_hal_subghz_preset_ook_650khz_async_regs[][2] = {
// https://e2e.ti.com/support/wireless-connectivity/sub-1-ghz-group/sub-1-ghz/f/sub-1-ghz-forum/382066/cc1101---don-t-know-the-correct-registers-configuration
/* GPIO GD0 */
{CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input
/* FIFO and internals */
{CC1101_FIFOTHR, 0x07}, // The only important bit is ADC_RETENTION
/* Packet engine */
{CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening
/* Frequency Synthesizer Control */
{CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz
// Modem Configuration
{CC1101_MDMCFG0, 0x00}, // Channel spacing is 25kHz
{CC1101_MDMCFG1, 0x00}, // Channel spacing is 25kHz
{CC1101_MDMCFG2, 0x30}, // Format ASK/OOK, No preamble/sync
{CC1101_MDMCFG3, 0x32}, // Data rate is 3.79372 kBaud
{CC1101_MDMCFG4, 0x17}, // Rx BW filter is 650.000kHz
/* Main Radio Control State Machine */
{CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us)
/* Frequency Offset Compensation Configuration */
{CC1101_FOCCFG,
0x18}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off
/* Automatic Gain Control */
// {CC1101_AGCTRL0,0x40}, // 01 - Low hysteresis, small asymmetric dead zone, medium gain; 00 - 8 samples agc; 00 - Normal AGC, 00 - 4dB boundary
// {CC1101_AGCTRL1,0x00}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET
// {CC1101_AGCCTRL2, 0x03}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 011 - MAIN_TARGET 24 dB
//MAGN_TARGET for RX filter BW =< 100 kHz is 0x3. For higher RX filter BW's MAGN_TARGET is 0x7.
{CC1101_AGCCTRL0,
0x91}, // 10 - Medium hysteresis, medium asymmetric dead zone, medium gain ; 01 - 16 samples agc; 00 - Normal AGC, 01 - 8dB boundary
{CC1101_AGCCTRL1,
0x0}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET
{CC1101_AGCCTRL2, 0x07}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 111 - MAIN_TARGET 42 dB
/* Wake on radio and timeouts control */
{CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours
/* Frontend configuration */
{CC1101_FREND0, 0x11}, // Adjusts current TX LO buffer + high is PATABLE[1]
{CC1101_FREND1, 0xB6}, //
/* End */
{0, 0},
};
static const uint8_t furi_hal_subghz_preset_2fsk_dev2_38khz_async_regs[][2] = {
/* GPIO GD0 */
{CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input
/* Frequency Synthesizer Control */
{CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz
/* Packet engine */
{CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening
{CC1101_PKTCTRL1, 0x04},
// // Modem Configuration
{CC1101_MDMCFG0, 0x00},
{CC1101_MDMCFG1, 0x02},
{CC1101_MDMCFG2, 0x04}, // Format 2-FSK/FM, No preamble/sync, Disable (current optimized)
{CC1101_MDMCFG3, 0x83}, // Data rate is 4.79794 kBaud
{CC1101_MDMCFG4, 0x67}, //Rx BW filter is 270.833333 kHz
{CC1101_DEVIATN, 0x04}, //Deviation 2.380371 kHz
/* Main Radio Control State Machine */
{CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us)
/* Frequency Offset Compensation Configuration */
{CC1101_FOCCFG,
0x16}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off
/* Automatic Gain Control */
{CC1101_AGCCTRL0,
0x91}, //10 - Medium hysteresis, medium asymmetric dead zone, medium gain ; 01 - 16 samples agc; 00 - Normal AGC, 01 - 8dB boundary
{CC1101_AGCCTRL1,
0x00}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET
{CC1101_AGCCTRL2, 0x07}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 111 - MAIN_TARGET 42 dB
/* Wake on radio and timeouts control */
{CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours
/* Frontend configuration */
{CC1101_FREND0, 0x10}, // Adjusts current TX LO buffer
{CC1101_FREND1, 0x56},
/* End */
{0, 0},
};
static const uint8_t furi_hal_subghz_preset_2fsk_dev4_76khz_async_regs[][2] = {
/* GPIO GD0 */
{CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input
/* Frequency Synthesizer Control */
{CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz
/* Packet engine */
{CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening
{CC1101_PKTCTRL1, 0x04},
// // Modem Configuration
{CC1101_MDMCFG0, 0x00},
{CC1101_MDMCFG1, 0x02},
{CC1101_MDMCFG2, 0x04}, // Format 2-FSK/FM, No preamble/sync, Disable (current optimized)
{CC1101_MDMCFG3, 0x83}, // Data rate is 4.79794 kBaud
{CC1101_MDMCFG4, 0x67}, //Rx BW filter is 270.833333 kHz
{CC1101_DEVIATN, 0x14}, //Deviation 4.760742 kHz
/* Main Radio Control State Machine */
{CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us)
/* Frequency Offset Compensation Configuration */
{CC1101_FOCCFG,
0x16}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off
/* Automatic Gain Control */
{CC1101_AGCCTRL0,
0x91}, //10 - Medium hysteresis, medium asymmetric dead zone, medium gain ; 01 - 16 samples agc; 00 - Normal AGC, 01 - 8dB boundary
{CC1101_AGCCTRL1,
0x00}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET
{CC1101_AGCCTRL2, 0x07}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 111 - MAIN_TARGET 42 dB
/* Wake on radio and timeouts control */
{CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours
/* Frontend configuration */
{CC1101_FREND0, 0x10}, // Adjusts current TX LO buffer
{CC1101_FREND1, 0x56},
/* End */
{0, 0},
};
static const uint8_t furi_hal_subghz_preset_msk_99_97kb_async_regs[][2] = {
/* GPIO GD0 */
{CC1101_IOCFG0, 0x06},
{CC1101_FIFOTHR, 0x07}, // The only important bit is ADC_RETENTION
{CC1101_SYNC1, 0x46},
{CC1101_SYNC0, 0x4C},
{CC1101_ADDR, 0x00},
{CC1101_PKTLEN, 0x00},
{CC1101_CHANNR, 0x00},
{CC1101_PKTCTRL0, 0x05},
{CC1101_FSCTRL0, 0x23},
{CC1101_FSCTRL1, 0x06},
{CC1101_MDMCFG0, 0xF8},
{CC1101_MDMCFG1, 0x22},
{CC1101_MDMCFG2, 0x72},
{CC1101_MDMCFG3, 0xF8},
{CC1101_MDMCFG4, 0x5B},
{CC1101_DEVIATN, 0x47},
{CC1101_MCSM0, 0x18},
{CC1101_FOCCFG, 0x16},
{CC1101_AGCCTRL0, 0xB2},
{CC1101_AGCCTRL1, 0x00},
{CC1101_AGCCTRL2, 0xC7},
{CC1101_FREND0, 0x10},
{CC1101_FREND1, 0x56},
{CC1101_BSCFG, 0x1C},
{CC1101_FSTEST, 0x59},
/* End */
{0, 0},
};
static const uint8_t furi_hal_subghz_preset_gfsk_9_99kb_async_regs[][2] = {
{CC1101_IOCFG0, 0x06}, //GDO0 Output Pin Configuration
{CC1101_FIFOTHR, 0x47}, //RX FIFO and TX FIFO Thresholds
//1 : CRC calculation in TX and CRC check in RX enabled,
//1 : Variable packet length mode. Packet length configured by the first byte after sync word
{CC1101_PKTCTRL0, 0x05},
{CC1101_FSCTRL1, 0x06}, //Frequency Synthesizer Control
{CC1101_SYNC1, 0x46},
{CC1101_SYNC0, 0x4C},
{CC1101_ADDR, 0x00},
{CC1101_PKTLEN, 0x00},
{CC1101_MDMCFG4, 0xC8}, //Modem Configuration 9.99
{CC1101_MDMCFG3, 0x93}, //Modem Configuration
{CC1101_MDMCFG2, 0x12}, // 2: 16/16 sync word bits detected
{CC1101_DEVIATN, 0x34}, //Deviation = 19.042969
{CC1101_MCSM0, 0x18}, //Main Radio Control State Machine Configuration
{CC1101_FOCCFG, 0x16}, //Frequency Offset Compensation Configuration
{CC1101_AGCCTRL2, 0x43}, //AGC Control
{CC1101_AGCCTRL1, 0x40},
{CC1101_AGCCTRL0, 0x91},
{CC1101_WORCTRL, 0xFB}, //Wake On Radio Control
/* End */
{0, 0},
};
static const uint8_t furi_hal_subghz_preset_ook_async_patable[8] = {
0x00,
0xC0, // 12dBm 0xC0, 10dBm 0xC5, 7dBm 0xCD, 5dBm 0x86, 0dBm 0x50, -6dBm 0x37, -10dBm 0x26, -15dBm 0x1D, -20dBm 0x17, -30dBm 0x03
0x00,
0x00,
0x00,
0x00,
0x00,
0x00};
static const uint8_t furi_hal_subghz_preset_ook_async_patable_au[8] = {
0x00,
0x37, // 12dBm 0xC0, 10dBm 0xC5, 7dBm 0xCD, 5dBm 0x86, 0dBm 0x50, -6dBm 0x37, -10dBm 0x26, -15dBm 0x1D, -20dBm 0x17, -30dBm 0x03
0x00,
0x00,
0x00,
0x00,
0x00,
0x00};
static const uint8_t furi_hal_subghz_preset_2fsk_async_patable[8] = {
0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00};
static const uint8_t furi_hal_subghz_preset_msk_async_patable[8] = {
0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00};
static const uint8_t furi_hal_subghz_preset_gfsk_async_patable[8] = {
0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00};
void furi_hal_subghz_init() {
furi_assert(furi_hal_subghz_state == SubGhzStateInit);
furi_hal_subghz_state = SubGhzStateIdle;
furi_hal_subghz_preset = FuriHalSubGhzPresetIDLE;
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
#ifdef FURI_HAL_SUBGHZ_TX_GPIO
hal_gpio_init(&FURI_HAL_SUBGHZ_TX_GPIO, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow);
#endif
// Reset
hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
cc1101_reset(&furi_hal_spi_bus_handle_subghz);
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHighImpedance);
// Prepare GD0 for power on self test
hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow);
// GD0 low
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHW);
while(hal_gpio_read(&gpio_cc1101_g0) != false)
;
// GD0 high
cc1101_write_reg(
&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHW | CC1101_IOCFG_INV);
while(hal_gpio_read(&gpio_cc1101_g0) != true)
;
// Reset GD0 to floating state
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHighImpedance);
hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
// RF switches
hal_gpio_init(&gpio_rf_sw_0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow);
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW);
// Go to sleep
cc1101_shutdown(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_subghz_sleep() {
furi_assert(furi_hal_subghz_state == SubGhzStateIdle);
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_switch_to_idle(&furi_hal_spi_bus_handle_subghz);
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHighImpedance);
hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
cc1101_shutdown(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
furi_hal_subghz_preset = FuriHalSubGhzPresetIDLE;
}
void furi_hal_subghz_dump_state() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
printf(
"[furi_hal_subghz] cc1101 chip %d, version %d\r\n",
cc1101_get_partnumber(&furi_hal_spi_bus_handle_subghz),
cc1101_get_version(&furi_hal_spi_bus_handle_subghz));
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_load_preset(FuriHalSubGhzPreset preset) {
if(preset == FuriHalSubGhzPresetOok650Async) {
furi_hal_subghz_load_registers(furi_hal_subghz_preset_ook_650khz_async_regs);
furi_hal_subghz_load_patable(furi_hal_subghz_preset_ook_async_patable);
} else if(preset == FuriHalSubGhzPresetOok270Async) {
furi_hal_subghz_load_registers(furi_hal_subghz_preset_ook_270khz_async_regs);
furi_hal_subghz_load_patable(furi_hal_subghz_preset_ook_async_patable);
} else if(preset == FuriHalSubGhzPreset2FSKDev238Async) {
furi_hal_subghz_load_registers(furi_hal_subghz_preset_2fsk_dev2_38khz_async_regs);
furi_hal_subghz_load_patable(furi_hal_subghz_preset_2fsk_async_patable);
} else if(preset == FuriHalSubGhzPreset2FSKDev476Async) {
furi_hal_subghz_load_registers(furi_hal_subghz_preset_2fsk_dev4_76khz_async_regs);
furi_hal_subghz_load_patable(furi_hal_subghz_preset_2fsk_async_patable);
} else if(preset == FuriHalSubGhzPresetMSK99_97KbAsync) {
furi_hal_subghz_load_registers(furi_hal_subghz_preset_msk_99_97kb_async_regs);
furi_hal_subghz_load_patable(furi_hal_subghz_preset_msk_async_patable);
} else if(preset == FuriHalSubGhzPresetGFSK9_99KbAsync) {
furi_hal_subghz_load_registers(furi_hal_subghz_preset_gfsk_9_99kb_async_regs);
furi_hal_subghz_load_patable(furi_hal_subghz_preset_gfsk_async_patable);
} else {
furi_crash(NULL);
}
furi_hal_subghz_preset = preset;
}
void furi_hal_subghz_load_registers(const uint8_t data[][2]) {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_reset(&furi_hal_spi_bus_handle_subghz);
uint32_t i = 0;
while(data[i][0]) {
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, data[i][0], data[i][1]);
i++;
}
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_load_patable(const uint8_t data[8]) {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_set_pa_table(&furi_hal_spi_bus_handle_subghz, data);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_write_packet(const uint8_t* data, uint8_t size) {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_flush_tx(&furi_hal_spi_bus_handle_subghz);
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_FIFO, size);
cc1101_write_fifo(&furi_hal_spi_bus_handle_subghz, data, size);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_flush_rx() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_flush_rx(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_flush_tx() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_flush_tx(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
bool furi_hal_subghz_rx_pipe_not_empty() {
CC1101RxBytes status[1];
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_read_reg(
&furi_hal_spi_bus_handle_subghz, (CC1101_STATUS_RXBYTES) | CC1101_BURST, (uint8_t*)status);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
// TODO: you can add a buffer overflow flag if needed
if(status->NUM_RXBYTES > 0) {
return true;
} else {
return false;
}
}
bool furi_hal_subghz_is_rx_data_crc_valid() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
uint8_t data[1];
cc1101_read_reg(&furi_hal_spi_bus_handle_subghz, CC1101_STATUS_LQI | CC1101_BURST, data);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
if(((data[0] >> 7) & 0x01)) {
return true;
} else {
return false;
}
}
void furi_hal_subghz_read_packet(uint8_t* data, uint8_t* size) {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_read_fifo(&furi_hal_spi_bus_handle_subghz, data, size);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_shutdown() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
// Reset and shutdown
cc1101_shutdown(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_reset() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
cc1101_switch_to_idle(&furi_hal_spi_bus_handle_subghz);
cc1101_reset(&furi_hal_spi_bus_handle_subghz);
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHighImpedance);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_idle() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_switch_to_idle(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
void furi_hal_subghz_rx() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_switch_to_rx(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
bool furi_hal_subghz_tx() {
if(furi_hal_subghz_regulation != SubGhzRegulationTxRx) return false;
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
cc1101_switch_to_tx(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
return true;
}
float furi_hal_subghz_get_rssi() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
int32_t rssi_dec = cc1101_get_rssi(&furi_hal_spi_bus_handle_subghz);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
float rssi = rssi_dec;
if(rssi_dec >= 128) {
rssi = ((rssi - 256.0f) / 2.0f) - 74.0f;
} else {
rssi = (rssi / 2.0f) - 74.0f;
}
return rssi;
}
uint8_t furi_hal_subghz_get_lqi() {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
uint8_t data[1];
cc1101_read_reg(&furi_hal_spi_bus_handle_subghz, CC1101_STATUS_LQI | CC1101_BURST, data);
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
return data[0] & 0x7F;
}
bool furi_hal_subghz_is_frequency_valid(uint32_t value) {
if(!(value >= 299999755 && value <= 348000335) &&
!(value >= 386999938 && value <= 464000000) &&
!(value >= 778999847 && value <= 928000000)) {
return false;
}
return true;
}
uint32_t furi_hal_subghz_set_frequency_and_path(uint32_t value) {
value = furi_hal_subghz_set_frequency(value);
if(value >= 299999755 && value <= 348000335) {
furi_hal_subghz_set_path(FuriHalSubGhzPath315);
} else if(value >= 386999938 && value <= 464000000) {
furi_hal_subghz_set_path(FuriHalSubGhzPath433);
} else if(value >= 778999847 && value <= 928000000) {
furi_hal_subghz_set_path(FuriHalSubGhzPath868);
} else {
furi_crash(NULL);
}
return value;
}
bool furi_hal_subghz_is_tx_allowed(uint32_t value) {
//checking regional settings
bool is_allowed = false;
switch(furi_hal_version_get_hw_region()) {
case FuriHalVersionRegionEuRu:
//433,05..434,79; 868,15..868,55
if(!(value >= 433050000 && value <= 434790000) &&
!(value >= 868150000 && value <= 868550000)) {
} else {
is_allowed = true;
}
break;
case FuriHalVersionRegionUsCaAu:
//304,10..321,95; 433,05..434,79; 915,00..928,00
if(!(value >= 304100000 && value <= 321950000) &&
!(value >= 433050000 && value <= 434790000) &&
!(value >= 915000000 && value <= 928000000)) {
} else {
if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) {
if((value >= 304100000 && value <= 321950000) &&
((furi_hal_subghz_preset == FuriHalSubGhzPresetOok270Async) ||
(furi_hal_subghz_preset == FuriHalSubGhzPresetOok650Async))) {
furi_hal_subghz_load_patable(furi_hal_subghz_preset_ook_async_patable_au);
}
}
is_allowed = true;
}
break;
case FuriHalVersionRegionJp:
//312,00..315,25; 920,50..923,50
if(!(value >= 312000000 && value <= 315250000) &&
!(value >= 920500000 && value <= 923500000)) {
} else {
is_allowed = true;
}
break;
default:
is_allowed = true;
break;
}
return is_allowed;
}
uint32_t furi_hal_subghz_set_frequency(uint32_t value) {
if(furi_hal_subghz_is_tx_allowed(value)) {
furi_hal_subghz_regulation = SubGhzRegulationTxRx;
} else {
furi_hal_subghz_regulation = SubGhzRegulationOnlyRx;
}
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
uint32_t real_frequency = cc1101_set_frequency(&furi_hal_spi_bus_handle_subghz, value);
cc1101_calibrate(&furi_hal_spi_bus_handle_subghz);
while(true) {
CC1101Status status = cc1101_get_status(&furi_hal_spi_bus_handle_subghz);
if(status.STATE == CC1101StateIDLE) break;
}
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
return real_frequency;
}
void furi_hal_subghz_set_path(FuriHalSubGhzPath path) {
furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz);
if(path == FuriHalSubGhzPath433) {
hal_gpio_write(&gpio_rf_sw_0, 0);
cc1101_write_reg(
&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW | CC1101_IOCFG_INV);
} else if(path == FuriHalSubGhzPath315) {
hal_gpio_write(&gpio_rf_sw_0, 1);
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW);
} else if(path == FuriHalSubGhzPath868) {
hal_gpio_write(&gpio_rf_sw_0, 1);
cc1101_write_reg(
&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW | CC1101_IOCFG_INV);
} else if(path == FuriHalSubGhzPathIsolate) {
hal_gpio_write(&gpio_rf_sw_0, 0);
cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW);
} else {
furi_crash(NULL);
}
furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz);
}
volatile uint32_t furi_hal_subghz_capture_delta_duration = 0;
volatile FuriHalSubGhzCaptureCallback furi_hal_subghz_capture_callback = NULL;
volatile void* furi_hal_subghz_capture_callback_context = NULL;
static void furi_hal_subghz_capture_ISR() {
// Channel 1
if(LL_TIM_IsActiveFlag_CC1(TIM2)) {
LL_TIM_ClearFlag_CC1(TIM2);
furi_hal_subghz_capture_delta_duration = LL_TIM_IC_GetCaptureCH1(TIM2);
if(furi_hal_subghz_capture_callback) {
furi_hal_subghz_capture_callback(
true,
furi_hal_subghz_capture_delta_duration,
(void*)furi_hal_subghz_capture_callback_context);
}
}
// Channel 2
if(LL_TIM_IsActiveFlag_CC2(TIM2)) {
LL_TIM_ClearFlag_CC2(TIM2);
if(furi_hal_subghz_capture_callback) {
furi_hal_subghz_capture_callback(
false,
LL_TIM_IC_GetCaptureCH2(TIM2) - furi_hal_subghz_capture_delta_duration,
(void*)furi_hal_subghz_capture_callback_context);
}
}
}
void furi_hal_subghz_start_async_rx(FuriHalSubGhzCaptureCallback callback, void* context) {
furi_assert(furi_hal_subghz_state == SubGhzStateIdle);
furi_hal_subghz_state = SubGhzStateAsyncRx;
furi_hal_subghz_capture_callback = callback;
furi_hal_subghz_capture_callback_context = context;
hal_gpio_init_ex(
&gpio_cc1101_g0, GpioModeAltFunctionPushPull, GpioPullNo, GpioSpeedLow, GpioAltFn1TIM2);
// Timer: base
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2);
FURI_CRITICAL_EXIT();
LL_TIM_InitTypeDef TIM_InitStruct = {0};
TIM_InitStruct.Prescaler = 64 - 1;
TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
TIM_InitStruct.Autoreload = 0x7FFFFFFE;
TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV4;
LL_TIM_Init(TIM2, &TIM_InitStruct);
// Timer: advanced
LL_TIM_SetClockSource(TIM2, LL_TIM_CLOCKSOURCE_INTERNAL);
LL_TIM_DisableARRPreload(TIM2);
LL_TIM_SetTriggerInput(TIM2, LL_TIM_TS_TI2FP2);
LL_TIM_SetSlaveMode(TIM2, LL_TIM_SLAVEMODE_RESET);
LL_TIM_SetTriggerOutput(TIM2, LL_TIM_TRGO_RESET);
LL_TIM_EnableMasterSlaveMode(TIM2);
LL_TIM_DisableDMAReq_TRIG(TIM2);
LL_TIM_DisableIT_TRIG(TIM2);
// Timer: channel 1 indirect
LL_TIM_IC_SetActiveInput(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_ACTIVEINPUT_INDIRECTTI);
LL_TIM_IC_SetPrescaler(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_ICPSC_DIV1);
LL_TIM_IC_SetPolarity(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_IC_POLARITY_FALLING);
LL_TIM_IC_SetFilter(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_IC_FILTER_FDIV1);
// Timer: channel 2 direct
LL_TIM_IC_SetActiveInput(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_ACTIVEINPUT_DIRECTTI);
LL_TIM_IC_SetPrescaler(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_ICPSC_DIV1);
LL_TIM_IC_SetPolarity(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_IC_POLARITY_RISING);
LL_TIM_IC_SetFilter(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_IC_FILTER_FDIV32_N8);
// ISR setup
furi_hal_interrupt_set_timer_isr(TIM2, furi_hal_subghz_capture_ISR);
NVIC_SetPriority(TIM2_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(TIM2_IRQn);
// Interrupts and channels
LL_TIM_EnableIT_CC1(TIM2);
LL_TIM_EnableIT_CC2(TIM2);
LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH1);
LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH2);
// Enable NVIC
NVIC_SetPriority(TIM2_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(TIM2_IRQn);
// Start timer
LL_TIM_SetCounter(TIM2, 0);
LL_TIM_EnableCounter(TIM2);
// Switch to RX
furi_hal_subghz_rx();
}
void furi_hal_subghz_stop_async_rx() {
furi_assert(furi_hal_subghz_state == SubGhzStateAsyncRx);
furi_hal_subghz_state = SubGhzStateIdle;
// Shutdown radio
furi_hal_subghz_idle();
FURI_CRITICAL_ENTER();
LL_TIM_DeInit(TIM2);
LL_APB1_GRP1_DisableClock(LL_APB1_GRP1_PERIPH_TIM2);
FURI_CRITICAL_EXIT();
furi_hal_interrupt_set_timer_isr(TIM2, NULL);
hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
}
#define API_HAL_SUBGHZ_ASYNC_TX_BUFFER_FULL (256)
#define API_HAL_SUBGHZ_ASYNC_TX_BUFFER_HALF (API_HAL_SUBGHZ_ASYNC_TX_BUFFER_FULL / 2)
#define API_HAL_SUBGHZ_ASYNC_TX_GUARD_TIME 333
typedef struct {
uint32_t* buffer;
bool flip_flop;
FuriHalSubGhzAsyncTxCallback callback;
void* callback_context;
uint64_t duty_high;
uint64_t duty_low;
} FuriHalSubGhzAsyncTx;
static FuriHalSubGhzAsyncTx furi_hal_subghz_async_tx = {0};
static void furi_hal_subghz_async_tx_refill(uint32_t* buffer, size_t samples) {
while(samples > 0) {
bool is_odd = samples % 2;
LevelDuration ld =
furi_hal_subghz_async_tx.callback(furi_hal_subghz_async_tx.callback_context);
if(level_duration_is_wait(ld)) {
return;
} else if(level_duration_is_reset(ld)) {
// One more even sample required to end at low level
if(is_odd) {
*buffer = API_HAL_SUBGHZ_ASYNC_TX_GUARD_TIME;
buffer++;
samples--;
furi_hal_subghz_async_tx.duty_low += API_HAL_SUBGHZ_ASYNC_TX_GUARD_TIME;
}
break;
} else {
// Inject guard time if level is incorrect
bool level = level_duration_get_level(ld);
if(is_odd == level) {
*buffer = API_HAL_SUBGHZ_ASYNC_TX_GUARD_TIME;
buffer++;
samples--;
if(!level) {
furi_hal_subghz_async_tx.duty_high += API_HAL_SUBGHZ_ASYNC_TX_GUARD_TIME;
} else {
furi_hal_subghz_async_tx.duty_low += API_HAL_SUBGHZ_ASYNC_TX_GUARD_TIME;
}
}
uint32_t duration = level_duration_get_duration(ld);
furi_assert(duration > 0);
*buffer = duration;
buffer++;
samples--;
if(level) {
furi_hal_subghz_async_tx.duty_high += duration;
} else {
furi_hal_subghz_async_tx.duty_low += duration;
}
}
}
memset(buffer, 0, samples * sizeof(uint32_t));
}
static void furi_hal_subghz_async_tx_dma_isr() {
furi_assert(furi_hal_subghz_state == SubGhzStateAsyncTx);
if(LL_DMA_IsActiveFlag_HT1(DMA1)) {
LL_DMA_ClearFlag_HT1(DMA1);
furi_hal_subghz_async_tx_refill(
furi_hal_subghz_async_tx.buffer, API_HAL_SUBGHZ_ASYNC_TX_BUFFER_HALF);
}
if(LL_DMA_IsActiveFlag_TC1(DMA1)) {
LL_DMA_ClearFlag_TC1(DMA1);
furi_hal_subghz_async_tx_refill(
furi_hal_subghz_async_tx.buffer + API_HAL_SUBGHZ_ASYNC_TX_BUFFER_HALF,
API_HAL_SUBGHZ_ASYNC_TX_BUFFER_HALF);
}
}
static void furi_hal_subghz_async_tx_timer_isr() {
if(LL_TIM_IsActiveFlag_UPDATE(TIM2)) {
LL_TIM_ClearFlag_UPDATE(TIM2);
if(LL_TIM_GetAutoReload(TIM2) == 0) {
if(furi_hal_subghz_state == SubGhzStateAsyncTx) {
furi_hal_subghz_state = SubGhzStateAsyncTxLast;
//forcibly pulls the pin to the ground so that there is no carrier
hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullDown, GpioSpeedLow);
} else {
furi_hal_subghz_state = SubGhzStateAsyncTxEnd;
LL_TIM_DisableCounter(TIM2);
}
}
}
}
bool furi_hal_subghz_start_async_tx(FuriHalSubGhzAsyncTxCallback callback, void* context) {
furi_assert(furi_hal_subghz_state == SubGhzStateIdle);
furi_assert(callback);
//If transmission is prohibited by regional settings
if(furi_hal_subghz_regulation != SubGhzRegulationTxRx) return false;
furi_hal_subghz_async_tx.callback = callback;
furi_hal_subghz_async_tx.callback_context = context;
furi_hal_subghz_state = SubGhzStateAsyncTx;
furi_hal_subghz_async_tx.duty_low = 0;
furi_hal_subghz_async_tx.duty_high = 0;
furi_hal_subghz_async_tx.buffer =
furi_alloc(API_HAL_SUBGHZ_ASYNC_TX_BUFFER_FULL * sizeof(uint32_t));
furi_hal_subghz_async_tx_refill(
furi_hal_subghz_async_tx.buffer, API_HAL_SUBGHZ_ASYNC_TX_BUFFER_FULL);
// Connect CC1101_GD0 to TIM2 as output
hal_gpio_init_ex(
&gpio_cc1101_g0, GpioModeAltFunctionPushPull, GpioPullDown, GpioSpeedLow, GpioAltFn1TIM2);
// Configure DMA
LL_DMA_InitTypeDef dma_config = {0};
dma_config.PeriphOrM2MSrcAddress = (uint32_t) & (TIM2->ARR);
dma_config.MemoryOrM2MDstAddress = (uint32_t)furi_hal_subghz_async_tx.buffer;
dma_config.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH;
dma_config.Mode = LL_DMA_MODE_CIRCULAR;
dma_config.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT;
dma_config.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT;
dma_config.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD;
dma_config.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD;
dma_config.NbData = API_HAL_SUBGHZ_ASYNC_TX_BUFFER_FULL;
dma_config.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP;
dma_config.Priority = LL_DMA_MODE_NORMAL;
LL_DMA_Init(DMA1, LL_DMA_CHANNEL_1, &dma_config);
furi_hal_interrupt_set_dma_channel_isr(
DMA1, LL_DMA_CHANNEL_1, furi_hal_subghz_async_tx_dma_isr);
LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_1);
LL_DMA_EnableIT_HT(DMA1, LL_DMA_CHANNEL_1);
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1);
// Configure TIM2
FURI_CRITICAL_ENTER();
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2);
FURI_CRITICAL_EXIT();
LL_TIM_InitTypeDef TIM_InitStruct = {0};
TIM_InitStruct.Prescaler = 64 - 1;
TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
TIM_InitStruct.Autoreload = 1000;
TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
LL_TIM_Init(TIM2, &TIM_InitStruct);
LL_TIM_SetClockSource(TIM2, LL_TIM_CLOCKSOURCE_INTERNAL);
LL_TIM_EnableARRPreload(TIM2);
// Configure TIM2 CH2
LL_TIM_OC_InitTypeDef TIM_OC_InitStruct = {0};
TIM_OC_InitStruct.OCMode = LL_TIM_OCMODE_TOGGLE;
TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_DISABLE;
TIM_OC_InitStruct.OCNState = LL_TIM_OCSTATE_DISABLE;
TIM_OC_InitStruct.CompareValue = 0;
TIM_OC_InitStruct.OCPolarity = LL_TIM_OCPOLARITY_HIGH;
LL_TIM_OC_Init(TIM2, LL_TIM_CHANNEL_CH2, &TIM_OC_InitStruct);
LL_TIM_OC_DisableFast(TIM2, LL_TIM_CHANNEL_CH2);
LL_TIM_DisableMasterSlaveMode(TIM2);
furi_hal_interrupt_set_timer_isr(TIM2, furi_hal_subghz_async_tx_timer_isr);
LL_TIM_EnableIT_UPDATE(TIM2);
LL_TIM_EnableDMAReq_UPDATE(TIM2);
LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH2);
// Start counter
LL_TIM_GenerateEvent_UPDATE(TIM2);
#ifdef FURI_HAL_SUBGHZ_TX_GPIO
hal_gpio_write(&FURI_HAL_SUBGHZ_TX_GPIO, true);
#endif
furi_hal_subghz_tx();
// Enable NVIC
NVIC_SetPriority(TIM2_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0));
NVIC_EnableIRQ(TIM2_IRQn);
LL_TIM_SetCounter(TIM2, 0);
LL_TIM_EnableCounter(TIM2);
return true;
}
bool furi_hal_subghz_is_async_tx_complete() {
return furi_hal_subghz_state == SubGhzStateAsyncTxEnd;
}
void furi_hal_subghz_stop_async_tx() {
furi_assert(
furi_hal_subghz_state == SubGhzStateAsyncTx ||
furi_hal_subghz_state == SubGhzStateAsyncTxLast ||
furi_hal_subghz_state == SubGhzStateAsyncTxEnd);
// Shutdown radio
furi_hal_subghz_idle();
#ifdef FURI_HAL_SUBGHZ_TX_GPIO
hal_gpio_write(&FURI_HAL_SUBGHZ_TX_GPIO, false);
#endif
// Deinitialize Timer
FURI_CRITICAL_ENTER();
LL_TIM_DeInit(TIM2);
LL_APB1_GRP1_DisableClock(LL_APB1_GRP1_PERIPH_TIM2);
furi_hal_interrupt_set_timer_isr(TIM2, NULL);
// Deinitialize DMA
LL_DMA_DeInit(DMA1, LL_DMA_CHANNEL_1);
furi_hal_interrupt_set_dma_channel_isr(DMA1, LL_DMA_CHANNEL_1, NULL);
// Deinitialize GPIO
hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
FURI_CRITICAL_EXIT();
free(furi_hal_subghz_async_tx.buffer);
float duty_cycle =
100.0f * (float)furi_hal_subghz_async_tx.duty_high /
((float)furi_hal_subghz_async_tx.duty_low + (float)furi_hal_subghz_async_tx.duty_high);
FURI_LOG_D(
TAG,
"Async TX Radio stats: on %0.0fus, off %0.0fus, DutyCycle: %0.0f%%",
(float)furi_hal_subghz_async_tx.duty_high,
(float)furi_hal_subghz_async_tx.duty_low,
duty_cycle);
furi_hal_subghz_state = SubGhzStateIdle;
}
@@ -0,0 +1,53 @@
#include "furi_hal_task.h"
//-----------------------------cmsis_os2.c-------------------------------
// helpers to get isr context
// get arch
#ifndef __ARM_ARCH_6M__
#define __ARM_ARCH_6M__ 0
#endif
#ifndef __ARM_ARCH_7M__
#define __ARM_ARCH_7M__ 0
#endif
#ifndef __ARM_ARCH_7EM__
#define __ARM_ARCH_7EM__ 0
#endif
#ifndef __ARM_ARCH_8M_MAIN__
#define __ARM_ARCH_8M_MAIN__ 0
#endif
#ifndef __ARM_ARCH_7A__
#define __ARM_ARCH_7A__ 0
#endif
// get masks
#if((__ARM_ARCH_7M__ == 1U) || (__ARM_ARCH_7EM__ == 1U) || (__ARM_ARCH_8M_MAIN__ == 1U))
#define IS_IRQ_MASKED() ((__get_PRIMASK() != 0U) || (__get_BASEPRI() != 0U))
#elif(__ARM_ARCH_6M__ == 1U)
#define IS_IRQ_MASKED() (__get_PRIMASK() != 0U)
#elif(__ARM_ARCH_7A__ == 1U)
/* CPSR mask bits */
#define CPSR_MASKBIT_I 0x80U
#define IS_IRQ_MASKED() ((__get_CPSR() & CPSR_MASKBIT_I) != 0U)
#else
#define IS_IRQ_MASKED() (__get_PRIMASK() != 0U)
#endif
// get is irq mode
#if(__ARM_ARCH_7A__ == 1U)
/* CPSR mode bitmasks */
#define CPSR_MODE_USER 0x10U
#define CPSR_MODE_SYSTEM 0x1FU
#define IS_IRQ_MODE() ((__get_mode() != CPSR_MODE_USER) && (__get_mode() != CPSR_MODE_SYSTEM))
#else
#define IS_IRQ_MODE() (__get_IPSR() != 0U)
#endif
// added osKernelGetState(), because KernelState is a static var
#define IS_IRQ() (IS_IRQ_MODE() || (IS_IRQ_MASKED() && (osKernelGetState() == osKernelRunning)))
//-------------------------end of cmsis_os2.c----------------------------
bool task_is_isr_context(void) {
return IS_IRQ();
}
@@ -0,0 +1,12 @@
#pragma once
#include "main.h"
#include <cmsis_os2.h>
#include <stdbool.h>
// Task stack size in bytes
#define DEFAULT_STACK_SIZE 4096
// Max system tasks count
#define MAX_TASK_COUNT 14
bool task_is_isr_context(void);
@@ -0,0 +1,212 @@
#include <furi_hal_uart.h>
#include <stdbool.h>
#include <stm32wbxx_ll_lpuart.h>
#include <stm32wbxx_ll_usart.h>
#include <furi_hal_resources.h>
#include <furi.h>
static void (*irq_cb[2])(uint8_t ev, uint8_t data, void* context);
static void* irq_ctx[2];
static void furi_hal_usart_init(uint32_t baud) {
hal_gpio_init_ex(
&gpio_usart_tx,
GpioModeAltFunctionPushPull,
GpioPullUp,
GpioSpeedVeryHigh,
GpioAltFn7USART1);
hal_gpio_init_ex(
&gpio_usart_rx,
GpioModeAltFunctionPushPull,
GpioPullUp,
GpioSpeedVeryHigh,
GpioAltFn7USART1);
LL_USART_InitTypeDef USART_InitStruct = {0};
USART_InitStruct.PrescalerValue = LL_USART_PRESCALER_DIV1;
USART_InitStruct.BaudRate = baud;
USART_InitStruct.DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct.StopBits = LL_USART_STOPBITS_1;
USART_InitStruct.Parity = LL_USART_PARITY_NONE;
USART_InitStruct.TransferDirection = LL_USART_DIRECTION_TX_RX;
USART_InitStruct.HardwareFlowControl = LL_USART_HWCONTROL_NONE;
USART_InitStruct.OverSampling = LL_USART_OVERSAMPLING_16;
LL_USART_Init(USART1, &USART_InitStruct);
LL_USART_SetTXFIFOThreshold(USART1, LL_USART_FIFOTHRESHOLD_1_2);
LL_USART_EnableFIFO(USART1);
LL_USART_ConfigAsyncMode(USART1);
LL_USART_Enable(USART1);
while(!LL_USART_IsActiveFlag_TEACK(USART1))
;
LL_USART_EnableIT_RXNE_RXFNE(USART1);
LL_USART_EnableIT_IDLE(USART1);
HAL_NVIC_SetPriority(USART1_IRQn, 5, 0);
}
static void furi_hal_lpuart_init(uint32_t baud) {
hal_gpio_init_ex(
&gpio_ext_pc0,
GpioModeAltFunctionPushPull,
GpioPullUp,
GpioSpeedVeryHigh,
GpioAltFn8LPUART1);
hal_gpio_init_ex(
&gpio_ext_pc1,
GpioModeAltFunctionPushPull,
GpioPullUp,
GpioSpeedVeryHigh,
GpioAltFn8LPUART1);
LL_LPUART_InitTypeDef LPUART_InitStruct = {0};
LPUART_InitStruct.PrescalerValue = LL_LPUART_PRESCALER_DIV1;
LPUART_InitStruct.BaudRate = 115200;
LPUART_InitStruct.DataWidth = LL_LPUART_DATAWIDTH_8B;
LPUART_InitStruct.StopBits = LL_LPUART_STOPBITS_1;
LPUART_InitStruct.Parity = LL_LPUART_PARITY_NONE;
LPUART_InitStruct.TransferDirection = LL_LPUART_DIRECTION_TX_RX;
LPUART_InitStruct.HardwareFlowControl = LL_LPUART_HWCONTROL_NONE;
LL_LPUART_Init(LPUART1, &LPUART_InitStruct);
LL_LPUART_SetTXFIFOThreshold(LPUART1, LL_LPUART_FIFOTHRESHOLD_1_8);
LL_LPUART_SetRXFIFOThreshold(LPUART1, LL_LPUART_FIFOTHRESHOLD_1_8);
LL_LPUART_EnableFIFO(LPUART1);
LL_LPUART_Enable(LPUART1);
while((!(LL_LPUART_IsActiveFlag_TEACK(LPUART1))) || (!(LL_LPUART_IsActiveFlag_REACK(LPUART1))))
;
furi_hal_uart_set_br(FuriHalUartIdLPUART1, baud);
LL_LPUART_EnableIT_RXNE_RXFNE(LPUART1);
LL_LPUART_EnableIT_IDLE(LPUART1);
HAL_NVIC_SetPriority(LPUART1_IRQn, 5, 0);
}
void furi_hal_uart_init(FuriHalUartId ch, uint32_t baud) {
if(ch == FuriHalUartIdLPUART1)
furi_hal_lpuart_init(baud);
else if(ch == FuriHalUartIdUSART1)
furi_hal_usart_init(baud);
}
void furi_hal_uart_set_br(FuriHalUartId ch, uint32_t baud) {
if(ch == FuriHalUartIdUSART1) {
if(LL_USART_IsEnabled(USART1)) {
// Wait for transfer complete flag
while(!LL_USART_IsActiveFlag_TC(USART1))
;
LL_USART_Disable(USART1);
uint32_t uartclk = LL_RCC_GetUSARTClockFreq(LL_RCC_USART1_CLKSOURCE);
LL_USART_SetBaudRate(
USART1, uartclk, LL_USART_PRESCALER_DIV1, LL_USART_OVERSAMPLING_16, baud);
LL_USART_Enable(USART1);
}
} else if(ch == FuriHalUartIdLPUART1) {
if(LL_LPUART_IsEnabled(LPUART1)) {
// Wait for transfer complete flag
while(!LL_LPUART_IsActiveFlag_TC(LPUART1))
;
LL_LPUART_Disable(LPUART1);
uint32_t uartclk = LL_RCC_GetLPUARTClockFreq(LL_RCC_LPUART1_CLKSOURCE);
if(uartclk / baud > 4095) {
LL_LPUART_SetPrescaler(LPUART1, LL_LPUART_PRESCALER_DIV32);
LL_LPUART_SetBaudRate(LPUART1, uartclk, LL_LPUART_PRESCALER_DIV32, baud);
} else {
LL_LPUART_SetPrescaler(LPUART1, LL_LPUART_PRESCALER_DIV1);
LL_LPUART_SetBaudRate(LPUART1, uartclk, LL_LPUART_PRESCALER_DIV1, baud);
}
LL_LPUART_Enable(LPUART1);
}
}
}
void furi_hal_uart_deinit(FuriHalUartId ch) {
furi_hal_uart_set_irq_cb(ch, NULL, NULL);
if(ch == FuriHalUartIdUSART1) {
LL_USART_Disable(USART1);
hal_gpio_init(&gpio_usart_tx, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
hal_gpio_init(&gpio_usart_rx, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
} else if(ch == FuriHalUartIdLPUART1) {
LL_LPUART_Disable(LPUART1);
hal_gpio_init(&gpio_ext_pc0, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
hal_gpio_init(&gpio_ext_pc1, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
}
}
void furi_hal_uart_tx(FuriHalUartId ch, uint8_t* buffer, size_t buffer_size) {
if(ch == FuriHalUartIdUSART1) {
if(LL_USART_IsEnabled(USART1) == 0) return;
while(buffer_size > 0) {
while(!LL_USART_IsActiveFlag_TXE(USART1))
;
LL_USART_TransmitData8(USART1, *buffer);
buffer++;
buffer_size--;
}
} else if(ch == FuriHalUartIdLPUART1) {
if(LL_LPUART_IsEnabled(LPUART1) == 0) return;
while(buffer_size > 0) {
while(!LL_LPUART_IsActiveFlag_TXE(LPUART1))
;
LL_LPUART_TransmitData8(LPUART1, *buffer);
buffer++;
buffer_size--;
}
}
}
void furi_hal_uart_set_irq_cb(
FuriHalUartId ch,
void (*cb)(UartIrqEvent ev, uint8_t data, void* ctx),
void* ctx) {
if(cb == NULL) {
if(ch == FuriHalUartIdUSART1)
NVIC_DisableIRQ(USART1_IRQn);
else if(ch == FuriHalUartIdLPUART1)
NVIC_DisableIRQ(LPUART1_IRQn);
irq_cb[ch] = cb;
irq_ctx[ch] = ctx;
} else {
irq_ctx[ch] = ctx;
irq_cb[ch] = cb;
if(ch == FuriHalUartIdUSART1)
NVIC_EnableIRQ(USART1_IRQn);
else if(ch == FuriHalUartIdLPUART1)
NVIC_EnableIRQ(LPUART1_IRQn);
}
}
void LPUART1_IRQHandler(void) {
if(LL_LPUART_IsActiveFlag_RXNE_RXFNE(LPUART1)) {
uint8_t data = LL_LPUART_ReceiveData8(LPUART1);
irq_cb[FuriHalUartIdLPUART1](UartIrqEventRXNE, data, irq_ctx[FuriHalUartIdLPUART1]);
} else if(LL_LPUART_IsActiveFlag_IDLE(LPUART1)) {
irq_cb[FuriHalUartIdLPUART1](UartIrqEventIDLE, 0, irq_ctx[FuriHalUartIdLPUART1]);
LL_LPUART_ClearFlag_IDLE(LPUART1);
} else if(LL_LPUART_IsActiveFlag_ORE(LPUART1)) {
LL_LPUART_ClearFlag_ORE(LPUART1);
}
//TODO: more events
}
void USART1_IRQHandler(void) {
if(LL_USART_IsActiveFlag_RXNE_RXFNE(USART1)) {
uint8_t data = LL_USART_ReceiveData8(USART1);
irq_cb[FuriHalUartIdUSART1](UartIrqEventRXNE, data, irq_ctx[FuriHalUartIdUSART1]);
} else if(LL_USART_IsActiveFlag_IDLE(USART1)) {
irq_cb[FuriHalUartIdUSART1](UartIrqEventIDLE, 0, irq_ctx[FuriHalUartIdUSART1]);
LL_USART_ClearFlag_IDLE(USART1);
} else if(LL_USART_IsActiveFlag_ORE(USART1)) {
LL_USART_ClearFlag_ORE(USART1);
}
}
@@ -0,0 +1,77 @@
/**
* @file furi_hal_uart.h
* @version 1.0
* @date 2021-11-19
*
* UART HAL api interface
*/
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* UART channels
*/
typedef enum {
FuriHalUartIdUSART1,
FuriHalUartIdLPUART1,
} FuriHalUartId;
/**
* UART events
*/
typedef enum {
UartIrqEventRXNE,
UartIrqEventIDLE,
//TODO: more events
} UartIrqEvent;
/**
* Init UART
* Configures GPIO to UART function, сonfigures UART hardware, enables UART hardware
* @param channel UART channel
* @param baud baudrate
*/
void furi_hal_uart_init(FuriHalUartId channel, uint32_t baud);
/**
* Deinit UART
* Configures GPIO to analog, clears callback and callback context, disables UART hardware
* @param channel UART channel
*/
void furi_hal_uart_deinit(FuriHalUartId channel);
/**
* Changes UART baudrate
* @param channel UART channel
* @param baud baudrate
*/
void furi_hal_uart_set_br(FuriHalUartId channel, uint32_t baud);
/**
* Transmits data
* @param channel UART channel
* @param buffer data
* @param buffer_size data size (in bytes)
*/
void furi_hal_uart_tx(FuriHalUartId channel, uint8_t* buffer, size_t buffer_size);
/**
* Sets UART event callback
* @param channel UART channel
* @param callback callback pointer
* @param context callback context
*/
void furi_hal_uart_set_irq_cb(
FuriHalUartId channel,
void (*callback)(UartIrqEvent event, uint8_t data, void* context),
void* context);
#ifdef __cplusplus
}
#endif
+159
View File
@@ -0,0 +1,159 @@
#include "furi_hal_version.h"
#include "furi_hal_usb_i.h"
#include "furi_hal_usb.h"
#include <furi.h>
#include "usb.h"
#define TAG "FuriHalUsb"
#define USB_RECONNECT_DELAY 500
static UsbInterface* usb_if_cur;
static UsbInterface* usb_if_next;
static const struct usb_string_descriptor dev_lang_desc = USB_ARRAY_DESC(USB_LANGID_ENG_US);
static uint32_t ubuf[0x20];
usbd_device udev;
static usbd_respond usb_descriptor_get(usbd_ctlreq* req, void** address, uint16_t* length);
static void susp_evt(usbd_device* dev, uint8_t event, uint8_t ep);
static void wkup_evt(usbd_device* dev, uint8_t event, uint8_t ep);
struct UsbCfg {
osTimerId_t reconnect_tmr;
bool enabled;
bool connected;
} usb_config;
static void furi_hal_usb_tmr_cb(void* context);
/* Low-level init */
void furi_hal_usb_init(void) {
LL_GPIO_InitTypeDef GPIO_InitStruct = {0};
LL_PWR_EnableVddUSB();
GPIO_InitStruct.Pin = LL_GPIO_PIN_11 | LL_GPIO_PIN_12;
GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE;
GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
GPIO_InitStruct.Pull = LL_GPIO_PULL_NO;
GPIO_InitStruct.Alternate = LL_GPIO_AF_10;
LL_GPIO_Init(GPIOA, &GPIO_InitStruct);
usbd_init(&udev, &usbd_hw, USB_EP0_SIZE, ubuf, sizeof(ubuf));
usbd_enable(&udev, true);
usbd_reg_descr(&udev, usb_descriptor_get);
usbd_reg_event(&udev, usbd_evt_susp, susp_evt);
usbd_reg_event(&udev, usbd_evt_wkup, wkup_evt);
usb_config.enabled = false;
usb_config.reconnect_tmr = NULL;
HAL_NVIC_SetPriority(USB_LP_IRQn, 5, 0);
NVIC_EnableIRQ(USB_LP_IRQn);
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_usb_set_config(UsbInterface* new_if) {
if(new_if != usb_if_cur) {
if(usb_config.enabled) {
usb_if_next = new_if;
if(usb_config.reconnect_tmr == NULL)
usb_config.reconnect_tmr =
osTimerNew(furi_hal_usb_tmr_cb, osTimerOnce, NULL, NULL);
furi_hal_usb_disable();
osTimerStart(usb_config.reconnect_tmr, USB_RECONNECT_DELAY);
} else {
if(usb_if_cur != NULL) usb_if_cur->deinit(&udev);
if(new_if != NULL) {
new_if->init(&udev, new_if);
FURI_LOG_I(TAG, "USB mode change");
usb_config.enabled = true;
usb_if_cur = new_if;
}
}
}
}
UsbInterface* furi_hal_usb_get_config() {
return usb_if_cur;
}
void furi_hal_usb_disable() {
if(usb_config.enabled) {
susp_evt(&udev, 0, 0);
usbd_connect(&udev, false);
usb_config.enabled = false;
FURI_LOG_I(TAG, "USB Disable");
}
}
void furi_hal_usb_enable() {
if((!usb_config.enabled) && (usb_if_cur != NULL)) {
usbd_connect(&udev, true);
usb_config.enabled = true;
FURI_LOG_I(TAG, "USB Enable");
}
}
static void furi_hal_usb_tmr_cb(void* context) {
furi_hal_usb_set_config(usb_if_next);
}
/* Get device / configuration descriptors */
static usbd_respond usb_descriptor_get(usbd_ctlreq* req, void** address, uint16_t* length) {
const uint8_t dtype = req->wValue >> 8;
const uint8_t dnumber = req->wValue & 0xFF;
const void* desc;
uint16_t len = 0;
if(usb_if_cur == NULL) return usbd_fail;
switch(dtype) {
case USB_DTYPE_DEVICE:
desc = usb_if_cur->dev_descr;
break;
case USB_DTYPE_CONFIGURATION:
desc = usb_if_cur->cfg_descr;
len = ((struct usb_string_descriptor*)(usb_if_cur->cfg_descr))->wString[0];
break;
case USB_DTYPE_STRING:
if(dnumber == UsbDevLang) {
desc = &dev_lang_desc;
} else if(dnumber == UsbDevManuf) {
desc = usb_if_cur->str_manuf_descr;
} else if(dnumber == UsbDevProduct) {
desc = usb_if_cur->str_prod_descr;
} else if(dnumber == UsbDevSerial) {
desc = usb_if_cur->str_serial_descr;
} else
return usbd_fail;
break;
default:
return usbd_fail;
}
if(desc == NULL) return usbd_fail;
if(len == 0) {
len = ((struct usb_header_descriptor*)desc)->bLength;
}
*address = (void*)desc;
*length = len;
return usbd_ack;
}
static void susp_evt(usbd_device* dev, uint8_t event, uint8_t ep) {
if((usb_if_cur != NULL) && (usb_config.connected == true)) {
usb_config.connected = false;
usb_if_cur->suspend(&udev);
}
}
static void wkup_evt(usbd_device* dev, uint8_t event, uint8_t ep) {
if((usb_if_cur != NULL) && (usb_config.connected == false)) {
usb_config.connected = true;
usb_if_cur->wakeup(&udev);
}
}
@@ -0,0 +1,664 @@
#include "furi_hal_version.h"
#include "furi_hal_usb_i.h"
#include "furi_hal_usb.h"
#include "furi_hal_usb_cdc_i.h"
#include <furi.h>
#include "usb.h"
#include "usb_cdc.h"
#define CDC0_RXD_EP 0x01
#define CDC0_TXD_EP 0x82
#define CDC0_NTF_EP 0x83
#define CDC1_RXD_EP 0x04
#define CDC1_TXD_EP 0x85
#define CDC1_NTF_EP 0x86
#define CDC_NTF_SZ 0x08
#define IF_NUM_MAX 2
struct CdcIadDescriptor {
struct usb_iad_descriptor comm_iad;
struct usb_interface_descriptor comm;
struct usb_cdc_header_desc cdc_hdr;
struct usb_cdc_call_mgmt_desc cdc_mgmt;
struct usb_cdc_acm_desc cdc_acm;
struct usb_cdc_union_desc cdc_union;
struct usb_endpoint_descriptor comm_ep;
struct usb_interface_descriptor data;
struct usb_endpoint_descriptor data_eprx;
struct usb_endpoint_descriptor data_eptx;
};
struct CdcConfigDescriptorSingle {
struct usb_config_descriptor config;
struct CdcIadDescriptor iad_0;
} __attribute__((packed));
struct CdcConfigDescriptorDual {
struct usb_config_descriptor config;
struct CdcIadDescriptor iad_0;
struct CdcIadDescriptor iad_1;
} __attribute__((packed));
static const struct usb_string_descriptor dev_manuf_desc = USB_STRING_DESC("Flipper Devices Inc.");
/* Device descriptor */
static const struct usb_device_descriptor cdc_device_desc = {
.bLength = sizeof(struct usb_device_descriptor),
.bDescriptorType = USB_DTYPE_DEVICE,
.bcdUSB = VERSION_BCD(2, 0, 0),
.bDeviceClass = USB_CLASS_IAD,
.bDeviceSubClass = USB_SUBCLASS_IAD,
.bDeviceProtocol = USB_PROTO_IAD,
.bMaxPacketSize0 = USB_EP0_SIZE,
.idVendor = 0x0483,
.idProduct = 0x5740,
.bcdDevice = VERSION_BCD(1, 0, 0),
.iManufacturer = UsbDevManuf,
.iProduct = UsbDevProduct,
.iSerialNumber = UsbDevSerial,
.bNumConfigurations = 1,
};
/* Device configuration descriptor - single mode*/
static const struct CdcConfigDescriptorSingle cdc_cfg_desc_single = {
.config =
{
.bLength = sizeof(struct usb_config_descriptor),
.bDescriptorType = USB_DTYPE_CONFIGURATION,
.wTotalLength = sizeof(struct CdcConfigDescriptorSingle),
.bNumInterfaces = 2,
.bConfigurationValue = 1,
.iConfiguration = NO_DESCRIPTOR,
.bmAttributes = USB_CFG_ATTR_RESERVED | USB_CFG_ATTR_SELFPOWERED,
.bMaxPower = USB_CFG_POWER_MA(100),
},
.iad_0 =
{
.comm_iad =
{
.bLength = sizeof(struct usb_iad_descriptor),
.bDescriptorType = USB_DTYPE_INTERFASEASSOC,
.bFirstInterface = 0,
.bInterfaceCount = 2,
.bFunctionClass = USB_CLASS_CDC,
.bFunctionSubClass = USB_CDC_SUBCLASS_ACM,
.bFunctionProtocol = USB_PROTO_NONE,
.iFunction = NO_DESCRIPTOR,
},
.comm =
{
.bLength = sizeof(struct usb_interface_descriptor),
.bDescriptorType = USB_DTYPE_INTERFACE,
.bInterfaceNumber = 0,
.bAlternateSetting = 0,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_CDC,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
.bInterfaceProtocol = USB_PROTO_NONE,
.iInterface = NO_DESCRIPTOR,
},
.cdc_hdr =
{
.bFunctionLength = sizeof(struct usb_cdc_header_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_HEADER,
.bcdCDC = VERSION_BCD(1, 1, 0),
},
.cdc_mgmt =
{
.bFunctionLength = sizeof(struct usb_cdc_call_mgmt_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_CALL_MANAGEMENT,
.bmCapabilities = 0,
.bDataInterface = 1,
},
.cdc_acm =
{
.bFunctionLength = sizeof(struct usb_cdc_acm_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_ACM,
.bmCapabilities = 0,
},
.cdc_union =
{
.bFunctionLength = sizeof(struct usb_cdc_union_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_UNION,
.bMasterInterface0 = 0,
.bSlaveInterface0 = 1,
},
.comm_ep =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC0_NTF_EP,
.bmAttributes = USB_EPTYPE_INTERRUPT,
.wMaxPacketSize = CDC_NTF_SZ,
.bInterval = 0xFF,
},
.data =
{
.bLength = sizeof(struct usb_interface_descriptor),
.bDescriptorType = USB_DTYPE_INTERFACE,
.bInterfaceNumber = 1,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = USB_SUBCLASS_NONE,
.bInterfaceProtocol = USB_PROTO_NONE,
.iInterface = NO_DESCRIPTOR,
},
.data_eprx =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC0_RXD_EP,
.bmAttributes = USB_EPTYPE_BULK,
.wMaxPacketSize = CDC_DATA_SZ,
.bInterval = 0x01,
},
.data_eptx =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC0_TXD_EP,
.bmAttributes = USB_EPTYPE_BULK,
.wMaxPacketSize = CDC_DATA_SZ,
.bInterval = 0x01,
},
},
};
/* Device configuration descriptor - dual mode*/
static const struct CdcConfigDescriptorDual
cdc_cfg_desc_dual =
{
.config =
{
.bLength = sizeof(struct usb_config_descriptor),
.bDescriptorType = USB_DTYPE_CONFIGURATION,
.wTotalLength = sizeof(struct CdcConfigDescriptorDual),
.bNumInterfaces = 4,
.bConfigurationValue = 1,
.iConfiguration = NO_DESCRIPTOR,
.bmAttributes = USB_CFG_ATTR_RESERVED | USB_CFG_ATTR_SELFPOWERED,
.bMaxPower = USB_CFG_POWER_MA(100),
},
.iad_0 =
{
.comm_iad =
{
.bLength = sizeof(struct usb_iad_descriptor),
.bDescriptorType = USB_DTYPE_INTERFASEASSOC,
.bFirstInterface = 0,
.bInterfaceCount = 2,
.bFunctionClass = USB_CLASS_CDC,
.bFunctionSubClass = USB_CDC_SUBCLASS_ACM,
.bFunctionProtocol = USB_PROTO_NONE,
.iFunction = NO_DESCRIPTOR,
},
.comm =
{
.bLength = sizeof(struct usb_interface_descriptor),
.bDescriptorType = USB_DTYPE_INTERFACE,
.bInterfaceNumber = 0,
.bAlternateSetting = 0,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_CDC,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
.bInterfaceProtocol = USB_PROTO_NONE,
.iInterface = NO_DESCRIPTOR,
},
.cdc_hdr =
{
.bFunctionLength = sizeof(struct usb_cdc_header_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_HEADER,
.bcdCDC = VERSION_BCD(1, 1, 0),
},
.cdc_mgmt =
{
.bFunctionLength = sizeof(struct usb_cdc_call_mgmt_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_CALL_MANAGEMENT,
.bmCapabilities = 0,
.bDataInterface = 1,
},
.cdc_acm =
{
.bFunctionLength = sizeof(struct usb_cdc_acm_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_ACM,
.bmCapabilities = 0,
},
.cdc_union =
{
.bFunctionLength = sizeof(struct usb_cdc_union_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_UNION,
.bMasterInterface0 = 0,
.bSlaveInterface0 = 1,
},
.comm_ep =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC0_NTF_EP,
.bmAttributes = USB_EPTYPE_INTERRUPT,
.wMaxPacketSize = CDC_NTF_SZ,
.bInterval = 0xFF,
},
.data =
{
.bLength = sizeof(struct usb_interface_descriptor),
.bDescriptorType = USB_DTYPE_INTERFACE,
.bInterfaceNumber = 1,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = USB_SUBCLASS_NONE,
.bInterfaceProtocol = USB_PROTO_NONE,
.iInterface = NO_DESCRIPTOR,
},
.data_eprx =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC0_RXD_EP,
.bmAttributes = USB_EPTYPE_BULK,
.wMaxPacketSize = CDC_DATA_SZ,
.bInterval = 0x01,
},
.data_eptx =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC0_TXD_EP,
.bmAttributes = USB_EPTYPE_BULK,
.wMaxPacketSize = CDC_DATA_SZ,
.bInterval = 0x01,
},
},
.iad_1 =
{
.comm_iad =
{
.bLength = sizeof(struct usb_iad_descriptor),
.bDescriptorType = USB_DTYPE_INTERFASEASSOC,
.bFirstInterface = 2,
.bInterfaceCount = 2,
.bFunctionClass = USB_CLASS_CDC,
.bFunctionSubClass = USB_CDC_SUBCLASS_ACM,
.bFunctionProtocol = USB_PROTO_NONE,
.iFunction = NO_DESCRIPTOR,
},
.comm =
{
.bLength = sizeof(struct usb_interface_descriptor),
.bDescriptorType = USB_DTYPE_INTERFACE,
.bInterfaceNumber = 2 + 0,
.bAlternateSetting = 0,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_CDC,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
.bInterfaceProtocol = USB_PROTO_NONE,
.iInterface = NO_DESCRIPTOR,
},
.cdc_hdr =
{
.bFunctionLength = sizeof(struct usb_cdc_header_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_HEADER,
.bcdCDC = VERSION_BCD(1, 1, 0),
},
.cdc_mgmt =
{
.bFunctionLength = sizeof(struct usb_cdc_call_mgmt_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_CALL_MANAGEMENT,
.bmCapabilities = 0,
.bDataInterface = 2 + 1,
},
.cdc_acm =
{
.bFunctionLength = sizeof(struct usb_cdc_acm_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_ACM,
.bmCapabilities = 0,
},
.cdc_union =
{
.bFunctionLength = sizeof(struct usb_cdc_union_desc),
.bDescriptorType = USB_DTYPE_CS_INTERFACE,
.bDescriptorSubType = USB_DTYPE_CDC_UNION,
.bMasterInterface0 = 2 + 0,
.bSlaveInterface0 = 2 + 1,
},
.comm_ep =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC1_NTF_EP,
.bmAttributes = USB_EPTYPE_INTERRUPT,
.wMaxPacketSize = CDC_NTF_SZ,
.bInterval = 0xFF,
},
.data =
{
.bLength = sizeof(struct usb_interface_descriptor),
.bDescriptorType = USB_DTYPE_INTERFACE,
.bInterfaceNumber = 2 + 1,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = USB_SUBCLASS_NONE,
.bInterfaceProtocol = USB_PROTO_NONE,
.iInterface = NO_DESCRIPTOR,
},
.data_eprx =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC1_RXD_EP,
.bmAttributes = USB_EPTYPE_BULK,
.wMaxPacketSize = CDC_DATA_SZ,
.bInterval = 0x01,
},
.data_eptx =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = CDC1_TXD_EP,
.bmAttributes = USB_EPTYPE_BULK,
.wMaxPacketSize = CDC_DATA_SZ,
.bInterval = 0x01,
},
},
};
static struct usb_cdc_line_coding cdc_config[IF_NUM_MAX] = {};
static uint8_t cdc_ctrl_line_state[IF_NUM_MAX];
static void cdc_init(usbd_device* dev, UsbInterface* intf);
static void cdc_deinit(usbd_device* dev);
static void cdc_on_wakeup(usbd_device* dev);
static void cdc_on_suspend(usbd_device* dev);
static usbd_respond cdc_ep_config(usbd_device* dev, uint8_t cfg);
static usbd_respond cdc_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback);
static usbd_device* usb_dev;
static UsbInterface* cdc_if_cur = NULL;
static bool connected = false;
static CdcCallbacks* callbacks[IF_NUM_MAX] = {NULL};
static void* cb_ctx[IF_NUM_MAX];
UsbInterface usb_cdc_single = {
.init = cdc_init,
.deinit = cdc_deinit,
.wakeup = cdc_on_wakeup,
.suspend = cdc_on_suspend,
.dev_descr = (struct usb_device_descriptor*)&cdc_device_desc,
.str_manuf_descr = (void*)&dev_manuf_desc,
.str_prod_descr = NULL,
.str_serial_descr = NULL,
.cfg_descr = (void*)&cdc_cfg_desc_single,
};
UsbInterface usb_cdc_dual = {
.init = cdc_init,
.deinit = cdc_deinit,
.wakeup = cdc_on_wakeup,
.suspend = cdc_on_suspend,
.dev_descr = (struct usb_device_descriptor*)&cdc_device_desc,
.str_manuf_descr = (void*)&dev_manuf_desc,
.str_prod_descr = NULL,
.str_serial_descr = NULL,
.cfg_descr = (void*)&cdc_cfg_desc_dual,
};
static void cdc_init(usbd_device* dev, UsbInterface* intf) {
usb_dev = dev;
cdc_if_cur = intf;
char* name = (char*)furi_hal_version_get_device_name_ptr();
uint8_t len = (name == NULL) ? (0) : (strlen(name));
struct usb_string_descriptor* dev_prod_desc = furi_alloc(len * 2 + 2);
dev_prod_desc->bLength = len * 2 + 2;
dev_prod_desc->bDescriptorType = USB_DTYPE_STRING;
for(uint8_t i = 0; i < len; i++) dev_prod_desc->wString[i] = name[i];
name = (char*)furi_hal_version_get_name_ptr();
len = (name == NULL) ? (0) : (strlen(name));
struct usb_string_descriptor* dev_serial_desc = furi_alloc((len + 5) * 2 + 2);
dev_serial_desc->bLength = (len + 5) * 2 + 2;
dev_serial_desc->bDescriptorType = USB_DTYPE_STRING;
memcpy(dev_serial_desc->wString, "f\0l\0i\0p\0_\0", 5 * 2);
for(uint8_t i = 0; i < len; i++) dev_serial_desc->wString[i + 5] = name[i];
cdc_if_cur->str_prod_descr = dev_prod_desc;
cdc_if_cur->str_serial_descr = dev_serial_desc;
usbd_reg_config(dev, cdc_ep_config);
usbd_reg_control(dev, cdc_control);
usbd_connect(dev, true);
}
static void cdc_deinit(usbd_device* dev) {
usbd_reg_config(dev, NULL);
usbd_reg_control(dev, NULL);
free(cdc_if_cur->str_prod_descr);
free(cdc_if_cur->str_serial_descr);
cdc_if_cur = NULL;
}
void furi_hal_cdc_set_callbacks(uint8_t if_num, CdcCallbacks* cb, void* context) {
furi_assert(if_num < IF_NUM_MAX);
if(callbacks[if_num] != NULL) {
if(callbacks[if_num]->state_callback != NULL) {
if(connected == true) callbacks[if_num]->state_callback(cb_ctx[if_num], 0);
}
}
callbacks[if_num] = cb;
cb_ctx[if_num] = context;
if(callbacks[if_num] != NULL) {
if(callbacks[if_num]->state_callback != NULL) {
if(connected == true) callbacks[if_num]->state_callback(cb_ctx[if_num], 1);
}
}
}
struct usb_cdc_line_coding* furi_hal_cdc_get_port_settings(uint8_t if_num) {
furi_assert(if_num < IF_NUM_MAX);
return &cdc_config[if_num];
}
uint8_t furi_hal_cdc_get_ctrl_line_state(uint8_t if_num) {
furi_assert(if_num < IF_NUM_MAX);
return cdc_ctrl_line_state[if_num];
}
void furi_hal_cdc_send(uint8_t if_num, uint8_t* buf, uint16_t len) {
if(if_num == 0)
usbd_ep_write(usb_dev, CDC0_TXD_EP, buf, len);
else
usbd_ep_write(usb_dev, CDC1_TXD_EP, buf, len);
}
int32_t furi_hal_cdc_receive(uint8_t if_num, uint8_t* buf, uint16_t max_len) {
int32_t len = 0;
if(if_num == 0)
len = usbd_ep_read(usb_dev, CDC0_RXD_EP, buf, max_len);
else
len = usbd_ep_read(usb_dev, CDC1_RXD_EP, buf, max_len);
return ((len < 0) ? 0 : len);
}
static void cdc_on_wakeup(usbd_device* dev) {
connected = true;
for(uint8_t i = 0; i < IF_NUM_MAX; i++) {
if(callbacks[i] != NULL) {
if(callbacks[i]->state_callback != NULL) callbacks[i]->state_callback(cb_ctx[i], 1);
}
}
}
static void cdc_on_suspend(usbd_device* dev) {
connected = false;
for(uint8_t i = 0; i < IF_NUM_MAX; i++) {
cdc_ctrl_line_state[i] = 0;
if(callbacks[i] != NULL) {
if(callbacks[i]->state_callback != NULL) callbacks[i]->state_callback(cb_ctx[i], 0);
}
}
}
static void cdc_rx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) {
uint8_t if_num = 0;
if(ep == CDC0_RXD_EP)
if_num = 0;
else
if_num = 1;
if(callbacks[if_num] != NULL) {
if(callbacks[if_num]->rx_ep_callback != NULL)
callbacks[if_num]->rx_ep_callback(cb_ctx[if_num]);
}
}
static void cdc_tx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) {
uint8_t if_num = 0;
if(ep == CDC0_TXD_EP)
if_num = 0;
else
if_num = 1;
if(callbacks[if_num] != NULL) {
if(callbacks[if_num]->tx_ep_callback != NULL)
callbacks[if_num]->tx_ep_callback(cb_ctx[if_num]);
}
}
static void cdc_txrx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) {
if(event == usbd_evt_eptx) {
cdc_tx_ep_callback(dev, event, ep);
} else {
cdc_rx_ep_callback(dev, event, ep);
}
}
/* Configure endpoints */
static usbd_respond cdc_ep_config(usbd_device* dev, uint8_t cfg) {
uint8_t if_cnt = ((struct usb_config_descriptor*)(cdc_if_cur->cfg_descr))->bNumInterfaces;
switch(cfg) {
case 0:
/* deconfiguring device */
if(if_cnt == 4) {
usbd_ep_deconfig(dev, CDC1_NTF_EP);
usbd_ep_deconfig(dev, CDC1_TXD_EP);
usbd_ep_deconfig(dev, CDC1_RXD_EP);
usbd_reg_endpoint(dev, CDC1_RXD_EP, 0);
usbd_reg_endpoint(dev, CDC1_TXD_EP, 0);
}
usbd_ep_deconfig(dev, CDC0_NTF_EP);
usbd_ep_deconfig(dev, CDC0_TXD_EP);
usbd_ep_deconfig(dev, CDC0_RXD_EP);
usbd_reg_endpoint(dev, CDC0_RXD_EP, 0);
usbd_reg_endpoint(dev, CDC0_TXD_EP, 0);
return usbd_ack;
case 1:
/* configuring device */
if((CDC0_TXD_EP & 0x7F) != (CDC0_RXD_EP & 0x7F)) {
// 2x unidirectional endpoint mode with dualbuf
usbd_ep_config(dev, CDC0_RXD_EP, USB_EPTYPE_BULK | USB_EPTYPE_DBLBUF, CDC_DATA_SZ);
usbd_ep_config(dev, CDC0_TXD_EP, USB_EPTYPE_BULK | USB_EPTYPE_DBLBUF, CDC_DATA_SZ);
usbd_ep_config(dev, CDC0_NTF_EP, USB_EPTYPE_INTERRUPT, CDC_NTF_SZ);
usbd_reg_endpoint(dev, CDC0_RXD_EP, cdc_rx_ep_callback);
usbd_reg_endpoint(dev, CDC0_TXD_EP, cdc_tx_ep_callback);
} else {
// 1x bidirectional endpoint mode
usbd_ep_config(dev, CDC0_RXD_EP, USB_EPTYPE_BULK, CDC_DATA_SZ);
usbd_ep_config(dev, CDC0_TXD_EP, USB_EPTYPE_BULK, CDC_DATA_SZ);
usbd_ep_config(dev, CDC0_NTF_EP, USB_EPTYPE_INTERRUPT, CDC_NTF_SZ);
usbd_reg_endpoint(dev, CDC0_RXD_EP, cdc_txrx_ep_callback);
usbd_reg_endpoint(dev, CDC0_TXD_EP, cdc_txrx_ep_callback);
}
usbd_ep_write(dev, CDC0_TXD_EP, 0, 0);
if(if_cnt == 4) {
if((CDC1_TXD_EP & 0x7F) != (CDC1_RXD_EP & 0x7F)) {
usbd_ep_config(dev, CDC1_RXD_EP, USB_EPTYPE_BULK | USB_EPTYPE_DBLBUF, CDC_DATA_SZ);
usbd_ep_config(dev, CDC1_TXD_EP, USB_EPTYPE_BULK | USB_EPTYPE_DBLBUF, CDC_DATA_SZ);
usbd_ep_config(dev, CDC1_NTF_EP, USB_EPTYPE_INTERRUPT, CDC_NTF_SZ);
usbd_reg_endpoint(dev, CDC1_RXD_EP, cdc_rx_ep_callback);
usbd_reg_endpoint(dev, CDC1_TXD_EP, cdc_tx_ep_callback);
} else {
usbd_ep_config(dev, CDC1_RXD_EP, USB_EPTYPE_BULK, CDC_DATA_SZ);
usbd_ep_config(dev, CDC1_TXD_EP, USB_EPTYPE_BULK, CDC_DATA_SZ);
usbd_ep_config(dev, CDC1_NTF_EP, USB_EPTYPE_INTERRUPT, CDC_NTF_SZ);
usbd_reg_endpoint(dev, CDC1_RXD_EP, cdc_txrx_ep_callback);
usbd_reg_endpoint(dev, CDC1_TXD_EP, cdc_txrx_ep_callback);
}
usbd_ep_write(dev, CDC1_TXD_EP, 0, 0);
}
return usbd_ack;
default:
return usbd_fail;
}
}
/* Control requests handler */
static usbd_respond cdc_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback) {
/* CDC control requests */
uint8_t if_num = 0;
if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) ==
(USB_REQ_INTERFACE | USB_REQ_CLASS) &&
(req->wIndex == 0 || req->wIndex == 2)) {
if(req->wIndex == 0)
if_num = 0;
else
if_num = 1;
switch(req->bRequest) {
case USB_CDC_SET_CONTROL_LINE_STATE:
if(callbacks[if_num] != NULL) {
cdc_ctrl_line_state[if_num] = req->wValue;
if(callbacks[if_num]->ctrl_line_callback != NULL)
callbacks[if_num]->ctrl_line_callback(
cb_ctx[if_num], cdc_ctrl_line_state[if_num]);
}
return usbd_ack;
case USB_CDC_SET_LINE_CODING:
memcpy(&cdc_config[if_num], req->data, sizeof(cdc_config[0]));
if(callbacks[if_num] != NULL) {
if(callbacks[if_num]->config_callback != NULL)
callbacks[if_num]->config_callback(cb_ctx[if_num], &cdc_config[if_num]);
}
return usbd_ack;
case USB_CDC_GET_LINE_CODING:
dev->status.data_ptr = &cdc_config[if_num];
dev->status.data_count = sizeof(cdc_config[0]);
return usbd_ack;
default:
return usbd_fail;
}
}
return usbd_fail;
}
@@ -0,0 +1,24 @@
#pragma once
#include <stdint.h>
#include "usb_cdc.h"
#define CDC_DATA_SZ 64
typedef struct {
void (*tx_ep_callback)(void* context);
void (*rx_ep_callback)(void* context);
void (*state_callback)(void* context, uint8_t state);
void (*ctrl_line_callback)(void* context, uint8_t state);
void (*config_callback)(void* context, struct usb_cdc_line_coding* config);
} CdcCallbacks;
void furi_hal_cdc_set_callbacks(uint8_t if_num, CdcCallbacks* cb, void* context);
struct usb_cdc_line_coding* furi_hal_cdc_get_port_settings(uint8_t if_num);
uint8_t furi_hal_cdc_get_ctrl_line_state(uint8_t if_num);
void furi_hal_cdc_send(uint8_t if_num, uint8_t* buf, uint16_t len);
int32_t furi_hal_cdc_receive(uint8_t if_num, uint8_t* buf, uint16_t max_len);
@@ -0,0 +1,482 @@
#include "furi_hal_version.h"
#include "furi_hal_usb_i.h"
#include "furi_hal_usb.h"
#include "furi_hal_usb_hid.h"
#include <furi.h>
#include "usb.h"
#include "usb_hid.h"
#include "hid_usage_desktop.h"
#include "hid_usage_button.h"
#include "hid_usage_keyboard.h"
#include "hid_usage_led.h"
#define HID_EP_IN 0x81
#define HID_EP_OUT 0x01
#define HID_EP_SZ 0x10
#define HID_KB_MAX_KEYS 6
#define HID_CONSUMER_MAX_KEYS 2
#define HID_PAGE_CONSUMER 0x0C
#define HID_CONSUMER_CONTROL 0x01
struct HidIadDescriptor {
struct usb_iad_descriptor hid_iad;
struct usb_interface_descriptor hid;
struct usb_hid_descriptor hid_desc;
struct usb_endpoint_descriptor hid_ep_in;
struct usb_endpoint_descriptor hid_ep_out;
};
struct HidConfigDescriptor {
struct usb_config_descriptor config;
struct HidIadDescriptor iad_0;
} __attribute__((packed));
enum HidReportId {
ReportIdKeyboard = 1,
ReportIdMouse = 2,
ReportIdConsumer = 3,
};
/* HID report: keyboard+mouse */
static const uint8_t hid_report_desc[] = {
HID_USAGE_PAGE(HID_PAGE_DESKTOP),
HID_USAGE(HID_DESKTOP_KEYBOARD),
HID_COLLECTION(HID_APPLICATION_COLLECTION),
HID_REPORT_ID(ReportIdKeyboard),
HID_USAGE_PAGE(HID_DESKTOP_KEYPAD),
HID_USAGE_MINIMUM(HID_KEYBOARD_L_CTRL),
HID_USAGE_MAXIMUM(HID_KEYBOARD_R_GUI),
HID_LOGICAL_MINIMUM(0),
HID_LOGICAL_MAXIMUM(1),
HID_REPORT_SIZE(1),
HID_REPORT_COUNT(8),
HID_INPUT(HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
HID_REPORT_COUNT(1),
HID_REPORT_SIZE(8),
HID_INPUT(HID_IOF_CONSTANT | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
HID_USAGE_PAGE(HID_PAGE_LED),
HID_REPORT_COUNT(8),
HID_REPORT_SIZE(1),
HID_USAGE_MINIMUM(1),
HID_USAGE_MAXIMUM(8),
HID_OUTPUT(HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
HID_REPORT_COUNT(HID_KB_MAX_KEYS),
HID_REPORT_SIZE(8),
HID_LOGICAL_MINIMUM(0),
HID_LOGICAL_MAXIMUM(101),
HID_USAGE_PAGE(HID_DESKTOP_KEYPAD),
HID_USAGE_MINIMUM(0),
HID_USAGE_MAXIMUM(101),
HID_INPUT(HID_IOF_DATA | HID_IOF_ARRAY | HID_IOF_ABSOLUTE),
HID_END_COLLECTION,
HID_USAGE_PAGE(HID_PAGE_DESKTOP),
HID_USAGE(HID_DESKTOP_MOUSE),
HID_COLLECTION(HID_APPLICATION_COLLECTION),
HID_USAGE(HID_DESKTOP_POINTER),
HID_COLLECTION(HID_PHYSICAL_COLLECTION),
HID_REPORT_ID(ReportIdMouse),
HID_USAGE_PAGE(HID_PAGE_BUTTON),
HID_USAGE_MINIMUM(1),
HID_USAGE_MAXIMUM(3),
HID_LOGICAL_MINIMUM(0),
HID_LOGICAL_MAXIMUM(1),
HID_REPORT_COUNT(3),
HID_REPORT_SIZE(1),
HID_INPUT(HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
HID_REPORT_SIZE(1),
HID_REPORT_COUNT(5),
HID_INPUT(HID_IOF_CONSTANT | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
HID_USAGE_PAGE(HID_PAGE_DESKTOP),
HID_USAGE(HID_DESKTOP_X),
HID_USAGE(HID_DESKTOP_Y),
HID_USAGE(HID_DESKTOP_WHEEL),
HID_LOGICAL_MINIMUM(-127),
HID_LOGICAL_MAXIMUM(127),
HID_REPORT_SIZE(8),
HID_REPORT_COUNT(3),
HID_INPUT(HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_RELATIVE),
HID_END_COLLECTION,
HID_END_COLLECTION,
HID_USAGE_PAGE(HID_PAGE_CONSUMER),
HID_USAGE(HID_CONSUMER_CONTROL),
HID_COLLECTION(HID_APPLICATION_COLLECTION),
HID_REPORT_ID(ReportIdConsumer),
HID_LOGICAL_MINIMUM(0),
HID_RI_LOGICAL_MAXIMUM(16, 0x3FF),
HID_USAGE_MINIMUM(0),
HID_RI_USAGE_MAXIMUM(16, 0x3FF),
HID_REPORT_COUNT(HID_CONSUMER_MAX_KEYS),
HID_REPORT_SIZE(16),
HID_INPUT(HID_IOF_DATA | HID_IOF_ARRAY | HID_IOF_ABSOLUTE),
HID_END_COLLECTION,
};
static const struct usb_string_descriptor dev_manuf_desc = USB_STRING_DESC("Logitech");
static const struct usb_string_descriptor dev_prod_desc = USB_STRING_DESC("USB Receiver");
static const struct usb_string_descriptor dev_serial_desc = USB_STRING_DESC("1234567890");
/* Device descriptor */
static const struct usb_device_descriptor hid_device_desc = {
.bLength = sizeof(struct usb_device_descriptor),
.bDescriptorType = USB_DTYPE_DEVICE,
.bcdUSB = VERSION_BCD(2, 0, 0),
.bDeviceClass = USB_CLASS_IAD,
.bDeviceSubClass = USB_SUBCLASS_IAD,
.bDeviceProtocol = USB_PROTO_IAD,
.bMaxPacketSize0 = USB_EP0_SIZE,
.idVendor = 0x046d,
.idProduct = 0xc529,
.bcdDevice = VERSION_BCD(1, 0, 0),
.iManufacturer = UsbDevManuf,
.iProduct = UsbDevProduct,
.iSerialNumber = UsbDevSerial,
.bNumConfigurations = 1,
};
/* Device configuration descriptor */
static const struct HidConfigDescriptor hid_cfg_desc = {
.config =
{
.bLength = sizeof(struct usb_config_descriptor),
.bDescriptorType = USB_DTYPE_CONFIGURATION,
.wTotalLength = sizeof(struct HidConfigDescriptor),
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = NO_DESCRIPTOR,
.bmAttributes = USB_CFG_ATTR_RESERVED | USB_CFG_ATTR_SELFPOWERED,
.bMaxPower = USB_CFG_POWER_MA(100),
},
.iad_0 =
{
.hid_iad =
{
.bLength = sizeof(struct usb_iad_descriptor),
.bDescriptorType = USB_DTYPE_INTERFASEASSOC,
.bFirstInterface = 0,
.bInterfaceCount = 1,
.bFunctionClass = USB_CLASS_PER_INTERFACE,
.bFunctionSubClass = USB_SUBCLASS_NONE,
.bFunctionProtocol = USB_PROTO_NONE,
.iFunction = NO_DESCRIPTOR,
},
.hid =
{
.bLength = sizeof(struct usb_interface_descriptor),
.bDescriptorType = USB_DTYPE_INTERFACE,
.bInterfaceNumber = 0,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_HID,
.bInterfaceSubClass = USB_HID_SUBCLASS_NONBOOT,
.bInterfaceProtocol = USB_HID_PROTO_NONBOOT,
.iInterface = NO_DESCRIPTOR,
},
.hid_desc =
{
.bLength = sizeof(struct usb_hid_descriptor),
.bDescriptorType = USB_DTYPE_HID,
.bcdHID = VERSION_BCD(1, 0, 0),
.bCountryCode = USB_HID_COUNTRY_NONE,
.bNumDescriptors = 1,
.bDescriptorType0 = USB_DTYPE_HID_REPORT,
.wDescriptorLength0 = sizeof(hid_report_desc),
},
.hid_ep_in =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = HID_EP_IN,
.bmAttributes = USB_EPTYPE_INTERRUPT,
.wMaxPacketSize = HID_EP_SZ,
.bInterval = 10,
},
.hid_ep_out =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = HID_EP_OUT,
.bmAttributes = USB_EPTYPE_INTERRUPT,
.wMaxPacketSize = HID_EP_SZ,
.bInterval = 10,
},
},
};
struct HidReportMouse {
uint8_t report_id;
uint8_t btn;
int8_t x;
int8_t y;
int8_t wheel;
} __attribute__((packed));
struct HidReportKB {
uint8_t report_id;
uint8_t mods;
uint8_t reserved;
uint8_t btn[HID_KB_MAX_KEYS];
} __attribute__((packed));
struct HidReportConsumer {
uint8_t report_id;
uint16_t btn[HID_CONSUMER_MAX_KEYS];
} __attribute__((packed));
struct HidReportLED {
uint8_t report_id;
uint8_t led_state;
} __attribute__((packed));
static struct HidReport {
struct HidReportKB keyboard;
struct HidReportMouse mouse;
struct HidReportConsumer consumer;
} __attribute__((packed)) hid_report;
static void hid_init(usbd_device* dev, UsbInterface* intf);
static void hid_deinit(usbd_device* dev);
static void hid_on_wakeup(usbd_device* dev);
static void hid_on_suspend(usbd_device* dev);
static bool hid_send_report(uint8_t report_id);
static usbd_respond hid_ep_config(usbd_device* dev, uint8_t cfg);
static usbd_respond hid_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback);
static usbd_device* usb_dev;
static osSemaphoreId_t hid_semaphore = NULL;
static bool hid_connected = false;
static HidStateCallback callback;
static void* cb_ctx;
static uint8_t led_state;
bool furi_hal_hid_is_connected() {
return hid_connected;
}
uint8_t furi_hal_hid_get_led_state() {
return led_state;
}
void furi_hal_hid_set_state_callback(HidStateCallback cb, void* ctx) {
if(callback != NULL) {
if(hid_connected == true) callback(false, cb_ctx);
}
callback = cb;
cb_ctx = ctx;
if(callback != NULL) {
if(hid_connected == true) callback(true, cb_ctx);
}
}
bool furi_hal_hid_kb_press(uint16_t button) {
for(uint8_t key_nb = 0; key_nb < HID_KB_MAX_KEYS; key_nb++) {
if(hid_report.keyboard.btn[key_nb] == 0) {
hid_report.keyboard.btn[key_nb] = button & 0xFF;
break;
}
}
hid_report.keyboard.mods |= (button >> 8);
return hid_send_report(ReportIdKeyboard);
}
bool furi_hal_hid_kb_release(uint16_t button) {
for(uint8_t key_nb = 0; key_nb < HID_KB_MAX_KEYS; key_nb++) {
if(hid_report.keyboard.btn[key_nb] == (button & 0xFF)) {
hid_report.keyboard.btn[key_nb] = 0;
break;
}
}
hid_report.keyboard.mods &= ~(button >> 8);
return hid_send_report(ReportIdKeyboard);
}
bool furi_hal_hid_kb_release_all() {
for(uint8_t key_nb = 0; key_nb < HID_KB_MAX_KEYS; key_nb++) {
hid_report.keyboard.btn[key_nb] = 0;
}
hid_report.keyboard.mods = 0;
return hid_send_report(ReportIdKeyboard);
}
bool furi_hal_hid_mouse_move(int8_t dx, int8_t dy) {
hid_report.mouse.x = dx;
hid_report.mouse.y = dy;
bool state = hid_send_report(ReportIdMouse);
hid_report.mouse.x = 0;
hid_report.mouse.y = 0;
return state;
}
bool furi_hal_hid_mouse_press(uint8_t button) {
hid_report.mouse.btn |= button;
return hid_send_report(ReportIdMouse);
}
bool furi_hal_hid_mouse_release(uint8_t button) {
hid_report.mouse.btn &= ~button;
return hid_send_report(ReportIdMouse);
}
bool furi_hal_hid_mouse_scroll(int8_t delta) {
hid_report.mouse.wheel = delta;
bool state = hid_send_report(ReportIdMouse);
hid_report.mouse.wheel = 0;
return state;
}
bool furi_hal_hid_consumer_key_press(uint16_t button) {
for(uint8_t key_nb = 0; key_nb < HID_CONSUMER_MAX_KEYS; key_nb++) {
if(hid_report.consumer.btn[key_nb] == 0) {
hid_report.consumer.btn[key_nb] = button;
break;
}
}
return hid_send_report(ReportIdConsumer);
}
bool furi_hal_hid_consumer_key_release(uint16_t button) {
for(uint8_t key_nb = 0; key_nb < HID_CONSUMER_MAX_KEYS; key_nb++) {
if(hid_report.consumer.btn[key_nb] == button) {
hid_report.consumer.btn[key_nb] = 0;
break;
}
}
return hid_send_report(ReportIdConsumer);
}
UsbInterface usb_hid = {
.init = hid_init,
.deinit = hid_deinit,
.wakeup = hid_on_wakeup,
.suspend = hid_on_suspend,
.dev_descr = (struct usb_device_descriptor*)&hid_device_desc,
.str_manuf_descr = (void*)&dev_manuf_desc,
.str_prod_descr = (void*)&dev_prod_desc,
.str_serial_descr = (void*)&dev_serial_desc,
.cfg_descr = (void*)&hid_cfg_desc,
};
static void hid_init(usbd_device* dev, UsbInterface* intf) {
if(hid_semaphore == NULL) hid_semaphore = osSemaphoreNew(1, 1, NULL);
usb_dev = dev;
hid_report.keyboard.report_id = ReportIdKeyboard;
hid_report.mouse.report_id = ReportIdMouse;
hid_report.consumer.report_id = ReportIdConsumer;
usbd_reg_config(dev, hid_ep_config);
usbd_reg_control(dev, hid_control);
usbd_connect(dev, true);
}
static void hid_deinit(usbd_device* dev) {
usbd_reg_config(dev, NULL);
usbd_reg_control(dev, NULL);
}
static void hid_on_wakeup(usbd_device* dev) {
if(hid_connected == false) {
hid_connected = true;
if(callback != NULL) callback(true, cb_ctx);
}
}
static void hid_on_suspend(usbd_device* dev) {
if(hid_connected == true) {
hid_connected = false;
osSemaphoreRelease(hid_semaphore);
if(callback != NULL) callback(false, cb_ctx);
}
}
static bool hid_send_report(uint8_t report_id) {
if((hid_semaphore == NULL) || (hid_connected == false)) return false;
furi_check(osSemaphoreAcquire(hid_semaphore, osWaitForever) == osOK);
if(hid_connected == true) {
if(report_id == ReportIdKeyboard)
usbd_ep_write(usb_dev, HID_EP_IN, &hid_report.keyboard, sizeof(hid_report.keyboard));
else if(report_id == ReportIdMouse)
usbd_ep_write(usb_dev, HID_EP_IN, &hid_report.mouse, sizeof(hid_report.mouse));
else if(report_id == ReportIdConsumer)
usbd_ep_write(usb_dev, HID_EP_IN, &hid_report.consumer, sizeof(hid_report.consumer));
return true;
}
return false;
}
static void hid_txrx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) {
if(event == usbd_evt_eptx) {
osSemaphoreRelease(hid_semaphore);
} else {
struct HidReportLED leds;
usbd_ep_read(usb_dev, ep, &leds, 2);
led_state = leds.led_state;
}
}
/* Configure endpoints */
static usbd_respond hid_ep_config(usbd_device* dev, uint8_t cfg) {
switch(cfg) {
case 0:
/* deconfiguring device */
usbd_ep_deconfig(dev, HID_EP_OUT);
usbd_ep_deconfig(dev, HID_EP_IN);
usbd_reg_endpoint(dev, HID_EP_OUT, 0);
usbd_reg_endpoint(dev, HID_EP_IN, 0);
return usbd_ack;
case 1:
/* configuring device */
usbd_ep_config(dev, HID_EP_IN, USB_EPTYPE_INTERRUPT, HID_EP_SZ);
usbd_ep_config(dev, HID_EP_OUT, USB_EPTYPE_INTERRUPT, HID_EP_SZ);
usbd_reg_endpoint(dev, HID_EP_IN, hid_txrx_ep_callback);
usbd_reg_endpoint(dev, HID_EP_OUT, hid_txrx_ep_callback);
usbd_ep_write(dev, HID_EP_IN, 0, 0);
return usbd_ack;
default:
return usbd_fail;
}
}
/* Control requests handler */
static usbd_respond hid_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback) {
/* HID control requests */
if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) ==
(USB_REQ_INTERFACE | USB_REQ_CLASS) &&
req->wIndex == 0) {
switch(req->bRequest) {
case USB_HID_SETIDLE:
return usbd_ack;
case USB_HID_GETREPORT:
dev->status.data_ptr = &hid_report;
dev->status.data_count = sizeof(hid_report);
return usbd_ack;
default:
return usbd_fail;
}
}
if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) ==
(USB_REQ_INTERFACE | USB_REQ_STANDARD) &&
req->wIndex == 0 && req->bRequest == USB_STD_GET_DESCRIPTOR) {
switch(req->wValue >> 8) {
case USB_DTYPE_HID:
dev->status.data_ptr = (uint8_t*)&(hid_cfg_desc.iad_0.hid_desc);
dev->status.data_count = sizeof(hid_cfg_desc.iad_0.hid_desc);
return usbd_ack;
case USB_DTYPE_HID_REPORT:
dev->status.data_ptr = (uint8_t*)hid_report_desc;
dev->status.data_count = sizeof(hid_report_desc);
return usbd_ack;
default:
return usbd_fail;
}
}
return usbd_fail;
}
@@ -0,0 +1,13 @@
#pragma once
#include "usb.h"
#define USB_EP0_SIZE 8
/* String descriptors */
enum UsbDevDescStr {
UsbDevLang = 0,
UsbDevManuf = 1,
UsbDevProduct = 2,
UsbDevSerial = 3,
};
@@ -0,0 +1,300 @@
#include "furi_hal_version.h"
#include "furi_hal_usb_i.h"
#include "furi_hal_usb_hid_u2f.h"
#include "furi_hal_usb.h"
#include <furi.h>
#include "usb.h"
#include "usb_hid.h"
#define HID_PAGE_FIDO 0xF1D0
#define HID_FIDO_U2F 0x01
#define HID_FIDO_INPUT 0x20
#define HID_FIDO_OUTPUT 0x21
#define HID_EP_IN 0x81
#define HID_EP_OUT 0x01
struct HidIadDescriptor {
struct usb_iad_descriptor hid_iad;
struct usb_interface_descriptor hid;
struct usb_hid_descriptor hid_desc;
struct usb_endpoint_descriptor hid_ep_in;
struct usb_endpoint_descriptor hid_ep_out;
};
struct HidConfigDescriptor {
struct usb_config_descriptor config;
struct HidIadDescriptor iad_0;
} __attribute__((packed));
/* HID report: FIDO U2F */
static const uint8_t hid_u2f_report_desc[] = {
HID_RI_USAGE_PAGE(16, HID_PAGE_FIDO),
HID_USAGE(HID_FIDO_U2F),
HID_COLLECTION(HID_APPLICATION_COLLECTION),
HID_USAGE(HID_FIDO_INPUT),
HID_LOGICAL_MINIMUM(0x00),
HID_LOGICAL_MAXIMUM(0xFF),
HID_REPORT_SIZE(8),
HID_REPORT_COUNT(HID_U2F_PACKET_LEN),
HID_INPUT(HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
HID_USAGE(HID_FIDO_OUTPUT),
HID_LOGICAL_MINIMUM(0x00),
HID_LOGICAL_MAXIMUM(0xFF),
HID_REPORT_SIZE(8),
HID_REPORT_COUNT(HID_U2F_PACKET_LEN),
HID_OUTPUT(HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
HID_END_COLLECTION,
};
static const struct usb_string_descriptor dev_manuf_desc = USB_STRING_DESC("Flipper Devices Inc.");
static const struct usb_string_descriptor dev_prod_desc = USB_STRING_DESC("U2F Token test");
static const struct usb_string_descriptor dev_serial_desc = USB_STRING_DESC("TODO: serial");
/* Device descriptor */
static const struct usb_device_descriptor hid_u2f_device_desc = {
.bLength = sizeof(struct usb_device_descriptor),
.bDescriptorType = USB_DTYPE_DEVICE,
.bcdUSB = VERSION_BCD(2, 0, 0),
.bDeviceClass = USB_CLASS_IAD,
.bDeviceSubClass = USB_SUBCLASS_IAD,
.bDeviceProtocol = USB_PROTO_IAD,
.bMaxPacketSize0 = USB_EP0_SIZE,
.idVendor = 0x0483,
.idProduct = 0x5741,
.bcdDevice = VERSION_BCD(1, 0, 0),
.iManufacturer = UsbDevManuf,
.iProduct = UsbDevProduct,
.iSerialNumber = UsbDevSerial,
.bNumConfigurations = 1,
};
/* Device configuration descriptor */
static const struct HidConfigDescriptor hid_u2f_cfg_desc = {
.config =
{
.bLength = sizeof(struct usb_config_descriptor),
.bDescriptorType = USB_DTYPE_CONFIGURATION,
.wTotalLength = sizeof(struct HidConfigDescriptor),
.bNumInterfaces = 1,
.bConfigurationValue = 1,
.iConfiguration = NO_DESCRIPTOR,
.bmAttributes = USB_CFG_ATTR_RESERVED | USB_CFG_ATTR_SELFPOWERED,
.bMaxPower = USB_CFG_POWER_MA(100),
},
.iad_0 =
{
.hid_iad =
{
.bLength = sizeof(struct usb_iad_descriptor),
.bDescriptorType = USB_DTYPE_INTERFASEASSOC,
.bFirstInterface = 0,
.bInterfaceCount = 1,
.bFunctionClass = USB_CLASS_PER_INTERFACE,
.bFunctionSubClass = USB_SUBCLASS_NONE,
.bFunctionProtocol = USB_PROTO_NONE,
.iFunction = NO_DESCRIPTOR,
},
.hid =
{
.bLength = sizeof(struct usb_interface_descriptor),
.bDescriptorType = USB_DTYPE_INTERFACE,
.bInterfaceNumber = 0,
.bAlternateSetting = 0,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_HID,
.bInterfaceSubClass = USB_HID_SUBCLASS_NONBOOT,
.bInterfaceProtocol = USB_HID_PROTO_NONBOOT,
.iInterface = NO_DESCRIPTOR,
},
.hid_desc =
{
.bLength = sizeof(struct usb_hid_descriptor),
.bDescriptorType = USB_DTYPE_HID,
.bcdHID = VERSION_BCD(1, 0, 0),
.bCountryCode = USB_HID_COUNTRY_NONE,
.bNumDescriptors = 1,
.bDescriptorType0 = USB_DTYPE_HID_REPORT,
.wDescriptorLength0 = sizeof(hid_u2f_report_desc),
},
.hid_ep_in =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = HID_EP_IN,
.bmAttributes = USB_EPTYPE_INTERRUPT,
.wMaxPacketSize = HID_U2F_PACKET_LEN,
.bInterval = 5,
},
.hid_ep_out =
{
.bLength = sizeof(struct usb_endpoint_descriptor),
.bDescriptorType = USB_DTYPE_ENDPOINT,
.bEndpointAddress = HID_EP_OUT,
.bmAttributes = USB_EPTYPE_INTERRUPT,
.wMaxPacketSize = HID_U2F_PACKET_LEN,
.bInterval = 5,
},
},
};
static void hid_u2f_init(usbd_device* dev, UsbInterface* intf);
static void hid_u2f_deinit(usbd_device* dev);
static void hid_u2f_on_wakeup(usbd_device* dev);
static void hid_u2f_on_suspend(usbd_device* dev);
//static bool hid_u2f_send_report(uint8_t report_id);
static usbd_respond hid_u2f_ep_config(usbd_device* dev, uint8_t cfg);
static usbd_respond
hid_u2f_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback);
static usbd_device* usb_dev;
static osSemaphoreId_t hid_u2f_semaphore = NULL;
static bool hid_u2f_connected = false;
static HidU2fCallback callback;
static void* cb_ctx;
bool furi_hal_hid_u2f_is_connected() {
return hid_u2f_connected;
}
void furi_hal_hid_u2f_set_callback(HidU2fCallback cb, void* ctx) {
if(callback != NULL) {
if(hid_u2f_connected == true) callback(HidU2fDisconnected, cb_ctx);
}
callback = cb;
cb_ctx = ctx;
if(callback != NULL) {
if(hid_u2f_connected == true) callback(HidU2fConnected, cb_ctx);
}
}
UsbInterface usb_hid_u2f = {
.init = hid_u2f_init,
.deinit = hid_u2f_deinit,
.wakeup = hid_u2f_on_wakeup,
.suspend = hid_u2f_on_suspend,
.dev_descr = (struct usb_device_descriptor*)&hid_u2f_device_desc,
.str_manuf_descr = (void*)&dev_manuf_desc,
.str_prod_descr = (void*)&dev_prod_desc,
.str_serial_descr = (void*)&dev_serial_desc,
.cfg_descr = (void*)&hid_u2f_cfg_desc,
};
static void hid_u2f_init(usbd_device* dev, UsbInterface* intf) {
if(hid_u2f_semaphore == NULL) hid_u2f_semaphore = osSemaphoreNew(1, 1, NULL);
usb_dev = dev;
usbd_reg_config(dev, hid_u2f_ep_config);
usbd_reg_control(dev, hid_u2f_control);
usbd_connect(dev, true);
}
static void hid_u2f_deinit(usbd_device* dev) {
usbd_reg_config(dev, NULL);
usbd_reg_control(dev, NULL);
}
static void hid_u2f_on_wakeup(usbd_device* dev) {
hid_u2f_connected = true;
if(callback != NULL) callback(HidU2fConnected, cb_ctx);
}
static void hid_u2f_on_suspend(usbd_device* dev) {
if(hid_u2f_connected == true) {
hid_u2f_connected = false;
osSemaphoreRelease(hid_u2f_semaphore);
if(callback != NULL) callback(HidU2fDisconnected, cb_ctx);
}
}
void furi_hal_hid_u2f_send_response(uint8_t* data, uint8_t len) {
if((hid_u2f_semaphore == NULL) || (hid_u2f_connected == false)) return;
furi_check(osSemaphoreAcquire(hid_u2f_semaphore, osWaitForever) == osOK);
if(hid_u2f_connected == true) {
usbd_ep_write(usb_dev, HID_EP_OUT, data, len);
}
}
uint32_t furi_hal_hid_u2f_get_request(uint8_t* data) {
int32_t len = usbd_ep_read(usb_dev, HID_EP_IN, data, HID_U2F_PACKET_LEN);
return ((len < 0) ? 0 : len);
}
static void hid_u2f_rx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) {
if(callback != NULL) callback(HidU2fRequest, cb_ctx);
}
static void hid_u2f_tx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) {
osSemaphoreRelease(hid_u2f_semaphore);
}
static void hid_u2f_txrx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) {
if(event == usbd_evt_eptx) {
hid_u2f_tx_ep_callback(dev, event, ep);
} else {
hid_u2f_rx_ep_callback(dev, event, ep);
}
}
/* Configure endpoints */
static usbd_respond hid_u2f_ep_config(usbd_device* dev, uint8_t cfg) {
switch(cfg) {
case 0:
/* deconfiguring device */
usbd_ep_deconfig(dev, HID_EP_OUT);
usbd_ep_deconfig(dev, HID_EP_IN);
usbd_reg_endpoint(dev, HID_EP_OUT, 0);
usbd_reg_endpoint(dev, HID_EP_IN, 0);
return usbd_ack;
case 1:
/* configuring device */
usbd_ep_config(dev, HID_EP_IN, USB_EPTYPE_INTERRUPT, HID_U2F_PACKET_LEN);
usbd_ep_config(dev, HID_EP_OUT, USB_EPTYPE_INTERRUPT, HID_U2F_PACKET_LEN);
usbd_reg_endpoint(dev, HID_EP_IN, hid_u2f_txrx_ep_callback);
usbd_reg_endpoint(dev, HID_EP_OUT, hid_u2f_txrx_ep_callback);
usbd_ep_write(dev, HID_U2F_PACKET_LEN, 0, 0);
return usbd_ack;
default:
return usbd_fail;
}
}
/* Control requests handler */
static usbd_respond
hid_u2f_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback) {
/* HID control requests */
if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) ==
(USB_REQ_INTERFACE | USB_REQ_CLASS) &&
req->wIndex == 0) {
switch(req->bRequest) {
case USB_HID_SETIDLE:
return usbd_ack;
default:
return usbd_fail;
}
}
if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) ==
(USB_REQ_INTERFACE | USB_REQ_STANDARD) &&
req->wIndex == 0 && req->bRequest == USB_STD_GET_DESCRIPTOR) {
switch(req->wValue >> 8) {
case USB_DTYPE_HID:
dev->status.data_ptr = (uint8_t*)&(hid_u2f_cfg_desc.iad_0.hid_desc);
dev->status.data_count = sizeof(hid_u2f_cfg_desc.iad_0.hid_desc);
return usbd_ack;
case USB_DTYPE_HID_REPORT:
dev->status.data_ptr = (uint8_t*)hid_u2f_report_desc;
dev->status.data_count = sizeof(hid_u2f_report_desc);
return usbd_ack;
default:
return usbd_fail;
}
}
return usbd_fail;
}
+295
View File
@@ -0,0 +1,295 @@
#include <furi_hal_usb_cdc_i.h>
#include <furi_hal_console.h>
#include <furi.h>
#include <stream_buffer.h>
#define TAG "FuriHalVcp"
#define USB_CDC_PKT_LEN CDC_DATA_SZ
#define VCP_RX_BUF_SIZE (USB_CDC_PKT_LEN * 3)
#define VCP_TX_BUF_SIZE (USB_CDC_PKT_LEN * 3)
#define VCP_IF_NUM 0
typedef enum {
VcpEvtReserved = (1 << 0), // Reserved for StreamBuffer internal event
VcpEvtEnable = (1 << 1),
VcpEvtDisable = (1 << 2),
VcpEvtConnect = (1 << 3),
VcpEvtDisconnect = (1 << 4),
VcpEvtStreamRx = (1 << 5),
VcpEvtRx = (1 << 6),
VcpEvtStreamTx = (1 << 7),
VcpEvtTx = (1 << 8),
} WorkerEvtFlags;
#define VCP_THREAD_FLAG_ALL \
(VcpEvtEnable | VcpEvtDisable | VcpEvtConnect | VcpEvtDisconnect | VcpEvtRx | VcpEvtTx | \
VcpEvtStreamRx | VcpEvtStreamTx)
typedef struct {
FuriThread* thread;
StreamBufferHandle_t tx_stream;
StreamBufferHandle_t rx_stream;
volatile bool connected;
uint8_t data_buffer[USB_CDC_PKT_LEN];
} FuriHalVcp;
static int32_t vcp_worker(void* context);
static void vcp_on_cdc_tx_complete(void* context);
static void vcp_on_cdc_rx(void* context);
static void vcp_state_callback(void* context, uint8_t state);
static void vcp_on_cdc_control_line(void* context, uint8_t state);
static CdcCallbacks cdc_cb = {
vcp_on_cdc_tx_complete,
vcp_on_cdc_rx,
vcp_state_callback,
vcp_on_cdc_control_line,
NULL,
};
static FuriHalVcp* vcp = NULL;
static const uint8_t ascii_soh = 0x01;
static const uint8_t ascii_eot = 0x04;
void furi_hal_vcp_init() {
vcp = furi_alloc(sizeof(FuriHalVcp));
vcp->connected = false;
vcp->tx_stream = xStreamBufferCreate(VCP_TX_BUF_SIZE, 1);
vcp->rx_stream = xStreamBufferCreate(VCP_RX_BUF_SIZE, 1);
vcp->thread = furi_thread_alloc();
furi_thread_set_name(vcp->thread, "VcpWorker");
furi_thread_set_stack_size(vcp->thread, 1024);
furi_thread_set_callback(vcp->thread, vcp_worker);
furi_thread_start(vcp->thread);
FURI_LOG_I(TAG, "Init OK");
}
static int32_t vcp_worker(void* context) {
bool enabled = true;
bool tx_idle = false;
size_t missed_rx = 0;
furi_hal_cdc_set_callbacks(VCP_IF_NUM, &cdc_cb, NULL);
while(1) {
uint32_t flags = osThreadFlagsWait(VCP_THREAD_FLAG_ALL, osFlagsWaitAny, osWaitForever);
furi_assert((flags & osFlagsError) == 0);
// VCP enabled
if((flags & VcpEvtEnable) && !enabled) {
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "Enable");
#endif
flags |= VcpEvtTx;
furi_hal_cdc_set_callbacks(VCP_IF_NUM, &cdc_cb, NULL);
enabled = true;
furi_hal_cdc_receive(VCP_IF_NUM, vcp->data_buffer, USB_CDC_PKT_LEN); // flush Rx buffer
if(furi_hal_cdc_get_ctrl_line_state(VCP_IF_NUM) & (1 << 0)) {
vcp->connected = true;
xStreamBufferSend(vcp->rx_stream, &ascii_soh, 1, osWaitForever);
}
}
// VCP disabled
if((flags & VcpEvtDisable) && enabled) {
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "Disable");
#endif
enabled = false;
vcp->connected = false;
xStreamBufferReceive(vcp->tx_stream, vcp->data_buffer, USB_CDC_PKT_LEN, 0);
xStreamBufferSend(vcp->rx_stream, &ascii_eot, 1, osWaitForever);
}
// VCP session opened
if((flags & VcpEvtConnect) && enabled) {
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "Connect");
#endif
if(vcp->connected == false) {
vcp->connected = true;
xStreamBufferSend(vcp->rx_stream, &ascii_soh, 1, osWaitForever);
}
}
// VCP session closed
if((flags & VcpEvtDisconnect) && enabled) {
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "Disconnect");
#endif
if(vcp->connected == true) {
vcp->connected = false;
xStreamBufferReceive(vcp->tx_stream, vcp->data_buffer, USB_CDC_PKT_LEN, 0);
xStreamBufferSend(vcp->rx_stream, &ascii_eot, 1, osWaitForever);
}
}
// Rx buffer was read, maybe there is enough space for new data?
if((flags & VcpEvtStreamRx) && enabled && missed_rx > 0) {
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "StreamRx");
#endif
if(xStreamBufferSpacesAvailable(vcp->rx_stream) >= USB_CDC_PKT_LEN) {
flags |= VcpEvtRx;
missed_rx--;
}
}
// New data received
if((flags & VcpEvtRx)) {
if(xStreamBufferSpacesAvailable(vcp->rx_stream) >= USB_CDC_PKT_LEN) {
int32_t len = furi_hal_cdc_receive(VCP_IF_NUM, vcp->data_buffer, USB_CDC_PKT_LEN);
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "Rx %d", len);
#endif
if(len > 0) {
furi_check(
xStreamBufferSend(vcp->rx_stream, vcp->data_buffer, len, osWaitForever) ==
len);
}
} else {
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "Rx missed");
#endif
missed_rx++;
}
}
// New data in Tx buffer
if((flags & VcpEvtStreamTx) && enabled) {
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "StreamTx");
#endif
if(tx_idle) {
flags |= VcpEvtTx;
}
}
// CDC write transfer done
if((flags & VcpEvtTx) && enabled) {
size_t len =
xStreamBufferReceive(vcp->tx_stream, vcp->data_buffer, USB_CDC_PKT_LEN, 0);
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "Tx %d", len);
#endif
if(len > 0) { // Some data left in Tx buffer. Sending it now
tx_idle = false;
furi_hal_cdc_send(VCP_IF_NUM, vcp->data_buffer, len);
} else { // There is nothing to send. Set flag to start next transfer instantly
tx_idle = true;
}
}
}
return 0;
}
void furi_hal_vcp_enable() {
osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtEnable);
}
void furi_hal_vcp_disable() {
osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtDisable);
}
size_t furi_hal_vcp_rx_with_timeout(uint8_t* buffer, size_t size, uint32_t timeout) {
furi_assert(vcp);
furi_assert(buffer);
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "rx %u start", size);
#endif
size_t rx_cnt = 0;
while(size > 0) {
size_t batch_size = size;
if(batch_size > VCP_RX_BUF_SIZE) batch_size = VCP_RX_BUF_SIZE;
size_t len = xStreamBufferReceive(vcp->rx_stream, buffer, batch_size, timeout);
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "%u ", batch_size);
#endif
if(len == 0) break;
osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtStreamRx);
size -= len;
buffer += len;
rx_cnt += len;
}
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "rx %u end", size);
#endif
return rx_cnt;
}
size_t furi_hal_vcp_rx(uint8_t* buffer, size_t size) {
furi_assert(vcp);
return furi_hal_vcp_rx_with_timeout(buffer, size, osWaitForever);
}
void furi_hal_vcp_tx(const uint8_t* buffer, size_t size) {
furi_assert(vcp);
furi_assert(buffer);
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "tx %u start", size);
#endif
while(size > 0 && vcp->connected) {
size_t batch_size = size;
if(batch_size > USB_CDC_PKT_LEN) batch_size = USB_CDC_PKT_LEN;
xStreamBufferSend(vcp->tx_stream, buffer, batch_size, osWaitForever);
osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtStreamTx);
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "%u ", batch_size);
#endif
size -= batch_size;
buffer += batch_size;
}
#ifdef FURI_HAL_USB_VCP_DEBUG
FURI_LOG_D(TAG, "tx %u end", size);
#endif
}
static void vcp_state_callback(void* context, uint8_t state) {
if(state == 0) {
osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtDisconnect);
}
}
static void vcp_on_cdc_control_line(void* context, uint8_t state) {
// bit 0: DTR state, bit 1: RTS state
bool dtr = state & (1 << 0);
if(dtr == true) {
osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtConnect);
} else {
osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtDisconnect);
}
}
static void vcp_on_cdc_rx(void* context) {
uint32_t ret = osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtRx);
furi_check((ret & osFlagsError) == 0);
}
static void vcp_on_cdc_tx_complete(void* context) {
osThreadFlagsSet(furi_thread_get_thread_id(vcp->thread), VcpEvtTx);
}
bool furi_hal_vcp_is_connected(void) {
furi_assert(vcp);
return vcp->connected;
}
@@ -0,0 +1,298 @@
#include <furi_hal_version.h>
#include <furi_hal_rtc.h>
#include <furi.h>
#include <stm32wbxx.h>
#include <stm32wbxx_ll_rtc.h>
#include <stdio.h>
#include "ble.h"
#define TAG "FuriHalVersion"
#define FURI_HAL_VERSION_OTP_HEADER_MAGIC 0xBABE
#define FURI_HAL_VERSION_OTP_ADDRESS OTP_AREA_BASE
/** OTP V0 Structure: prototypes and early EVT */
typedef struct {
uint8_t board_version;
uint8_t board_target;
uint8_t board_body;
uint8_t board_connect;
uint32_t header_timestamp;
char name[FURI_HAL_VERSION_NAME_LENGTH];
} FuriHalVersionOTPv0;
/** OTP V1 Structure: late EVT, DVT */
typedef struct {
/* First 64 bits: header */
uint16_t header_magic;
uint8_t header_version;
uint8_t header_reserved;
uint32_t header_timestamp;
/* Second 64 bits: board info */
uint8_t board_version; /** Board version */
uint8_t board_target; /** Board target firmware */
uint8_t board_body; /** Board body */
uint8_t board_connect; /** Board interconnect */
uint8_t board_color; /** Board color */
uint8_t board_region; /** Board region */
uint16_t board_reserved; /** Reserved for future use, 0x0000 */
/* Third 64 bits: Unique Device Name */
char name[FURI_HAL_VERSION_NAME_LENGTH]; /** Unique Device Name */
} FuriHalVersionOTPv1;
/** OTP V2 Structure: DVT2, PVT, Production */
typedef struct {
/* Early First 64 bits: header */
uint16_t header_magic;
uint8_t header_version;
uint8_t header_reserved;
uint32_t header_timestamp;
/* Early Second 64 bits: board info */
uint8_t board_version; /** Board version */
uint8_t board_target; /** Board target firmware */
uint8_t board_body; /** Board body */
uint8_t board_connect; /** Board interconnect */
uint8_t board_display; /** Board display */
uint8_t board_reserved2_0; /** Reserved for future use, 0x00 */
uint16_t board_reserved2_1; /** Reserved for future use, 0x0000 */
/* Late Third 64 bits: device info */
uint8_t board_color; /** Board color */
uint8_t board_region; /** Board region */
uint16_t board_reserved3_0; /** Reserved for future use, 0x0000 */
uint32_t board_reserved3_1; /** Reserved for future use, 0x00000000 */
/* Late Fourth 64 bits: Unique Device Name */
char name[FURI_HAL_VERSION_NAME_LENGTH]; /** Unique Device Name */
} FuriHalVersionOTPv2;
/** Represenation Model: */
typedef struct {
uint32_t timestamp;
uint8_t board_version; /** Board version */
uint8_t board_target; /** Board target firmware */
uint8_t board_body; /** Board body */
uint8_t board_connect; /** Board interconnect */
uint8_t board_color; /** Board color */
uint8_t board_region; /** Board region */
uint8_t board_display; /** Board display */
char name[FURI_HAL_VERSION_ARRAY_NAME_LENGTH]; /** \0 terminated name */
char device_name[FURI_HAL_VERSION_DEVICE_NAME_LENGTH]; /** device name for special needs */
uint8_t ble_mac[6];
} FuriHalVersion;
static FuriHalVersion furi_hal_version = {0};
static void furi_hal_version_set_name(const char* name) {
if(name != NULL) {
strlcpy(furi_hal_version.name, name, FURI_HAL_VERSION_ARRAY_NAME_LENGTH);
snprintf(
furi_hal_version.device_name,
FURI_HAL_VERSION_DEVICE_NAME_LENGTH,
"xFlipper %s",
furi_hal_version.name);
} else {
snprintf(furi_hal_version.device_name, FURI_HAL_VERSION_DEVICE_NAME_LENGTH, "xFlipper");
}
furi_hal_version.device_name[0] = AD_TYPE_COMPLETE_LOCAL_NAME;
// BLE Mac address
uint32_t udn = LL_FLASH_GetUDN();
uint32_t company_id = LL_FLASH_GetSTCompanyID();
uint32_t device_id = LL_FLASH_GetDeviceID();
furi_hal_version.ble_mac[0] = (uint8_t)(udn & 0x000000FF);
furi_hal_version.ble_mac[1] = (uint8_t)((udn & 0x0000FF00) >> 8);
furi_hal_version.ble_mac[2] = (uint8_t)((udn & 0x00FF0000) >> 16);
furi_hal_version.ble_mac[3] = (uint8_t)device_id;
furi_hal_version.ble_mac[4] = (uint8_t)(company_id & 0x000000FF);
furi_hal_version.ble_mac[5] = (uint8_t)((company_id & 0x0000FF00) >> 8);
}
static void furi_hal_version_load_otp_default() {
furi_hal_version_set_name(NULL);
}
static void furi_hal_version_load_otp_v0() {
const FuriHalVersionOTPv0* otp = (FuriHalVersionOTPv0*)FURI_HAL_VERSION_OTP_ADDRESS;
furi_hal_version.timestamp = otp->header_timestamp;
furi_hal_version.board_version = otp->board_version;
furi_hal_version.board_target = otp->board_target;
furi_hal_version.board_body = otp->board_body;
furi_hal_version.board_connect = otp->board_connect;
furi_hal_version_set_name(otp->name);
}
static void furi_hal_version_load_otp_v1() {
const FuriHalVersionOTPv1* otp = (FuriHalVersionOTPv1*)FURI_HAL_VERSION_OTP_ADDRESS;
furi_hal_version.timestamp = otp->header_timestamp;
furi_hal_version.board_version = otp->board_version;
furi_hal_version.board_target = otp->board_target;
furi_hal_version.board_body = otp->board_body;
furi_hal_version.board_connect = otp->board_connect;
furi_hal_version.board_color = otp->board_color;
furi_hal_version.board_region = otp->board_region;
furi_hal_version_set_name(otp->name);
}
static void furi_hal_version_load_otp_v2() {
const FuriHalVersionOTPv2* otp = (FuriHalVersionOTPv2*)FURI_HAL_VERSION_OTP_ADDRESS;
// 1st block, programmed afer baking
furi_hal_version.timestamp = otp->header_timestamp;
// 2nd block, programmed afer baking
furi_hal_version.board_version = otp->board_version;
furi_hal_version.board_target = otp->board_target;
furi_hal_version.board_body = otp->board_body;
furi_hal_version.board_connect = otp->board_connect;
furi_hal_version.board_display = otp->board_display;
// 3rd and 4th blocks, programmed on FATP stage
if(otp->board_color != 0xFF) {
furi_hal_version.board_color = otp->board_color;
furi_hal_version.board_region = otp->board_region;
furi_hal_version_set_name(otp->name);
} else {
furi_hal_version.board_color = 0;
furi_hal_version.board_region = 0;
furi_hal_version_set_name(NULL);
}
}
void furi_hal_version_init() {
switch(furi_hal_version_get_otp_version()) {
case FuriHalVersionOtpVersionUnknown:
furi_hal_version_load_otp_default();
break;
case FuriHalVersionOtpVersionEmpty:
furi_hal_version_load_otp_default();
break;
case FuriHalVersionOtpVersion0:
furi_hal_version_load_otp_v0();
break;
case FuriHalVersionOtpVersion1:
furi_hal_version_load_otp_v1();
break;
case FuriHalVersionOtpVersion2:
furi_hal_version_load_otp_v2();
break;
default:
furi_crash(NULL);
}
furi_hal_rtc_set_register(FuriHalRtcRegisterSystemVersion, (uint32_t)version_get());
FURI_LOG_I(TAG, "Init OK");
}
bool furi_hal_version_do_i_belong_here() {
return furi_hal_version_get_hw_target() == 7;
}
const char* furi_hal_version_get_model_name() {
return "Flipper Zero";
}
const FuriHalVersionOtpVersion furi_hal_version_get_otp_version() {
if(*(uint64_t*)FURI_HAL_VERSION_OTP_ADDRESS == 0xFFFFFFFF) {
return FuriHalVersionOtpVersionEmpty;
} else {
if(((FuriHalVersionOTPv1*)FURI_HAL_VERSION_OTP_ADDRESS)->header_magic ==
FURI_HAL_VERSION_OTP_HEADER_MAGIC) {
// Version 1+
uint8_t version = ((FuriHalVersionOTPv1*)FURI_HAL_VERSION_OTP_ADDRESS)->header_version;
if(version >= FuriHalVersionOtpVersion1 && version <= FuriHalVersionOtpVersion2) {
return version;
} else {
return FuriHalVersionOtpVersionUnknown;
}
} else if(((FuriHalVersionOTPv0*)FURI_HAL_VERSION_OTP_ADDRESS)->board_version <= 10) {
// Version 0
return FuriHalVersionOtpVersion0;
} else {
// Version Unknown
return FuriHalVersionOtpVersionUnknown;
}
}
}
const uint8_t furi_hal_version_get_hw_version() {
return furi_hal_version.board_version;
}
const uint8_t furi_hal_version_get_hw_target() {
return furi_hal_version.board_target;
}
const uint8_t furi_hal_version_get_hw_body() {
return furi_hal_version.board_body;
}
const FuriHalVersionColor furi_hal_version_get_hw_color() {
return furi_hal_version.board_color;
}
const uint8_t furi_hal_version_get_hw_connect() {
return furi_hal_version.board_connect;
}
const FuriHalVersionRegion furi_hal_version_get_hw_region() {
return furi_hal_version.board_region;
}
const FuriHalVersionDisplay furi_hal_version_get_hw_display() {
return furi_hal_version.board_display;
}
const uint32_t furi_hal_version_get_hw_timestamp() {
return furi_hal_version.timestamp;
}
const char* furi_hal_version_get_name_ptr() {
return *furi_hal_version.name == 0x00 ? NULL : furi_hal_version.name;
}
const char* furi_hal_version_get_device_name_ptr() {
return furi_hal_version.device_name + 1;
}
const char* furi_hal_version_get_ble_local_device_name_ptr() {
return furi_hal_version.device_name;
}
const uint8_t* furi_hal_version_get_ble_mac() {
return furi_hal_version.ble_mac;
}
const struct Version* furi_hal_version_get_firmware_version(void) {
return version_get();
}
const struct Version* furi_hal_version_get_bootloader_version(void) {
#ifdef NO_BOOTLOADER
return 0;
#else
/* Backup register which points to structure in flash memory */
return (const struct Version*)furi_hal_rtc_get_register(FuriHalRtcRegisterBootVersion);
#endif
}
size_t furi_hal_version_uid_size() {
return 64 / 8;
}
const uint8_t* furi_hal_version_uid() {
return (const uint8_t*)UID64_BASE;
}
@@ -0,0 +1,14 @@
#include <furi_hal_vibro.h>
#include <furi_hal_gpio.h>
#define TAG "FuriHalVibro"
void furi_hal_vibro_init() {
hal_gpio_init(&vibro_gpio, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow);
hal_gpio_write(&vibro_gpio, false);
FURI_LOG_I(TAG, "Init OK");
}
void furi_hal_vibro_on(bool value) {
hal_gpio_write(&vibro_gpio, value);
}