Move to a struct with args in channel_set_cb()

This commit is contained in:
Pim van Pelt
2018-11-01 20:57:24 +01:00
parent 8eb6bcb112
commit 75eccd0447

View File

@ -144,26 +144,37 @@ uint8_t channel_idx_by_gpio(int gpio) {
return GPIO_INVALID; return GPIO_INVALID;
} }
// Slightly tricky callback (installed on a timer by channel_set and struct channel_set_cb_args {
// channel_toggle carries information in the arg pointer -- top 16 bits are uint8_t idx;
// the channel idx, LSB is boolean value to set the channel to. bool value;
};
static void channel_set_cb(void *arg) { static void channel_set_cb(void *arg) {
uint32_t input=(uint32_t) arg; struct channel_set_cb_args *cb_args = (struct channel_set_cb_args *)arg;
int idx = input>>16; if (!arg) {
int value = input & 0x1; LOG(LL_ERROR, ("Callback arg is NULL"));
LOG(LL_INFO, ("Channel callback for channel %d value %d", idx, value)); return;
channel_set(idx, (bool)value); }
LOG(LL_INFO, ("Channel callback for channel %d value %d", cb_args->idx, cb_args->value));
channel_set(cb_args->idx, cb_args->value);
free(arg);
} }
void channel_set_duration(int idx, bool state, uint16_t seconds) { void channel_set_duration(int idx, bool state, uint16_t seconds) {
uint32_t val; struct channel_set_cb_args *cb_args = calloc(1, sizeof(struct channel_set_cb_args));
if (!cb_args) {
LOG(LL_ERROR, ("Could not calloc() the callback args struct, aborting"));
return;
}
channel_set(idx, state); channel_set(idx, state);
// Pass an argument to the channel_set_cb callback, top 16 bits is channel, // Set a timer to call back with the new intended state on the channel.
// bottom bit is what to set it to cb_args->value = !state;
val = idx<<16+(!state); cb_args->idx = idx;
LOG(LL_INFO, ("Setting timer for %d seconds on channel %d with future value %d", seconds, idx, !state)); LOG(LL_INFO, ("Setting timer for %d seconds on channel %d with future value %d", seconds, cb_args->idx, cb_args->value));
mgos_set_timer (1000 * seconds, false /* oneshot */, channel_set_cb, (void *)val); mgos_set_timer (1000 * seconds, false /* oneshot */, channel_set_cb, cb_args);
} }
void channel_set(int idx, bool state) { void channel_set(int idx, bool state) {