Merge branch 'master' into development

Conflicts:
	libraries/MySensors/utility/RFM69.h
This commit is contained in:
Henrik Ekblad
2015-09-05 22:58:56 +02:00
23 changed files with 834 additions and 159 deletions
+3
View File
@@ -26,6 +26,9 @@
// to see what is actually is happening when developing
#define DEBUG
// Disable this line, If you are using TX(1), RX(0) as normal I/O pin
#define ENABLED_SERIAL
// Serial output baud rate (for debug prints and serial gateway)
#define BAUD_RATE 115200
+12 -3
View File
@@ -17,6 +17,8 @@
* version 2 as published by the Free Software Foundation.
*/
#ifdef ARDUINO_ARCH_AVR
#include "MyHw.h"
#include "MyHwATMega328.h"
@@ -119,7 +121,9 @@ void powerDown(period_t period) {
void MyHwATMega328::internalSleep(unsigned long ms) {
// Let serial prints finish (debug, log etc)
Serial.flush();
#ifdef ENABLED_SERIAL
Serial.flush();
#endif
pinIntTrigger = 0;
while (!pinIntTrigger && ms >= 8000) { powerDown(SLEEP_8S); ms -= 8000; }
if (!pinIntTrigger && ms >= 4000) { powerDown(SLEEP_4S); ms -= 4000; }
@@ -148,7 +152,9 @@ bool MyHwATMega328::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) {
pinTriggeredWakeup = false;
}
} else {
Serial.flush();
#ifdef ENABLED_SERIAL
Serial.flush();
#endif
powerDown(SLEEP_FOREVER);
}
detachInterrupt(interrupt);
@@ -166,7 +172,9 @@ inline uint8_t MyHwATMega328::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t i
retVal = -1;
}
} else {
Serial.flush();
#ifdef ENABLED_SERIAL
Serial.flush();
#endif
powerDown(SLEEP_FOREVER);
}
detachInterrupt(interrupt1);
@@ -209,3 +217,4 @@ void MyHwATMega328::debugPrint(bool isGW, const char *fmt, ... ) {
}
#endif
#endif // #ifdef ARDUINO_ARCH_AVR
+3
View File
@@ -20,6 +20,8 @@
#ifndef MyHwATMega328_h
#define MyHwATMega328_h
#ifdef ARDUINO_ARCH_AVR
#include "MyHw.h"
#include "MyConfig.h"
#include "MyMessage.h"
@@ -116,3 +118,4 @@ private:
void internalSleep(unsigned long ms);
};
#endif
#endif // #ifdef ARDUINO_ARCH_AVR
+184
View File
@@ -0,0 +1,184 @@
/**
* 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.
*/
#ifdef ARDUINO_ARCH_ESP8266
#include "MyHw.h"
#include "MyHwESP8266.h"
#include <EEPROM.h>
/*
int8_t pinIntTrigger = 0;
void wakeUp() //place to send the interrupts
{
pinIntTrigger = 1;
}
void wakeUp2() //place to send the second interrupts
{
pinIntTrigger = 2;
}
// Watchdog Timer interrupt service routine. This routine is required
// to allow automatic WDIF and WDIE bit clearance in hardware.
ISR (WDT_vect)
{
// WDIE & WDIF is cleared in hardware upon entering this ISR
wdt_disable();
}
*/
static void hw_initConfigBlock( size_t length = 1024 /*ATMega328 has 1024 bytes*/ )
{
static bool initDone = false;
if (!initDone)
{
EEPROM.begin(length);
initDone = true;
}
}
void hw_readConfigBlock(void* buf, void* adr, size_t length)
{
hw_initConfigBlock();
uint8_t* dst = static_cast<uint8_t*>(buf);
int offs = reinterpret_cast<int>(adr);
while (length-- > 0)
{
*dst++ = EEPROM.read(offs++);
}
}
void hw_writeConfigBlock(void* buf, void* adr, size_t length)
{
hw_initConfigBlock();
uint8_t* src = static_cast<uint8_t*>(buf);
int offs = reinterpret_cast<int>(adr);
while (length-- > 0)
{
EEPROM.write(offs++, *src++);
}
EEPROM.commit();
}
uint8_t hw_readConfig(int adr)
{
uint8_t value;
hw_readConfigBlock(&value, reinterpret_cast<void*>(adr), 1);
return value;
}
void hw_writeConfig(int adr, uint8_t value)
{
uint8_t curr = hw_readConfig(adr);
if (curr != value)
{
hw_writeConfigBlock(&value, reinterpret_cast<void*>(adr), 1);
}
}
MyHwESP8266::MyHwESP8266() : MyHw()
{
}
/*
// The following was redifined as macros to save space
inline uint8_t MyHwATMega328::readConfig(uint8_t pos) {
return eeprom_read_byte((uint8_t*)pos);
}
inline void MyHwATMega328::writeConfig(uint8_t pos, uint8_t value) {
eeprom_update_byte((uint8_t*)pos, value);
}
inline void MyHwATMega328::readConfigBlock(void* buf, void * pos, size_t length) {
eeprom_read_block(buf, (void*)pos, length);
}
inline void MyHwATMega328::writeConfigBlock(void* pos, void* buf, size_t length) {
eeprom_write_block((void*)pos, (void*)buf, length);
}
inline void MyHwATMega328::init() {
Serial.begin(BAUD_RATE);
}
inline void MyHwATMega328::watchdogReset() {
wdt_reset();
}
inline void MyHwATMega328::reboot() {
wdt_enable(WDTO_15MS); for (;;);
}
inline unsigned long MyHwATMega328::millis() {
return ::millis();
}
*/
void MyHwESP8266::sleep(unsigned long ms) {
// TODO: Not supported!
}
bool MyHwESP8266::sleep(uint8_t interrupt, uint8_t mode, unsigned long ms) {
// TODO: Not supported!
return false;
}
inline uint8_t MyHwESP8266::sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms) {
// TODO: Not supported!
return 0;
}
#ifdef DEBUG
void MyHwESP8266::debugPrint(bool isGW, const char *fmt, ... ) {
char fmtBuffer[300];
if (isGW) {
// prepend debug message to be handled correctly by controller (C_INTERNAL, I_LOG_MESSAGE)
snprintf_P(fmtBuffer, 299, PSTR("0;0;%d;0;%d;"), C_INTERNAL, I_LOG_MESSAGE);
Serial.print(fmtBuffer);
}
va_list args;
va_start (args, fmt );
va_end (args);
if (isGW) {
// Truncate message if this is gateway node
vsnprintf_P(fmtBuffer, 60, fmt, args);
fmtBuffer[59] = '\n';
fmtBuffer[60] = '\0';
} else {
vsnprintf_P(fmtBuffer, 299, fmt, args);
}
va_end (args);
Serial.print(fmtBuffer);
Serial.flush();
//Serial.write(freeRam());
}
#endif
#endif // #ifdef ARDUINO_ARCH_ESP8266
+86
View File
@@ -0,0 +1,86 @@
/**
* 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.
*/
#ifdef ARDUINO_ARCH_ESP8266
#ifndef MyHwESP8266_h
#define MyHwESP8266_h
#include "MyHw.h"
#include "MyConfig.h"
#include "MyMessage.h"
#ifdef __cplusplus
#include <Arduino.h>
#include <SPI.h>
#endif
// Define these as macros to save valuable space
#define hw_digitalWrite(__pin, __value) (digitalWrite(__pin, __value))
#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()
void hw_readConfigBlock(void* buf, void* adr, size_t length);
void hw_writeConfigBlock(void* buf, void* adr, size_t length);
void hw_writeConfig(int adr, uint8_t value);
uint8_t hw_readConfig(int adr);
enum period_t
{
SLEEP_15Ms,
SLEEP_30MS,
SLEEP_60MS,
SLEEP_120MS,
SLEEP_250MS,
SLEEP_500MS,
SLEEP_1S,
SLEEP_2S,
SLEEP_4S,
SLEEP_8S,
SLEEP_FOREVER
};
class MyHwESP8266 : public MyHw
{
public:
MyHwESP8266();
/* void init();
void watchdogReset();
void reboot();
unsigned long millis();
uint8_t readConfig(uint8_t pos);
void writeConfig(uint8_t pos, uint8_t value);
void readConfigBlock(void* buf, void * pos, size_t length);
void writeConfigBlock(void* pos, void* buf, size_t length); */
void sleep(unsigned long ms);
bool sleep(uint8_t interrupt, uint8_t mode, unsigned long ms);
uint8_t sleep(uint8_t interrupt1, uint8_t mode1, uint8_t interrupt2, uint8_t mode2, unsigned long ms);
#ifdef DEBUG
void debugPrint(bool isGW, const char *fmt, ... );
#endif
};
#endif
#endif // #ifdef ARDUINO_ARCH_ESP8266
+2
View File
@@ -167,7 +167,9 @@ typedef enum {
#ifndef BIT
#define BIT(n) ( 1<<(n) )
#endif
// Create a bitmask of length len.
#define BIT_MASK(len) ( BIT(len)-1 )
// Create a bitfield mask of length starting at bit 'start'.
+5 -5
View File
@@ -95,14 +95,12 @@ bool MySensor::isValidFirmware() {
#ifdef WITH_LEDS_BLINKING
void MySensor::handleLedsBlinking() {
static unsigned long next_time = hw_millis() + ledBlinkPeriod;
// Just return if it is not the time...
// http://playground.arduino.cc/Code/TimingRollover
if ((long)(hw_millis() - next_time) < 0)
if ((long)(hw_millis() - blink_next_time) < 0)
return;
else
next_time = hw_millis() + ledBlinkPeriod;
blink_next_time = hw_millis() + ledBlinkPeriod;
// do the actual blinking
if(countRx && countRx != 255) {
@@ -153,7 +151,9 @@ void MySensor::errBlink(uint8_t cnt) {
#endif
void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, boolean _repeaterMode, uint8_t _parentNodeId) {
hw_init();
#ifdef ENABLED_SERIAL
hw_init();
#endif
repeaterMode = _repeaterMode;
msgCallback = _msgCallback;
failedTransmissions = 0;
+6
View File
@@ -41,8 +41,13 @@
// Set the hardware driver to use (initialized by MySensor-class)
//#if defined __AVR_ATmega328P__
#if defined(ARDUINO_ARCH_ESP8266)
#include "MyHwESP8266.h"
typedef MyHwESP8266 MyHwDriver;
#elif defined(ARDUINO_ARCH_AVR)
#include "MyHwATMega328.h"
typedef MyHwATMega328 MyHwDriver;
#endif
//#endif
@@ -362,6 +367,7 @@ class MySensor
unsigned long ledBlinkPeriod;
void handleLedsBlinking(); // do the actual blinking
unsigned long blink_next_time;
#endif
MyTransport& radio;
@@ -24,6 +24,7 @@
* HMAC-SHA256 authentication with a readout-protected key.
*
*/
#if defined(ARDUINO_ARCH_AVR)
#include "MySigning.h"
#include "MySigningAtsha204.h"
@@ -266,3 +267,4 @@ uint8_t* MySigningAtsha204::sha256(const uint8_t* data, size_t sz) {
DEBUG_SIGNING_PRINTBUF(F("SHA:"), &rx_buffer[SHA204_BUFFER_POS_DATA], 32);
return &rx_buffer[SHA204_BUFFER_POS_DATA];
}
#endif // #if defined(ARDUINO_ARCH_AVR)
+1 -1
View File
@@ -33,7 +33,7 @@ bool MyTransportRFM69::init() {
// Start up the radio library (_address will be set later by the MySensors library)
radio.initialize(_freqBand, _address, _networkId);
#ifdef RFM69_ENABLE_ENCRYPTION
radio.encrypt(ENCRYPTKEY);
radio.encrypt(RFM69_ENCRYPTKEY);
#endif
return true;
}
@@ -0,0 +1,265 @@
/**
* 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 - Henrik EKblad
* Contribution by a-lurker and Anticimex,
* Contribution by Norbert Truchsess <norbert.truchsess@t-online.de>
* Contribution by Ivo Pullens (ESP8266 support)
*
* DESCRIPTION
* The EthernetGateway sends data received from sensors to the WiFi link.
* The gateway also accepts input on ethernet interface, which is then sent out to the radio network.
*
* VERA CONFIGURATION:
* Enter "ip-number:port" in the ip-field of the Arduino GW device. This will temporarily override any serial configuration for the Vera plugin.
* E.g. If you want to use the defualt values in this sketch enter: 192.168.178.66:5003
*
* LED purposes:
* - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h
* - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved
* - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly
* - ERR (red) - fast blink on error during transmission error or recieve crc error
*
* See http://www.mysensors.org/build/ethernet_gateway for wiring instructions.
* The ESP8266 however requires different wiring:
* nRF24L01+ ESP8266
* VCC VCC
* CE GPIO4
* CSN/CS GPIO15
* SCK GPIO14
* MISO GPIO12
* MOSI GPIO13
*
* Not all ESP8266 modules have all pins available on their external interface.
* This code has been tested on an ESP-12 module.
* The ESP8266 requires a certain pin configuration to download code, and another one to run code:
* - Connect REST (reset) via 10K pullup resistor to VCC, and via switch to GND ('reset switch')
* - Connect GPIO15 via 10K pulldown resistor to GND
* - Connect CH_PD via 10K resistor to VCC
* - Connect GPIO2 via 10K resistor to VCC
* - Connect GPIO0 via 10K resistor to VCC, and via switch to GND ('bootload switch')
*
* Inclusion mode button:
* - Connect GPIO5 via switch to GND ('inclusion switch')
*
* Hardware SHA204 signing is currently not supported!
*
* Make sure to fill in your ssid and WiFi password below for ssid & pass.
*/
#define NO_PORTB_PINCHANGES
#include <SPI.h>
#include <MySigningNone.h>
#include <MySigningAtsha204Soft.h>
#include <MyTransportNRF24.h>
#include <MyTransportRFM69.h>
#include <EEPROM.h>
#include <MyHwESP8266.h>
#include <ESP8266WiFi.h>
#include <MyParserSerial.h>
#include <MySensor.h>
#include <stdarg.h>
#include "GatewayUtil.h"
const char *ssid = "MySSID"; // cannot be longer than 32 characters!
const char *pass = "MyVerySecretPassword"; //
#define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled
#define INCLUSION_MODE_PIN 5 // Digital pin used for inclusion mode button
#define RADIO_CE_PIN 4 // radio chip enable
#define RADIO_SPI_SS_PIN 15 // radio SPI serial select
#ifdef WITH_LEDS_BLINKING
#define RADIO_ERROR_LED_PIN 7 // Error led pin
#define RADIO_RX_LED_PIN 8 // Receive led pin
#define RADIO_TX_LED_PIN 9 // the PCB, on board LED
#endif
// NRFRF24L01 radio driver (set low transmit power by default)
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)
#ifdef MY_SIGNING_FEATURE
MySigningNone signer;
//MySigningAtsha204Soft signer;
#endif
// Hardware profile
MyHwESP8266 hw;
// Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
// To use LEDs blinking, uncomment WITH_LEDS_BLINKING in MyConfig.h
MySensor gw(transport, hw
#ifdef MY_SIGNING_FEATURE
, signer
#endif
#ifdef WITH_LEDS_BLINKING
, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN
#endif
);
#define IP_PORT 5003 // The port you want to open
#define MAX_SRV_CLIENTS 5 // how many clients should be able to telnet to this ESP8266
// a R/W server on the port
static WiFiServer server(IP_PORT);
static WiFiClient clients[MAX_SRV_CLIENTS];
static bool clientsConnected[MAX_SRV_CLIENTS];
static inputBuffer inputString[MAX_SRV_CLIENTS];
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
void output(const char *fmt, ... )
{
char serialBuffer[MAX_SEND_LENGTH];
va_list args;
va_start (args, fmt );
vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args);
va_end (args);
Serial.print(serialBuffer);
for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++)
{
if (clients[i] && clients[i].connected())
{
// Serial.print("Client "); Serial.print(i); Serial.println(" write");
clients[i].write((uint8_t*)serialBuffer, strlen(serialBuffer));
}
}
}
void setup()
{
// Setup console
hw_init();
Serial.println(); Serial.println();
Serial.println("ESP8266 MySensors Gateway");
Serial.print("Connecting to "); Serial.println(ssid);
(void)WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("Connected!");
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.flush();
setupGateway(INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output);
// Initialize gateway at maximum PA level, channel 70 and callback for write operations
gw.begin(incomingMessage, 0, true, 0);
// start listening for clients
server.begin();
server.setNoDelay(true);
}
void loop() {
gw.process();
checkButtonTriggeredInclusion();
checkInclusionFinished();
// Go over list of clients and stop any that are no longer connected.
// If the server has a new client connection it will be assigned to a free slot.
bool allSlotsOccupied = true;
for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++)
{
if (!clients[i].connected())
{
if (clientsConnected[i])
{
Serial.print("Client "); Serial.print(i); Serial.println(" disconnected");
clients[i].stop();
}
//check if there are any new clients
if (server.hasClient())
{
clients[i] = server.available();
inputString[i].idx = 0;
Serial.print("Client "); Serial.print(i); Serial.println(" connected");
output(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY);
}
}
bool connected = clients[i].connected();
clientsConnected[i] = connected;
allSlotsOccupied &= connected;
}
if (allSlotsOccupied && server.hasClient())
{
//no free/disconnected spot so reject
Serial.println("No free slot available");
WiFiClient c = server.available();
c.stop();
}
// Loop over clients connect and read available data
for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++)
{
while(clients[i].connected() && clients[i].available())
{
char inChar = clients[i].read();
if ( inputString[i].idx < MAX_RECEIVE_LENGTH - 1 )
{
// if newline then command is complete
if (inChar == '\n')
{
// a command was issued by the client
// we will now try to send it to the actuator
inputString[i].string[inputString[i].idx] = 0;
// echo the string to the serial port
Serial.print("Client "); Serial.print(i); Serial.print(": "); Serial.println(inputString[i].string);
parseAndSend(gw, inputString[i].string);
// clear the string:
inputString[i].idx = 0;
// Finished with this client's message. Next loop() we'll see if there's more to read.
break;
} else {
// add it to the inputString:
inputString[i].string[inputString[i].idx++] = inChar;
}
} else {
// Incoming message too long. Throw away
Serial.print("Client "); Serial.print(i); Serial.println(": Message too long");
inputString[i].idx = 0;
// Finished with this client's message. Next loop() we'll see if there's more to read.
break;
}
}
}
}
@@ -0,0 +1,136 @@
#ifndef __GATEWAYUTIL_H__
#define __GATEWAYUTIL_H__
#ifdef ARDUINO
static uint8_t inclusionTime = 1; // Number of minutes inclusion mode is enabled
static uint8_t pinInclusion = 3; // Input pin that should trigger inclusion mode
#define MAX_RECEIVE_LENGTH 100 // Max buffersize needed for messages coming from controller
#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages destined for controller
typedef struct
{
char string[MAX_RECEIVE_LENGTH];
uint8_t idx;
} inputBuffer;
static volatile boolean buttonTriggeredInclusion;
static boolean inclusionMode; // Keeps track on inclusion mode
bool inclusionButtonSupported = false;
void (*serial)(const char *fmt, ... );
MyParserSerial parser;
void setInclusionMode(boolean newMode);
char convBuf[MAX_PAYLOAD*2+1];
unsigned long inclusionStartTime;
void startInclusionInterrupt() {
buttonTriggeredInclusion = true;
}
void setupGateway(uint8_t _inc, uint8_t _incTime, void (* _serial)(const char *, ... )) {
inclusionMode = 0;
buttonTriggeredInclusion = false;
serial = _serial;
inclusionTime = _incTime;
inclusionButtonSupported = (_inc != 255);
if (inclusionButtonSupported)
{
pinInclusion = _inc;
// Setup digital in that triggers inclusion mode
pinMode(pinInclusion, INPUT_PULLUP);
// Add interrupt for inclusion button to pin
attachInterrupt(pinInclusion, startInclusionInterrupt, FALLING);
}
}
void incomingMessage(const MyMessage &message) {
// if (mGetCommand(message) == C_PRESENTATION && inclusionMode) {
// gw.rxBlink(3);
// } else {
// gw.rxBlink(1);
// }
// Pass along the message from sensors to serial line
serial(PSTR("%d;%d;%d;%d;%d;%s\n"),message.sender, message.sensor, mGetCommand(message), mGetAck(message), message.type, message.getString(convBuf));
}
void checkButtonTriggeredInclusion() {
if (inclusionButtonSupported)
{
if (buttonTriggeredInclusion) {
// Ok, someone pressed the inclusion button on the gateway
// start inclusion mode for 1 munute.
#ifdef DEBUG
serial(PSTR("0;0;%d;0;%d;Inclusion started by button.\n"), C_INTERNAL, I_LOG_MESSAGE);
#endif
buttonTriggeredInclusion = false;
setInclusionMode(true);
}
}
}
void checkInclusionFinished() {
if (inclusionMode && millis()-inclusionStartTime>60000UL*inclusionTime) {
// inclusionTimeInMinutes minute(s) has passed.. stop inclusion mode
setInclusionMode(false);
}
}
void parseAndSend(MySensor &gw, char *commandBuffer) {
boolean ok;
MyMessage &msg = gw.getLastMessage();
if (parser.parse(msg, commandBuffer)) {
uint8_t command = mGetCommand(msg);
if (msg.destination==GATEWAY_ADDRESS && command==C_INTERNAL) {
// Handle messages directed to gateway
if (msg.type == I_VERSION) {
// Request for version
serial(PSTR("0;0;%d;0;%d;%s\n"), C_INTERNAL, I_VERSION, LIBRARY_VERSION);
} else if (msg.type == I_INCLUSION_MODE) {
// Request to change inclusion mode
setInclusionMode(atoi(msg.data) == 1);
}
} else {
#ifdef WITH_LEDS_BLINKING
gw.txBlink(1);
#endif
ok = gw.sendRoute(msg);
if (!ok) {
#ifdef WITH_LEDS_BLINKING
gw.errBlink(1);
#endif
}
}
}
}
void setInclusionMode(boolean newMode) {
if (newMode != inclusionMode) {
inclusionMode = newMode;
// Send back mode change on serial line to ack command
serial(PSTR("0;0;%d;0;%d;%d\n"), C_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0);
if (inclusionMode) {
inclusionStartTime = millis();
}
}
}
#else
#error This example is only for use on Arduino.
#endif // ARDUINO
#endif
@@ -1,81 +1,9 @@
/**
* 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 - idefix
*
* DESCRIPTION
* Arduino BH1750FVI Light sensor
* communicate using I2C Protocol
* this library enable 2 slave device addresses
* Main address 0x23
* secondary address 0x5C
* connect the sensor as follows :
*
* VCC >>> 5V
* Gnd >>> Gnd
* ADDR >>> NC or GND
* SCL >>> A5
* SDA >>> A4
* http://www.mysensors.org/build/light
*/
#include <MySensor.h>
#include <SPI.h>
#include <MySensor.h>
#include <BH1750.h>
#include <Wire.h>
#define CHILD_ID_LIGHT 0
unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
MyTransportNRF24 transport;
MyHwATMega328 hw;
MySensor gw(transport, hw);
BH1750 lightSensor;
MySensor gw;
// V_LIGHT_LEVEL should only be used for uncalibrated light level 0-100%.
// If your controller supports the new V_LEVEL variable, use this instead for
// transmitting LUX light level.
MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL);
// MyMessage msg(CHILD_ID_LIGHT, V_LEVEL);
uint16_t lastlux;
void setup()
{
gw.begin();
// Send the sketch version information to the gateway and Controller
gw.sendSketchInfo("Light Lux Sensor", "1.0");
// Register all sensors to gateway (they will be created as child devices)
gw.present(CHILD_ID_LIGHT, S_LIGHT_LEVEL);
lightSensor.begin();
}
void loop()
{
uint16_t lux = lightSensor.readLightLevel();// Get Lux value
Serial.println(lux);
if (lux != lastlux) {
gw.send(msg.set(lux));
lastlux = lux;
}
gw.sleep(SLEEP_TIME);
}
void setup() {}
void loop() {}
@@ -56,6 +56,8 @@
#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)
#define PARK_OFF_TIMEOUT 20000 // Number of milliseconds until turning off light when parked.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
@@ -67,10 +69,11 @@ NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and
#define CHILD_ID 1
MySensor gw;
MyMessage msg(CHILD_ID,V_TRIPPED);
int oldParkedStatus=-1;
#endif
unsigned long sendInterval = 5000; // Send park status at maximum every 5 second.
unsigned long lastSend;
#endif
int oldParkedStatus=-1;
unsigned long blinkInterval = 100; // blink interval (milliseconds)
unsigned long lastBlinkPeriod;
@@ -109,7 +112,6 @@ void loop() {
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) {
@@ -117,48 +119,56 @@ void loop() {
Serial.println("Car Parked");
else
Serial.println("Car Gone");
#ifdef SEND_STATUS_TO_CONTROLLER
gw.send(msg.set(parked));
#endif
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++){
if (parked && now-lastSend > PARK_OFF_TIMEOUT) {
// We've been parked for a while now. Turn off all pixels
for(int i=0;i<NUMPIXELS;i++){
pixels.setPixelColor(i, pixels.Color(0,0,0));
}
} else {
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.
}
}
}
@@ -20,6 +20,7 @@
*
* REVISION HISTORY
* Version 1.0 - Henrik Ekblad
* Version 1.1 - GizMoCuz
*
* DESCRIPTION
* Use this sensor to measure volume and flow of your house watermeter.
@@ -33,8 +34,8 @@
* http://www.mysensors.org/build/pulse_water
*/
#include <SPI.h>
#include <MySensor.h>
#include <SPI.h>
#define DIGITAL_INPUT_SENSOR 3 // The digital input you attached your sensor. (Only 2 and 3 generates interrupt!)
#define SENSOR_INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
@@ -47,7 +48,7 @@
#define CHILD_ID 1 // Id of the sensor child
unsigned long SEND_FREQUENCY = 20000; // Minimum time between send (in milliseconds). We don't want to spam the gateway.
unsigned long SEND_FREQUENCY = 30000; // Minimum time between send (in milliseconds). We don't want to spam the gateway.
MySensor gw;
MyMessage flowMsg(CHILD_ID,V_FLOW);
@@ -72,8 +73,11 @@ void setup()
{
gw.begin(incomingMessage);
// initialize our digital pins internal pullup resistor so one pulse switches from high to low (less distortion)
pinMode(DIGITAL_INPUT_SENSOR, INPUT_PULLUP);
// Send the sketch version information to the gateway and Controller
gw.sendSketchInfo("Water Meter", "1.2");
gw.sendSketchInfo("Water Meter", "1.1");
// Register this device as Waterflow sensor
gw.present(CHILD_ID, S_WATER);
@@ -85,7 +89,7 @@ void setup()
lastSend = lastPulse = millis();
attachInterrupt(SENSOR_INTERRUPT, onPulse, RISING);
attachInterrupt(SENSOR_INTERRUPT, onPulse, FALLING);
}
@@ -93,7 +97,7 @@ void loop()
{
gw.process();
unsigned long currentTime = millis();
// Only send values at a maximum frequency or woken up from sleep
if (SLEEP_MODE || (currentTime - lastSend > SEND_FREQUENCY))
{
@@ -124,7 +128,7 @@ void loop()
}
// Pulse count has changed
if (pulseCount != oldPulseCount) {
if ((pulseCount != oldPulseCount)||(!SLEEP_MODE)) {
oldPulseCount = pulseCount;
Serial.print("pulsecount:");
@@ -133,7 +137,7 @@ void loop()
gw.send(lastCounterMsg.set(pulseCount)); // Send pulsecount value to gw in VAR1
double volume = ((double)pulseCount/((double)PULSE_FACTOR));
if (volume != oldvolume) {
if ((volume != oldvolume)||(!SLEEP_MODE)) {
oldvolume = volume;
Serial.print("volume:");
@@ -152,6 +156,7 @@ void incomingMessage(const MyMessage &message) {
if (message.type==V_VAR1) {
unsigned long gwPulseCount=message.getULong();
pulseCount += gwPulseCount;
flow=oldflow=0;
Serial.print("Received last pulse count from gw:");
Serial.println(pulseCount);
pcReceived = true;
@@ -178,4 +183,3 @@ void onPulse()
}
pulseCount++;
}
+4
View File
@@ -1,3 +1,5 @@
#if defined(ARDUINO_ARCH_AVR)
#include "Arduino.h"
#include "ATSHA204.h"
@@ -572,3 +574,5 @@ uint8_t ATSHA204Class::sha204c_check_crc(uint8_t *response)
return (crc[0] == response[count] && crc[1] == response[count + 1])
? SHA204_SUCCESS : SHA204_BAD_CRC;
}
#endif // defined(ARDUINO_ARCH_AVR)
+32 -19
View File
@@ -498,7 +498,7 @@ void RF24::begin(void)
// Reset current status
// Notice reset and flush is the last thing we do
write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
write_register(RF24_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
// Set up default configuration. Callers can always change it later.
// This channel should be universally safe and not bleed over into adjacent
@@ -525,7 +525,7 @@ void RF24::startListening(void)
powerUp();
#endif
write_register(CONFIG, read_register(CONFIG) | _BV(PRIM_RX));
write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
write_register(RF24_STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
// Restore the pipe0 adddress, if exists
if (pipe0_reading_address[0] > 0){
@@ -546,22 +546,35 @@ void RF24::startListening(void)
}
/****************************************************************************/
static const uint8_t child_pipe_enable[] PROGMEM =
static uint8_t get_child_pipe_mask(const uint8_t idx)
{
ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5
};
#ifdef ESP8266
static const uint8_t child_pipe_enable[] =
{
_BV(ERX_P0), _BV(ERX_P1), _BV(ERX_P2), _BV(ERX_P3), _BV(ERX_P4), _BV(ERX_P5)
};
return child_pipe_enable[idx];
#else
static const uint8_t child_pipe_enable[] PROGMEM =
{
_BV(ERX_P0), _BV(ERX_P1), _BV(ERX_P2), _BV(ERX_P3), _BV(ERX_P4), _BV(ERX_P5)
};
return pgm_read_byte(&child_pipe_enable[idx]);
#endif
}
void RF24::stopListening(void)
{
ce(LOW);
#if defined(__arm__)
delayMicroseconds(300);
#endif
delayMicroseconds(130);
if(read_register(FEATURE) & _BV(EN_ACK_PAY)){
flush_tx();
}
//flush_rx();
write_register(CONFIG, ( read_register(CONFIG) ) & ~_BV(PRIM_RX) );
@@ -569,13 +582,13 @@ void RF24::stopListening(void)
// for 3 pins solution TX mode is only left with additonal powerDown/powerUp cycle
if (ce_pin == csn_pin) {
powerDown();
powerUp();
powerUp();
}
#endif
write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[0]))); // Enable RX on pipe0
write_register(EN_RXADDR,read_register(EN_RXADDR) | get_child_pipe_mask(0)); // Enable RX on pipe0
delayMicroseconds(100);
}
/****************************************************************************/
@@ -636,7 +649,7 @@ bool RF24::write( const void* buf, uint8_t len, const bool multicast )
ce(LOW);
uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
uint8_t status = write_register(RF24_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
//Max retries exceeded
if( status & _BV(MAX_RT)){
@@ -686,7 +699,7 @@ bool RF24::writeBlocking( const void* buf, uint8_t len, uint32_t timeout )
/****************************************************************************/
void RF24::reUseTX(){
write_register(STATUS,_BV(MAX_RT) ); //Clear max retry flag
write_register(RF24_STATUS,_BV(MAX_RT) ); //Clear max retry flag
spiTrans( REUSE_TX_PL );
ce(LOW); //Re-Transfer packet
ce(HIGH);
@@ -709,7 +722,7 @@ bool RF24::writeFast( const void* buf, uint8_t len, const bool multicast )
if( get_status() & _BV(MAX_RT)){
//reUseTX(); //Set re-transmit
write_register(STATUS,_BV(MAX_RT) ); //Clear max retry flag
write_register(RF24_STATUS,_BV(MAX_RT) ); //Clear max retry flag
return 0; //Return 0. The previous payload has been retransmitted
//From the user perspective, if you get a 0, just keep trying to send the same payload
}
@@ -777,7 +790,7 @@ bool RF24::txStandBy(){
#endif
while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){
if( get_status() & _BV(MAX_RT)){
write_register(STATUS,_BV(MAX_RT) );
write_register(RF24_STATUS,_BV(MAX_RT) );
ce(LOW);
flush_tx(); //Non blocking, flush the data
return 0;
@@ -802,7 +815,7 @@ bool RF24::txStandBy(uint32_t timeout){
while( ! (read_register(FIFO_STATUS) & _BV(TX_EMPTY)) ){
if( get_status() & _BV(MAX_RT)){
write_register(STATUS,_BV(MAX_RT) );
write_register(RF24_STATUS,_BV(MAX_RT) );
ce(LOW); //Set re-transmit
ce(HIGH);
if(millis() - start >= timeout){
@@ -891,7 +904,7 @@ void RF24::read( void* buf, uint8_t len ){
read_payload( buf, len );
//Clear the two possible interrupt flags with one command
write_register(STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS) );
write_register(RF24_STATUS,_BV(RX_DR) | _BV(MAX_RT) | _BV(TX_DS) );
}
@@ -901,7 +914,7 @@ void RF24::whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready)
{
// Read the status & reset the status in one easy call
// Or is that such a good idea?
uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
uint8_t status = write_register(RF24_STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
// Report to the user what happened
tx_ok = status & _BV(TX_DS);
@@ -972,7 +985,7 @@ void RF24::openReadingPipe(uint8_t child, uint64_t address)
// Note it would be more efficient to set all of the bits for all open
// pipes at once. However, I thought it would make the calling code
// more simple to do it this way.
write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child])));
write_register(EN_RXADDR,read_register(EN_RXADDR) | get_child_pipe_mask(child));
}
}
@@ -1009,7 +1022,7 @@ void RF24::openReadingPipe(uint8_t child, const uint8_t *address)
// Note it would be more efficient to set all of the bits for all open
// pipes at once. However, I thought it would make the calling code
// more simple to do it this way.
write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child])));
write_register(EN_RXADDR,read_register(EN_RXADDR) | get_child_pipe_mask(child));
}
}
@@ -1018,7 +1031,7 @@ void RF24::openReadingPipe(uint8_t child, const uint8_t *address)
void RF24::closeReadingPipe( uint8_t pipe )
{
write_register(EN_RXADDR,read_register(EN_RXADDR) & ~_BV(pgm_read_byte(&child_pipe_enable[pipe])));
write_register(EN_RXADDR,read_register(EN_RXADDR) & ~get_child_pipe_mask(pipe));
}
/****************************************************************************/
+7 -4
View File
@@ -87,7 +87,7 @@
// Avoid spurious warnings
// Arduino DUE is arm and uses traditional PROGMEM constructs
#if 1
#if ! defined( NATIVE ) && defined( ARDUINO ) && ! defined(__arm__) && ! defined( CORE_TEENSY3 )
#if ! defined( NATIVE ) && defined( ARDUINO ) && ! defined(__arm__) && ! defined( CORE_TEENSY3 ) && ! defined(ESP8266)
#undef PROGMEM
#define PROGMEM __attribute__(( section(".progmem.data") ))
#undef PSTR
@@ -97,18 +97,21 @@
// Progmem is Arduino-specific
// Arduino DUE is arm and does not include avr/pgmspace
#if defined(ARDUINO) && ! defined(__arm__)
#if defined(__AVR__)
#include <avr/pgmspace.h>
#define PRIPSTR "%S"
#else
#if defined(ESP8266)
#include <pgmspace.h>
#else
#if ! defined(ARDUINO) // This doesn't work on Arduino DUE
typedef char const char;
#else // Fill in pgm_read_byte that is used, but missing from DUE
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#endif
#endif
#if !defined ( CORE_TEENSY )
#if !defined ( CORE_TEENSY ) && ! defined(ESP8266)
typedef uint16_t prog_uint16_t;
#define PSTR(x) (x)
#define printf_P printf
+4
View File
@@ -384,8 +384,10 @@ void RFM69::writeReg(byte addr, byte value)
void RFM69::select() {
noInterrupts();
//save current SPI settings
#ifndef ESP8266
_SPCR = SPCR;
_SPSR = SPSR;
#endif
//set RFM69 SPI settings
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
@@ -397,8 +399,10 @@ void RFM69::select() {
void RFM69::unselect() {
digitalWrite(_slaveSelectPin, HIGH);
//restore SPI settings to what they were before talking to RFM69
#ifndef ESP8266
SPCR = _SPCR;
SPSR = _SPSR;
#endif
interrupts();
}
+3
View File
@@ -47,10 +47,13 @@
#define RF69_IRQ_PIN 3
#define RF69_IRQ_NUM 0
#else
// ESP8266 should fall into this category now
// TODO !! Untested code! Entering unknown territory...
#define RF69_IRQ_PIN 2
#define RF69_IRQ_NUM 0
#endif
#define CSMA_LIMIT -90 // upper RX signal sensitivity threshold in dBm for carrier sense access
#define RF69_MODE_SLEEP 0 // XTAL OFF
#define RF69_MODE_STANDBY 1 // XTAL ON
+6
View File
@@ -56,8 +56,10 @@ void SPIFlash::select() {
#ifndef SPI_HAS_TRANSACTION
noInterrupts();
#endif
#ifndef ESP8266
_SPCR = SPCR;
_SPSR = SPSR;
#endif
#ifdef SPI_HAS_TRANSACTION
SPI.beginTransaction(_settings);
@@ -80,15 +82,19 @@ void SPIFlash::unselect() {
#else
interrupts();
#endif
#ifndef ESP8266
SPCR = _SPCR;
SPSR = _SPSR;
#endif
}
/// setup SPI, read device ID etc...
boolean SPIFlash::initialize()
{
#ifndef ESP8266
_SPCR = SPCR;
_SPSR = SPSR;
#endif
pinMode(_slaveSelectPin, OUTPUT);
#ifdef SPI_HAS_TRANSACTION
_settings = SPISettings(4000000, MSBFIRST, SPI_MODE0);
+1 -1
View File
@@ -31,7 +31,7 @@
#define SETUP_RETR 0x04
#define RF_CH 0x05
#define RF_SETUP 0x06
#define STATUS 0x07
#define RF24_STATUS 0x07
#define OBSERVE_TX 0x08
#define CD 0x09
#define RX_ADDR_P0 0x0A
+6 -2
View File
@@ -1,6 +1,10 @@
#include <string.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#if defined(__AVR__)
#include <avr/pgmspace.h>
#define PRIPSTR "%S"
#elif defined(ESP8266)
#include <pgmspace.h>
#endif
#include "sha256.h"