Merge pull request #342 from valeklubomir/main

Consumption counter storing functionality
This commit is contained in:
openshwprojects
2022-10-28 09:22:47 +02:00
committed by GitHub
40 changed files with 1365 additions and 751 deletions

View File

@@ -212,6 +212,8 @@ There are multiple console commands that allow you to automate your devices. Com
| DGR_SendBrightness | [GroupName][Brightness] | Sends a Brightness message to given Tasmota Device Group with no reliability. Requires no prior setup and can control any group, but won't retransmit. |
| EnergyCntReset | | Used for BL0942/BL0937/etc consumption measurement data reset |
| SetupEnergyStats | [enable] [sample_time] [sample_count] [enableJSON] | Used for BL0942/BL0937/etc. Configure consumptio history stats. enable: 0/1 sample_time:10..900 sample_count: 10..180 enableJSON: 0/1 |
| PowerMax | [limit] | Used for BL0937 to setup limiter for maximal output filter based on device definition 3680W for 16A devices. Prevention of sending ridicilus numbers to Cloud |
| ConsumptionThreshold | [threshold] | Used for BL0942/BL0937/etc for define threshold for change of total counter to execute automatic store of consumption counters to flash |
Are you looking for extra commands? Just search the code:
https://github.com/openshwprojects/OpenBK7231T_App/search?q=CMD_RegisterCommand

View File

@@ -83,7 +83,9 @@ bool strCompareBound(const char *s, const char *templ, const char *stopper, int
if(bAllowWildCard && *templ == '*') {
} else {
if(tolower(*s) != tolower(*templ)) {
char c1 = tolower((unsigned char)*s);
char c2 = tolower((unsigned char)*templ);
if(c1 != c2) {
return false;
}
}

View File

@@ -35,9 +35,12 @@ uint32_t res_p = 0;
float BL0937_VREF = 0.13253012048f;
float BL0937_PREF = 1.5f;
float BL0937_CREF = 0.0118577075f;
float BL0937_PMAX = 3680.0f;
float last_p = 0.0f;
volatile uint32_t g_vc_pulses = 0;
volatile uint32_t g_p_pulses = 0;
static portTickType pulseStamp;
void HlwCf1Interrupt(unsigned char pinNum) { // Service Voltage and Current
g_vc_pulses++;
@@ -56,7 +59,7 @@ int BL0937_PowerSet(const void *context, const char *cmd, const char *args, int
BL0937_PREF = realPower / res_p;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_POWER,BL0937_PREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,BL0937_PREF);
{
char dbg[128];
@@ -65,6 +68,29 @@ int BL0937_PowerSet(const void *context, const char *cmd, const char *args, int
}
return 0;
}
int BL0937_PowerMax(const void *context, const char *cmd, const char *args, int cmdFlags) {
float maxPower;
if(args==0||*args==0) {
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER,"This command needs one argument");
return 1;
}
maxPower = atof(args);
if ((maxPower>200.0) && (maxPower<7200.0f))
{
BL0937_PMAX = maxPower;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_POWER_MAX, BL0937_PMAX);
{
char dbg[128];
snprintf(dbg, sizeof(dbg),"PowerMax: set max to %f\n", BL0937_PMAX);
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER,dbg);
}
}
return 0;
}
int BL0937_PowerRef(const void *context, const char *cmd, const char *args, int cmdFlags) {
if(args==0||*args==0) {
@@ -74,7 +100,7 @@ int BL0937_PowerRef(const void *context, const char *cmd, const char *args, int
BL0937_PREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_POWER,BL0937_PREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,BL0937_PREF);
return 0;
}
@@ -87,7 +113,7 @@ int BL0937_CurrentRef(const void *context, const char *cmd, const char *args, in
BL0937_CREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_CURRENT,BL0937_CREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,BL0937_CREF);
return 0;
}
@@ -100,7 +126,7 @@ int BL0937_VoltageRef(const void *context, const char *cmd, const char *args, in
BL0937_VREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,BL0937_VREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,BL0937_VREF);
return 0;
}
@@ -115,7 +141,7 @@ int BL0937_VoltageSet(const void *context, const char *cmd, const char *args, in
BL0937_VREF = realV / res_v;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,BL0937_VREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,BL0937_VREF);
{
char dbg[128];
@@ -136,7 +162,7 @@ int BL0937_CurrentSet(const void *context, const char *cmd, const char *args, in
BL0937_CREF = realI / res_c;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_CURRENT,BL0937_CREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,BL0937_CREF);
{
char dbg[128];
@@ -155,9 +181,10 @@ void BL0937_Init()
GPIO_HLW_CF1 = PIN_FindPinIndexForRole(IOR_BL0937_CF1,GPIO_HLW_CF1);
// UPDATE: now they are automatically saved
BL0937_VREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,BL0937_VREF);
BL0937_PREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_POWER,BL0937_PREF);
BL0937_CREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_CURRENT,BL0937_CREF);
BL0937_VREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,BL0937_VREF);
BL0937_PREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,BL0937_PREF);
BL0937_CREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,BL0937_CREF);
BL0937_PMAX = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_POWER_MAX,BL0937_PMAX);
HAL_PIN_Setup_Output(GPIO_HLW_SEL);
HAL_PIN_SetOutputValue(GPIO_HLW_SEL, g_sel);
@@ -175,13 +202,24 @@ void BL0937_Init()
CMD_RegisterCommand("PREF","",BL0937_PowerRef, "Sets the calibration multiplier", NULL);
CMD_RegisterCommand("VREF","",BL0937_VoltageRef, "Sets the calibration multiplier", NULL);
CMD_RegisterCommand("IREF","",BL0937_CurrentRef, "Sets the calibration multiplier", NULL);
CMD_RegisterCommand("PowerMax","",BL0937_PowerMax, "Sets Maximum power value measurement limiter", NULL);
g_vc_pulses = 0;
g_p_pulses = 0;
pulseStamp = xTaskGetTickCount();
}
void BL0937_RunFrame() {
void BL0937_RunFrame()
{
float final_v;
float final_c;
float final_p;
portTickType ticksElapsed;
ticksElapsed = (xTaskGetTickCount() - pulseStamp);
GLOBAL_INT_DECLARATION();
GLOBAL_INT_DISABLE();
if(g_sel) {
res_v = g_vc_pulses;
g_sel = false;
@@ -194,12 +232,37 @@ void BL0937_RunFrame() {
res_p = g_p_pulses;
g_p_pulses = 0;
GLOBAL_INT_RESTORE();
pulseStamp = xTaskGetTickCount();
//addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER,"Voltage pulses %i, current %i, power %i\n", res_v, res_c, res_p);
final_v = res_v * BL0937_VREF;
final_c = res_c * BL0937_CREF;
final_p = res_p * BL0937_PREF;
final_v *= (float)ticksElapsed;
final_v /= (1000.0f / (float)portTICK_PERIOD_MS);
final_c = res_c * BL0937_CREF;
final_c *= (float)ticksElapsed;
final_c /= (1000.0f / (float)portTICK_PERIOD_MS);
final_p = res_p * BL0937_PREF;
final_p *= (float)ticksElapsed;
final_p /= (1000.0f / (float)portTICK_PERIOD_MS);
/* patch to limit max power reading, filter random reading errors */
if (final_p > BL0937_PMAX)
{
/* MAX value breach, use last value */
{
char dbg[128];
snprintf(dbg, sizeof(dbg),"Power reading: %f exceeded MAX limit: %f, Last: %f\n", final_p, BL0937_PMAX, last_p);
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, dbg);
}
final_p = last_p;
} else {
/* Valid value save for next time */
last_p = final_p;
}
#if 0
{
char dbg[128];

View File

@@ -137,7 +137,7 @@ int BL0942_PowerSet(const void *context, const char *cmd, const char *args, int
BL0942_PREF = raw_unscaled_power / realPower;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_POWER,BL0942_PREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,BL0942_PREF);
{
char dbg[128];
@@ -155,7 +155,7 @@ int BL0942_PowerRef(const void *context, const char *cmd, const char *args, int
BL0942_PREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_POWER,BL0942_PREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,BL0942_PREF);
return 0;
}
@@ -168,7 +168,7 @@ int BL0942_CurrentRef(const void *context, const char *cmd, const char *args, in
BL0942_IREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_CURRENT,BL0942_IREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,BL0942_IREF);
return 0;
}
@@ -181,7 +181,7 @@ int BL0942_VoltageRef(const void *context, const char *cmd, const char *args, in
BL0942_UREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,BL0942_UREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,BL0942_UREF);
return 0;
}
@@ -196,7 +196,7 @@ int BL0942_VoltageSet(const void *context, const char *cmd, const char *args, in
BL0942_UREF = raw_unscaled_voltage / realV;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,BL0942_UREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,BL0942_UREF);
{
char dbg[128];
@@ -217,7 +217,7 @@ int BL0942_CurrentSet(const void *context, const char *cmd, const char *args, in
BL0942_IREF = raw_unscaled_current / realI;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_CURRENT,BL0942_IREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,BL0942_IREF);
{
char dbg[128];
@@ -231,9 +231,9 @@ void BL0942_Init()
BL_Shared_Init();
// UPDATE: now they are automatically saved
BL0942_UREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,BL0942_UREF);
BL0942_PREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_POWER,BL0942_PREF);
BL0942_IREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_CURRENT,BL0942_IREF);
BL0942_UREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,BL0942_UREF);
BL0942_PREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,BL0942_PREF);
BL0942_IREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,BL0942_IREF);
UART_InitUART(BL0942_BAUD_RATE);
UART_InitReceiveRingBuffer(256);

View File

@@ -10,6 +10,12 @@
#include "drv_uart.h"
#include "../httpserver/new_http.h"
#include "../cJSON/cJSON.h"
#include <time.h>
#include "drv_ntp.h"
#include "../hal/hal_flashVars.h"
#include "../ota/ota.h"
#define DAILY_STATS_LENGTH 4
int stat_updatesSkipped = 0;
int stat_updatesSent = 0;
@@ -43,6 +49,13 @@ int noChangeFrameEnergyCounter;
float lastSentEnergyCounterValue = 0.0f;
float changeSendThresholdEnergy = 0.1f;
float lastSentEnergyCounterLastHour = 0.0f;
float dailyStats[DAILY_STATS_LENGTH];
int actual_mday = -1;
float lastSavedEnergyCounterValue = 0.0f;
float changeSavedThresholdEnergy = 10.0f;
long ConsumptionSaveCounter = 0;
portTickType lastConsumptionSaveStamp;
time_t ConsumptionResetTime = 0;
// how much of value have to change in order to be send over MQTT again?
int changeSendThresholds[OBK_NUM_MEASUREMENTS] = {
@@ -59,6 +72,7 @@ void BL09XX_AppendInformationToHTTPIndexPage(http_request_t *request)
{
int i;
const char *mode;
struct tm *ltm;
if(DRV_IsRunning("BL0937")) {
mode = "BL0937";
@@ -71,7 +85,8 @@ void BL09XX_AppendInformationToHTTPIndexPage(http_request_t *request)
}
hprintf255(request,"<h2>%s Voltage=%f, Current=%f, Power=%f",mode, lastReadings[OBK_VOLTAGE],lastReadings[OBK_CURRENT], lastReadings[OBK_POWER]);
hprintf255(request,", Total Consumption=%1.1f Wh (changes sent %i, skipped %i)</h2>",energyCounter, stat_updatesSent, stat_updatesSkipped);
hprintf255(request,", Total Consumption=%1.1f Wh (changes sent %i, skipped %i, saved %li)</h2>",energyCounter, stat_updatesSent, stat_updatesSkipped,
ConsumptionSaveCounter);
if (energyCounterStatsEnable == true)
{
@@ -96,15 +111,58 @@ void BL09XX_AppendInformationToHTTPIndexPage(http_request_t *request)
}
}
// energyCounterMinutesIndex is a long type, we need to use %ld instead of %d
hprintf255(request, "<br>History Index: %ld<br>JSON Stats: %s </h5>", energyCounterMinutesIndex,
if ((i%20)!=0)
hprintf255(request, "<br>");
hprintf255(request, "History Index: %ld<br>JSON Stats: %s <br>", energyCounterMinutesIndex,
(energyCounterStatsJSONEnable == true) ? "enabled" : "disabled");
}
if(NTP_IsTimeSynced() == true)
{
hprintf255(request, "Today: %1.1f Wh DailyStats: [", dailyStats[0]);
for(i = 1; i < DAILY_STATS_LENGTH; i++)
{
if (i==1)
hprintf255(request, "%1.1f", dailyStats[i]);
else
hprintf255(request, ",%1.1f", dailyStats[i]);
}
hprintf255(request, "]<br>");
ltm = localtime(&ConsumptionResetTime);
hprintf255(request, "Consumption Reset Time: %04d/%02d/%02d %02d:%02d:%02d",
ltm->tm_year+1900, ltm->tm_mon+1, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
} else {
if(DRV_IsRunning("NTP")==false)
hprintf255(request,"NTP driver is not started, daily stats disbled.");
else
hprintf255(request,"Daily stats require NTP driver to sync real time.");
}
hprintf255(request, "</h5>");
} else {
hprintf255(request,"<h5>Periodic Statistics disabled. Use startup command SetupEnergyStats to enable function.</h5>");
}
/********************************************************************************************************************/
}
void BL09XX_SaveEmeteringStatistics()
{
ENERGY_METERING_DATA data;
memset(&data, 0, sizeof(ENERGY_METERING_DATA));
data.TotalConsumption = energyCounter;
data.TodayConsumpion = dailyStats[0];
data.YesterdayConsumption = dailyStats[1];
data.actual_mday = actual_mday;
data.ConsumptionHistory[0] = dailyStats[2];
data.ConsumptionHistory[1] = dailyStats[3];
data.ConsumptionResetTime = ConsumptionResetTime;
ConsumptionSaveCounter++;
data.save_counter = ConsumptionSaveCounter;
HAL_SetEnergyMeterStatus(&data);
}
int BL09XX_ResetEnergyCounter(const void *context, const char *cmd, const char *args, int cmdFlags)
{
float value;
@@ -126,11 +184,21 @@ int BL09XX_ResetEnergyCounter(const void *context, const char *cmd, const char *
energyCounterMinutesStamp = xTaskGetTickCount();
energyCounterMinutesIndex = 0;
}
for(i = 0; i < DAILY_STATS_LENGTH; i++)
{
dailyStats[i] = 0.0;
}
} else {
value = atof(args);
energyCounter = value;
energyCounterStamp = xTaskGetTickCount();
}
ConsumptionResetTime = (time_t)NTP_GetCurrentTime();
if (ota_progress()==-1)
{
BL09XX_SaveEmeteringStatistics();
lastConsumptionSaveStamp = xTaskGetTickCount();
}
return 0;
}
@@ -146,7 +214,7 @@ int BL09XX_SetupEnergyStatistic(const void *context, const char *cmd, const char
if(Tokenizer_GetArgsCount() < 3)
{
addLogAdv(LOG_INFO, LOG_FEATURE_TUYAMCU,"BL09XX_SetupEnergyStatistic: requires 3 arguments (enable, sample_time, sample_count)\n");
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "BL09XX_SetupEnergyStatistic: requires 3 arguments (enable, sample_time, sample_count)\n");
return -1;
}
@@ -173,7 +241,7 @@ int BL09XX_SetupEnergyStatistic(const void *context, const char *cmd, const char
/* process changes */
if (enable != 0)
{
addLogAdv(LOG_INFO, LOG_FEATURE_TUYAMCU,"Consumption History enabled\n");
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "Consumption History enabled\n");
/* Enable function */
energyCounterStatsEnable = true;
if (energyCounterSampleCount != sample_count)
@@ -184,7 +252,7 @@ int BL09XX_SetupEnergyStatistic(const void *context, const char *cmd, const char
energyCounterMinutes = NULL;
energyCounterSampleCount = sample_count;
}
addLogAdv(LOG_INFO, LOG_FEATURE_TUYAMCU,"Sample Count: %d\n", energyCounterSampleCount);
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "Sample Count: %d\n", energyCounterSampleCount);
if (energyCounterSampleInterval != sample_time)
{
/* change sample time */
@@ -202,13 +270,13 @@ int BL09XX_SetupEnergyStatistic(const void *context, const char *cmd, const char
memset(energyCounterMinutes, 0, energyCounterSampleCount*sizeof(float));
}
}
addLogAdv(LOG_INFO, LOG_FEATURE_TUYAMCU,"Sample Interval: %d\n", energyCounterSampleInterval);
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "Sample Interval: %d\n", energyCounterSampleInterval);
energyCounterMinutesStamp = xTaskGetTickCount();
energyCounterMinutesIndex = 0;
} else {
/* Disable Consimption Nistory */
addLogAdv(LOG_INFO, LOG_FEATURE_TUYAMCU,"Consumption History disabled\n");
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "Consumption History disabled\n");
energyCounterStatsEnable = false;
if (energyCounterMinutes != NULL)
{
@@ -224,6 +292,29 @@ int BL09XX_SetupEnergyStatistic(const void *context, const char *cmd, const char
return 0;
}
int BL09XX_SetupConsumptionThreshold(const void *context, const char *cmd, const char *args, int cmdFlags)
{
float threshold;
Tokenizer_TokenizeString(args,0);
if(Tokenizer_GetArgsCount() < 1)
{
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "BL09XX_SetupConsumptionThreshold: requires argument (threshold)\n");
return -1;
}
threshold = atof(Tokenizer_GetArg(0));
if (threshold<1.0f)
threshold = 1.0f;
if (threshold>200.0f)
threshold = 200.0f;
changeSavedThresholdEnergy = threshold;
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "ConsumptionThreshold: %1.1f\n", changeSavedThresholdEnergy);
return 0;
}
void BL_ProcessUpdate(float voltage, float current, float power)
{
int i;
@@ -233,6 +324,9 @@ void BL_ProcessUpdate(float voltage, float current, float power)
cJSON* stats;
char *msg;
portTickType interval;
time_t g_time;
struct tm *ltm;
char datetime[64];
// those are final values, like 230V
lastReadings[OBK_POWER] = power;
@@ -245,9 +339,50 @@ void BL_ProcessUpdate(float voltage, float current, float power)
energy = (float)xPassedTicks;
energy *= power;
energy /= (3600000.0f / (float)portTICK_PERIOD_MS);
if (energy < 0)
{
energy = 0.0;
}
energyCounter += energy;
energyCounterStamp = xTaskGetTickCount();
HAL_FlashVars_SaveTotalConsumption(energyCounter);
if(NTP_IsTimeSynced() == true)
{
g_time = (time_t)NTP_GetCurrentTime();
ltm = localtime(&g_time);
if (ConsumptionResetTime == 0)
ConsumptionResetTime = (time_t)g_time;
if (actual_mday == -1)
{
actual_mday = ltm->tm_mday;
}
if (actual_mday != ltm->tm_mday)
{
for(i = 7; i > 0; i--)
{
dailyStats[i] = dailyStats[i - 1];
}
dailyStats[0] = 0.0;
actual_mday = ltm->tm_mday;
MQTT_PublishMain_StringFloat(counter_mqttNames[3], dailyStats[1]);
stat_updatesSent++;
if (ota_progress()==-1)
{
BL09XX_SaveEmeteringStatistics();
lastConsumptionSaveStamp = xTaskGetTickCount();
}
ltm = localtime(&ConsumptionResetTime);
sprintf(datetime, "%04i-%02i-%02i %02i:%02i:%02i",
ltm->tm_year+1900, ltm->tm_mon+1, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
MQTT_PublishMain_StringString(counter_mqttNames[5], datetime, 0);
stat_updatesSent++;
}
}
dailyStats[0] += energy;
if (energyCounterStatsEnable == true)
{
@@ -264,6 +399,15 @@ void BL_ProcessUpdate(float voltage, float current, float power)
cJSON_AddNumberToObject(root, "consumption_stat_index", energyCounterMinutesIndex);
cJSON_AddNumberToObject(root, "consumption_sample_count", energyCounterSampleCount);
cJSON_AddNumberToObject(root, "consumption_sampling_period", energyCounterSampleInterval);
if(NTP_IsTimeSynced() == true)
{
cJSON_AddNumberToObject(root, "consumption_today", dailyStats[0]);
cJSON_AddNumberToObject(root, "consumption_yesterday", dailyStats[1]);
ltm = localtime(&ConsumptionResetTime);
sprintf(datetime, "%04i-%02i-%02i %02i:%02i:%02i",
ltm->tm_year+1900, ltm->tm_mon+1, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
cJSON_AddStringToObject(root, "consumption_clear_date", datetime);
}
if (energyCounterMinutes != NULL)
{
@@ -275,9 +419,21 @@ void BL_ProcessUpdate(float voltage, float current, float power)
cJSON_AddItemToObject(root, "consumption_samples", stats);
}
msg = cJSON_Print(root);
if(NTP_IsTimeSynced() == true)
{
stats = cJSON_CreateArray();
for(i = 0; i < DAILY_STATS_LENGTH; i++)
{
cJSON_AddItemToArray(stats, cJSON_CreateNumber(dailyStats[i]));
}
cJSON_AddItemToObject(root, "consumption_daily", stats);
}
msg = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "JSON Printed: %d bytes\n", strlen(msg));
MQTT_PublishMain_StringString(counter_mqttNames[2], msg, 0);
stat_updatesSent++;
os_free(msg);
@@ -287,7 +443,12 @@ void BL_ProcessUpdate(float voltage, float current, float power)
{
for (i=energyCounterSampleCount-1;i>0;i--)
{
energyCounterMinutes[i] = energyCounterMinutes[i-1];
if (energyCounterMinutes[i-1]>0.0)
{
energyCounterMinutes[i] = energyCounterMinutes[i-1];
} else {
energyCounterMinutes[i] = 0.0;
}
}
energyCounterMinutes[0] = 0.0;
}
@@ -345,15 +506,38 @@ void BL_ProcessUpdate(float voltage, float current, float power)
EventHandlers_ProcessVariableChange_Integer(CMD_EVENT_CHANGE_CONSUMPTION_LAST_HOUR, lastSentEnergyCounterLastHour, DRV_GetReading(OBK_CONSUMPTION_LAST_HOUR));
lastSentEnergyCounterLastHour = DRV_GetReading(OBK_CONSUMPTION_LAST_HOUR);
stat_updatesSent++;
if(NTP_IsTimeSynced() == true)
{
MQTT_PublishMain_StringFloat(counter_mqttNames[3], dailyStats[1]);
stat_updatesSent++;
MQTT_PublishMain_StringFloat(counter_mqttNames[4], dailyStats[0]);
stat_updatesSent++;
ltm = localtime(&ConsumptionResetTime);
sprintf(datetime, "%04i-%02i-%02i %02i:%02i:%02i",
ltm->tm_year+1900, ltm->tm_mon+1, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
MQTT_PublishMain_StringString(counter_mqttNames[5], datetime, 0);
stat_updatesSent++;
}
} else {
noChangeFrameEnergyCounter++;
stat_updatesSkipped++;
}
if (((energyCounter - lastSavedEnergyCounterValue) >= changeSavedThresholdEnergy) ||
((xTaskGetTickCount() - lastConsumptionSaveStamp) >= (6 * 3600 * 1000 / portTICK_PERIOD_MS)))
{
if (ota_progress() == -1)
{
lastSavedEnergyCounterValue = energyCounter;
BL09XX_SaveEmeteringStatistics();
lastConsumptionSaveStamp = xTaskGetTickCount();
}
}
}
void BL_Shared_Init()
{
int i;
ENERGY_METERING_DATA data;
for(i = 0; i < OBK_NUM_MEASUREMENTS; i++)
{
@@ -380,8 +564,30 @@ void BL_Shared_Init()
energyCounterMinutesIndex = 0;
}
for(i = 0; i < DAILY_STATS_LENGTH; i++)
{
dailyStats[i] = 0;
}
addLogAdv(LOG_INFO, LOG_FEATURE_ENERGYMETER, "Read ENERGYMETER status values. sizeof(ENERGY_METERING_DATA)=%d\n", sizeof(ENERGY_METERING_DATA));
HAL_GetEnergyMeterStatus(&data);
energyCounter = data.TotalConsumption;
dailyStats[0] = data.TodayConsumpion;
dailyStats[1] = data.YesterdayConsumption;
actual_mday = data.actual_mday;
lastSavedEnergyCounterValue = energyCounter;
dailyStats[2] = data.ConsumptionHistory[0];
dailyStats[3] = data.ConsumptionHistory[1];
ConsumptionResetTime = data.ConsumptionResetTime;
ConsumptionSaveCounter = data.save_counter;
lastConsumptionSaveStamp = xTaskGetTickCount();
//int HAL_SetEnergyMeterStatus(ENERGY_METERING_DATA *data);
CMD_RegisterCommand("EnergyCntReset", "", BL09XX_ResetEnergyCounter, "Reset Energy Counter", NULL);
CMD_RegisterCommand("SetupEnergyStats", "", BL09XX_SetupEnergyStatistic, "Setup Energy Statistic Parameters: [enable<0|1>] [sample_time<10..900>] [sample_count<10..180>]", NULL);
CMD_RegisterCommand("ConsumptionThresold", "", BL09XX_SetupConsumptionThreshold, "Setup value for automatic save of consumption data [1..100]", NULL);
}
// OBK_POWER etc
@@ -409,6 +615,10 @@ float DRV_GetReading(int type)
}
}
return hourly_sum;
case OBK_CONSUMPTION_YESTERDAY:
return dailyStats[1];
case OBK_CONSUMPTION_TODAY:
return dailyStats[0];
default:
break;
}

View File

@@ -209,7 +209,7 @@ int CSE7766_PowerSet(const void *context, const char *cmd, const char *args, int
CSE7766_PREF = realPower * raw_unscaled_power;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_POWER,CSE7766_PREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,CSE7766_PREF);
{
char dbg[128];
@@ -227,7 +227,7 @@ int CSE7766_PowerRef(const void *context, const char *cmd, const char *args, int
CSE7766_PREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_POWER,CSE7766_PREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,CSE7766_PREF);
return 0;
}
@@ -240,7 +240,7 @@ int CSE7766_CurrentRef(const void *context, const char *cmd, const char *args, i
CSE7766_IREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_CURRENT,CSE7766_IREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,CSE7766_IREF);
return 0;
}
@@ -253,7 +253,7 @@ int CSE7766_VoltageRef(const void *context, const char *cmd, const char *args, i
CSE7766_UREF = atof(args);
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,CSE7766_UREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,CSE7766_UREF);
return 0;
}
@@ -268,7 +268,7 @@ int CSE7766_VoltageSet(const void *context, const char *cmd, const char *args, i
CSE7766_UREF = realV * raw_unscaled_voltage;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,CSE7766_UREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,CSE7766_UREF);
{
char dbg[128];
@@ -289,7 +289,7 @@ int CSE7766_CurrentSet(const void *context, const char *cmd, const char *args, i
CSE7766_IREF = realI * raw_unscaled_current;
// UPDATE: now they are automatically saved
CFG_SetPowerMeasurementCalibrationFloat(OBK_CURRENT,CSE7766_IREF);
CFG_SetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,CSE7766_IREF);
{
char dbg[128];
@@ -303,9 +303,9 @@ void CSE7766_Init()
BL_Shared_Init();
// UPDATE: now they are automatically saved
CSE7766_UREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_VOLTAGE,CSE7766_UREF);
CSE7766_PREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_POWER,CSE7766_PREF);
CSE7766_IREF = CFG_GetPowerMeasurementCalibrationFloat(OBK_CURRENT,CSE7766_IREF);
CSE7766_UREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_VOLTAGE,CSE7766_UREF);
CSE7766_PREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_POWER,CSE7766_PREF);
CSE7766_IREF = CFG_GetPowerMeasurementCalibrationFloat(CFG_OBK_CURRENT,CSE7766_IREF);
UART_InitUART(CSE7766_BAUD_RATE);
UART_InitReceiveRingBuffer(512);

View File

@@ -223,6 +223,7 @@ class myIRsend : public IRsend {
our_ms = 0;
resetsendqueue();
}
~myIRsend() { }
void enableIROut(uint_fast8_t aFrequencyKHz){
// just setup variables for use in ISR
@@ -599,7 +600,7 @@ extern "C" void DRV_IR_RunFrame(){
if (publishrepeats || !repeat){
if (ourReceiver->decodedIRData.protocol == UNKNOWN){
snprintf(out, sizeof(out), "IR_%s 0x%X %d", name, ourReceiver->decodedIRData.decodedRawData, repeat);
snprintf(out, sizeof(out), "IR_%s 0x%lX %d", name, (unsigned long)ourReceiver->decodedIRData.decodedRawData, repeat);
} else {
snprintf(out, sizeof(out), "IR_%s 0x%X 0x%X %d", name, ourReceiver->decodedIRData.address, ourReceiver->decodedIRData.command, repeat);
}
@@ -635,6 +636,8 @@ extern "C" void DRV_IR_RunFrame(){
case SONY:
tgType = CMD_EVENT_IR_SONY;
break;
default:
break;
}
// we should include repeat here?

View File

@@ -35,13 +35,19 @@ const char* sensor_mqtt_device_units[OBK_NUM_MEASUREMENTS] = {
const char* counter_mqttNames[OBK_NUM_COUNTERS] = {
"energycounter",
"energycounter_last_hour",
"consumption_stats"
"consumption_stats",
"energycounter_yesterday",
"energycounter_today",
"energycounter_clear_date",
};
const char* counter_devClasses[OBK_NUM_COUNTERS] = {
"energy",
"energy",
""
"",
"energy",
"energy",
"date"
};
typedef struct driver_s {
@@ -58,7 +64,7 @@ typedef struct driver_s {
// startDriver BL0937
static driver_t g_drivers[] = {
{ "TuyaMCU", TuyaMCU_Init, TuyaMCU_RunFrame, NULL, NULL, NULL, NULL, false },
{ "NTP", NTP_Init, NTP_OnEverySecond, NULL, NULL, NULL, NULL, false },
{ "NTP", NTP_Init, NTP_OnEverySecond, NTP_AppendInformationToHTTPIndexPage, NULL, NULL, NULL, false },
{ "I2C", DRV_I2C_Init, DRV_I2C_EverySecond, NULL, NULL, NULL, NULL, false },
//These 4 measure power

View File

@@ -2,14 +2,17 @@
// Based on my previous work here:
// https://www.elektroda.pl/rtvforum/topic3712112.html
#include <time.h>
#include "../new_common.h"
#include "../new_cfg.h"
// Commands register, execution API and cmd tokenizer
#include "../cmnds/cmd_public.h"
#include "../httpserver/new_http.h"
#include "../logging/logging.h"
#include "drv_ntp.h"
#define LOG_FEATURE LOG_FEATURE_NTP
typedef struct
@@ -55,6 +58,7 @@ static int adrLen;
static int g_ntp_delay = 5;
// current time
static unsigned int g_time;
static bool g_synced;
// time offset (time zone?)
static int g_timeOffsetHours;
@@ -95,6 +99,7 @@ void NTP_Init() {
CMD_RegisterCommand("ntp_info", "", NTP_Info, "Display NTP related settings", NULL);
addLogAdv(LOG_INFO, LOG_FEATURE_NTP, "NTP driver initialized with server=%s, offset=%d\n", CFG_GetNTPServer(), g_timeOffsetHours);
g_synced = false;
}
unsigned int NTP_GetCurrentTime() {
@@ -112,7 +117,7 @@ void NTP_Shutdown() {
}
g_ntp_socket = 0;
// can attempt in next 10 seconds
g_ntp_delay = 10;
g_ntp_delay = 60;
}
void NTP_SendRequest(bool bBlocking) {
byte *ptr;
@@ -182,6 +187,7 @@ void NTP_CheckForReceive() {
unsigned int secsSince1900;
ntp_packet packet = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
ptr = (byte*)&packet;
struct tm *ltm;
// Receive the server's response:
i = sizeof(packet);
@@ -201,11 +207,15 @@ void NTP_CheckForReceive() {
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
secsSince1900 = highWord << 16 | lowWord;
addLogAdv(LOG_INFO, LOG_FEATURE_NTP,"Seconds since Jan 1 1900 = %u",secsSince1900);
addLogAdv(LOG_INFO, LOG_FEATURE_NTP,"Seconds since Jan 1 1900 = %u\n",secsSince1900);
g_time = secsSince1900 - NTP_OFFSET;
g_time += g_timeOffsetHours;
addLogAdv(LOG_INFO, LOG_FEATURE_NTP,"Unix time = %u",g_time);
addLogAdv(LOG_INFO, LOG_FEATURE_NTP,"Unix time : %u\n",g_time);
ltm = localtime((time_t*)&g_time);
addLogAdv(LOG_INFO, LOG_FEATURE_NTP,"Local Time : %04d/%02d/%02d %02d:%02d:%02d\n",
ltm->tm_year+1900, ltm->tm_mon+1, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
g_synced = true;
#if 0
//ptm = localtime (&g_time);
ptm = gmtime(&g_time);
@@ -255,3 +265,22 @@ void NTP_OnEverySecond() {
}
}
}
void NTP_AppendInformationToHTTPIndexPage(http_request_t* request)
{
struct tm *ltm;
ltm = localtime((time_t*)&g_time);
if (g_synced == true)
hprintf255(request, "<h5>NTP: Local Time: %04d/%02d/%02d %02d:%02d:%02d </h5>",
ltm->tm_year+1900, ltm->tm_mon+1, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
else
hprintf255(request, "<h5>NTP: Syncing....");
}
bool NTP_IsTimeSynced()
{
return g_synced;
}

View File

@@ -1,6 +1,14 @@
#ifndef __DRV_NTP_H__
#define __DRV_NTP_H__
#include "../httpserver/new_http.h"
void NTP_Init();
void NTP_OnEverySecond();
// returns number of seconds passed after 1900
unsigned int NTP_GetCurrentTime();
void NTP_AppendInformationToHTTPIndexPage(http_request_t* request);
bool NTP_IsTimeSynced();
#endif /* __DRV_NTP_H__ */

View File

@@ -1,4 +1,5 @@
#ifndef __DRV_PUBLIC_H__
#define __DRV_PUBLIC_H__
#include "../httpserver/new_http.h"
@@ -13,7 +14,10 @@ enum {
OBK_CONSUMPTION_TOTAL = OBK_NUM_MEASUREMENTS,
OBK_CONSUMPTION_LAST_HOUR,
OBK_CONSUMPTION_STATS,
OBK_NUM_EMUNS_MAX
OBK_CONSUMPTION_YESTERDAY,
OBK_CONSUMPTION_TODAY,
OBK_CONSUMPTION_CLEAR_DATE,
OBK_NUM_EMUNS_MAX
};
#define OBK_NUM_COUNTERS (OBK_NUM_EMUNS_MAX-OBK_NUM_MEASUREMENTS)
@@ -43,3 +47,7 @@ void DRV_DGR_OnLedEnableAllChange(int iVal);
// OBK_POWER etc
float DRV_GetReading(int type);
bool DRV_IsMeasuringPower();
void BL09XX_SaveEmeteringStatistics();
#endif /* __DRV_PUBLIC_H__ */

View File

@@ -352,7 +352,7 @@ void DRV_DGR_RunQuickTick() {
def.cbs.processRGBCW = DRV_DGR_processRGBCW;
def.cbs.checkSequence = DGR_CheckSequence;
DGR_Parse(msgbuf, nbytes, &def, &addr);
DGR_Parse((byte*)msgbuf, nbytes, &def, (struct sockaddr *)&addr);
//DGR_Parse(msgbuf, nbytes);
// puts(msgbuf);
}

View File

@@ -436,7 +436,7 @@ struct tm * TuyaMCU_Get_NTP_Time() {
g_time = NTP_GetCurrentTime();
addLogAdv(LOG_INFO, LOG_FEATURE_TUYAMCU,"MCU time to set: %i\n", g_time);
ptm = gmtime(&g_time);
ptm = gmtime((time_t*)&g_time);
addLogAdv(LOG_INFO, LOG_FEATURE_TUYAMCU,"ptime ->gmtime => tm_hour: %i\n",ptm->tm_hour );
addLogAdv(LOG_INFO, LOG_FEATURE_TUYAMCU,"ptime ->gmtime => tm_min: %i\n", ptm->tm_min );

View File

@@ -13,6 +13,7 @@
#include <saradc_pub.h>
#include <drv_model_pub.h>
void turnon_PA_in_temp_dect(void);
static int adcToGpio[] = {
-1, // ADC0 - VBAT

View File

@@ -26,15 +26,17 @@
typedef struct flash_vars_structure
{
// offset 0
// offset 0
unsigned short boot_count; // number of times the device has booted
unsigned short boot_success_count; // if a device boots completely (>30s), will equal boot_success_count
// offset 4
// offset 4
short savedValues[MAX_RETAIN_CHANNELS];
// offset 28
ENERGY_METERING_DATA emetering;
// offset 60
unsigned char rgb[3];
unsigned char len; // length of the whole structure (i.e. 2+2+1 = 5) MUST NOT BE 255
// size 32
// size 64
} FLASH_VARS_STRUCTURE;
extern FLASH_VARS_STRUCTURE flash_vars;
@@ -641,5 +643,42 @@ int HAL_FlashVars_GetChannelValue(int ch){
return flash_vars.savedValues[ch];
}
int HAL_GetEnergyMeterStatus(ENERGY_METERING_DATA *data)
{
#ifndef DISABLE_FLASH_VARS_VARS
if (!flash_vars_initialised)
{
flash_vars_init();
}
if (data != NULL)
{
memcpy(data, &flash_vars.emetering, sizeof(ENERGY_METERING_DATA));
}
#endif
return 0;
}
int HAL_SetEnergyMeterStatus(ENERGY_METERING_DATA *data)
{
#ifndef DISABLE_FLASH_VARS_VARS
FLASH_VARS_STRUCTURE tmp;
// mark that we have completed a boot.
if (data != NULL)
{
memcpy(&flash_vars.emetering, data, sizeof(ENERGY_METERING_DATA));
flash_vars_write();
flash_vars_read(&tmp);
}
#endif
return 0;
}
void HAL_FlashVars_SaveTotalConsumption(float total_consumption)
{
#ifndef DISABLE_FLASH_VARS_VARS
flash_vars.emetering.TotalConsumption = total_consumption;
#endif
}
#endif

View File

@@ -255,6 +255,10 @@ void HAL_ConnectToWiFi(const char* oob_ssid, const char* connect_key)
bk_wlan_start(&network_cfg);
}
void HAL_DisconnectFromWifi()
{
bk_wlan_stop(STATION);
}
int HAL_SetupWiFiOpenAccessPoint(const char* ssid)
{

View File

@@ -1,6 +1,7 @@
#ifdef PLATFORM_BL602
#include "../hal_flashConfig.h"
#include "../hal_flashVars.h"
#include "../../logging/logging.h"
#include <easyflash.h>
@@ -15,6 +16,7 @@ typedef struct bl602_bootCounts_s {
unsigned short boot_count; // number of times the device has booted
unsigned short boot_success_count; // if a device boots completely (>30s), will equal boot_success_count
short channelStates[BL602_SAVED_CHANNELS_MAX];
ENERGY_METERING_DATA emetering;
} bl602_bootCounts_t;
static bl602_bootCounts_t g_bootCounts;
@@ -105,6 +107,33 @@ int HAL_FlashVars_GetChannelValue(int ch) {
return g_bootCounts.channelStates[ch];
}
int HAL_GetEnergyMeterStatus(ENERGY_METERING_DATA *data)
{
if (data != NULL)
{
if (g_loaded==0)
{
BL602_ReadFlashVars(&g_bootCounts,sizeof(g_bootCounts));
}
memcpy(data, &g_bootCounts.emetering, sizeof(ENERGY_METERING_DATA));
}
return 0;
}
int HAL_SetEnergyMeterStatus(ENERGY_METERING_DATA *data)
{
if (data != NULL)
{
memcpy(&g_bootCounts.emetering, data, sizeof(ENERGY_METERING_DATA));
BL602_SaveFlashVars(&g_bootCounts,sizeof(g_bootCounts));
}
return 0;
}
void HAL_FlashVars_SaveTotalConsumption(float total_consumption)
{
g_bootCounts.emetering.TotalConsumption = total_consumption;
}
#endif // PLATFORM_BL602

View File

@@ -30,6 +30,12 @@ void HAL_ConnectToWiFi(const char *ssid, const char *psk)
g_bAccessPointMode = 0;
}
void HAL_DisconnectFromWifi()
{
}
int HAL_SetupWiFiOpenAccessPoint(const char *ssid) {
uint8_t hidden_ssid = 0;

View File

@@ -1,3 +1,5 @@
#ifndef __HALK_FLASH_VARS_H__
#define __HALK_FLASH_VARS_H__
//#define DISABLE_FLASH_VARS_VARS
#include "../new_common.h"
@@ -5,6 +7,18 @@
#define BOOT_COMPLETE_SECONDS 30
#define MAX_RETAIN_CHANNELS 12
/* Fixed size 32 bytes */
typedef struct ENERGY_METERING_DATA {
float TotalConsumption;
float TodayConsumpion;
float YesterdayConsumption;
long save_counter;
float ConsumptionHistory[2];
time_t ConsumptionResetTime;
unsigned char reseved[3];
char actual_mday;
} ENERGY_METERING_DATA;
// call at startup
void HAL_FlashVars_IncreaseBootCount();
// call once started (>30s?)
@@ -16,4 +30,9 @@ void HAL_FlashVars_SaveChannel(int index, int value);
void HAL_FlashVars_SaveLED(byte mode, short brightness, short temperature, byte r, byte g, byte b);
void HAL_FlashVars_ReadLED(byte *mode, short *brightness, short *temperature, byte *rgb);
int HAL_FlashVars_GetChannelValue(int ch);
int HAL_GetEnergyMeterStatus(ENERGY_METERING_DATA *data);
int HAL_SetEnergyMeterStatus(ENERGY_METERING_DATA *data);
void HAL_FlashVars_SaveTotalConsumption(float total_consumption);
#endif /* __HALK_FLASH_VARS_H__ */

View File

@@ -13,6 +13,7 @@ enum HALWifiStatus {
int HAL_SetupWiFiOpenAccessPoint(const char* ssid);
void HAL_ConnectToWiFi(const char* oob_ssid, const char* connect_key);
void HAL_DisconnectFromWifi();
void HAL_WiFi_SetupStatusCallback(void (*cb)(int code));
// This must return correct IP for both SOFT_AP and STATION modes,
// because, for example, javascript control panel requires it

View File

@@ -32,5 +32,24 @@ void HAL_FlashVars_ReadLED(byte *mode, short *brightness, short *temperature, by
}
int HAL_GetEnergyMeterStatus(ENERGY_METERING_DATA *data)
{
/* default values */
if (data != NULL)
{
memset(data, 0, sizeof(ENERGY_METERING_DATA));
data->actual_mday = -1;
}
return 0;
}
int HAL_SetEnergyMeterStatus(ENERGY_METERING_DATA *data)
{
return 0;
}
void HAL_FlashVars_SaveTotalConsumption(float total_consumption)
{
}
#endif

View File

@@ -188,6 +188,12 @@ void HAL_ConnectToWiFi(const char* oob_ssid, const char* connect_key)
connect_wifi_demo(oob_ssid, connect_key);
}
void HAL_DisconnectFromWifi()
{
}
/*1)Add sta add callback function
2)Add sta list monitor task*/
static tls_os_timer_t* sta_monitor_tim = NULL;

View File

@@ -1,6 +1,7 @@
#ifdef PLATFORM_XR809
#include "../hal_flashConfig.h"
#include "../hal_flashVars.h"
#include "../../logging/logging.h"
void HAL_FlashVars_SaveBootComplete(){
@@ -28,8 +29,25 @@ void HAL_FlashVars_ReadLED(byte *mode, short *brightness, short *temperature, by
}
int HAL_GetEnergyMeterStatus(ENERGY_METERING_DATA *data)
{
/* default values */
if (data != NULL)
{
memset(data, 0, sizeof(ENERGY_METERING_DATA));
data->actual_mday = -1;
}
return 0;
}
int HAL_SetEnergyMeterStatus(ENERGY_METERING_DATA *data)
{
return 0;
}
void HAL_FlashVars_SaveTotalConsumption(float total_consumption)
{
}
#endif // PLATFORM_XR809

View File

@@ -40,6 +40,12 @@ void HAL_ConnectToWiFi(const char *ssid, const char *psk)
//OS_Sleep(60);
printf("ok set wifii\n\r");
}
void HAL_DisconnectFromWifi()
{
}
int HAL_SetupWiFiOpenAccessPoint(const char *ssid) {
char ap_psk[8] = { 0 };
@@ -146,4 +152,4 @@ const char *HAL_GetMACStr(char *macstr) {
return macstr;
}
#endif // PLATFORM_XR809
#endif // PLATFORM_XR809

View File

@@ -35,6 +35,11 @@
#include "BkDriverFlash.h"
#endif
#if defined(PLATFORM_BK7231T) || defined(PLATFORM_BK7231N)
int tuya_os_adapt_wifi_all_ap_scan(AP_IF_S **ap_ary, unsigned int *num);
int tuya_os_adapt_wifi_release_ap(AP_IF_S *ap);
#endif
static char* UNIQUE_ID_FORMAT = " - unique_id: \"%s\"\n";
static char* HASS_INDEXED_NAME_CONFIG = " name: \"%s %i\"\n";
static char* HASS_STATE_TOPIC_CONFIG = " state_topic: \"%s/%i/get\"\n";
@@ -543,6 +548,10 @@ int http_fn_index(http_request_t* request) {
hprintf255(request, "<h5>Ping watchdog - %i lost, %i ok!</h5>",
PingWatchDog_GetTotalLost(), PingWatchDog_GetTotalReceived());
if (Main_HasWiFiConnected())
{
hprintf255(request, "<h5>Wifi RSSI: %s (%idBm)</h5>", str_rssi[wifi_rssi_scale(HAL_GetWifiStrength())], HAL_GetWifiStrength());
}
hprintf255(request, "<h5>MQTT State: %s RES: %d(%s)<br>", (Main_HasMQTTConnected() == 1) ? "connected" : "disconnected",
MQTT_GetConnectResult(), get_error_name(MQTT_GetConnectResult()));
hprintf255(request, "MQTT ErrMsg: %s <br>", (MQTT_GetStatusMessage() != NULL) ? MQTT_GetStatusMessage() : "");
@@ -554,7 +563,7 @@ int http_fn_index(http_request_t* request) {
{
for (i = 0;i < 29;i++)
{
if ((PIN_GetPinRoleForPinIndex(i) == IOR_None) && (i != 10) && (i != 11))
if ((PIN_GetPinRoleForPinIndex(i) == IOR_None) && (i != 0) && (i != 1))
{
HAL_PIN_Setup_Input(i);
}
@@ -563,11 +572,12 @@ int http_fn_index(http_request_t* request) {
hprintf255(request, "<h5> PIN States<br>");
for (i = 0;i < 29;i++)
{
if ((PIN_GetPinRoleForPinIndex(i) != IOR_None) || (i == 10) || (i == 11))
if ((PIN_GetPinRoleForPinIndex(i) != IOR_None) || (i == 0) || (i == 1))
{
hprintf255(request, "P%02i: NA ", i);
}
else {
else
{
hprintf255(request, "P%02i: %i ", i, (int)HAL_PIN_ReadDigitalInput(i));
}
if (i % 10 == 9)
@@ -578,6 +588,13 @@ int http_fn_index(http_request_t* request) {
hprintf255(request, "</h5>");
}
#if defined(PLATFORM_BK7231T) || defined(PLATFORM_BK7231N)
if (ota_progress()>=0)
{
hprintf255(request, "<h5>OTA In Progress. Status: %06lXh</h5>", ota_progress());
}
#endif
// for normal page loads, show the rest of the HTML
if (!http_getArg(request->url, "state", tmpA, sizeof(tmpA))) {
poststr(request, "</div>"); // end div#state
@@ -813,7 +830,7 @@ int http_fn_cfg_wifi(http_request_t* request) {
uint32_t num;
bk_printf("Scan begin...\r\n");
tuya_os_adapt_wifi_all_ap_scan(&ar, &num);
tuya_os_adapt_wifi_all_ap_scan(&ar, (unsigned int*)&num);
bk_printf("Scan returned %i networks\r\n", num);
for (i = 0; i < num; i++) {
hprintf255(request, "[%i/%i] SSID: %s, Channel: %i, Signal %i<br>", i + 1, (int)num, ar[i].ssid, ar[i].channel, ar[i].rssi);

View File

@@ -429,6 +429,7 @@ int hprintf255(http_request_t* request, const char* fmt, ...) {
va_list argList;
//BaseType_t taken;
char tmp[256];
memset(tmp, 0, 256);
va_start(argList, fmt);
vsnprintf(tmp, 255, fmt, argList);
va_end(argList);

View File

@@ -14,7 +14,6 @@
#define LCD_PIC_LINE_3_ADDRESS 0x14
#define LCD_PIC_LINE_4_ADDRESS 0x54
static byte PCF8574_LCD_Build_Byte(i2cDevice_PCF8574_t *lcd)
{
byte ret = 0x00;

View File

@@ -439,6 +439,7 @@ extern IRrecv IrReceiver;
class IRsend {
public:
IRsend();
virtual ~IRsend() = default;
/*
* IR_SEND_PIN is defined

View File

@@ -143,13 +143,13 @@
* TODO aNumberOfRepeats are handled not correctly if ENABLE_BEO_WITHOUT_FRAME_GAP is defined
*/
void IRsend::sendBangOlufsen(uint16_t aHeader, uint8_t aData, int_fast8_t aNumberOfRepeats, int8_t aNumberOfHeaderBits) {
for (uint_fast8_t i = 0; i < aNumberOfRepeats + 1; ++i) {
for (uint_fast8_t i = 0; i < (uint_fast8_t)aNumberOfRepeats + 1; ++i) {
sendBangOlufsenRaw((uint32_t(aHeader) << 8) | aData, aNumberOfHeaderBits + 8, i != 0);
}
}
void IRsend::sendBangOlufsenDataLink(uint32_t aHeader, uint8_t aData, int_fast8_t aNumberOfRepeats, int8_t aNumberOfHeaderBits) {
for (uint_fast8_t i = 0; i < aNumberOfRepeats + 1; ++i) {
for (uint_fast8_t i = 0; i < (uint_fast8_t)aNumberOfRepeats + 1; ++i) {
sendBangOlufsenRawDataLink((uint64_t(aHeader) << 8) | aData, aNumberOfHeaderBits + 8, i != 0, true);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -549,4 +549,4 @@ void CFG_InitAndLoad() {
}
g_configInitialized = 1;
CFG_Save_IfThereArePendingChanges();
}
}

View File

@@ -74,7 +74,6 @@ void CFG_SetButtonLongPressTime(int value);
void CFG_SetButtonShortPressTime(int value);
void CFG_SetButtonRepeatPressTime(int value);
#endif

View File

@@ -1,5 +1,7 @@
#include "new_common.h"
const char *str_rssi[] = { "N/A", "Weak", "Fair", "Good", "Excellent" };
// Why strdup breaks strings?
// backlog lcd_clearAndGoto I2C1 0x23 1 1; lcd_print I2C1 0x23 Enabled
// it got broken around 64 char
@@ -144,3 +146,22 @@ void urldecode2_safe(char *dst, const char *srcin, int maxDstLen)
*dst++ = '\0';
}
WIFI_RSSI_LEVEL wifi_rssi_scale(int8_t rssi_value)
{
#define LEVEL_WEAK -70 //-70
#define LEVEL_FAIR -60 //-60
#define LEVEL_GOOD -50 //-50
WIFI_RSSI_LEVEL retVal = NOT_CONNECTED;
if (rssi_value <= LEVEL_WEAK)
retVal = WEAK;
else if ((rssi_value <= LEVEL_FAIR) && (rssi_value > LEVEL_WEAK))
retVal = FAIR;
else if ((rssi_value <= LEVEL_GOOD) && (rssi_value > LEVEL_FAIR))
retVal = GOOD;
else if (rssi_value > LEVEL_GOOD)
retVal = EXCELLENT;
return retVal;
}

View File

@@ -161,8 +161,6 @@ OSStatus rtos_create_thread( beken_thread_t* thread,
beken_thread_function_t function,
uint32_t stack_size, beken_thread_arg_t arg );
#include "common/framework/platform_init.h"
#include "kernel/os/os.h"
@@ -223,13 +221,13 @@ OSStatus rtos_create_thread( beken_thread_t* thread,
#define printf addLog
void delay_ms(UINT32 ms_count);
#endif
typedef unsigned char byte;
#endif
#if PLATFORM_XR809
#define LWIP_COMPAT_SOCKETS 1
@@ -290,6 +288,7 @@ void Main_OnPingCheckerReply(int ms);
// new_ping.c
void Main_SetupPingWatchDog(const char *target/*, int delayBetweenPings_Seconds*/);
void Main_PingWatchDogSilent();
int PingWatchDog_GetTotalLost();
int PingWatchDog_GetTotalReceived();
@@ -301,3 +300,18 @@ int LWIP_GetActiveSockets();
// linear mapping function --> https://www.arduino.cc/reference/en/language/functions/math/map/
#define MAP(x, in_min, in_max, out_min, out_max) (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
typedef enum
{
NOT_CONNECTED,
WEAK,
FAIR,
GOOD,
EXCELLENT,
} WIFI_RSSI_LEVEL;
WIFI_RSSI_LEVEL wifi_rssi_scale(int8_t rssi_value);
extern const char *str_rssi[];
#endif /* __NEW_COMMON_H__ */

View File

@@ -57,7 +57,10 @@ static struct raw_pcb *ping_pcb;
static unsigned int ping_lost = 0;
static unsigned int ping_received = 0;
static int bReceivedLastOneSend = -1;
//static int g_delayBetweenPings_MS = 1000;
static bool ping_handler_active = false;
static bool ping_handler_silent = false;
//static int g_delayBetweenPings_MS = 1000 / portTICK_PERIOD_MS;
static void ping_prepare_echo( struct icmp_echo_hdr *iecho, u16_t len)
{
@@ -101,6 +104,7 @@ static void ping_send(struct raw_pcb *raw, const ip_addr_t *addr)
if(bReceivedLastOneSend == 0) {
//addLogAdv(LOG_INFO,LOG_FEATURE_MAIN,"Ping lost: (total lost %i, recv %i)\r\n",ping_lost,ping_received);
ping_lost++;
}
bReceivedLastOneSend = 0;
@@ -116,11 +120,13 @@ static void ping_timeout(void *arg)
{
struct raw_pcb *pcb = (struct raw_pcb*)arg;
LWIP_ASSERT("ping_timeout: no pcb given!", pcb != NULL);
if (ping_handler_silent == false)
{
LWIP_ASSERT("ping_timeout: no pcb given!", pcb != NULL);
ping_send(pcb, &ping_target);
// void sys_timeout (u32_t msecs, sys_timeout_handler handler, void *arg)
ping_send(pcb, &ping_target);
}
// void sys_timeout (u32_t msecs, sys_timeout_handler handler, void *arg)
sys_timeout(PING_DELAY, ping_timeout, pcb);
}
@@ -166,20 +172,32 @@ int PingWatchDog_GetTotalLost() {
int PingWatchDog_GetTotalReceived() {
return ping_received;
}
void Main_SetupPingWatchDog(const char *target/*, int delayBetweenPings_Seconds*/) {
void Main_SetupPingWatchDog(const char *target/*, int delayBetweenPings_Seconds*/)
{
// none sent yet.
bReceivedLastOneSend = -1;
//g_delayBetweenPings_MS = delayBetweenPings_Seconds * 1000;
///ipaddr_aton("192.168.0.1",&ping_target)
//ipaddr_aton("8.8.8.8",&ping_target);
ipaddr_aton(target,&ping_target);
if (ping_handler_active == false)
{
//g_delayBetweenPings_MS = delayBetweenPings_Seconds * 1000;
///ipaddr_aton("192.168.0.1",&ping_target)
//ipaddr_aton("8.8.8.8",&ping_target);
ipaddr_aton(target,&ping_target);
ping_pcb = raw_new(IP_PROTO_ICMP);
LWIP_ASSERT("ping_pcb != NULL", ping_pcb != NULL);
ping_pcb = raw_new(IP_PROTO_ICMP);
LWIP_ASSERT("ping_pcb != NULL", ping_pcb != NULL);
raw_recv(ping_pcb, ping_recv, NULL);
raw_bind(ping_pcb, IP_ADDR_ANY);
// void sys_timeout (u32_t msecs, sys_timeout_handler handler, void *arg)
sys_timeout(PING_DELAY, ping_timeout, ping_pcb);
}
ping_handler_active = true;
ping_handler_silent = false;
raw_recv(ping_pcb, ping_recv, NULL);
raw_bind(ping_pcb, IP_ADDR_ANY);
// void sys_timeout (u32_t msecs, sys_timeout_handler handler, void *arg)
sys_timeout(PING_DELAY, ping_timeout, ping_pcb);
}
void Main_PingWatchDogSilent()
{
ping_handler_silent = true;
}

View File

@@ -258,7 +258,7 @@ static uint8_t PIN_ReadDigitalInputValue_WithInversionIncluded(int index) {
// support inverted button
if(BTN_ShouldInvert(index)) {
return !iVal;
return (iVal==0) ? 1 : 0;
}
return iVal;
}
@@ -446,7 +446,7 @@ void PIN_SetPinRoleForPinIndex(int index, int role) {
{
case IOR_Button:
case IOR_Button_n:
case IOR_Button_ToggleAll:
case IOR_Button_ToggleAll:
case IOR_Button_ToggleAll_n:
case IOR_Button_NextColor:
case IOR_Button_NextColor_n:
@@ -459,7 +459,7 @@ void PIN_SetPinRoleForPinIndex(int index, int role) {
HAL_PIN_Setup_Input_Pullup(index);
// init button after initializing pin role
NEW_button_init(bt, button_generic_get_gpio_value, 0);
NEW_button_init(bt, button_generic_get_gpio_value, 1);
}
break;
case IOR_ToggleChannelOnToggle:

View File

@@ -159,6 +159,13 @@ typedef struct cfgPowerMeasurementCalibration_s {
#define CFG_DEFAULT_BTN_LONG 10
#define CFG_DEFAULT_BTN_REPEAT 5
enum {
CFG_OBK_VOLTAGE = 0,
CFG_OBK_CURRENT,
CFG_OBK_POWER,
CFG_OBK_POWER_MAX
};
//
// Main config structure (less than 2KB)
//

View File

@@ -7,10 +7,12 @@
//#include "flash.h"
#include "../logging/logging.h"
#include "../httpclient/http_client.h"
#include "../driver/drv_public.h"
static unsigned char *sector = (void *)0;
int sectorlen = 0;
unsigned int addr = 0xff000;
int ota_status = -1;
#define SECTOR_SIZE 0x1000
static void store_sector(unsigned int addr, unsigned char *data);
extern void flash_protection_op(UINT8 mode,PROTECT_TYPE type);
@@ -97,6 +99,7 @@ static void store_sector(unsigned int addr, unsigned char *data){
flash_ctrl(CMD_FLASH_ERASE_SECTOR, &addr);
flash_ctrl(CMD_FLASH_WRITE_ENABLE, (void *)0);
flash_write((char *)data , SECTOR_SIZE, addr);
ota_status += SECTOR_SIZE;
}
@@ -127,6 +130,7 @@ int myhttpclientcallback(httprequest_t* request){
break;
case 2: // ended, write any remaining bytes to the sector
close_ota();
ota_status = -1;
addLogAdv(LOG_INFO, LOG_FEATURE_OTA,"\r\nmyhttpclientcallback state %d total %d/%d\r\n", request->state, total_bytes, request->client_data.response_content_len);
addLogAdv(LOG_INFO, LOG_FEATURE_OTA,"Rebooting in 1 seconds...");
@@ -135,7 +139,10 @@ int myhttpclientcallback(httprequest_t* request){
CFG_IncrementOTACount();
// make sure it's saved before reboot
CFG_Save_IfThereArePendingChanges();
if (DRV_IsMeasuringPower())
{
BL09XX_SaveEmeteringStatistics();
}
rtos_delay_milliseconds(1000);
bk_reboot();
break;
@@ -197,5 +204,11 @@ void otarequest(const char *urlin){
request->method = HTTPCLIENT_GET;
request->timeout = 10000;
HTTPClient_Async_SendGeneric(request);
ota_status = 0;
}
int ota_progress()
{
return ota_status;
}

View File

@@ -1,4 +1,5 @@
#ifndef __OTA_H__
#define __OTA_H__
// NOTE: this offset was taken from BkDriverFlash.c
// search for BK_PARTITION_OTA
@@ -22,3 +23,8 @@ void add_otadata(unsigned char *data, int len);
void close_ota();
void otarequest(const char *urlin);
int ota_progress();
#endif /* __OTA_H__ */

View File

@@ -34,6 +34,10 @@
#include "driver/drv_ntp.h"
#ifdef PLATFORM_BEKEN
void bg_register_irda_check_func(FUNCPTR func);
#endif
static int g_secondsElapsed = 0;
// open access point after this number of seconds
static int g_openAP = 0;
@@ -139,8 +143,16 @@ void Main_OnWiFiStatusChange(int code)
break;
case WIFI_STA_DISCONNECTED:
// try to connect again in few seconds
if (g_bHasWiFiConnected != 0)
{
HAL_DisconnectFromWifi();
Main_PingWatchDogSilent();
}
g_connectToWiFi = 15;
g_bHasWiFiConnected = 0;
g_timeSinceLastPingReply = -1;
g_bPingWatchDogStarted = 0;
g_startPingWatchDogAfter = 0;
ADDLOGF_INFO("Main_OnWiFiStatusChange - WIFI_STA_DISCONNECTED\r\n");
break;
case WIFI_STA_AUTH_FAILED:
@@ -223,11 +235,19 @@ void Main_OnEverySecond()
if(g_timeSinceLastPingReply != -1 && g_secondsElapsed > 60)
{
g_timeSinceLastPingReply++;
if(g_timeSinceLastPingReply == CFG_GetPingDisconnectedSecondsToRestart())
if(g_timeSinceLastPingReply >= CFG_GetPingDisconnectedSecondsToRestart())
{
ADDLOGF_INFO("[Ping watchdog] No ping replies within %i seconds. Will try to reconnect.\n",g_timeSinceLastPingReply);
g_bHasWiFiConnected = 0;
g_connectToWiFi = 10;
if (g_bHasWiFiConnected != 0)
{
ADDLOGF_INFO("[Ping watchdog] No ping replies within %i seconds. Will try to reconnect.\n",g_timeSinceLastPingReply);
HAL_DisconnectFromWifi();
g_bHasWiFiConnected = 0;
g_connectToWiFi = 10;
g_timeSinceLastPingReply = -1;
g_bPingWatchDogStarted = 0;
g_startPingWatchDogAfter = 0;
Main_PingWatchDogSilent();
}
}
}
@@ -321,7 +341,7 @@ void Main_OnEverySecond()
if(0==g_startPingWatchDogAfter)
{
const char *pingTargetServer;
///int pingInterval;
//int pingInterval;
int restartAfterNoPingsSeconds;
g_bPingWatchDogStarted = 1;
@@ -330,14 +350,13 @@ void Main_OnEverySecond()
//pingInterval = CFG_GetPingIntervalSeconds();
restartAfterNoPingsSeconds = CFG_GetPingDisconnectedSecondsToRestart();
if(*pingTargetServer /* && pingInterval > 0*/ && restartAfterNoPingsSeconds > 0)
if((pingTargetServer != NULL) && (strlen(pingTargetServer)>0) &&
/*(pingInterval > 0) && */ (restartAfterNoPingsSeconds > 0))
{
// mark as enabled
g_timeSinceLastPingReply = 0;
//Main_SetupPingWatchDog(pingTargetServer,pingInterval);
Main_SetupPingWatchDog(pingTargetServer
/*,1*/
);
Main_SetupPingWatchDog(pingTargetServer);
} else {
// mark as disabled
g_timeSinceLastPingReply = -1;
@@ -378,6 +397,12 @@ void Main_OnEverySecond()
if (!g_reset){
// ensure any config changes are saved before reboot.
CFG_Save_IfThereArePendingChanges();
#ifndef OBK_DISABLE_ALL_DRIVERS
if (DRV_IsMeasuringPower())
{
BL09XX_SaveEmeteringStatistics();
}
#endif
ADDLOGF_INFO("Going to call HAL_RebootModule\r\n");
HAL_RebootModule();
} else {
@@ -526,6 +551,10 @@ void Main_Init()
// but DON't run autoexec if we have had 2+ boot failures
CMD_Init();
/* Automatic disable of PIN MONITOR after reboot */
if (CFG_HasFlag(OBK_FLAG_HTTP_PINMONITOR))
CFG_SetFlag(OBK_FLAG_HTTP_PINMONITOR, false);
// autostart drivers
if(PIN_FindPinIndexForRole(IOR_SM2135_CLK,-1) != -1 && PIN_FindPinIndexForRole(IOR_SM2135_DAT,-1) != -1)
{