From b08e168d16dc89f6bd4e9fefbd4f4f2e8367cc93 Mon Sep 17 00:00:00 2001 From: Damme Date: Wed, 13 Aug 2014 21:08:51 +0200 Subject: [PATCH 1/8] Create MQTTGateway.ino MQTTGateway Beta 0.1 --- MQTTGateway/MQTTGateway.ino | 83 +++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 MQTTGateway/MQTTGateway.ino diff --git a/MQTTGateway/MQTTGateway.ino b/MQTTGateway/MQTTGateway.ino new file mode 100644 index 0000000..d59e4b6 --- /dev/null +++ b/MQTTGateway/MQTTGateway.ino @@ -0,0 +1,83 @@ +// MyMQTT Gateway 0.1b +// +// Created by Daniel Wiegert +// Based on Mysensors Ethernet Gateway by Henrik Ekblad +// http://www.mysensors.org +// +// Requires MySensors lib 1.4b +// +// Don't forget to look at the definitions in MyMQTT.h! +// Don't forget to configure Radio pins, IP and MAC-address! +// +// Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/Light +// NodeID and SensorID is Decimal number. +// Last segment is translation of the sensor type, look inside MyMQTT.cpp for +// the definitions. User can change this to their needs. +// +// Features: +// Supports automatic nodeID delegation +// Recieve sketchname and version Example: (openhab item) +//String sketch20 "Node 20 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/20/255/Sketch_name:state:default]"} +//String sketch21 "Node 21 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/21/255/Sketch_name:state:default]"} +// ... +// +// Todo: +// DOCUMENTATION... +// Special commands : clear or set EEPROM Values +// Special commands : Reboot +// ... + + +#include +#include +#include + + +// Use this for IBOARD modded to use standard MISO/MOSI/SCK More information see; +// http://forum.mysensors.org/topic/224/iboard-cheap-single-board-ethernet-arduino-with-radio/5 +#define RADIO_CE_PIN 3 // radio chip enable +#define RADIO_SPI_SS_PIN 8 // radio SPI serial select + +//Use this for default configured pro mini / nano etc : +//#define RADIO_CE_PIN 5 // radio chip enable +//#define RADIO_SPI_SS_PIN 6 // radio SPI serial select + +#define IP_PORT 1883 // MQTT Listening port +IPAddress myIp ( 192, 168, 0, 234 ); // Configure your static ip-address here +byte mac[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - Change this! +// * NOTE: Keep first byte at x2, x6, xA or xE (replace x with any hex value) for using Locally Administered Address Ranges. + +EthernetServer server = EthernetServer(IP_PORT); +MyMQTT gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); + +void processEthernetMessages() { + char inputString[MQTT_MAX_PACKET_SIZE] = ""; + int inputSize = 0; + EthernetClient client = server.available(); + if (client) { + while (client.available()) { + char inChar = client.read(); + inputString[inputSize] = inChar; + inputSize++; + } + gw.processMQTTMessage(inputString, inputSize); + } +} + +void writeEthernet(char *writeBuffer, int *writeSize) { + server.write(writeBuffer, *writeSize); // Should this really be *writeSize? +} + +int main(void) { + init(); + Ethernet.begin(mac, myIp); + delay(1000); // Wait for Ethernet to get configured. + gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet); + server.begin(); + while (1) { + processEthernetMessages(); + gw.processRadioMessage(); + } +} + + From 9eca431b91b53e618f448f70952397c0b6226277 Mon Sep 17 00:00:00 2001 From: Damme Date: Wed, 13 Aug 2014 21:11:45 +0200 Subject: [PATCH 2/8] Create MyMQTT.cpp MQTTGateway beta 0.1 --- libraries/MySensors/MyMQTT.cpp | 312 +++++++++++++++++++++++++++++++++ 1 file changed, 312 insertions(+) create mode 100644 libraries/MySensors/MyMQTT.cpp diff --git a/libraries/MySensors/MyMQTT.cpp b/libraries/MySensors/MyMQTT.cpp new file mode 100644 index 0000000..71d49a5 --- /dev/null +++ b/libraries/MySensors/MyMQTT.cpp @@ -0,0 +1,312 @@ +/* +The MySensors library adds a new layer on top of the RF24 library. +It handles radio network routing, relaying and ids. + +Created by Henrik Ekblad +Modified by Daniel Wiegert +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. +*/ + +#include "MyMQTT.h" + +char broker[] PROGMEM = MQTT_BROKER_PREFIX; +char S_0[] PROGMEM = "Temperature"; +char S_1[] PROGMEM = "Humidity"; +char S_2[] PROGMEM = "Light"; +char S_3[] PROGMEM = "Dimmer"; +char S_4[] PROGMEM = "Pressure"; +char S_5[] PROGMEM = "Forecast"; +char S_6[] PROGMEM = "Rain"; +char S_7[] PROGMEM = "Rainrate"; +char S_8[] PROGMEM = "Wind"; +char S_9[] PROGMEM = "Gust"; +char S_10[] PROGMEM = "Direction"; +char S_11[] PROGMEM = "UV"; +char S_12[] PROGMEM = "Weight"; +char S_13[] PROGMEM = "Distance"; +char S_14[] PROGMEM = "Impedance"; +char S_15[] PROGMEM = "Armed"; +char S_16[] PROGMEM = "Tripped"; +char S_17[] PROGMEM = "Watt"; +char S_18[] PROGMEM = "KWH"; +char S_19[] PROGMEM = "Scene_ON"; +char S_20[] PROGMEM = "Scene_OFF"; +char S_21[] PROGMEM = "Heater"; +char S_22[] PROGMEM = "Heater_SW"; +char S_23[] PROGMEM = "LightLVL"; +char S_24[] PROGMEM = "Var1"; +char S_25[] PROGMEM = "Var2"; +char S_26[] PROGMEM = "Var3"; +char S_27[] PROGMEM = "Var4"; +char S_28[] PROGMEM = "Var5,"; +char S_29[] PROGMEM = "Up"; +char S_30[] PROGMEM = "Down"; +char S_31[] PROGMEM = "Stop"; +char S_32[] PROGMEM = "IR_Send"; +char S_33[] PROGMEM = "IR_Receive"; +char S_34[] PROGMEM = "Flow"; +char S_35[] PROGMEM = "Volume"; +char S_36[] PROGMEM = "Lock_Status"; +char S_37[] PROGMEM = "Volt_Batt"; // Does not exist in mysensors lib! +char S_38[] PROGMEM = ""; +char S_39[] PROGMEM = ""; +char S_40[] PROGMEM = ""; +char S_41[] PROGMEM = ""; +char S_42[] PROGMEM = ""; +char S_43[] PROGMEM = ""; +char S_44[] PROGMEM = ""; +char S_45[] PROGMEM = ""; +char S_46[] PROGMEM = ""; +char S_47[] PROGMEM = ""; +char S_48[] PROGMEM = ""; +char S_49[] PROGMEM = "Sketch_name"; // Does not exist in mysensors lib! +char S_50[] PROGMEM = "Sketch_version"; // Does not exist in mysensors lib! + + +PROGMEM const char *sType[] = +{ S_0, S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, + S_11, S_12, S_13, S_14, S_15, S_16, S_17, S_18, S_19, S_20, + S_21, S_22, S_23, S_24, S_25, S_26, S_27, S_28, S_29, S_30, + S_31, S_32, S_33, S_34, S_35, S_36, S_37, S_38, S_39, S_40, + S_41, S_42, S_43, S_44, S_45, S_46, S_47, S_48, S_49, S_50}; + + +MyMQTT::MyMQTT(uint8_t _cepin, uint8_t _cspin) : +MySensor(_cepin, _cspin) { +} + +void MyMQTT::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback)(char *, int *)) { + Serial.begin(BAUD_RATE); + repeaterMode = true; + isGateway = true; + MQTTClient = false; + setupRepeaterMode(); + + if (inDataCallback != NULL) { + useWriteCallback = true; + dataCallback = inDataCallback; + } + else { + useWriteCallback = false; + } + + nc.nodeId = 0; + nc.distance = 0; + + // Start up the radio library + setupRadio(paLevel, channel, dataRate); + RF24::openReadingPipe(WRITE_PIPE, BASE_RADIO_ID); + RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID); + RF24::startListening(); + // Send startup log message on serial + //Serial.print(PSTR("Started\n"));//TODO: progmem gives error..? error: sType causes a section type conflict with __c + Serial.print("Started\n");//TODO: fix this... +} + +void MyMQTT::processRadioMessage() { + if (process()) { + // A new message was received from one of the sensors + MyMessage message = getLastMessage(); + // Pass along the message from sensors to serial line + SendMQTT(message); + } + +} + +void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { + char *str, *p, *value=NULL; + char i = 0; + buffer[0]= 0; + buffsize = 0; +#ifdef TCPDUMP + Serial.print("<<"); + char buf[4]; + for (int a=0; a> 4 == MQTTCONNECT) { + buffer[buffsize++] = MQTTCONNACK << 4; + buffer[buffsize++] = 0x02; // Remaining length + buffer[buffsize++] = 0x00; // Connection accepted + buffer[buffsize++] = 0x00; // Reserved + MQTTClient=true; + } + if ((byte)inputString[0] >> 4 == MQTTPINGREQ) { + buffer[buffsize++] = MQTTPINGRESP << 4; + buffer[buffsize++] = 0x00; + } + if ((byte)inputString[0] >> 4 == MQTTSUBSCRIBE) { + buffer[buffsize++] = MQTTSUBACK << 4; // Just ack everything, we actually dont really care! + buffer[buffsize++] = 0x03; // Remaining length + buffer[buffsize++] = (byte)inputString[2]; // Message ID MSB + buffer[buffsize++] = (byte)inputString[3]; // Message ID LSB + buffer[buffsize++] = MQTTQOS0; // QOS level + } + if ((byte)inputString[0] >> 4 == MQTTUNSUBSCRIBE) { + buffer[buffsize++] = MQTTUNSUBACK << 4; + buffer[buffsize++] = 0x02; // Remaining length + buffer[buffsize++] = (byte)inputString[2]; // Message ID MSB + buffer[buffsize++] = (byte)inputString[3]; // Message ID LSB + } + if ((byte)inputString[0] >> 4 == MQTTDISCONNECT) { + MQTTClient=false; + } + if (buffsize > 0) { +#ifdef TCPDUMP + Serial.print(">>"); + char buf[4]; + for (int a=0; a> 4 == MQTTPUBLISH || (MQTT_SEND_SUBSCRIPTION && (byte)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + buffer[0]= 0; + buffsize = 0; + if ((byte)inputString[0] >> 4 == MQTTSUBSCRIBE) { + strncat(buffer,inputString+6,inputString[5]); + } else { + strncat(buffer,inputString+4,inputString[3]); + } + msg.sender = GATEWAY_ADDRESS; + for (str = strtok_r(buffer, "/", &p); // split using semicolon + str && i < 4; str = strtok_r(NULL, "/", &p) //get subsequent tokens (?) + ) { + switch (i) { + case 0: // Radioid (destination) + if (strcmp_P(str,broker)!=0) { + return; //Message not for us or malformatted! + } + break; + case 1: + msg.destination = atoi(str); + break; + case 2: + msg.sensor = atoi(str); + break; + case 3: + char match=0; + for (int j=0; strcpy_P(convBuf, (char*)pgm_read_word(&(sType[j]))) ; j++) { + if (strcmp(str,convBuf)==0) { + match=j; + break; + } + } + msg.type = match; + break; + } + i++; + } + if ((char)inputString[1] > (char)(inputString[3]+2) && !((byte)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + strcpy(convBuf,inputString+(inputString[3]+4)); + msg.set(convBuf); + } else { + msg.set(""); + } + msg.sender = GATEWAY_ADDRESS; + mSetCommand(msg,C_SET); + mSetRequestAck(msg,false); + mSetAck(msg,false); + mSetVersion(msg, PROTOCOL_VERSION); + sendRoute(msg); + } +} + + +void MyMQTT::SendMQTT(MyMessage &msg) { +//serial(PSTR("%d;%d;%d;%d;%s\n"),msg.sender, msg.sensor, mGetCommand(msg), msg.type, msg.getString(convBuf)); + buffsize = 0; + if (!MQTTClient) return; + if (msg.isAck()) { +Serial.println("msg is ack!"); + if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { + // TODO: sending ACK request on id_response fucks node up. doesn't work. + // The idea was to confirm id and save to EEPROM_LATEST_NODE_ADDRESS. + } + } else { + // we have to check every message if its a newly assigned id or not. + // Ack on I_ID_RESPONSE does not work, and checking on C_PRESENTATION isn't reliable. + char newNodeID = loadState(EEPROM_LATEST_NODE_ADDRESS)+1; + if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; + if (msg.sender==newNodeID) { + saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); + } + if (mGetCommand(msg)==C_INTERNAL && msg.type==I_CONFIG) { // CONFIG + // As for now there is only one 'config' request. + // We force SI! Resistance is futile! + // + // Todo : Support for more config types, Maybe just read from own EEPROM? + // Use internal EEPROM_CONTROLLER_CONFIG_ADDRESS and special MQTT address to write to + // EEPROM_CONTROLLER_CONFIG_ADDRESS & EEPROM_LOCAL_CONFIG_ADDRESS + msg.destination = msg.sender; //NodeID + msg.sender = GATEWAY_ADDRESS; + msg.sensor = 255; //SensorID + msg.type = I_CONFIG; //msgType + mSetCommand(msg,C_INTERNAL); //Subtype + mSetRequestAck(msg,false); + mSetAck(msg,false); + msg.set("M"); + mSetVersion(msg, PROTOCOL_VERSION); + sendRoute(msg); + } else if (mGetCommand(msg)==C_PRESENTATION && (msg.type==S_ARDUINO_NODE || msg.type==S_ARDUINO_REPEATER_NODE)) { + //Doesnt work to check new sensorID here, this message does not always arrive.. See above. + } else if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { + char newNodeID = loadState(EEPROM_LATEST_NODE_ADDRESS)+1; + if (newNodeID <= MQTT_FIRST_SENSORID) newNodeID = MQTT_FIRST_SENSORID; + if (newNodeID >= MQTT_LAST_SENSORID) return; // Sorry no more id's left :( + msg.destination = msg.sender; //NodeID + msg.sender = GATEWAY_ADDRESS; + msg.sensor = 255; //SensorID + msg.type = I_ID_RESPONSE; //MsgType + mSetCommand(msg,C_INTERNAL); //Subtype + mSetRequestAck(msg,false); //Request ack doesn't work, node/gateway gets stuck in enless loop. + mSetAck(msg,false); + msg.set((uint8_t)newNodeID); //Payload + mSetVersion(msg, PROTOCOL_VERSION); + sendRoute(msg); +// if (sendRoute(msg)) saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); // If send OK save to eeprom. DOES NOT ALWAYS RETURN 'OK'!? + } else if (mGetCommand(msg)!=0) { + if (mGetCommand(msg)==3) msg.type=msg.type+38; + buffer[buffsize++] = MQTTPUBLISH << 4; // 0: + buffer[buffsize++] = 0x09; // 1: Remaining length with no payload, we'll set this later to correct value, buffsize -2 + buffer[buffsize++] = 0x00; // 2: Length MSB (Remaing length can never exceed ff,so MSB must be 0!) + buffer[buffsize++] = 0x08; // 3: Length LSB (ADDR), We'll set this later + strcpy_P(buffer+4, broker); + buffsize+=strlen_P(broker); + buffsize+=sprintf(&buffer[buffsize],"/%i/%i/",msg.sender,msg.sensor); + buffsize+=strncpysType_retL(buffer,msg.type,buffsize); + buffer[3]=buffsize-4; // Set correct address length on byte 4. +#ifdef DEBUG + Serial.println((char*)&buffer[4]); +#endif + msg.getString(convBuf); + for (int a=0; a>"); + char buf[4]; + for (int a=0; a Date: Wed, 13 Aug 2014 21:12:06 +0200 Subject: [PATCH 3/8] Create MyMQTT.h MQTTGateway beta 0.1 --- libraries/MySensors/MyMQTT.h | 80 ++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 libraries/MySensors/MyMQTT.h diff --git a/libraries/MySensors/MyMQTT.h b/libraries/MySensors/MyMQTT.h new file mode 100644 index 0000000..5ddc907 --- /dev/null +++ b/libraries/MySensors/MyMQTT.h @@ -0,0 +1,80 @@ +/* +The MySensors library adds a new layer on top of the RF24 library. +It handles radio network routing, relaying and ids. + +Created by Henrik Ekblad +Modified by Daniel Wiegert +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. +*/ + +#ifndef MyMQTT_h +#define MyMQTT_h + +#include "MySensor.h" + + +/////////////////////////////////////////////////////////////////////////////////// + +#ifdef DEBUG +#define TCPDUMP // Dump TCP packages. +#endif + +#define MQTT_FIRST_SENSORID 20 // If you want manually configured nodes below this value. +#define MQTT_LAST_SENSORID 254 // 254 is max! 255 reserved. +#define MQTT_BROKER_PREFIX "MyMQTT" // First prefix in MQTT tree, keep short! +#define MQTT_SEND_SUBSCRIPTION 1 // Send empty payload (request) to node upon MQTT client subscribe request. +// NOTE above : Beware to check if there is any length on payload in your incommingMessage code: +// Example: if (msg.type==V_LIGHT && strlen(msg.getString())>0) otherwise the code might do strange things. + +/////////////////////////////////////////////////////////////////////////////////// + +#define EEPROM_LATEST_NODE_ADDRESS EEPROM_LOCAL_CONFIG_ADDRESS+0 +#define MQTT_MAX_PACKET_SIZE 100 + +#define MQTTPROTOCOLVERSION 3 +#define MQTTCONNECT 1 // Client request to connect to Server +#define MQTTCONNACK 2 // Connect Acknowledgment +#define MQTTPUBLISH 3 // Publish message +#define MQTTPUBACK 4 // Publish Acknowledgment +#define MQTTPUBREC 5 // Publish Received (assured delivery part 1) +#define MQTTPUBREL 6 // Publish Release (assured delivery part 2) +#define MQTTPUBCOMP 7 // Publish Complete (assured delivery part 3) +#define MQTTSUBSCRIBE 8 // Client Subscribe request +#define MQTTSUBACK 9 // Subscribe Acknowledgment +#define MQTTUNSUBSCRIBE 10 // Client Unsubscribe request +#define MQTTUNSUBACK 11 // Unsubscribe Acknowledgment +#define MQTTPINGREQ 12 // PING Request +#define MQTTPINGRESP 13 // PING Response +#define MQTTDISCONNECT 14 // Client is Disconnecting +#define MQTTReserved 15 // Reserved + +#define MQTTQOS0 (0 << 1) +#define MQTTQOS1 (1 << 1) +#define MQTTQOS2 (2 << 1) + +class MyMQTT : +public MySensor { +public: + MyMQTT(uint8_t _cepin=9, uint8_t _cspin=10); + + void begin(rf24_pa_dbm_e paLevel=RF24_PA_LEVEL_GW, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE, void (*dataCallback)(char *, int *)=NULL); + void processRadioMessage(); + void processMQTTMessage(char *inputString, int inputPos); + +private: + bool MQTTClient; + char buffer[MQTT_MAX_PACKET_SIZE]; + int buffsize; + char convBuf[MAX_PAYLOAD*2+1]; + boolean useWriteCallback; + void (*dataCallback)(char *, int *); + void SendMQTT(MyMessage &msg); + char strncpysType_retL(char *str, char index, char start); +}; + + + +#endif + From 7d501307ee7a73f7fc8d68dc613fa3a12793cebf Mon Sep 17 00:00:00 2001 From: Damme Date: Wed, 13 Aug 2014 21:25:03 +0200 Subject: [PATCH 4/8] missed \n -> debug(PSTR("version mismatch\n")); --- libraries/MySensors/MySensor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 61d23d0..11fcf18 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -275,7 +275,7 @@ boolean MySensor::process() { msg.sender, msg.last, msg.destination, msg.sensor, mGetCommand(msg), msg.type, mGetPayloadType(msg), mGetLength(msg), msg.getString(convBuf)); if(!(mGetVersion(msg) == PROTOCOL_VERSION)) { - debug(PSTR("version mismatch")); + debug(PSTR("version mismatch\n")); return false; } From 3a63ae619d04bc26f144b1febe17f86c16ea301e Mon Sep 17 00:00:00 2001 From: Damme Date: Wed, 13 Aug 2014 21:29:18 +0200 Subject: [PATCH 5/8] Check if incomming message contains anything. --- .../RelayWithButtonActuator/RelayWithButtonActuator.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/RelayWithButtonActuator/RelayWithButtonActuator.ino b/libraries/MySensors/examples/RelayWithButtonActuator/RelayWithButtonActuator.ino index 94424bb..77b5f8d 100644 --- a/libraries/MySensors/examples/RelayWithButtonActuator/RelayWithButtonActuator.ino +++ b/libraries/MySensors/examples/RelayWithButtonActuator/RelayWithButtonActuator.ino @@ -70,7 +70,7 @@ void incomingMessage(const MyMessage &message) { Serial.println("This is an ack from gateway"); } - if (message.type==V_LIGHT) { + if (message.type == V_LIGHT && strlen(msg.getString()) != 0) { // Change relay state state = message.getBool(); digitalWrite(RELAY_PIN, state?RELAY_ON:RELAY_OFF); From 172d58782ce86bababb216b00822cf5fb230e99a Mon Sep 17 00:00:00 2001 From: Damme Date: Wed, 13 Aug 2014 22:48:06 +0200 Subject: [PATCH 6/8] Little better readme... --- MQTTGateway/MQTTGateway.ino | 87 +++++++++++++++++++++++++------------ 1 file changed, 59 insertions(+), 28 deletions(-) diff --git a/MQTTGateway/MQTTGateway.ino b/MQTTGateway/MQTTGateway.ino index d59e4b6..816c2b0 100644 --- a/MQTTGateway/MQTTGateway.ino +++ b/MQTTGateway/MQTTGateway.ino @@ -1,32 +1,63 @@ -// MyMQTT Gateway 0.1b -// -// Created by Daniel Wiegert -// Based on Mysensors Ethernet Gateway by Henrik Ekblad -// http://www.mysensors.org -// -// Requires MySensors lib 1.4b -// -// Don't forget to look at the definitions in MyMQTT.h! -// Don't forget to configure Radio pins, IP and MAC-address! -// -// Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/Light -// NodeID and SensorID is Decimal number. -// Last segment is translation of the sensor type, look inside MyMQTT.cpp for -// the definitions. User can change this to their needs. -// -// Features: -// Supports automatic nodeID delegation -// Recieve sketchname and version Example: (openhab item) -//String sketch20 "Node 20 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/20/255/Sketch_name:state:default]"} -//String sketch21 "Node 21 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/21/255/Sketch_name:state:default]"} -// ... -// -// Todo: -// DOCUMENTATION... -// Special commands : clear or set EEPROM Values -// Special commands : Reboot -// ... +/* MyMQTT Gateway 0.1b + Created by Daniel Wiegert + Based on Mysensors Ethernet Gateway by Henrik Ekblad + Requires MySensors lib 1.4b + http://www.mysensors.org + + * Don't forget to look at the definitions in MyMQTT.h! + * Don't forget to configure Radio pins, IP and MAC-address! + + * Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/Light + NodeID and SensorID is number (0-255). + Last segment is translation of the sensor type, look inside MyMQTT.cpp for + the definitions. User can change this to their needs. + +Example openhab setup: http://www.openhab.org/ + +* openhab.cfg +--- +mqtt:mysensor.url=tcp://192.168.0.234:1883 +mqtt:mysensor.clientId=MQTT +--- + +* items/test.items +--- +Group test +Number Temp_test "Temp [%.1f °C]" (test) {mqtt="<[mysensor:MyMQTT/20/#/Temperature:state:default]"} +Number Hum_test "Hum [%.1f %%]" (test) {mqtt="<[mysensor:MyMQTT/20/#/Humidity:state:default]"} +Number test_test "test [%s]" (test) {mqtt="<[mysensor:MyMQTT/20/3/#:state:default]"} +Switch sw1 "sw 1" (test) {<[mysensor:MyMQTT/21/1/Light:command:MAP(1.map)]"} +--- (Note; # = Wildcard character) + +* sitemap/test.site +--- +sitemap demo label="Menu" +Frame label="Openhab" { + Group item=test label="Test group" +} +--- + +* transform/1.map +--- +1=ON +0=OFF +--- + +* Features: + - Supports automatic nodeID delegation + - Recieve sketchname and version Example: (openhab item) +String sketch20 "Node 20 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/20/255/Sketch_name:state:default]"} +String sketch21 "Node 21 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/21/255/Sketch_name:state:default]"} +[...] + +* Todo: + - DOCUMENTATION... + - Special commands + Read and set EEPROM Values + Send Reboot, And reboot gateway itself. +... +*/ #include #include From 5ebc1c812940458b77d863f1c1d24ce392ab2125 Mon Sep 17 00:00:00 2001 From: Daniel Wiegert Date: Fri, 15 Aug 2014 14:56:07 +0200 Subject: [PATCH 7/8] Minor changes + reinserted led-blinking --- MQTTGateway/MQTTGateway.ino | 118 ++++++++++++++---------------- libraries/MySensors/MyMQTT.cpp | 126 +++++++++++++++++++++++---------- libraries/MySensors/MyMQTT.h | 30 +++++--- 3 files changed, 163 insertions(+), 111 deletions(-) mode change 100644 => 100755 MQTTGateway/MQTTGateway.ino mode change 100644 => 100755 libraries/MySensors/MyMQTT.cpp mode change 100644 => 100755 libraries/MySensors/MyMQTT.h diff --git a/MQTTGateway/MQTTGateway.ino b/MQTTGateway/MQTTGateway.ino old mode 100644 new mode 100755 index 816c2b0..868cc54 --- a/MQTTGateway/MQTTGateway.ino +++ b/MQTTGateway/MQTTGateway.ino @@ -1,77 +1,56 @@ -/* MyMQTT Gateway 0.1b - - Created by Daniel Wiegert - Based on Mysensors Ethernet Gateway by Henrik Ekblad - Requires MySensors lib 1.4b - http://www.mysensors.org - - * Don't forget to look at the definitions in MyMQTT.h! - * Don't forget to configure Radio pins, IP and MAC-address! - - * Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/Light - NodeID and SensorID is number (0-255). - Last segment is translation of the sensor type, look inside MyMQTT.cpp for - the definitions. User can change this to their needs. - -Example openhab setup: http://www.openhab.org/ - -* openhab.cfg ---- -mqtt:mysensor.url=tcp://192.168.0.234:1883 -mqtt:mysensor.clientId=MQTT ---- - -* items/test.items ---- -Group test -Number Temp_test "Temp [%.1f °C]" (test) {mqtt="<[mysensor:MyMQTT/20/#/Temperature:state:default]"} -Number Hum_test "Hum [%.1f %%]" (test) {mqtt="<[mysensor:MyMQTT/20/#/Humidity:state:default]"} -Number test_test "test [%s]" (test) {mqtt="<[mysensor:MyMQTT/20/3/#:state:default]"} -Switch sw1 "sw 1" (test) {<[mysensor:MyMQTT/21/1/Light:command:MAP(1.map)]"} ---- (Note; # = Wildcard character) - -* sitemap/test.site ---- -sitemap demo label="Menu" -Frame label="Openhab" { - Group item=test label="Test group" -} ---- - -* transform/1.map ---- -1=ON -0=OFF ---- - -* Features: - - Supports automatic nodeID delegation - - Recieve sketchname and version Example: (openhab item) -String sketch20 "Node 20 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/20/255/Sketch_name:state:default]"} -String sketch21 "Node 21 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/21/255/Sketch_name:state:default]"} -[...] - -* Todo: - - DOCUMENTATION... - - Special commands - Read and set EEPROM Values - Send Reboot, And reboot gateway itself. -... +// MyMQTT Gateway 0.1b +// +// Created by Daniel Wiegert +// Based on Mysensors Ethernet Gateway by Henrik Ekblad +// http://www.mysensors.org +// +// Requires MySensors lib 1.4b +// +// Don't forget to look at the definitions in MyMQTT.h! +// Don't forget to configure Radio pins, IP and MAC-address! +// +// Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/Light +// NodeID and SensorID is Decimal number. +// Last segment is translation of the sensor type, look inside MyMQTT.cpp for +// the definitions. User can change this to their needs. +// +// Features: +// Supports automatic nodeID delegation +// Recieve sketchname and version Example: (openhab item) +//String sketch20 "Node 20 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/20/255/Sketch_name:state:default]"} +//String sketch21 "Node 21 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/21/255/Sketch_name:state:default]"} +// ... +// +// Todo: +// DOCUMENTATION... +// Special commands : clear or set EEPROM Values +// Special commands : Reboot +// ... +/* +Sketch uses 23,666 bytes (77%) of program storage space. Maximum is 30,720 bytes. +Global variables use 766 bytes (37%) of dynamic memory, leaving 1,282 bytes for local variables. Maximum is 2,048 bytes. */ #include #include #include +#include // Use this for IBOARD modded to use standard MISO/MOSI/SCK More information see; // http://forum.mysensors.org/topic/224/iboard-cheap-single-board-ethernet-arduino-with-radio/5 -#define RADIO_CE_PIN 3 // radio chip enable -#define RADIO_SPI_SS_PIN 8 // radio SPI serial select +//#define RADIO_CE_PIN 3 // radio chip enable +//#define RADIO_SPI_SS_PIN 8 // radio SPI serial select +//#define RADIO_ERROR_LED_PIN A2 // Error led pin +//#define RADIO_RX_LED_PIN A1 // Receive led pin +//#define RADIO_TX_LED_PIN A0 // the PCB, on board LED //Use this for default configured pro mini / nano etc : -//#define RADIO_CE_PIN 5 // radio chip enable -//#define RADIO_SPI_SS_PIN 6 // radio SPI serial select +#define RADIO_CE_PIN 5 // radio chip enable +#define RADIO_SPI_SS_PIN 6 // radio SPI serial select +#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 #define IP_PORT 1883 // MQTT Listening port IPAddress myIp ( 192, 168, 0, 234 ); // Configure your static ip-address here @@ -80,6 +59,8 @@ byte mac[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - Change th EthernetServer server = EthernetServer(IP_PORT); MyMQTT gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN); +// Uncomment this constructor if you have leds and include button attached to your gateway +// MyMQTT gw(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); void processEthernetMessages() { char inputString[MQTT_MAX_PACKET_SIZE] = ""; @@ -99,16 +80,23 @@ void writeEthernet(char *writeBuffer, int *writeSize) { server.write(writeBuffer, *writeSize); // Should this really be *writeSize? } +void ledTimersInterrupt() { + gw.ledTimersInterrupt(); +} + int main(void) { init(); Ethernet.begin(mac, myIp); delay(1000); // Wait for Ethernet to get configured. gw.begin(RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, writeEthernet); server.begin(); + if (gw.isLedMode()) { + // Add led timer interrupt + MsTimer2::set(300, ledTimersInterrupt); + MsTimer2::start(); + } while (1) { processEthernetMessages(); gw.processRadioMessage(); } } - - diff --git a/libraries/MySensors/MyMQTT.cpp b/libraries/MySensors/MyMQTT.cpp old mode 100644 new mode 100755 index 71d49a5..7d8c9a3 --- a/libraries/MySensors/MyMQTT.cpp +++ b/libraries/MySensors/MyMQTT.cpp @@ -66,31 +66,39 @@ char S_50[] PROGMEM = "Sketch_version"; // Does not exist in mysensors lib! PROGMEM const char *sType[] = -{ S_0, S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, +{ S_0, S_1, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_11, S_12, S_13, S_14, S_15, S_16, S_17, S_18, S_19, S_20, - S_21, S_22, S_23, S_24, S_25, S_26, S_27, S_28, S_29, S_30, + S_21, S_22, S_23, S_24, S_25, S_26, S_27, S_28, S_29, S_30, S_31, S_32, S_33, S_34, S_35, S_36, S_37, S_38, S_39, S_40, S_41, S_42, S_43, S_44, S_45, S_46, S_47, S_48, S_49, S_50}; - -MyMQTT::MyMQTT(uint8_t _cepin, uint8_t _cspin) : + +MyMQTT::MyMQTT(uint8_t _cepin, uint8_t _cspin, uint8_t _rx, uint8_t _tx, uint8_t _er) : MySensor(_cepin, _cspin) { + if (_rx != NULL) { + pinRx = _rx; + pinMode(pinRx, OUTPUT); + ledMode = true; + } + if (_tx != NULL) { + pinTx = _tx; + pinMode(pinTx, OUTPUT); + ledMode = true; + } + if (_er != NULL) { + pinEr = _er; + pinMode(pinEr, OUTPUT); + ledMode = true; + } } void MyMQTT::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e dataRate, void (*inDataCallback)(char *, int *)) { Serial.begin(BAUD_RATE); repeaterMode = true; isGateway = true; - MQTTClient = false; + MQTTClientConnected = false; setupRepeaterMode(); - - if (inDataCallback != NULL) { - useWriteCallback = true; - dataCallback = inDataCallback; - } - else { - useWriteCallback = false; - } + dataCallback = inDataCallback; nc.nodeId = 0; nc.distance = 0; @@ -110,6 +118,7 @@ void MyMQTT::processRadioMessage() { // A new message was received from one of the sensors MyMessage message = getLastMessage(); // Pass along the message from sensors to serial line + rxBlink(3); SendMQTT(message); } @@ -121,7 +130,7 @@ void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { buffer[0]= 0; buffsize = 0; #ifdef TCPDUMP - Serial.print("<<"); + Serial.print("<<"); char buf[4]; for (int a=0; a> 4 == MQTTPINGREQ) { buffer[buffsize++] = MQTTPINGRESP << 4; @@ -150,18 +159,18 @@ void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { buffer[buffsize++] = (byte)inputString[3]; // Message ID LSB } if ((byte)inputString[0] >> 4 == MQTTDISCONNECT) { - MQTTClient=false; + MQTTClientConnected=false; } if (buffsize > 0) { #ifdef TCPDUMP - Serial.print(">>"); + Serial.print(">>"); char buf[4]; - for (int a=0; a> 4 == MQTTPUBLISH || (MQTT_SEND_SUBSCRIPTION && (byte)inputString[0] >> 4 == MQTTSUBSCRIBE)) { + if ((byte)inputString[0] >> 4 == MQTTPUBLISH || (MQTT_SEND_SUBSCRIPTION && (byte)inputString[0] >> 4 == MQTTSUBSCRIBE)) { buffer[0]= 0; buffsize = 0; if ((byte)inputString[0] >> 4 == MQTTSUBSCRIBE) { @@ -171,7 +180,7 @@ void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { } msg.sender = GATEWAY_ADDRESS; for (str = strtok_r(buffer, "/", &p); // split using semicolon - str && i < 4; str = strtok_r(NULL, "/", &p) //get subsequent tokens (?) + str && i < 4; str = strtok_r(NULL, "/", &p) //get subsequent tokens (?) ) { switch (i) { case 0: // Radioid (destination) @@ -188,11 +197,11 @@ void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { case 3: char match=0; for (int j=0; strcpy_P(convBuf, (char*)pgm_read_word(&(sType[j]))) ; j++) { - if (strcmp(str,convBuf)==0) { - match=j; + if (strcmp(str,convBuf)==0) { + match=j; break; } - } + } msg.type = match; break; } @@ -201,7 +210,7 @@ void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { if ((char)inputString[1] > (char)(inputString[3]+2) && !((byte)inputString[0] >> 4 == MQTTSUBSCRIBE)) { strcpy(convBuf,inputString+(inputString[3]+4)); msg.set(convBuf); - } else { + } else { msg.set(""); } msg.sender = GATEWAY_ADDRESS; @@ -209,7 +218,8 @@ void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { mSetRequestAck(msg,false); mSetAck(msg,false); mSetVersion(msg, PROTOCOL_VERSION); - sendRoute(msg); + txBlink(1); + if (!sendRoute(msg)) errBlink(1); } } @@ -217,11 +227,11 @@ void MyMQTT::processMQTTMessage(char *inputString, int inputPos) { void MyMQTT::SendMQTT(MyMessage &msg) { //serial(PSTR("%d;%d;%d;%d;%s\n"),msg.sender, msg.sensor, mGetCommand(msg), msg.type, msg.getString(convBuf)); buffsize = 0; - if (!MQTTClient) return; + if (!MQTTClientConnected) return; if (msg.isAck()) { Serial.println("msg is ack!"); if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { - // TODO: sending ACK request on id_response fucks node up. doesn't work. + // TODO: sending ACK request on id_response fucks node up. doesn't work. // The idea was to confirm id and save to EEPROM_LATEST_NODE_ADDRESS. } } else { @@ -233,11 +243,11 @@ Serial.println("msg is ack!"); saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); } if (mGetCommand(msg)==C_INTERNAL && msg.type==I_CONFIG) { // CONFIG - // As for now there is only one 'config' request. + // As for now there is only one 'config' request. // We force SI! Resistance is futile! // - // Todo : Support for more config types, Maybe just read from own EEPROM? - // Use internal EEPROM_CONTROLLER_CONFIG_ADDRESS and special MQTT address to write to + // Todo : Support for more config types, Maybe just read from own EEPROM? + // Use internal EEPROM_CONTROLLER_CONFIG_ADDRESS and special MQTT address to write to // EEPROM_CONTROLLER_CONFIG_ADDRESS & EEPROM_LOCAL_CONFIG_ADDRESS msg.destination = msg.sender; //NodeID msg.sender = GATEWAY_ADDRESS; @@ -248,7 +258,8 @@ Serial.println("msg is ack!"); mSetAck(msg,false); msg.set("M"); mSetVersion(msg, PROTOCOL_VERSION); - sendRoute(msg); + txBlink(1); + if (!sendRoute(msg)) errBlink(1); } else if (mGetCommand(msg)==C_PRESENTATION && (msg.type==S_ARDUINO_NODE || msg.type==S_ARDUINO_REPEATER_NODE)) { //Doesnt work to check new sensorID here, this message does not always arrive.. See above. } else if (msg.sender==255 && mGetCommand(msg)==C_INTERNAL && msg.type==I_ID_REQUEST) { @@ -264,11 +275,12 @@ Serial.println("msg is ack!"); mSetAck(msg,false); msg.set((uint8_t)newNodeID); //Payload mSetVersion(msg, PROTOCOL_VERSION); - sendRoute(msg); + txBlink(1); + if (!sendRoute(msg)) errBlink(1); // if (sendRoute(msg)) saveState(EEPROM_LATEST_NODE_ADDRESS,newNodeID); // If send OK save to eeprom. DOES NOT ALWAYS RETURN 'OK'!? } else if (mGetCommand(msg)!=0) { if (mGetCommand(msg)==3) msg.type=msg.type+38; - buffer[buffsize++] = MQTTPUBLISH << 4; // 0: + buffer[buffsize++] = MQTTPUBLISH << 4; // 0: buffer[buffsize++] = 0x09; // 1: Remaining length with no payload, we'll set this later to correct value, buffsize -2 buffer[buffsize++] = 0x00; // 2: Length MSB (Remaing length can never exceed ff,so MSB must be 0!) buffer[buffsize++] = 0x08; // 3: Length LSB (ADDR), We'll set this later @@ -289,17 +301,59 @@ Serial.println("msg is ack!"); #ifdef TCPDUMP Serial.print(">>"); char buf[4]; - for (int a=0; a Date: Fri, 15 Aug 2014 14:59:41 +0200 Subject: [PATCH 8/8] Forgot Readme changes --- MQTTGateway/MQTTGateway.ino | 89 +++++++++++++++++++++++++------------ 1 file changed, 60 insertions(+), 29 deletions(-) diff --git a/MQTTGateway/MQTTGateway.ino b/MQTTGateway/MQTTGateway.ino index 868cc54..9cbc641 100755 --- a/MQTTGateway/MQTTGateway.ino +++ b/MQTTGateway/MQTTGateway.ino @@ -1,32 +1,63 @@ -// MyMQTT Gateway 0.1b -// -// Created by Daniel Wiegert -// Based on Mysensors Ethernet Gateway by Henrik Ekblad -// http://www.mysensors.org -// -// Requires MySensors lib 1.4b -// -// Don't forget to look at the definitions in MyMQTT.h! -// Don't forget to configure Radio pins, IP and MAC-address! -// -// Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/Light -// NodeID and SensorID is Decimal number. -// Last segment is translation of the sensor type, look inside MyMQTT.cpp for -// the definitions. User can change this to their needs. -// -// Features: -// Supports automatic nodeID delegation -// Recieve sketchname and version Example: (openhab item) -//String sketch20 "Node 20 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/20/255/Sketch_name:state:default]"} -//String sketch21 "Node 21 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/21/255/Sketch_name:state:default]"} -// ... -// -// Todo: -// DOCUMENTATION... -// Special commands : clear or set EEPROM Values -// Special commands : Reboot -// ... -/* +/* MyMQTT Gateway 0.1b + + Created by Daniel Wiegert + Based on Mysensors Ethernet Gateway by Henrik Ekblad + Requires MySensors lib 1.4b + http://www.mysensors.org + + * Don't forget to look at the definitions in MyMQTT.h! + * Don't forget to configure Radio pins, IP and MAC-address! + + * Address-layout is : [MQTT_BROKER_PREFIX]/[NodeID]/[SensorID]/Light + NodeID and SensorID is number (0-255). + Last segment is translation of the sensor type, look inside MyMQTT.cpp for + the definitions. User can change this to their needs. + +Example openhab setup: http://www.openhab.org/ + +* openhab.cfg +--- +mqtt:mysensor.url=tcp://192.168.0.234:1883 +mqtt:mysensor.clientId=MQTT +--- + +* items/test.items +--- +Group test +Number Temp_test "Temp [%.1f °C]" (test) {mqtt="<[mysensor:MyMQTT/20/#/Temperature:state:default]"} +Number Hum_test "Hum [%.1f %%]" (test) {mqtt="<[mysensor:MyMQTT/20/#/Humidity:state:default]"} +Number test_test "test [%s]" (test) {mqtt="<[mysensor:MyMQTT/20/3/#:state:default]"} +Switch sw1 "sw 1" (test) {<[mysensor:MyMQTT/21/1/Light:command:MAP(1.map)]"} +--- (Note; # = Wildcard character) + +* sitemap/test.site +--- +sitemap demo label="Menu" +Frame label="Openhab" { + Group item=test label="Test group" +} +--- + +* transform/1.map +--- +1=ON +0=OFF +--- + +* Features: + - Supports automatic nodeID delegation + - Recieve sketchname and version Example: (openhab item) +String sketch20 "Node 20 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/20/255/Sketch_name:state:default]"} +String sketch21 "Node 21 Sketch name [%s]" (sketch,name,a) {mqtt="<[mysensor:MyMQTT/21/255/Sketch_name:state:default]"} +[...] + +* Todo: + - DOCUMENTATION... + - Special commands + Read and set EEPROM Values + Send Reboot, And reboot gateway itself. +... + Sketch uses 23,666 bytes (77%) of program storage space. Maximum is 30,720 bytes. Global variables use 766 bytes (37%) of dynamic memory, leaving 1,282 bytes for local variables. Maximum is 2,048 bytes. */