Merge branch 'master' into development

This commit is contained in:
Henrik Ekblad
2015-08-03 23:52:16 +02:00
20 changed files with 2613 additions and 56 deletions
+1 -2
View File
@@ -94,8 +94,7 @@
#define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this)
// Key to use for HMAC calculation in MySigningAtsha204Soft (32 bytes)
#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
/**********************************
+27 -1
View File
@@ -37,13 +37,39 @@
#include <SPI.h>
#endif
#if defined __AVR_ATmega328P__
#ifndef sleep_bod_disable
#define sleep_bod_disable() \
do { \
unsigned char tempreg; \
__asm__ __volatile__("in %[tempreg], %[mcucr]" "\n\t" \
"ori %[tempreg], %[bods_bodse]" "\n\t" \
"out %[mcucr], %[tempreg]" "\n\t" \
"andi %[tempreg], %[not_bodse]" "\n\t" \
"out %[mcucr], %[tempreg]" \
: [tempreg] "=&d" (tempreg) \
: [mcucr] "I" _SFR_IO_ADDR(MCUCR), \
[bods_bodse] "i" (_BV(BODS) | _BV(BODSE)), \
[not_bodse] "i" (~_BV(BODSE))); \
} while (0)
#endif
#endif
// Define these as macros to save valuable space
#define hw_init() Serial.begin(BAUD_RATE)
#define hw_watchdogReset() wdt_reset()
#define hw_reboot() wdt_enable(WDTO_15MS); while (1)
#define hw_millis() millis()
#define hw_readConfig(__pos) (eeprom_read_byte((uint8_t*)(__pos)))
#define hw_writeConfig(__pos, __value) (eeprom_update_byte((uint8_t*)(__pos), (__value)))
#ifndef eeprom_update_byte
#define hw_writeConfig(loc, val) if((uint8_t)(val) != eeprom_read_byte((uint8_t*)(loc))) { eeprom_write_byte((uint8_t*)(loc), (val)); }
#else
#define hw_writeConfig(__pos, __value) (eeprom_update_byte((uint8_t*)(__pos), (__value)))
#endif
//
#define hw_readConfigBlock(__buf, __pos, __length) (eeprom_read_block((__buf), (void*)(__pos), (__length)))
#define hw_writeConfigBlock(__pos, __buf, __length) (eeprom_write_block((void*)(__pos), (void*)__buf, (__length)))
+31 -31
View File
@@ -522,7 +522,7 @@ boolean MySensor::process() {
#ifdef MY_OTA_FIRMWARE_FEATURE
unsigned long enter = hw_millis();
if (fwUpdateOngoing && (enter - fwLastRequestTime > MY_OTA_RETRY_DELAY)) {
if (fwRetry == 0) {
if (!fwRetry) {
debug(PSTR("fw upd fail\n"));
// Give up. We have requested MY_OTA_RETRY times without any packet in return.
fwUpdateOngoing = false;
@@ -746,38 +746,38 @@ boolean MySensor::process() {
return false;
} else debug(PSTR("fw update skipped\n"));
} else if (type == ST_FIRMWARE_RESPONSE) {
// Save block to flash
debug(PSTR("fw block %d\n"), fwBlock);
// extract FW block
ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data;
// 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() );
fwBlock--;
if (!fwBlock) {
// We're finished! Do a checksum and reboot.
if (isValidFirmware()) {
debug(PSTR("fw checksum ok\n"));
// All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it)
flash.writeBytes(0, "FLXIMG:", 7);
// FW size in flash
uint16_t fwsize = FIRMWARE_BLOCK_SIZE * fc.blocks;
flash.writeByte(7, fwsize >> 8);
flash.writeByte(8, fwsize);
// end of header
flash.writeByte(9, ':');
// Write the new firmware config to eeprom
hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig));
hw_reboot();
} else {
debug(PSTR("fw checksum fail\n"));
if (fwUpdateOngoing) {
// Save block to flash
debug(PSTR("fw block %d\n"), fwBlock);
// extract FW block
ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data;
// 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() );
fwBlock--;
if (!fwBlock) {
// We're finished! Do a checksum and reboot.
fwUpdateOngoing = false;
}
if (isValidFirmware()) {
debug(PSTR("fw checksum ok\n"));
// All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it)
uint16_t fwsize = FIRMWARE_BLOCK_SIZE * fc.blocks;
uint8_t OTAbuffer[10] = {'F','L','X','I','M','G',':',(fwsize >> 8),fwsize,':'};
flash.writeBytes(0, OTAbuffer, 10);
// Write the new firmware config to eeprom
hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig));
hw_reboot();
} else {
debug(PSTR("fw checksum fail\n"));
}
}
// reset flags
fwRetry = MY_OTA_RETRY+1;
fwLastRequestTime = 0;
} else {
debug(PSTR("No fw update ongoing\n"));
}
// reset flags
fwRetry = MY_OTA_RETRY+1;
fwLastRequestTime = 0;
return false;
}
@@ -61,6 +61,9 @@ static void DEBUG_SIGNING_PRINTBUF(const __FlashStringHelper* str, uint8_t* buf,
#define DEBUG_SIGNING_PRINTBUF(str, buf, sz)
#endif
// Initialize hmacKey from MyConfig.h (codebender didn't like static initialization in constructor)
uint8_t MySigningAtsha204Soft::hmacKey[32] = { MY_HMAC_KEY };
MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures,
#ifdef MY_SECURE_NODE_WHITELISTING
uint8_t nof_whitelist_entries, const whitelist_entry_t* the_whitelist,
@@ -70,7 +73,6 @@ MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures,
:
MySigning(requestSignatures),
rndPin(randomseedPin),
hmacKey({MY_HMAC_KEY}),
#ifdef MY_SECURE_NODE_WHITELISTING
whitlist_sz(nof_whitelist_entries),
whitelist(the_whitelist),
+1 -1
View File
@@ -73,7 +73,7 @@ private:
bool verification_ongoing;
uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH];
uint8_t temp_message[32];
uint8_t hmacKey[32];
static uint8_t hmacKey[32];
uint8_t rndPin;
uint8_t hmac[32];
void calculateSignature(MyMessage &msg);
@@ -92,7 +92,7 @@
// NRFRF24L01 radio driver (set low transmit power by default)
MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);
MyTransportNRF24 transport(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RF24_PA_LEVEL_GW);
//MyTransportRFM69 transport;
// Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
@@ -135,7 +135,7 @@ void output(const char *fmt, ... ) {
vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args);
va_end (args);
Serial.print(serialBuffer);
client.write(serialBuffer);
server.write(serialBuffer);
}
void setup()
@@ -118,7 +118,7 @@ byte TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You sh
//////////////////////////////////////////////////////////////////
// NRFRF24L01 radio driver (set low transmit power by default)
MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);
MyTransportNRF24 transport(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RF24_PA_LEVEL_GW);
//MyTransportRFM69 transport;
// Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
@@ -0,0 +1,164 @@
/**
* 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.
*
*******************************
*
* REVISION HISTORY
* Version 1.0 - Created by Henrik Ekblad
*
* DESCRIPTION
* Parking sensor using a neopixel led ring and distance sensor (HC-SR04).
* Configure the digital pins used for distance sensor and neopixels below.
* NOTE! Remeber to feed leds and distance sensor serparatly from your Arduino.
* It will probably not survive feeding more than a couple of LEDs. You
* can also adjust intesity below to reduce the power requirements.
*
* Sends parking status to the controller as a DOOR sensor if SEND_STATUS_TO_CONTROLLER
* is defined below. You can also use this _standalone_ without any radio by
* removing the SEND_STATUS_TO_CONTROLLER define.
*/
#define SEND_STATUS_TO_CONTROLLER // Put a comment on this line for standalone mode
#include <Adafruit_NeoPixel.h>
#include <NewPing.h>
#ifdef SEND_STATUS_TO_CONTROLLER
#include <SPI.h>
#include <MySensor.h>
#endif
#define NEO_PIN 4 // NeoPixels input pin
#define TRIGGER_PIN 6 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 5 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define NUMPIXELS 24 // Number of nexpixels in ring/strip
#define MAX_INTESITY 20 // Intesity of leds (in percentage). Remeber more intesity requires more power.
// The maximum rated measuring range for the HC-SR04 is about 400-500cm.
#define MAX_DISTANCE 100 // Max distance we want to start indicating green (in cm)
#define PANIC_DISTANCE 5 // Mix distance we red warning indication should be active (in cm)
#define PARKED_DISTANCE 20 // Distance when "parked signal" should be sent to controller (in cm)
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, NEO_PIN, NEO_GRB + NEO_KHZ400);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
#ifdef SEND_STATUS_TO_CONTROLLER
#define CHILD_ID 1
MySensor gw;
MyMessage msg(CHILD_ID,V_TRIPPED);
int oldParkedStatus=-1;
int sendInterval = 5000; // Send park status at maximum every 5 second.
unsigned long lastSend;
#endif
int blinkInterval = 100; // blink interval (milliseconds)
unsigned long lastBlinkPeriod;
bool blinkColor = true;
// To make a fading motion on the led ring/tape we only move one pixel/distDebounce time
int distDebounce = 30;
unsigned long lastDebouncePeriod;
int numLightPixels=0;
int skipZero=0;
void setup() {
Serial.begin(115200);
Serial.println("Starting distance sensor");
pixels.begin(); // This initializes the NeoPixel library.
Serial.println("Neopixels initialized");
#ifdef SEND_STATUS_TO_CONTROLLER
gw.begin();
gw.sendSketchInfo("Parking Sensor", "1.0");
gw.present(CHILD_ID, S_DOOR, "Parking Status");
#endif
}
void loop() {
unsigned long now = millis();
int fullDist = sonar.ping_cm();
// Serial.println(fullDist);
int displayDist = min(fullDist, MAX_DISTANCE);
if (displayDist == 0 && skipZero<10) {
// Try to filter zero readings
skipZero++;
return;
}
// Check if it is time to alter the leds
if (now-lastDebouncePeriod > distDebounce) {
lastDebouncePeriod = now;
#ifdef SEND_STATUS_TO_CONTROLLER
// Update parked status
int parked = displayDist != 0 && displayDist<PARKED_DISTANCE;
if (parked != oldParkedStatus && now-lastSend > sendInterval) {
if (parked)
Serial.println("Car Parked");
else
Serial.println("Car Gone");
gw.send(msg.set(parked));
oldParkedStatus = parked;
lastSend = now;
}
#endif
if (displayDist == 0) {
// No reading from sensor, assume no object found
numLightPixels--;
} else {
skipZero = 0;
int newLightPixels = NUMPIXELS - (NUMPIXELS*(displayDist-PANIC_DISTANCE)/MAX_DISTANCE);
if (newLightPixels>numLightPixels) {
// Fast raise
numLightPixels += max((newLightPixels - numLightPixels) / 2, 1);
} else if (newLightPixels<numLightPixels) {
// Slow decent
numLightPixels--;
}
}
if (numLightPixels>=NUMPIXELS) {
// Do some intense red blinking
if (now-lastBlinkPeriod > blinkInterval) {
blinkColor = !blinkColor;
lastBlinkPeriod = now;
}
for(int i=0;i<numLightPixels;i++){
pixels.setPixelColor(i, pixels.Color(blinkColor?255*MAX_INTESITY/100:0,0,0));
}
} else {
for(int i=0;i<numLightPixels;i++){
int r = 255 * i/NUMPIXELS;
int g = 255 - r;
// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(r*MAX_INTESITY/100,g*MAX_INTESITY/100,0));
}
// Turn off the rest
for(int i=numLightPixels;i<NUMPIXELS;i++){
pixels.setPixelColor(i, pixels.Color(0,0,0));
}
}
pixels.show(); // This sends the updated pixel color to the hardware.
}
}
@@ -1,9 +1,41 @@
// Default sensor sketch for Sensebender Micro module
// Act as a temperature / humidity sensor by default.
//
// If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals
//
// Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below)
/**
* 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.
*
*******************************
*
* REVISION HISTORY
* Version 1.0 - Thomas Bowman Mørch
*
* DESCRIPTION
* Default sensor sketch for Sensebender Micro module
* Act as a temperature / humidity sensor by default.
*
* If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals
*
* Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below)
*
*
* Version 1.3 - Thomas Bowman Mørch
* Improved transmission logic, eliminating spurious transmissions (when temperatuere / humidity fluctuates 1 up and down between measurements)
*
* Added OTA boot mode, need to hold A1 low while applying power. (uses slightly more power as it's waiting for bootloader messages)
*
*/
#include <MySensor.h>
@@ -15,7 +47,7 @@
#include <sha204_lib_return_codes.h>
#include <sha204_library.h>
#include <RunningAverage.h>
#include <avr/power.h>
//#include <avr/power.h>
// Define a static node address, remove if you want auto address assignment
//#define NODE_ADDRESS 3
@@ -23,7 +55,7 @@
// Uncomment the line below, to transmit battery voltage as a normal sensor value
//#define BATT_SENSOR 199
#define RELEASE "1.2"
#define RELEASE "1.3"
#define AVERAGES 2
@@ -34,6 +66,9 @@
// How many milli seconds between each measurement
#define MEASURE_INTERVAL 60000
// How many milli seconds should we wait for OTA?
#define OTA_WAIT_PERIOD 300
// FORCE_TRANSMIT_INTERVAL, this number of times of wakeup, the sensor is forced to report all values to the controller
#define FORCE_TRANSMIT_INTERVAL 30
@@ -47,6 +82,7 @@
// Pin definitions
#define TEST_PIN A0
#define OTA_ENABLE A1
#define LED_PIN A2
#define ATSHA204_PIN 17 // A3
@@ -71,6 +107,8 @@ int measureCount = 0;
int sendBattery = 0;
boolean isMetric = true;
boolean highfreq = true;
boolean ota_enabled = false;
boolean transmission_occured = false;
// Storage of old measurements
float lastTemperature = -100;
@@ -100,11 +138,19 @@ void setup() {
digitalWrite(TEST_PIN, HIGH); // Enable pullup
if (!digitalRead(TEST_PIN)) testMode();
pinMode(OTA_ENABLE, INPUT);
digitalWrite(OTA_ENABLE, HIGH);
if (!digitalRead(OTA_ENABLE)) {
ota_enabled = true;
}
// Make sure that ATSHA204 is not floating
pinMode(ATSHA204_PIN, INPUT);
digitalWrite(ATSHA204_PIN, HIGH);
digitalWrite(TEST_PIN,LOW);
digitalWrite(OTA_ENABLE, LOW); // remove pullup, save some power.
digitalWrite(LED_PIN, HIGH);
#ifdef NODE_ADDRESS
@@ -134,6 +180,8 @@ void setup() {
raHum.clear();
sendTempHumidityMeasurements(false);
sendBattLevel(false);
if (ota_enabled) Serial.println("OTA FW update enabled");
}
@@ -143,13 +191,14 @@ void setup() {
*
***********************************************/
void loop() {
measureCount ++;
sendBattery ++;
bool forceTransmit = false;
transmission_occured = false;
if ((measureCount == 5) && highfreq)
{
clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power.
if (!ota_enabled) clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power.
highfreq = false;
}
@@ -166,7 +215,11 @@ void loop() {
sendBattLevel(forceTransmit); // Not needed to send battery info that often
sendBattery = 0;
}
if (ota_enabled & transmission_occured) {
gw.wait(OTA_WAIT_PERIOD);
}
gw.sleep(MEASURE_INTERVAL);
}
@@ -182,21 +235,20 @@ void loop() {
void sendTempHumidityMeasurements(bool force)
{
bool tx = force;
si7021_env data = humiditySensor.getHumidityAndTemperature();
float oldAvgHum = raHum.getAverage();
raHum.addValue(data.humidityPercent);
float diffTemp = abs(lastTemperature - (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths)/100);
float diffHum = abs(oldAvgHum - raHum.getAverage());
float diffHum = abs(lastHumidity - raHum.getAverage());
Serial.print(F("TempDiff :"));Serial.println(diffTemp);
Serial.print(F("HumDiff :"));Serial.println(diffHum);
if (isnan(diffHum)) tx = true;
if (diffTemp > TEMP_TRANSMIT_THRESHOLD) tx = true;
if (diffHum >= HUMI_TRANSMIT_THRESHOLD) tx = true;
if (diffHum > HUMI_TRANSMIT_THRESHOLD) tx = true;
if (tx) {
measureCount = 0;
@@ -210,6 +262,7 @@ void sendTempHumidityMeasurements(bool force)
gw.send(msgHum.set(humidity));
lastTemperature = temperature;
lastHumidity = humidity;
transmission_occured = true;
}
}
@@ -238,6 +291,7 @@ void sendBattLevel(bool force)
long percent = vcc / 14.0;
gw.sendBatteryLevel(percent);
transmission_occured = true;
}
}
@@ -270,6 +324,7 @@ long readVcc() {
result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
return result; // Vcc in millivolts
}
/****************************************************