@@ -27,6 +27,7 @@ extern "C" {
27
27
#include " pinmap_impl.h"
28
28
#include " gpio_hal.h"
29
29
#include " check.h"
30
+ #include " scope_guard.h"
30
31
31
32
#if HAL_PLATFORM_IO_EXTENSION && MODULE_FUNCTION != MOD_FUNC_BOOTLOADER
32
33
#if HAL_PLATFORM_MCP23S17
@@ -36,6 +37,7 @@ using namespace particle;
36
37
#endif
37
38
38
39
extern uintptr_t link_ram_interrupt_vectors_location[];
40
+ static uint32_t hal_interrupts_handler_backup[MAX_VECTOR_TABLE_NUM] = {};
39
41
40
42
namespace {
41
43
@@ -258,23 +260,35 @@ int hal_interrupt_set_direct_handler(IRQn_Type irqn, hal_interrupt_direct_handle
258
260
}
259
261
260
262
int32_t state = HAL_disable_irq ();
261
- volatile uint32_t * isrs = (volatile uint32_t *)&link_ram_interrupt_vectors_location;
263
+
264
+ SCOPE_GUARD ({
265
+ HAL_enable_irq (state);
266
+ });
262
267
263
268
if (handler == nullptr && (flags & HAL_INTERRUPT_DIRECT_FLAG_RESTORE)) {
264
- // Restore
265
- // HAL_Core_Restore_Interrupt(irqn);
269
+ // Restore old handler only if one was backed up
270
+ uint32_t old_handler = hal_interrupts_handler_backup[IRQN_TO_IDX (irqn)];
271
+ if (old_handler) {
272
+ __NVIC_SetVector (irqn, (uint32_t )old_handler);
273
+ hal_interrupts_handler_backup[IRQN_TO_IDX (irqn)] = 0 ;
274
+ }
266
275
} else {
267
- isrs[IRQN_TO_IDX (irqn)] = (uint32_t )handler;
276
+ // If there is currently a handler backup: Return error
277
+ CHECK_FALSE (hal_interrupts_handler_backup[IRQN_TO_IDX (irqn)], SYSTEM_ERROR_ALREADY_EXISTS);
278
+
279
+ // If there is a current handler, back it up
280
+ uint32_t current_handler = __NVIC_GetVector (irqn);
281
+ if (current_handler) {
282
+ hal_interrupts_handler_backup[IRQN_TO_IDX (irqn)] = current_handler;
283
+ }
268
284
}
269
285
270
286
if (flags & HAL_INTERRUPT_DIRECT_FLAG_DISABLE) {
271
287
// Disable
272
- // sd_nvic_DisableIRQ (irqn);
288
+ __NVIC_DisableIRQ (irqn);
273
289
} else if (flags & HAL_INTERRUPT_DIRECT_FLAG_ENABLE) {
274
- // sd_nvic_EnableIRQ (irqn);
290
+ __NVIC_SetVector (irqn, ( uint32_t )handler );
275
291
}
276
292
277
- HAL_enable_irq (state);
278
-
279
293
return 0 ;
280
294
}
0 commit comments