Added {} to control structures for clarity (#600)

This commit is contained in:
Thomas Mørch
2016-10-16 12:46:42 +02:00
committed by Olivier
parent 80659ddb00
commit 54776a4520
34 changed files with 740 additions and 406 deletions
+4 -3
View File
@@ -6,7 +6,7 @@
* network topology allowing messages to be routed to nodes.
*
* Created by Tomas Hozza <thozza@gmail.com>
* Copyright (C) 2015 Tomas Hozza
* Copyright (C) 2015 Tomas Hozza
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
@@ -135,7 +135,7 @@ bool gatewayTransportInit() {
_w5100_spi_en(false);
return false;
}
#endif
#endif
MY_SERIALDEVICE.print(F("IP: "));
MY_SERIALDEVICE.println(Ethernet.localIP());
// give the Ethernet interface a second to initialize
@@ -437,8 +437,9 @@ void gatewayTransportRenewIP()
unsigned long now = hwMillis();
// http://playground.arduino.cc/Code/TimingRollover
if ((long)(now - next_time) < 0)
if ((long)(now - next_time) < 0) {
return;
}
if (Ethernet.maintain() & ~(0x06)) {
debug(PSTR("IP was not renewed correctly\n"));
/* Error occured -> IP was not renewed */
+7 -5
View File
@@ -49,8 +49,9 @@ static bool _MQTT_available = false;
static MyMessage _MQTT_msg;
bool gatewayTransportSend(MyMessage &message) {
if (!_MQTT_client.connected())
if (!_MQTT_client.connected()) {
return false;
}
setIndication(INDICATION_GW_TX);
char *topic = protocolFormatMQTTTopic(MY_MQTT_PUBLISH_TOPIC_PREFIX, message);
debug(PSTR("Sending message on topic: %s\n"), topic);
@@ -134,7 +135,7 @@ bool gatewayTransportInit() {
(void)WiFi.begin(MY_ESP8266_SSID, MY_ESP8266_PASSWORD);
#ifdef MY_IP_ADDRESS
WiFi.config(_MQTT_clientIp, _gatewayIp, _subnetIp);
#endif
#endif
#endif
gatewayTransportConnect();
@@ -144,15 +145,16 @@ bool gatewayTransportInit() {
}
bool gatewayTransportAvailable() {
if (_MQTT_connecting)
if (_MQTT_connecting) {
return false;
}
//keep lease on dhcp address
//Ethernet.maintain();
if (!_MQTT_client.connected()) {
//reinitialise client
if (gatewayTransportConnect())
if (gatewayTransportConnect()) {
reconnectMQTT();
}
return false;
}
_MQTT_client.loop();
+32 -23
View File
@@ -81,7 +81,7 @@ void hwPowerDown(period_t period) {
sei();
// Directly sleep CPU, to prevent race conditions! (see chapter 7.7 of ATMega328P datasheet)
sleep_cpu();
sleep_disable();
sleep_disable();
// restore previous WDT settings
cli();
wdt_reset();
@@ -124,12 +124,16 @@ int8_t hwSleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mo
// Disable interrupts until going to sleep, otherwise interrupts occurring between attachInterrupt()
// and sleep might cause the ATMega to not wakeup from sleep as interrupt has already be handled!
cli();
// attach interrupts
// attach interrupts
_wakeUp1Interrupt = interrupt1;
_wakeUp2Interrupt = interrupt2;
if (interrupt1 != INVALID_INTERRUPT_NUM) attachInterrupt(interrupt1, wakeUp1, mode1);
if (interrupt2 != INVALID_INTERRUPT_NUM) attachInterrupt(interrupt2, wakeUp2, mode2);
if (interrupt1 != INVALID_INTERRUPT_NUM) {
attachInterrupt(interrupt1, wakeUp1, mode1);
}
if (interrupt2 != INVALID_INTERRUPT_NUM) {
attachInterrupt(interrupt2, wakeUp2, mode2);
}
if (ms>0) {
// sleep for defined time
hwInternalSleep(ms);
@@ -137,15 +141,20 @@ int8_t hwSleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mo
// sleep until ext interrupt triggered
hwPowerDown(SLEEP_FOREVER);
}
// Assure any interrupts attached, will get detached when they did not occur.
if (interrupt1 != INVALID_INTERRUPT_NUM) detachInterrupt(interrupt1);
if (interrupt2 != INVALID_INTERRUPT_NUM) detachInterrupt(interrupt2);
if (interrupt1 != INVALID_INTERRUPT_NUM) {
detachInterrupt(interrupt1);
}
if (interrupt2 != INVALID_INTERRUPT_NUM) {
detachInterrupt(interrupt2);
}
// Return what woke the mcu.
int8_t ret = MY_WAKE_UP_BY_TIMER; // default: no interrupt triggered, timer wake up
if (interruptWakeUp()) ret = static_cast<int8_t>(_wokeUpByInterrupt);
int8_t ret = MY_WAKE_UP_BY_TIMER; // default: no interrupt triggered, timer wake up
if (interruptWakeUp()) {
ret = static_cast<int8_t>(_wokeUpByInterrupt);
}
// Clear woke-up-by-interrupt flag, so next sleeps won't return immediately.
_wokeUpByInterrupt = INVALID_INTERRUPT_NUM;
@@ -153,7 +162,7 @@ int8_t hwSleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mo
}
uint16_t hwCPUVoltage() {
// Measure Vcc against 1.1V Vref
// Measure Vcc against 1.1V Vref
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
ADMUX = (_BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1));
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
@@ -162,12 +171,12 @@ uint16_t hwCPUVoltage() {
ADMUX = (_BV(MUX3) | _BV(MUX2));
#else
ADMUX = (_BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1));
#endif
#endif
// Vref settle
delay(70);
delay(70);
// Do conversion
ADCSRA |= _BV(ADSC);
while (bit_is_set(ADCSRA,ADSC));
while (bit_is_set(ADCSRA,ADSC)) {};
// return Vcc in mV
return (1125300UL) / ADC;
}
@@ -175,8 +184,8 @@ uint16_t hwCPUVoltage() {
uint16_t hwCPUFrequency() {
cli();
// setup timer1
TIFR1 = 0xFF;
TCNT1 = 0;
TIFR1 = 0xFF;
TCNT1 = 0;
TCCR1A = 0;
TCCR1C = 0;
// save WDT settings
@@ -186,24 +195,24 @@ uint16_t hwCPUFrequency() {
WDTCSR |= (1 << WDIE);
wdt_reset();
// start timer1 with 1024 prescaling
TCCR1B = _BV(CS12) | _BV(CS10);
TCCR1B = _BV(CS12) | _BV(CS10);
// wait until wdt interrupt
while (bit_is_clear(WDTCSR,WDIF));
while (bit_is_clear(WDTCSR,WDIF)) {};
// stop timer
TCCR1B = 0;
// restore WDT settings
wdt_reset();
WDTCSR |= (1 << WDCE) | (1 << WDE);
WDTCSR = WDTsave;
sei();
sei();
// return frequency in 1/10MHz (accuracy +- 10%)
return TCNT1 * 2048UL / 100000UL;
}
uint16_t hwFreeMem() {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
+3 -1
View File
@@ -58,7 +58,9 @@ byte i2c_eeprom_read_byte(unsigned int eeaddress ) {
Wire.write((int)(eeaddress & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(I2C_EEP_ADDRESS,1);
if (Wire.available()) rdata = Wire.read();
if (Wire.available()) {
rdata = Wire.read();
}
return rdata;
}
+3 -2
View File
@@ -43,6 +43,7 @@ void setIndication( const indication_t ind )
ledsBlinkErr(ind-INDICATION_ERR_START);
}
#endif
if (indication)
indication(ind);
if (indication) {
indication(ind);
}
}
+11 -4
View File
@@ -51,8 +51,9 @@ inline void ledsInit()
void ledsProcess() {
// Just return if it is not the time...
if ((hwMillis() - prevTime) < LED_PROCESS_INTERVAL_MS)
if ((hwMillis() - prevTime) < LED_PROCESS_INTERVAL_MS) {
return;
}
prevTime += LED_PROCESS_INTERVAL_MS;
@@ -63,19 +64,25 @@ void ledsProcess() {
#if defined(MY_DEFAULT_RX_LED_PIN)
state = (countRx & (LED_ON_OFF_RATIO-1)) ? LED_ON : LED_OFF;
hwDigitalWrite(MY_DEFAULT_RX_LED_PIN, state);
if (countRx) --countRx;
if (countRx) {
--countRx;
}
#endif
#if defined(MY_DEFAULT_TX_LED_PIN)
state = (countTx & (LED_ON_OFF_RATIO-1)) ? LED_ON : LED_OFF;
hwDigitalWrite(MY_DEFAULT_TX_LED_PIN, state);
if (countTx) --countTx;
if (countTx) {
--countTx;
}
#endif
#if defined(MY_DEFAULT_ERR_LED_PIN)
state = (countErr & (LED_ON_OFF_RATIO-1)) ? LED_ON : LED_OFF;
hwDigitalWrite(MY_DEFAULT_ERR_LED_PIN, state);
if (countErr) --countErr;
if (countErr) {
--countErr;
}
#endif
}
+25 -2
View File
@@ -1,3 +1,22 @@
/**
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
* Copyright (C) 2013-2015 Sensnology AB
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*/
// Initialize library and handle sketch functions like we want to
int main(void) {
@@ -12,8 +31,12 @@ int main(void) {
for(;;) {
_process(); // Process incoming data
if (loop) loop(); // Call sketch loop
if (serialEventRun) serialEventRun();
if (loop) {
loop(); // Call sketch loop
}
if (serialEventRun) {
serialEventRun();
}
}
return 0;
}
+22 -3
View File
@@ -1,4 +1,22 @@
/**
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
* Copyright (C) 2013-2015 Sensnology AB
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*/
//This may be used to change user task stack size:
//#define CONT_STACKSIZE 4096
#include "Schedule.h"
@@ -109,8 +127,9 @@ static void loop_task(os_event_t *events) {
static void do_global_ctors(void) {
void(**p)(void) = &__init_array_end;
while (p != &__init_array_start)
while (p != &__init_array_start) {
(*--p)();
}
}
extern "C" void __gdb_init() {}
@@ -144,4 +163,4 @@ extern "C" void user_init(void) {
LOOP_QUEUE_SIZE);
system_init_done_cb(&init_done);
}
}
+22 -2
View File
@@ -1,4 +1,22 @@
// Initialize library and handle sketch functions like we want to
/**
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
* Copyright (C) 2013-2015 Sensnology AB
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*/
// Initialize library and handle sketch functions like we want to
#include <stdio.h>
#include <csignal>
@@ -129,7 +147,9 @@ int main(int argc, char *argv[])
for (;;) {
_process(); // Process incoming data
if (loop) loop(); // Call sketch loop
if (loop) {
loop(); // Call sketch loop
}
}
return 0;
}
+8 -6
View File
@@ -75,10 +75,12 @@ const char* MyMessage::getString() const {
// handles single character hex (0 - 15)
char MyMessage::i2h(uint8_t i) const {
uint8_t k = i & 0x0F;
if (k <= 9)
if (k <= 9) {
return '0' + k;
else
}
else {
return 'A' + k - 10;
}
}
char* MyMessage::getCustomString(char *buffer) const {
@@ -173,7 +175,7 @@ uint32_t MyMessage::getULong() const {
}
int16_t MyMessage::getInt() const {
if (miGetPayloadType() == P_INT16) {
if (miGetPayloadType() == P_INT16) {
return iValue;
} else if (miGetPayloadType() == P_STRING) {
return atoi(data);
@@ -183,7 +185,7 @@ int16_t MyMessage::getInt() const {
}
uint16_t MyMessage::getUInt() const {
if (miGetPayloadType() == P_UINT16) {
if (miGetPayloadType() == P_UINT16) {
return uiValue;
} else if (miGetPayloadType() == P_STRING) {
return atoi(data);
@@ -211,7 +213,7 @@ MyMessage& MyMessage::setDestination(uint8_t _destination) {
// Set payload
MyMessage& MyMessage::set(void* value, uint8_t length) {
uint8_t payloadLength = value == NULL ? 0 : min(length, (uint8_t)MAX_PAYLOAD);
miSetLength(payloadLength);
miSetLength(payloadLength);
miSetPayloadType(P_CUSTOM);
memcpy(data, value, payloadLength);
return *this;
@@ -221,7 +223,7 @@ MyMessage& MyMessage::set(const char* value) {
uint8_t length = value == NULL ? 0 : min(strlen(value), (size_t)MAX_PAYLOAD);
miSetLength(length);
miSetPayloadType(P_STRING);
if (length) {
if (length) {
strncpy(data, value, length);
}
// null terminate string
+10 -8
View File
@@ -16,7 +16,7 @@
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*/
#include "MyOTAFirmwareUpdate.h"
// global variables
@@ -76,7 +76,7 @@ bool firmwareOTAUpdateProcess() {
// erase lower 32K -> max flash size for ATMEGA328
_flash.blockErase32K(0);
// wait until flash erased
while ( _flash.busy() );
while ( _flash.busy() ) {}
_fwBlock = _fc.blocks;
_fwUpdateOngoing = true;
// reset flags
@@ -96,7 +96,7 @@ bool firmwareOTAUpdateProcess() {
// write to flash
_flash.writeBytes( ((_fwBlock - 1) * FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE);
// wait until flash written
while ( _flash.busy() );
while ( _flash.busy() ) {}
_fwBlock--;
if (!_fwBlock) {
// We're finished! Do a checksum and reboot.
@@ -137,7 +137,7 @@ void presentBootloaderInformation(){
// add bootloader information
reqFWConfig->BLVersion = MY_OTA_BOOTLOADER_VERSION;
_fwUpdateOngoing = false;
_sendRoute(build(_msgTmp, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_STREAM, ST_FIRMWARE_CONFIG_REQUEST, false));
_sendRoute(build(_msgTmp, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_STREAM, ST_FIRMWARE_CONFIG_REQUEST, false));
}
// do a crc16 on the whole received firmware
bool transportIsValidFirmware() {
@@ -146,10 +146,12 @@ bool transportIsValidFirmware() {
for (uint16_t i = 0; i < _fc.blocks * FIRMWARE_BLOCK_SIZE; ++i) {
crc ^= _flash.readByte(i + FIRMWARE_START_OFFSET);
for (int8_t j = 0; j < 8; ++j) {
if (crc & 1)
crc = (crc >> 1) ^ 0xA001;
else
crc = (crc >> 1);
if (crc & 1) {
crc = (crc >> 1) ^ 0xA001;
}
else {
crc = (crc >> 1);
}
}
}
return crc == _fc.crc;
+3 -3
View File
@@ -36,7 +36,7 @@
*
* |E| SYS | SUB | Message | Comment
* |-|------|-------|-------------------------------------------|----------------------------------------------------------------------------
* | | OTA | FWP | UPDATE | FW update initiated
* | | OTA | FWP | UPDATE | FW update initiated
* |!| OTA | FWP | FLASH INIT FAIL | Failed to initialise flash
* | | OTA | FWP | UPDATE SKIPPED | FW update skipped, no newer version available
* | | OTA | FWP | RECV B=%04X | Received FW block (B)
@@ -132,10 +132,10 @@ bool firmwareOTAUpdateProcess();
*/
bool transportIsValidFirmware();
/**
* @brief Present bootloader/FW information upon startup
* @brief Present bootloader/FW information upon startup
*/
void presentBootloaderInformation();
#endif
/** @}*/
/** @}*/
+18 -10
View File
@@ -70,10 +70,12 @@ bool protocolParse(MyMessage &message, char *inputString) {
value = str;
// Remove trailing carriage return and newline character (if it exists)
uint8_t lastCharacter = strlen(value)-1;
if (value[lastCharacter] == '\r')
if (value[lastCharacter] == '\r') {
value[lastCharacter] = 0;
if (value[lastCharacter] == '\n')
}
if (value[lastCharacter] == '\n') {
value[lastCharacter] = 0;
}
}
break;
}
@@ -81,16 +83,18 @@ bool protocolParse(MyMessage &message, char *inputString) {
}
//debug(PSTR("Received %d"), i);
// Check for invalid input
if (i < 5)
if (i < 5) {
return false;
}
message.sender = GATEWAY_ADDRESS;
message.last = GATEWAY_ADDRESS;
mSetAck(message, false);
if (command == C_STREAM)
if (command == C_STREAM) {
message.set(bvalue, blen);
else
}
else {
message.set(value);
}
return true;
}
@@ -158,8 +162,9 @@ bool protocolMQTTParse(MyMessage &message, char* topic, uint8_t* payload, unsign
i++;
}
if (i != 6)
if (i != 6) {
return false;
}
message.sender = GATEWAY_ADDRESS;
message.last = GATEWAY_ADDRESS;
@@ -190,11 +195,14 @@ bool protocolMQTTParse(MyMessage &message, char* topic, uint8_t* payload, unsign
uint8_t protocolH2i(char c) {
uint8_t i = 0;
if (c <= '9')
if (c <= '9') {
i += c - '0';
else if (c >= 'a')
}
else if (c >= 'a') {
i += c - 'a' + 10;
else
}
else {
i += c - 'A' + 10;
}
return i;
}
+17 -9
View File
@@ -72,8 +72,9 @@ void _infiniteLoop(void) {
void _begin(void) {
hwWatchdogReset();
if (preHwInit)
if (preHwInit) {
preHwInit();
}
hwInit();
@@ -120,7 +121,7 @@ void _begin(void) {
pinMode(MY_NODE_UNLOCK_PIN, INPUT_PULLUP);
// Make a short delay so we are sure any large external nets are fully pulled
unsigned long enter = hwMillis();
while (hwMillis() - enter < 2);
while (hwMillis() - enter < 2) {}
if (digitalRead(MY_NODE_UNLOCK_PIN) == 0) {
// Pin is grounded, reset lock counter
hwWriteConfig(EEPROM_NODE_LOCK_COUNTER, MY_NODE_LOCK_COUNTER_MAX);
@@ -224,9 +225,9 @@ void presentNode(void) {
#endif
if (presentation)
if (presentation) {
presentation();
}
}
@@ -299,8 +300,12 @@ bool present(const uint8_t childSensorId, const uint8_t sensorType, const char *
bool sendSketchInfo(const char *name, const char *version, const bool ack) {
bool result = true;
if (name) result &= _sendRoute(build(_msgTmp, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_SKETCH_NAME, ack).set(name));
if (version) result &= _sendRoute(build(_msgTmp, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_SKETCH_VERSION, ack).set(version));
if (name) {
result &= _sendRoute(build(_msgTmp, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_SKETCH_NAME, ack).set(name));
}
if (version) {
result &= _sendRoute(build(_msgTmp, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_SKETCH_VERSION, ack).set(version));
}
return result;
}
@@ -345,8 +350,9 @@ bool _processInternalMessages(void) {
}
else if (type == I_TIME) {
// Deliver time to callback
if (receiveTime)
if (receiveTime) {
receiveTime(_msg.getULong());
}
}
else if (type == I_CHILDREN) {
#if defined(MY_REPEATER_FEATURE)
@@ -385,7 +391,9 @@ bool _processInternalMessages(void) {
}
else if (debug_msg == 'E') { // clear MySensors eeprom area and reboot
(void)_sendRoute(build(_msgTmp, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_DEBUG).set("OK"));
for (int i = EEPROM_START; i<EEPROM_LOCAL_CONFIG_ADDRESS; i++) hwWriteConfig(i, 0xFF);
for (int i = EEPROM_START; i<EEPROM_LOCAL_CONFIG_ADDRESS; i++) {
hwWriteConfig(i, 0xFF);
}
setIndication(INDICATION_REBOOT);
hwReboot();
}
@@ -405,7 +413,7 @@ bool _processInternalMessages(void) {
#if defined(MY_CORE_COMPATIBILITY_CHECK)
approveRegistration = (_msg.getByte() >= MY_CORE_MIN_VERSION);
#endif
#if (F_CPU>16000000)
// delay for fast GW and slow nodes
delay(5);
+13 -9
View File
@@ -52,10 +52,12 @@ static uint8_t* signerSha256(const uint8_t* data, size_t sz);
static char i2h(uint8_t i)
{
uint8_t k = i & 0x0F;
if (k <= 9)
if (k <= 9) {
return '0' + k;
else
}
else {
return 'A' + k - 10;
}
}
static void DEBUG_SIGNING_PRINTBUF(const __FlashStringHelper* str, uint8_t* buf, uint8_t sz) {
@@ -98,7 +100,7 @@ bool signerAtsha204CheckTimer(void) {
memset(_signing_signing_nonce, 0x00, NONCE_NUMIN_SIZE_PASSTHROUGH);
memset(_signing_verifying_nonce, 0x00, NONCE_NUMIN_SIZE_PASSTHROUGH);
_signing_verification_ongoing = false;
return false;
return false;
}
}
return true;
@@ -132,7 +134,9 @@ bool signerAtsha204GetNonce(MyMessage &msg) {
// Be a little fancy to handle turnover (prolong the time allowed to timeout after turnover)
// Note that if message is "too" quick, and arrives before turnover, it will be rejected
// but this is consider such a rare case that it is accepted and rejects are 'safe'
if (_signing_timestamp + MY_VERIFICATION_TIMEOUT_MS < hwMillis()) _signing_timestamp = 0;
if (_signing_timestamp + MY_VERIFICATION_TIMEOUT_MS < hwMillis()) {
_signing_timestamp = 0;
}
return true;
}
@@ -148,7 +152,7 @@ bool signerAtsha204SignMsg(MyMessage &msg) {
// If we cannot fit any signature in the message, refuse to sign it
if (mGetLength(msg) > MAX_PAYLOAD-2) {
DEBUG_SIGNING_PRINTBUF(F("Message too large"), NULL, 0);
return false;
return false;
}
// Calculate signature of message
@@ -180,18 +184,18 @@ bool signerAtsha204SignMsg(MyMessage &msg) {
bool signerAtsha204VerifyMsg(MyMessage &msg) {
if (!_signing_verification_ongoing) {
DEBUG_SIGNING_PRINTBUF(F("No active verification session"), NULL, 0);
return false;
return false;
} else {
// Make sure we have not expired
if (!signerCheckTimer()) {
return false;
return false;
}
_signing_verification_ongoing = false;
if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) {
DEBUG_SIGNING_PRINTBUF(F("Incorrect signing identifier"), NULL, 0);
return false;
return false;
}
DEBUG_SIGNING_PRINTBUF(F("Signature in message: "), (uint8_t*)&msg.data[mGetLength(msg)], MAX_PAYLOAD-mGetLength(msg));
@@ -230,7 +234,7 @@ bool signerAtsha204VerifyMsg(MyMessage &msg) {
#ifdef MY_SIGNING_NODE_WHITELISTING
DEBUG_SIGNING_PRINTBUF(F("Is the sender whitelisted and serial correct?"), NULL, 0);
#endif
return false;
return false;
} else {
DEBUG_SIGNING_PRINTBUF(F("Signature OK"), NULL, 0);
return true;
+50 -22
View File
@@ -56,10 +56,12 @@ static void signerCalculateSignature(MyMessage &msg, bool signing);
static char i2h(uint8_t i)
{
uint8_t k = i & 0x0F;
if (k <= 9)
if (k <= 9) {
return '0' + k;
else
}
else {
return 'A' + k - 10;
}
}
static void DEBUG_SIGNING_PRINTBUF(const __FlashStringHelper* str, uint8_t* buf, uint8_t sz) {
@@ -106,7 +108,7 @@ bool signerAtsha204SoftCheckTimer(void) {
memset(_signing_signing_nonce, 0xAA, 32);
memset(_signing_verifying_nonce, 0xAA, 32);
_signing_verification_ongoing = false;
return false;
return false;
}
}
return true;
@@ -115,7 +117,7 @@ bool signerAtsha204SoftCheckTimer(void) {
bool signerAtsha204SoftGetNonce(MyMessage &msg) {
DEBUG_SIGNING_PRINTBUF(F("Signing backend: ATSHA204Soft"), NULL, 0);
// We used a basic whitening technique that XORs a random byte with the current hwMillis() counter and then the byte is
// We used a basic whitening technique that XORs a random byte with the current hwMillis() counter and then the byte is
// hashed (SHA256) to produce the resulting nonce
_signing_sha256.init();
for (int i = 0; i < 32; i++) {
@@ -134,7 +136,9 @@ bool signerAtsha204SoftGetNonce(MyMessage &msg) {
// Be a little fancy to handle turnover (prolong the time allowed to timeout after turnover)
// Note that if message is "too" quick, and arrives before turnover, it will be rejected
// but this is consider such a rare case that it is accepted and rejects are 'safe'
if (_signing_timestamp + MY_VERIFICATION_TIMEOUT_MS < hwMillis()) _signing_timestamp = 0;
if (_signing_timestamp + MY_VERIFICATION_TIMEOUT_MS < hwMillis()) {
_signing_timestamp = 0;
}
return true;
}
@@ -150,7 +154,7 @@ bool signerAtsha204SoftSignMsg(MyMessage &msg) {
// If we cannot fit any signature in the message, refuse to sign it
if (mGetLength(msg) > MAX_PAYLOAD-2) {
DEBUG_SIGNING_PRINTBUF(F("Message too large"), NULL, 0);
return false;
return false;
}
// Calculate signature of message
@@ -160,9 +164,13 @@ bool signerAtsha204SoftSignMsg(MyMessage &msg) {
if (DO_WHITELIST(msg.destination)) {
// Salt the signature with the senders nodeId and the (hopefully) unique serial The Creator has provided
_signing_sha256.init();
for (int i=0; i<32; i++) _signing_sha256.write(_signing_hmac[i]);
for (int i=0; i<32; i++) {
_signing_sha256.write(_signing_hmac[i]);
}
_signing_sha256.write(msg.sender);
for (int i=0; i<SHA204_SERIAL_SZ; i++) _signing_sha256.write(_signing_node_serial_info[i]);
for (int i=0; i<SHA204_SERIAL_SZ; i++) {
_signing_sha256.write(_signing_node_serial_info[i]);
}
memcpy(_signing_hmac, _signing_sha256.result(), 32);
DEBUG_SIGNING_PRINTBUF(F("SHA256: "), _signing_hmac, 32);
DEBUG_SIGNING_PRINTBUF(F("Signature salted with serial"), NULL, 0);
@@ -181,18 +189,18 @@ bool signerAtsha204SoftSignMsg(MyMessage &msg) {
bool signerAtsha204SoftVerifyMsg(MyMessage &msg) {
if (!_signing_verification_ongoing) {
DEBUG_SIGNING_PRINTBUF(F("No active verification session"), NULL, 0);
return false;
return false;
} else {
// Make sure we have not expired
if (!signerCheckTimer()) {
return false;
return false;
}
_signing_verification_ongoing = false;
if (msg.data[mGetLength(msg)] != SIGNING_IDENTIFIER) {
DEBUG_SIGNING_PRINTBUF(F("Incorrect signing identifier"), NULL, 0);
return false;
return false;
}
// Get signature of message
@@ -206,9 +214,13 @@ bool signerAtsha204SoftVerifyMsg(MyMessage &msg) {
if (_signing_whitelist[j].nodeId == msg.sender) {
DEBUG_SIGNING_PRINTBUF(F("Sender found in whitelist"), NULL, 0);
_signing_sha256.init();
for (int i=0; i<32; i++) _signing_sha256.write(_signing_hmac[i]);
for (int i=0; i<32; i++) {
_signing_sha256.write(_signing_hmac[i]);
}
_signing_sha256.write(msg.sender);
for (int i=0; i<SHA204_SERIAL_SZ; i++) _signing_sha256.write(_signing_whitelist[j].serial[i]);
for (int i=0; i<SHA204_SERIAL_SZ; i++) {
_signing_sha256.write(_signing_whitelist[j].serial[i]);
}
memcpy(_signing_hmac, _signing_sha256.result(), 32);
DEBUG_SIGNING_PRINTBUF(F("SHA256: "), _signing_hmac, 32);
break;
@@ -229,7 +241,7 @@ bool signerAtsha204SoftVerifyMsg(MyMessage &msg) {
#ifdef MY_SIGNING_NODE_WHITELISTING
DEBUG_SIGNING_PRINTBUF(F("Is the sender whitelisted and serial correct?"), NULL, 0);
#endif
return false;
return false;
} else {
DEBUG_SIGNING_PRINTBUF(F("Signature OK"), NULL, 0);
return true;
@@ -268,7 +280,9 @@ static void signerCalculateSignature(MyMessage &msg, bool signing) {
// Calculate message digest first
_signing_sha256.init();
for (int i=0; i<32; i++) _signing_sha256.write(_signing_temp_message[i]);
for (int i=0; i<32; i++) {
_signing_sha256.write(_signing_temp_message[i]);
}
_signing_sha256.write(0x15); // OPCODE
_signing_sha256.write(0x02); // param1
_signing_sha256.write(0x08); // param2(1)
@@ -276,26 +290,40 @@ static void signerCalculateSignature(MyMessage &msg, bool signing) {
_signing_sha256.write(0xEE); // SN[8]
_signing_sha256.write(0x01); // SN[0]
_signing_sha256.write(0x23); // SN[1]
for (int i=0; i<25; i++) _signing_sha256.write(0x00);
for (int i=0; i<32; i++) _signing_sha256.write(signing ? _signing_signing_nonce[i] : _signing_verifying_nonce[i]);
for (int i=0; i<25; i++) {
_signing_sha256.write(0x00);
}
for (int i=0; i<32; i++) {
_signing_sha256.write(signing ? _signing_signing_nonce[i] : _signing_verifying_nonce[i]);
}
// Purge nonce when used
memset(signing ? _signing_signing_nonce : _signing_verifying_nonce, 0xAA, 32);
memcpy(_signing_temp_message, _signing_sha256.result(), 32);
// Feed "message" to HMAC calculator
_signing_sha256.initHmac(_signing_hmac_key,32); // Set the key to use
for (int i=0; i<32; i++) _signing_sha256.write(0x00); // 32 bytes zeroes
for (int i=0; i<32; i++) _signing_sha256.write(_signing_temp_message[i]); // 32 bytes digest
for (int i=0; i<32; i++) {
_signing_sha256.write(0x00); // 32 bytes zeroes
}
for (int i=0; i<32; i++) {
_signing_sha256.write(_signing_temp_message[i]); // 32 bytes digest
}
_signing_sha256.write(0x11); // OPCODE
_signing_sha256.write(0x04); // Mode
_signing_sha256.write(0x00); // SlotID(1)
_signing_sha256.write(0x00); // SlotID(2)
for (int i=0; i<11; i++) _signing_sha256.write(0x00); // 11 bytes zeroes
for (int i=0; i<11; i++) {
_signing_sha256.write(0x00); // 11 bytes zeroes
}
_signing_sha256.write(0xEE); // SN[8]
for (int i=0; i<4; i++) _signing_sha256.write(0x00); // 4 bytes zeroes
for (int i=0; i<4; i++) {
_signing_sha256.write(0x00); // 4 bytes zeroes
}
_signing_sha256.write(0x01); // SN[0]
_signing_sha256.write(0x23); // SN[1]
for (int i=0; i<2; i++) _signing_sha256.write(0x00); // 2 bytes zeroes
for (int i=0; i<2; i++) {
_signing_sha256.write(0x00); // 2 bytes zeroes
}
memcpy(_signing_hmac, _signing_sha256.resultHmac(), 32);
+31 -26
View File
@@ -112,7 +112,7 @@ void stInitUpdate(void) {
// ID invalid (0 or 255)
transportSwitchSM(stFailure);
}
#endif
#endif
}
}
@@ -191,7 +191,7 @@ void stIDUpdate(void) {
TRANSPORT_DEBUG(PSTR("TSM:ID:OK\n"));
setIndication(INDICATION_GOT_NODEID);
// proceed to next state
transportSwitchSM(stUplink);
transportSwitchSM(stUplink);
}
else if (transportTimeInState() > MY_TRANSPORT_STATE_TIMEOUT_MS) {
// timeout
@@ -261,7 +261,7 @@ void stReadyTransition(void) {
// stReadyUpdate: monitors link
void stReadyUpdate(void) {
#if defined(MY_GATEWAY_FEATURE)
#if defined(MY_GATEWAY_FEATURE)
if (hwMillis() - _lastNetworkDiscovery > MY_TRANSPORT_DISCOVERY_INTERVAL_MS) {
_lastNetworkDiscovery = hwMillis();
TRANSPORT_DEBUG(PSTR("TSM:READY:NWD REQ\n")); // send transport network discovery
@@ -319,7 +319,9 @@ void transportSwitchSM(transportState& newState) {
else {
_transportSM.stateRetries++; // increment retries
}
if (_transportSM.currentState->Transition) _transportSM.currentState->Transition(); // State transition
if (_transportSM.currentState->Transition) {
_transportSM.currentState->Transition(); // State transition
}
_transportSM.stateEnter = hwMillis(); // save time
}
@@ -328,7 +330,9 @@ uint32_t transportTimeInState(void) {
}
void transportUpdateSM(void) {
if (_transportSM.currentState->Update) _transportSM.currentState->Update();
if (_transportSM.currentState->Update) {
_transportSM.currentState->Update();
}
}
bool isTransportReady(void) {
@@ -363,7 +367,7 @@ void transportInitialise(void) {
// update TSM and process incoming messages
void transportProcess(void) {
// update state machine
transportUpdateSM();
transportUpdateSM();
// process transport FIFO
transportProcessFIFO();
}
@@ -415,7 +419,7 @@ bool transportAssignNodeID(const uint8_t newNodeId) {
bool transportRouteMessage(MyMessage &message) {
const uint8_t destination = message.destination;
uint8_t route = _nc.parentNodeId; // by default, all traffic is routed via parent node
if (_transportSM.findingParentNode && destination != BROADCAST_ADDRESS) {
TRANSPORT_DEBUG(PSTR("!TSF:RTE:FPAR ACTIVE\n")); // find parent active, message not sent
// request to send a non-BC message while finding parent active, abort
@@ -438,7 +442,7 @@ bool transportRouteMessage(MyMessage &message) {
if (message.last != _nc.parentNodeId) {
// message not from parent, i.e. child node - route it to parent
route = _nc.parentNodeId;
}
}
else {
// route unknown and msg received from parent, send it to destination assuming in rx radius
route = destination;
@@ -464,7 +468,9 @@ bool transportRouteMessage(MyMessage &message) {
else _transportSM.failedUplinkTransmissions = 0u;
}
#else
if(!result) setIndication(INDICATION_ERR_TX);
if(!result) {
setIndication(INDICATION_ERR_TX);
}
#endif
return result;
@@ -532,7 +538,7 @@ void transportProcessMessage(void) {
setIndication(INDICATION_RX);
const uint8_t payloadLength = transportReceive((uint8_t *)&_msg);
// get message length and limit size
const uint8_t msgLength = min(mGetLength(_msg), (uint8_t)MAX_PAYLOAD);
const uint8_t msgLength = min(mGetLength(_msg), (uint8_t)MAX_PAYLOAD);
// calculate expected length
const uint8_t expectedMessageLength = HEADER_SIZE + (mGetSigned(_msg) ? MAX_PAYLOAD : msgLength);
const uint8_t command = mGetCommand(_msg);
@@ -557,12 +563,12 @@ void transportProcessMessage(void) {
TRANSPORT_DEBUG(PSTR("!TSF:MSG:PVER,%d=%d\n"), mGetVersion(_msg), PROTOCOL_VERSION); // protocol version mismatch
return;
}
// Reject messages that do not pass verification
if (!signerVerifyMsg(_msg)) {
setIndication(INDICATION_ERR_SIGN);
TRANSPORT_DEBUG(PSTR("!TSF:MSG:SIGN VERIFY FAIL\n"));
return;
return;
}
// update routing table if msg not from parent
@@ -580,7 +586,7 @@ void transportProcessMessage(void) {
// set message received flag
_transportSM.msgReceived = true;
// Is message addressed to this node?
if (destination == _nc.nodeId) {
// prevent buffer overflow by limiting max. possible message length (5 bits=31 bytes max) to MAX_PAYLOAD (25 bytes)
@@ -590,14 +596,14 @@ void transportProcessMessage(void) {
// Check if sender requests an ack back.
if (mGetRequestAck(_msg)) {
TRANSPORT_DEBUG(PSTR("TSF:MSG:ACK REQ\n")); // ACK requested
_msgTmp = _msg; // Copy message
_msgTmp = _msg; // Copy message
mSetRequestAck(_msgTmp, false); // Reply without ack flag (otherwise we would end up in an eternal loop)
mSetAck(_msgTmp, true); // set ACK flag
_msgTmp.sender = _nc.nodeId;
_msgTmp.destination = sender;
// send ACK, use transportSendRoute since ACK reply is not internal, i.e. if !transportOK do not reply
(void)transportSendRoute(_msgTmp);
}
}
if(!mGetAck(_msg)) {
// only process if not ACK
if (command == C_INTERNAL) {
@@ -683,7 +689,7 @@ void transportProcessMessage(void) {
if (receive) {
receive(_msg);
}
}
}
else if (destination == BROADCAST_ADDRESS) {
TRANSPORT_DEBUG(PSTR("TSF:MSG:BC\n")); // broadcast msg
if (command == C_INTERNAL) {
@@ -707,7 +713,7 @@ void transportProcessMessage(void) {
}
}
#endif
return; // no further processing required, do not forward
return; // no further processing required, do not forward
}
} // isTransportReady
if (type == I_FIND_PARENT_RESPONSE) {
@@ -732,12 +738,14 @@ void transportProcessMessage(void) {
(void)transportRouteMessage(_msg);
}
#endif
// Callback for BC, only for non-internal messages
if (command != C_INTERNAL) {
#if !defined(MY_GATEWAY_FEATURE)
// only proceed if message received from parent
if (last != _nc.parentNodeId) return;
if (last != _nc.parentNodeId) {
return;
}
#endif
#if defined(MY_GATEWAY_FEATURE)
// Hand over message to controller
@@ -747,10 +755,10 @@ void transportProcessMessage(void) {
receive(_msg);
}
}
}
}
else {
// msg not to us and not BC, relay msg
// msg not to us and not BC, relay msg
#if defined(MY_REPEATER_FEATURE)
if (isTransportReady()) {
TRANSPORT_DEBUG(PSTR("TSF:MSG:REL MSG\n")); // relay msg
@@ -817,7 +825,7 @@ bool transportSendWrite(const uint8_t to, MyMessage &message) {
setIndication(INDICATION_ERR_SIGN);
return false;
}
// msg length changes if signed
const uint8_t totalMsgLength = HEADER_SIZE + ( mGetSigned(message) ? MAX_PAYLOAD : mGetLength(message) );
@@ -873,6 +881,3 @@ uint8_t transportGetRoute(const uint8_t node) {
#endif
return result;
}
// EOF MyTransport.cpp
+6 -4
View File
@@ -125,7 +125,9 @@ bool _serialProcess()
{
char inch;
unsigned char i;
if (!_dev.available()) return false;
if (!_dev.available()) {
return false;
}
while(_dev.available()) {
inch = _dev.read();
@@ -263,7 +265,9 @@ bool transportSend(uint8_t to, const void* data, uint8_t len)
#endif
// Start of header by writing multiple SOH
for(byte w=0;w<1;w++) _dev.write(SOH);
for(byte w=0;w<1;w++) {
_dev.write(SOH);
}
_dev.write(to); // Destination address
cs += to;
_dev.write(_nodeId); // Source address
@@ -351,5 +355,3 @@ uint8_t transportReceive(void* data) {
void transportPowerDown() {
// Nothing to shut down here
}
+18
View File
@@ -1,3 +1,21 @@
/**
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
* Copyright (C) 2013-2015 Sensnology AB
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*/
/***
* This file defines the Sensor library version number
* Normally, contributors should not modify this directly