mac save&AC swmode fixes, sha256 sign for cmd tst

This commit is contained in:
Климов Андрей Николаевич
2023-07-16 20:29:59 +03:00
parent eb68556012
commit 3907158437
11 changed files with 143 additions and 41 deletions

View File

@@ -30,7 +30,7 @@ bool systemConfig::isValidSysConf()
stream->close(); stream->close();
return false; return false;
} }
stream->close(); stream->close();
return true; return true;
}; };
@@ -44,7 +44,7 @@ bool systemConfig::isValidSysConf()
bool isMacValid = false; bool isMacValid = false;
for (short i = 0; i < 6; i++) { for (short i = 0; i < 6; i++) {
mac[i] = stream->read(); mac[i] = stream->read();
if (mac[i] != 0 && mac[i] != 0xff) isMacValid = true; if ((mac[i] != 0) && (mac[i] != 0xff)) isMacValid = true;
} }
stream->close(); stream->close();
return isMacValid; return isMacValid;
@@ -53,7 +53,7 @@ bool systemConfig::isValidSysConf()
bool systemConfig::setMAC(macAddress& _mac) bool systemConfig::setMAC(macAddress& _mac)
{ {
if (!stream || !isValidSysConf()) return false; if (!stream || !isValidSysConf()) return false;
openStream('a'); openStream('r'); //was 'a'
stream->seek(offsetof(systemConfigData,mac)); stream->seek(offsetof(systemConfigData,mac));
stream->write ((const uint8_t *)&_mac,sizeof(_mac)); stream->write ((const uint8_t *)&_mac,sizeof(_mac));
memcpy(mac, _mac, sizeof(mac)); memcpy(mac, _mac, sizeof(mac));

View File

@@ -23,30 +23,13 @@
#if defined(__SAM3X8E__) #if defined(__SAM3X8E__)
#include <DueFlashStorage.h> #include <DueFlashStorage.h>
extern DueFlashStorage EEPROM;
#endif
#ifdef NRF5
#include <NRFFlashStorage.h> //STUB
extern NRFFlashStorage EEPROM;
#endif
//#ifdef ARDUINO_ARCH_STM32
//#include <NRFFlashStorage.h> //STUB
//extern NRFFlashStorage EEPROM;
// static char samBuffer[64];
// short samBufferPos = 0;
//#endif
#if defined(__SAM3X8E__)
DueFlashStorage EEPROM; DueFlashStorage EEPROM;
static char samBuffer[64]; static char samBuffer[64];
short samBufferPos = 0; short samBufferPos = 0;
#endif #endif
#ifdef NRF5 #ifdef NRF5
#include <NRFFlashStorage.h> //STUB
NRFFlashStorage EEPROM; NRFFlashStorage EEPROM;
#endif #endif
@@ -200,8 +183,10 @@ NRFFlashStorage EEPROM;
//eeprom_buffer_flush(); //eeprom_buffer_flush();
#endif #endif
pos=min(_pos, streamSize); pos=min(_pos, streamSize);
//debugSerial<<F("Seek:")<<pos<<endl; //Serial.print("StartPos=");Serial.println(startPos);
//Serial.print("Pos=");Serial.println(pos);
//Serial.print("streamSize=");Serial.println(streamSize);
return pos; return pos;
}; };

View File

@@ -26,6 +26,7 @@ e-mail anklimov@gmail.com
#include "main.h" #include "main.h"
#include "bright.h" #include "bright.h"
#include "itemCmd.h" #include "itemCmd.h"
//#include "SHA256.h"
#ifdef _dmxout #ifdef _dmxout
#include "dmx.h" #include "dmx.h"
@@ -597,6 +598,17 @@ if (suffixCode == S_RAW)
return Ctrl(ic,subItem); return Ctrl(ic,subItem);
} }
//debugSerial<<F("SuffixCode: ")<<suffixCode<<endl; //debugSerial<<F("SuffixCode: ")<<suffixCode<<endl;
bool authorized = false;
char * authPos = strchr(payload,'@');
if (authPos)
{
*authPos=0;
//char * authToken=payload;
authorized = checkToken(payload,authPos+1);
payload=authPos+1;
}
int i=0; int i=0;
while (payload[i]) {payload[i]=toupper(payload[i]);i++;}; while (payload[i]) {payload[i]=toupper(payload[i]);i++;};
@@ -660,7 +672,7 @@ st.setSuffix(suffixCode);
} }
} }
return Ctrl(st,subItem); return Ctrl(st,subItem,true,authorized);
} //Void command } //Void command
break; break;
@@ -824,7 +836,7 @@ int Item::scheduleCommand(itemCmd cmd)
// -3 ignored // -3 ignored
// -1 system error // -1 system error
// -4 invalid argument // -4 invalid argument
int Item::Ctrl(itemCmd cmd, char* subItem, bool allowRecursion) int Item::Ctrl(itemCmd cmd, char* subItem, bool allowRecursion, bool authorized)
{ {
int fr = freeRam(); int fr = freeRam();
if (fr < minimalMemory) if (fr < minimalMemory)
@@ -945,6 +957,8 @@ int Item::Ctrl(itemCmd cmd, char* subItem, bool allowRecursion)
} }
break; break;
case CMD_TOGGLE: case CMD_TOGGLE:
if (suffixCode != S_CTRL)
{
chActive=(isActive()>0); chActive=(isActive()>0);
toExecute=true; toExecute=true;
@@ -955,6 +969,13 @@ int Item::Ctrl(itemCmd cmd, char* subItem, bool allowRecursion)
cmd.Cmd(CMD_ON); cmd.Cmd(CMD_ON);
} }
status2Send |=FLAG_COMMAND | FLAG_SEND_IMMEDIATE; status2Send |=FLAG_COMMAND | FLAG_SEND_IMMEDIATE;
}
else
{
if (getFlag(FLAG_DISABLED)) clearFlag(FLAG_DISABLED); else setFlag(FLAG_DISABLED);
status2Send |= FLAG_FLAGS | FLAG_SEND_IMMEDIATE;
res=1;
}
break; break;
@@ -1127,7 +1148,7 @@ int Item::Ctrl(itemCmd cmd, char* subItem, bool allowRecursion)
else // Fast track for commands to subitems else // Fast track for commands to subitems
{ {
if (driver) return driver->Ctrl(cmd,subItem,toExecute); if (driver) return driver->Ctrl(cmd,subItem,toExecute);
return 0; ///// return 0;
} }
} }

View File

@@ -119,7 +119,7 @@ class Item
boolean Setup(); boolean Setup();
void Stop(); void Stop();
//int Ctrl(short cmd, short n=0, int * Parameters=NULL, int suffixCode=0, char* subItem=NULL); //int Ctrl(short cmd, short n=0, int * Parameters=NULL, int suffixCode=0, char* subItem=NULL);
int Ctrl(itemCmd cmd, char* subItem=NULL, bool allowRecursion = true); int Ctrl(itemCmd cmd, char* subItem=NULL, bool allowRecursion = true, bool authorized=false);
int Ctrl(char * payload, char * subItem=NULL); int Ctrl(char * payload, char * subItem=NULL);
int getArg(short n=0); int getArg(short n=0);

View File

@@ -46,8 +46,8 @@ const cmdstr commands_P[] PROGMEM =
#define CMD_ENABLE 0xa /// for PID regulator and XON/XOFF - chan limitation #define CMD_ENABLE 0xa /// for PID regulator and XON/XOFF - chan limitation
#define CMD_DISABLE 0xb /// for PID regulator #define CMD_DISABLE 0xb /// for PID regulator
#define CMD_UNFREEZE 0xc /// Aliase for ON #define CMD_UNFREEZE 0xc ///
#define CMD_FREEZE 0xd /// Aliase for OFF #define CMD_FREEZE 0xd ///
#define CMD_AUTO 0xe /// Thermostat/AC set to Auto mode #define CMD_AUTO 0xe /// Thermostat/AC set to Auto mode
#define CMD_FAN 0xf /// AC set to Fan-only mode #define CMD_FAN 0xf /// AC set to Fan-only mode

View File

@@ -27,6 +27,9 @@ e-mail anklimov@gmail.com
#include "TimerInterrupt_Generic.h" #include "TimerInterrupt_Generic.h"
#endif #endif
#ifdef CRYPT
#include "RNG.h"
#endif
#ifdef SYSLOG_ENABLE #ifdef SYSLOG_ENABLE
#include <Syslog.h> #include <Syslog.h>
@@ -132,6 +135,7 @@ volatile uint32_t timerSensorCheck =0;
volatile unsigned long timerCount=0; volatile unsigned long timerCount=0;
volatile int16_t timerNumber=-1; volatile int16_t timerNumber=-1;
volatile int8_t timerHandlerBusy=0; volatile int8_t timerHandlerBusy=0;
volatile uint32_t cryptoSalt=0;
aJsonObject *pollingItem = NULL; aJsonObject *pollingItem = NULL;
@@ -681,6 +685,12 @@ lan_status lanLoop() {
onMQTTConnect(); onMQTTConnect();
#ifdef CRYPT
//setTopic(buf,sizeof(buf),T_OUT);
strncpy(buf, "+/+/$salt", sizeof(buf)); // Only on separated cmd/val topics
mqttClient.subscribe(buf);
#endif
lanStatus = OPERATION;//3; lanStatus = OPERATION;//3;
infoSerial<<F("Accepting commands...\n"); infoSerial<<F("Accepting commands...\n");
} }
@@ -839,6 +849,16 @@ void onMQTTConnect(){
strncpy_P(buf, statsval_P, sizeof(buf)-1); strncpy_P(buf, statsval_P, sizeof(buf)-1);
mqttClient.publish(topic,buf,true); mqttClient.publish(topic,buf,true);
#ifdef CRYPT
RNG.rand((uint8_t *) &cryptoSalt,sizeof(cryptoSalt));
setTopic(topic,sizeof(topic),T_DEV);
//strncat_P(topic, stats_P, sizeof(topic)-1);
//strncat(topic, "/", sizeof(topic));
strncat_P(topic, salt_P, sizeof(topic)-1);
printUlongValueToStr(buf, cryptoSalt);
mqttClient.publish(topic,buf,true);
#endif
#ifndef NO_HOMIE #ifndef NO_HOMIE
// strncpy_P(topic, outprefix, sizeof(topic)); // strncpy_P(topic, outprefix, sizeof(topic));
@@ -1510,7 +1530,7 @@ int loadConfigFromEEPROM()
#endif #endif
if (sysConfStream.peek() == '{') { if (sysConfStream.peek() == '{') {
debugSerial<<F("Trying Load from EEPROM")<<endl; debugSerial<<F("JSON detected")<<endl;
aJsonStream as = aJsonStream(&sysConfStream); aJsonStream as = aJsonStream(&sysConfStream);
cleanConf(); cleanConf();
root = aJson.parse(&as); root = aJson.parse(&as);
@@ -2178,17 +2198,18 @@ void setup_main() {
debugSerialPort.println(F("No valid EEPROM data. Initializing.")); debugSerialPort.println(F("No valid EEPROM data. Initializing."));
#endif #endif
sysConf.clear(); sysConf.clear();
} }
else debugSerialPort << F("EEPROM signature ok")<<endl;
// scan_i2c_bus(); // scan_i2c_bus();
serialDebugLevel=sysConf.getSerialDebuglevel(); serialDebugLevel=sysConf.getSerialDebuglevel();
udpDebugLevel=sysConf.getUdpDebuglevel(); udpDebugLevel=sysConf.getUdpDebuglevel();
#if defined(__SAM3X8E__) #if defined(__SAM3X8E__)
memset(&UniqueID,0,sizeof(UniqueID)); memset(&UniqueID,0,sizeof(UniqueID));
#endif #endif
#if defined(M5STACK) #if defined(M5STACK)
// Initialize the M5Stack object // Initialize the M5Stack object
M5.begin(); M5.begin();
#endif #endif
@@ -2200,7 +2221,9 @@ void setup_main() {
#ifdef SD_CARD_INSERTED #ifdef SD_CARD_INSERTED
sd_card_w5100_setup(); sd_card_w5100_setup();
#endif #endif
setupMacAddress(); // Serial.print("Sig4=");
// Serial.println(FLASH_START[0],HEX);
setupMacAddress(); //тут почему-то не считывается из флэш
#ifdef _modbus #ifdef _modbus
#ifdef CONTROLLINO #ifdef CONTROLLINO
@@ -2254,8 +2277,8 @@ WiFi.onEvent(WiFiEvent);
infoSerial<<F("Use W5500 pin: "); infoSerial<<F("Use W5500 pin: ");
infoSerial<<QUOTE(W5500_CS_PIN)<<endl; infoSerial<<QUOTE(W5500_CS_PIN)<<endl;
#endif #endif
loadConfigFromEEPROM(); loadConfigFromEEPROM();
} }
void printFirmwareVersionAndBuildOptions() { void printFirmwareVersionAndBuildOptions() {
@@ -2485,10 +2508,21 @@ void publishStat(){
strncat_P(topic, state_P, sizeof(topic)-1); strncat_P(topic, state_P, sizeof(topic)-1);
strncpy_P(intbuf, ready_P, sizeof(intbuf)-1); strncpy_P(intbuf, ready_P, sizeof(intbuf)-1);
mqttClient.publish(topic,intbuf,true); mqttClient.publish(topic,intbuf,true);
#ifdef CRYPT
RNG.rand((uint8_t *) &cryptoSalt,sizeof(cryptoSalt));
setTopic(topic,sizeof(topic),T_DEV);
//strncat_P(topic, stats_P, sizeof(topic)-1);
//strncat(topic, "/", sizeof(topic));
strncat_P(topic, salt_P, sizeof(topic)-1);
printUlongValueToStr(intbuf, cryptoSalt);
mqttClient.publish(topic,intbuf,true);
#endif
} }
void setupMacAddress() { void setupMacAddress() {
//Check MAC, stored in NVRAM //Check MAC, stored in NVRAM
if (!sysConf.getMAC()) { if (!sysConf.getMAC()) {
infoSerial<<F("No MAC configured: set firmware's MAC\n"); infoSerial<<F("No MAC configured: set firmware's MAC\n");

View File

@@ -124,7 +124,7 @@ void out_AC::InsertData(byte data[], size_t size){
publishTopic(item->itemArr->name, "OFF","/compressor"); publishTopic(item->itemArr->name, "OFF","/compressor");
publishTopic(item->itemArr->name, (long) swing,"/swing"); //publishTopic(item->itemArr->name, (long) swing,"/swing");
//publishTopic(item->itemArr->name, (long) fan_spd,"/fan"); //publishTopic(item->itemArr->name, (long) fan_spd,"/fan");
///////////////////////////////// /////////////////////////////////

View File

@@ -3,6 +3,7 @@
const char state_P[] PROGMEM = "$state"; const char state_P[] PROGMEM = "$state";
const char disconnected_P[] PROGMEM = "disconnected"; const char disconnected_P[] PROGMEM = "disconnected";
const char ready_P[] PROGMEM = "ready"; const char ready_P[] PROGMEM = "ready";
const char salt_P[] PROGMEM = "$salt";
const char homie_P[] PROGMEM = "$homie"; const char homie_P[] PROGMEM = "$homie";
const char homiever_P[] PROGMEM = "3.0.1"; const char homiever_P[] PROGMEM = "3.0.1";

View File

@@ -28,6 +28,10 @@ e-mail anklimov@gmail.com
#include <PubSubClient.h> #include <PubSubClient.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#ifdef CRYPT
#include "SHA256.h"
#endif
#ifndef debugSerialPort #ifndef debugSerialPort
#define debugSerialPort Serial #define debugSerialPort Serial
#endif #endif
@@ -324,8 +328,8 @@ Awesome work Mark T!*/
__attribute__ ((section (".ramfunc"))) __attribute__ ((section (".ramfunc")))
// #pragma optimize("", off)
void ReadUniqueID( uint32_t * pdwUniqueID ) uint32_t ReadUniqueID( uint32_t * pdwUniqueID )
{ {
unsigned int status ; unsigned int status ;
@@ -354,8 +358,14 @@ void ReadUniqueID( uint32_t * pdwUniqueID )
{ {
status = EFC1->EEFC_FSR ; status = EFC1->EEFC_FSR ;
} while ( (status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY ) ; } while ( (status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY ) ;
return *(uint32_t *)(IFLASH1_ADDR + 128); // dont remove: SAM defect workaround - MPU dont leave Unique Identifier mode until read flash out UID of range
#endif #endif
} }
//#pragma optimize("", on)
int _inet_aton(const char* aIPAddrString, IPAddress& aResult) int _inet_aton(const char* aIPAddrString, IPAddress& aResult)
@@ -804,7 +814,55 @@ bool getPinVal(uint8_t pin)
{ {
return (0!=(*portOutputRegister( digitalPinToPort(pin) ) & digitalPinToBitMask(pin))); return (0!=(*portOutputRegister( digitalPinToPort(pin) ) & digitalPinToBitMask(pin)));
} }
#ifdef CRYPT
#define HASH_SIZE 32
SHA256 sha256;
extern uint32_t cryptoSalt;
//extern
const char cryptoKey[] ="12345678";
bool checkToken(char * token, char * data)
{
// Make valid random salted data
char saltStr[32];
printUlongValueToStr(saltStr, cryptoSalt);
// get hash
uint8_t result[HASH_SIZE];
memset(result, 0xAA, sizeof(result));
sha256.reset();
sha256.update(saltStr,strlen(saltStr));
sha256.update(cryptoKey,strlen(cryptoKey));
if (data) sha256.update(data,strlen(data));
sha256.finalize(result,sizeof(result));
sha256.clear();
//hmac<SHA256>(result, HASH_SIZE, cryptoKey, strlen(cryptoKey), testData, strlen(testData));
//for (int i=0;i<HASH_SIZE;i++) {if(result[i]<0x10) debugSerial.print('0'); debugSerial.print(result[i],HEX);}
//debugSerial.println();
for (unsigned int i=0;i<strlen(token)/2;i++)
{
uint8_t digit = ((((token[i*2] <= '9') ? token[i*2] - '0' : (token[i*2] & 0x7) + 9) << 4) +
((token[i*2+1] <= '9') ? token[i*2+1] - '0' : (token[i*2+1] & 0x7) + 9));
//debugSerial.print(digit,HEX);
if (digit!=result[i])
{
debugSerial.println(F("signature Failed"));
return false;
}
}
debugSerial.println(F("signature Passed"));
return true;
}
#else
bool checkToken(char * token, char * data)
{return true;}
#endif
#pragma message(VAR_NAME_VALUE(debugSerial)) #pragma message(VAR_NAME_VALUE(debugSerial))
#pragma message(VAR_NAME_VALUE(SERIAL_BAUD)) #pragma message(VAR_NAME_VALUE(SERIAL_BAUD))

View File

@@ -59,7 +59,7 @@ unsigned long freeRam ();
void parseBytes(const char* str, char separator, byte* bytes, int maxBytes, int base); void parseBytes(const char* str, char separator, byte* bytes, int maxBytes, int base);
int log(const char *str, ...); int log(const char *str, ...);
void printFloatValueToStr(char *valstr, float value); void printFloatValueToStr(char *valstr, float value);
void ReadUniqueID( uint32_t * pdwUniqueID ); uint32_t ReadUniqueID( uint32_t * pdwUniqueID );
int _inet_aton(const char* aIPAddrString, IPAddress& aResult); int _inet_aton(const char* aIPAddrString, IPAddress& aResult);
char *_inet_ntoa_r(IPAddress addr, char *buf, int buflen); char *_inet_ntoa_r(IPAddress addr, char *buf, int buflen);
void printIPAddress(IPAddress ipAddress); void printIPAddress(IPAddress ipAddress);
@@ -77,3 +77,4 @@ serialParamType str2SerialParam(char * str);
String toString(const IPAddress& address); String toString(const IPAddress& address);
bool getPinVal(uint8_t pin); bool getPinVal(uint8_t pin);
int str2regSize(char * str); int str2regSize(char * str);
bool checkToken(char * token, char * data);

View File

@@ -325,6 +325,7 @@ lib_deps =
br3ttb/PID@^1.2.1 br3ttb/PID@^1.2.1
ArduinoMDNS ArduinoMDNS
https://github.com/khoih-prog/TimerInterrupt_Generic.git https://github.com/khoih-prog/TimerInterrupt_Generic.git
rweather/Crypto
monitor_speed = 115200 monitor_speed = 115200
[env:mega2560slim-5100] [env:mega2560slim-5100]
@@ -460,6 +461,7 @@ lib_deps =
br3ttb/PID@^1.2.1 br3ttb/PID@^1.2.1
ArduinoMDNS ArduinoMDNS
https://github.com/khoih-prog/TimerInterrupt_Generic.git https://github.com/khoih-prog/TimerInterrupt_Generic.git
rweather/Crypto
monitor_speed = 115200 monitor_speed = 115200
@@ -713,7 +715,7 @@ lib_deps =
ArduinoMDNS ArduinoMDNS
https://github.com/khoih-prog/TimerInterrupt_Generic.git https://github.com/khoih-prog/TimerInterrupt_Generic.git
https://github.com/rlogiacco/CircularBuffer https://github.com/rlogiacco/CircularBuffer
rweather/Crypto
monitor_speed = 115200 monitor_speed = 115200
[env:controllino] [env:controllino]