Skip to content

Commit

Permalink
Fix for Issue 808: Door/Window sensor lost data after deep sleep (#1176)
Browse files Browse the repository at this point in the history
* Fix for Issue 808

Queueing sensor state changes while device is offline and publishing them as MQTT connection is established.

* minor typo fixes

* fix network data log (#1175)

* Add watchdog for LN882 (#1179)

* Fix index page performance for LN882H (#1180)

* Use ISO time everywhere (#1181)

* Fix windows build

* Tokenizer_GetArgFloatDefault

* support dpID mult for TuyaMCU

* add self test for TuyaMCU mult

* fix incorrect naming (cosmetic change only)

* update docs

* allow auto creation of tuya dpid storage

* add requestest flag for ac dir

* Add AHT10/AHT2X/AHT30 I2C driver (#1187)

* add aht sensor driver

* disable by default

* revert comment

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* add self tests for addChangeHandler Power > 60 SetChannel 10 1234

* voltage change self tests

* Update selftest_energyMeter.c

* Update README.md

* Update README.md

* allow SM16703P driver compilation on windows (self test stub)

* per pixel led self test base

* WS2812 stub for simulator

* add reverse decoding of WS2812 pixels

* more ws self test

* add a link between simulator and per pixel drv

* adding deduplication of similar messages

* code cleanup

* Update OpenLN882H

* LN882H enable or disable sleep mode while using a PowerSave (#1186)

* add second state for PowerSave with LN882H to enable sleep mode

* delayed powersave - in sta connect callback - not tested

* Moved code for delayed application of changes to PowerSave settings

* Delaying only settings if WiFi is not connected

---------

Co-authored-by: Tester23 <[email protected]>

* better pi9xel self test, fix DDP define

* adding some comments, fixing typo

* declaring variables

* Set DNS hostname for ln882h (#1189)

* pixelanim (#1192)

* px

* it animates

* h

* bridge per pixel to LED driver

* link to led driver

* fire

* fixes

* tr

* pwm freqq (#1203)

* rename pwm freq command (#1204)

* pwm freqq

* rename

* Update OpenLN882H

* silence messages on each spi send in drv_spidma.c

* Update drv_pixelAnim.c

* hide CW bar fdr SM16703P

* pixelanim speed p1, reorganize

* add shooting star

* make LED basecolors public

* add command to change LED anim

* spoeed cmd

* Remove strftime to save space (#1210)

strftime takes a lot of space and we only use simple number printing for it. Should save 8kb

* Enable calendar events for bl602 (#1208)

* respect OBK_DISABLE_ALL_DRIVERS

* fix typo pointed by Wolfieee

* fix  buffer for pixelanim

* add pixe;lanim to prtoject

* add Motion channeltype

* self test for motion

* hass discovery test for illuminance

* try BL602 with ENABLE_EXPAND_CONSTANT	1 (#1212)

* add support for 7 segment driver HD2015E (#1214)

qqq

* second fix for channel type priority

* includfe HD2015 in prj

* Update drv_tm_gn_display_shared.c

* Update drv_tm_gn_display_shared.c

* Update drv_tm_gn_display_shared.c

* cosmetic rename

* Publish file (#1221)

* fix broken DSTime change at runtime

* publishfile

* ENABLE_LITTLEFS

* fix HASS discovery with unusually long name

* add test for HASS discovery with unusually long name

* docs

* docs

* Fix unknown method handling, lock on logging (#1224)

* extend doorsensor DSTime command

* add door sensor self test

* a bit better docs

* docs

* docs

* some more docs work

* optimized pins page? - part 1

* filter

* pins page is now down to 8kb (was 90kb, then 10kb)

* Implement LittleFS for LN882H - only first basic testing from WebApp … (#1191)

* Implement LittleFS for LN882H - only first basic testing from WebApp !!!!

- need to add littlefs-source to sdk/OpenLN882H/project/OpenBeken/CMakeLists.txt

Remarks:
I had to move the import part of LittleFS

in various cmd-source files to nearer to the top of the files

otherwise I had very strange (false!!!) compiler errors regarding
"conflicting types" for equal(!) typed prototypes and functions or even variables in .h and .c files

e.g.:

/OpenBK7231T_App/sdk/OpenLN882H/project/OpenBeken/app/src/cmnds/cmd_main.c:47:6: error: conflicting types for 'g_powersave'
   47 | bool g_powersave;
      |      ^~~~~~~~~~~
In file included from /OpenBK7231T_App/sdk/OpenLN882H/project/OpenBeken/app/src/cmnds/cmd_local.h:4,
                 from /OpenBK7231T_App/sdk/OpenLN882H/project/OpenBeken/app/src/cmnds/cmd_main.c:6:
/OpenBK7231T_App/sdk/OpenLN882H/project/OpenBeken/app/src/cmnds/cmd_public.h:33:13: note: previous declaration of 'g_powersave' was here
   33 | extern bool g_powersave;
      |             ^~~~~~~~~~~
/OpenBK7231T_App/sdk/OpenLN882H/project/OpenBeken/app/src/cmnds/cmd_main.c:47:6: error: conflicting types for 'g_powersave'
   47 | bool g_powersave;
      |      ^~~~~~~~~~~

Also I had to disable other drivers, or the OTA image would not be flashed (after rebbot old version was still present)
Is there a size limit to respect for OTA? the size was well below the shown OTA-size of 0xAA000 (696320k if I calculated correct)

* Moved "bool" from local int definition to stdbool.h
So I got rid of all those "conflicting types" errors.

Thanks to @giedriuslt for pointing this out!

This commit also includes a define of "ENABLE_TEST_COMMANDS" for the littlefs tests (lfs_test<n>).

* Restored all #defines to 1
Last image loaded without any problem

* Update cmd_main.c - temporarily removed one define to be able to sync to master

Changed 
#if (defined WINDOWS) || (defined PLATFORM_BEKEN) || (defined PLATFORM_BL602) || (defined PLATFORM_LN882H)
back to
#if (defined WINDOWS) || (defined PLATFORM_BEKEN) || (defined PLATFORM_BL602)

in src/cmnds/cmd_main.c

* Update cmd_main.c

Restored change in cmd_main.c after syncing

* Update user_main.c

Changed user_main.c to allow SVM_RunThreads() for LN882H with LittleFS

* Merged updated OpenLN882H

* Disable building test commands in obk_config.h

* Also "#define ENABLE_EXPAND_CONSTANT 1" to allow more advanced scripting

* Added LN882H to some more "#if defined" lines to allow scripting ...
Added BL602 in two lines missing this platform, too

---------

Co-authored-by: openshwprojects <[email protected]>

* door sensor clear self test

* allow bl602 to use constants in publishFloat ant similar (#1229)

It was under platform define, should be fixed to proper define

* better door sensor clear self test

* test command with spaces - ok?

* fix and selftest - backlog should not return non-zero value when commands list has empty command

* Stack size for BL is not enough to execute backlog commands (#1226)

Specifically "Save, Reset SVM and run file as script thread" crashes the chip due to stack overflow

* move more test commands to... cmd_test.c

move more test commands to... cmd_test.c

* correct BMP280.c startdriver example, add bmp280.h detected flash ID output, add BME680 detection (only) (#1230)

* testBMP

* correct startdriver example 8bitaddress

* add BME680 chip ID, add BME680 chip detection

* correct BME680_CHIP_ID

* Update obk_config.h

---------

Co-authored-by: openshwprojects <[email protected]>

* extend pin cfg page: (#1228)

introduce a function te get number of channels for an IO role
in JS code generate all elements, but hide and disable unused fields. This way the should not count for POST action

* Update workflow.yaml

* Update workflow.yaml

* few more self tests for command backlog

* Update workflow.yaml (#1234)

Deprecation notice: v1, v2, and v3 of the artifact actions
The following artifacts were uploaded using a version of actions/upload-artifact that is scheduled for deprecation: "OpenBK7231T_App_1232_merge_36e61294cc71".
Please update your workflow to use v4 of the artifact actions.
Learn more: https://github.blog/changelog/2024-04-16-deprecation-notice-v3-of-the-artifact-actions/

* Update workflow.yaml (#1235)

both upload and download artifact should be v4...

* Update workflow.yaml

* negation method self test

* Drawers (#1232)

* drawers draft

* test

* support post as well

* Update drv_drawers.c

* ambient

* add led_ambient

* foolproof compile

* disable drivers before merge

* allow disabling Tasmota JSON API (#1236)

* allow disabling Tasmota JSON API

* test enable

* Update README.md

* add smart LED drawers project information

* Fix possible wrong index /  shorten JS code (#1238)

* extend pin cfg page:
introduce a function te get number of channels for an IO role
in JS code generate all elements, but hide and disable unused fields. This way the should not count for POST action

* Fix for possible wrong index when pin can't be PWM
shorten code

---------

Co-authored-by: openshwprojects <[email protected]>

* refresh docs

* reenable tasmota json on simulator

* add a waitfor channel self test

* add bInv to TuyaMCU

* add bInv selftest

* add mult self test for tuyamcu

* cosmetic change only - rename to dpID

* selftest vcp constants

* self test - turn off script for a user - part 1

* Publish internal temperature to Home Assistant (#1243)

* allow auto wake up of DoorSensor

* Use functional define for constant expansion (#1244)

This fixes constants in publishFloat for LN882H and publishInt for BL602 and LN882H

* Update README.md

* Fix for Issue 808

Queueing sensor state changes while device is offline and publishing them as MQTT connection is established.

* minor typo fixes

* adding deduplication of similar messages

* code cleanup

* adding some comments, fixing typo

* typo fixes

---------

Co-authored-by: giedriuslt <[email protected]>
Co-authored-by: Tester23 <[email protected]>
Co-authored-by: NonPIayerCharacter <[email protected]>
Co-authored-by: openshwprojects <[email protected]>
Co-authored-by: MaxineMuster <[email protected]>
Co-authored-by: divadiow <[email protected]>
Co-authored-by: DeDaMrAzR <[email protected]>
  • Loading branch information
8 people authored May 24, 2024
1 parent 84f1176 commit dda037b
Showing 1 changed file with 58 additions and 45 deletions.
103 changes: 58 additions & 45 deletions src/driver/drv_doorSensorWithDeepSleep.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
#include "../hal/hal_adc.h"
#include "../ota/ota.h"

static int setting_timeRequiredUntilDeepSleep = 60;
static int g_noChangeTimePassed = 0;
static int g_initialStateSent = 0;
static int g_emergencyTimeWithNoConnection = 0;
static int g_noChangeTimePassed = 0; // time without change. Every event in any of the doorsensor channels resets it.
static int g_emergencyTimeWithNoConnection = 0; // time without connection to MQTT. Extends the interval till Deep Sleep until connection is established or EMERGENCY_TIME_TO_SLEEP_WITHOUT_MQTT
static int g_lastEventState = -1; // last state of doorsensor channel
static int setting_automaticWakeUpAfterSleepTime = 0;
static int setting_timeRequiredUntilDeepSleep = 60;

#define EMERGENCY_TIME_TO_SLEEP_WITHOUT_MQTT 60 * 5

Expand All @@ -32,6 +32,7 @@ int Simulator_GetNoChangeTimePassed() {
int Simulator_GetDoorSennsorAutomaticWakeUpAfterSleepTime() {
return setting_automaticWakeUpAfterSleepTime;
}

// addEventHandler OnClick 8 DSTime +100
commandResult_t DoorDeepSleep_SetTime(const void* context, const char* cmd, const char* args, int cmdFlags) {
const char *a;
Expand All @@ -57,9 +58,9 @@ commandResult_t DoorDeepSleep_SetTime(const void* context, const char* cmd, cons
setting_automaticWakeUpAfterSleepTime = Tokenizer_GetArgInteger(1);
}


return CMD_RES_OK;
}

void DoorDeepSleep_Init() {
// 0 seconds since last change
g_noChangeTimePassed = 0;
Expand All @@ -71,9 +72,41 @@ void DoorDeepSleep_Init() {
CMD_RegisterCommand("DSTime", DoorDeepSleep_SetTime, NULL);
}

void DoorDeepSleep_QueueNewEvents() {
int i, curr_value;
char sChannel[8]; // channel as a string
char sValue[8]; // channel value as a string

for (i = 0; i < PLATFORM_GPIO_MAX; i++) {
if (g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep ||
g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep_NoPup ||
g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep_pd) {

int channel = g_cfg.pins.channels[i];
sprintf(sChannel, "%i/get", channel); // manually adding the suffix "/get" to the topic
// Explanation: I manually add "/get" suffix to the sChannel, because for some reason,
// when queued messages are published through PublishQueuedItems(), the
// functionality of appendding /get is disabled (in MQTT_PublishTopicToClient()),
// and there is no flag to enforce it.
// There is only a flag (OBK_PUBLISH_FLAG_FORCE_REMOVE_GET) to remove
// suffix, but for some reason there is no flag to add it.
// Would be great if such flag exists, so I can add it when calling
// MQTT_QueuePublish(), so /get is appended when published through
// PublishQueuedItems().

curr_value = CHANNEL_Get(channel);
if (curr_value != g_lastEventState) {
g_lastEventState = curr_value;
sprintf(sValue, "%i", curr_value); // get the value of the channel
MQTT_QueuePublish(CFG_GetMQTTClientId(), sChannel, sValue, 0); // queue the publishing
// Current state (or state change) will be queued and published when device establishes
// the connection to WiFi and MQTT Broker (300 seconds by default for that).
}
}
}
}

void DoorDeepSleep_OnEverySecond() {
int i, bValue;
char tmp[8];

#if PLATFORM_BK7231N || PLATFORM_BK7231T
if (ota_progress() >= 0) {
Expand All @@ -83,39 +116,25 @@ void DoorDeepSleep_OnEverySecond() {
// update active
g_noChangeTimePassed = 0;
g_emergencyTimeWithNoConnection = 0;
} else if (Main_HasMQTTConnected() && Main_HasWiFiConnected()) {
if (g_initialStateSent < 3) {
for (i = 0; i < PLATFORM_GPIO_MAX; i++) {
if (g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep ||
g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep_NoPup ||
g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep_pd) {
sprintf(tmp, "%i", g_cfg.pins.channels[i]);
bValue = BIT_CHECK(g_initialPinStates, i);
MQTT_PublishMain_StringInt(tmp,bValue, 0);
}
}
g_initialStateSent++;
} else {
for (i = 0; i < PLATFORM_GPIO_MAX; i++) {
if (g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep ||
g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep_NoPup ||
g_cfg.pins.roles[i] == IOR_DoorSensorWithDeepSleep_pd) {
MQTT_ChannelPublish(g_cfg.pins.channels[i], 0);
}
} else if (Main_HasMQTTConnected() && Main_HasWiFiConnected()) { // executes every second when connection is established

DoorDeepSleep_QueueNewEvents();
PublishQueuedItems(); // publish those items that were queued when device was offline

g_noChangeTimePassed++;
if (g_noChangeTimePassed >= setting_timeRequiredUntilDeepSleep) {
// start deep sleep in the next loop
// The deep sleep start will check for role: IOR_DoorSensorWithDeepSleep
// and for those pins, it will wake up on the pin change to opposite state
// (so if door sensor is low, it will wake up on rising edge,
// if door sensor is high, it will wake up on falling)
g_bWantPinDeepSleep = true;
g_pinDeepSleepWakeUp = setting_automaticWakeUpAfterSleepTime;
}
}
g_noChangeTimePassed++;
if (g_noChangeTimePassed >= setting_timeRequiredUntilDeepSleep) {
// start deep sleep in the next loop
// The deep sleep start will check for role: IOR_DoorSensorWithDeepSleep
// and for those pins, it will wake up on the pin change to opposite state
// (so if door sensor is low, it will wake up on rising edge,
// if door sensor is high, it will wake up on falling)
g_bWantPinDeepSleep = true;
g_pinDeepSleepWakeUp = setting_automaticWakeUpAfterSleepTime;
}
}
else {
else { // executes every second while the device is woken up, but offline
DoorDeepSleep_QueueNewEvents();

g_emergencyTimeWithNoConnection++;
if (g_emergencyTimeWithNoConnection >= EMERGENCY_TIME_TO_SLEEP_WITHOUT_MQTT) {
g_bWantPinDeepSleep = true;
Expand All @@ -124,10 +143,10 @@ void DoorDeepSleep_OnEverySecond() {
}
}


void DoorDeepSleep_StopDriver() {

}

void DoorDeepSleep_AppendInformationToHTTPIndexPage(http_request_t* request)
{
int untilSleep;
Expand All @@ -152,9 +171,3 @@ void DoorDeepSleep_OnChannelChanged(int ch, int value) {
g_emergencyTimeWithNoConnection = 0;
}
}






0 comments on commit dda037b

Please sign in to comment.