Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save skleeschulte/f33f9773fa3eb29e28229693ed824d0e to your computer and use it in GitHub Desktop.

Select an option

Save skleeschulte/f33f9773fa3eb29e28229693ed824d0e to your computer and use it in GitHub Desktop.
Toggle Shelly AP depending on WiFi client connection status
const ENABLE_AP_AFTER_MINS = 3;
let enableApTimer = null;
function setApStatusCb(res, errCode, errMsg, enabled) {
if (errCode) print((enabled ? 'Enabling' : 'Disabling') + ' AP with WiFi.SetConfig failed:', errCode, errMsg);
}
function setApStatus(enabled) {
Shelly.call('WiFi.SetConfig', { config: { ap: { enable: enabled } } }, setApStatusCb, enabled);
}
function enableApTimerCb() {
enableApTimer = null;
print('Enabling AP');
setApStatus(true);
}
function handleWifiStatus(wifiConnected) {
if (wifiConnected) {
if (enableApTimer) {
Timer.clear(enableApTimer);
enableApTimer = null;
}
print('WiFi connected, disabling AP');
setApStatus(false);
} else if (!enableApTimer) {
print('WiFi disconnected, enabling AP in ' + ENABLE_AP_AFTER_MINS + ' minute(s)');
enableApTimer = Timer.set(ENABLE_AP_AFTER_MINS * 60 * 1000, false, enableApTimerCb);
}
}
function handleEvent(event) {
if (!event || !event.info || event.component !== 'wifi') return;
if (event.info.event === 'sta_ip_acquired') {
handleWifiStatus(true);
} else if (event.info.event === 'sta_disconnected') {
handleWifiStatus(false);
}
}
Shelly.addEventHandler(handleEvent);
// initially query current wifi state manually once
function wifiStatusCb(res, errCode, errMsg) {
if (errCode) print('WiFi.GetStatus failed:', errCode, errMsg);
handleWifiStatus(res && res.status === 'got ip' && !errCode);
}
Shelly.call('WiFi.GetStatus', {}, wifiStatusCb);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment