webgui updates

This commit is contained in:
esp8266nu
2015-06-28 11:28:59 +00:00
parent d87447ce00
commit 6c41e550f0
9 changed files with 1180 additions and 475 deletions
+489 -56
View File
@@ -1,82 +1,110 @@
//********************************************************************************
// Interface for Domoticz Controller, get and set data through json
//********************************************************************************
/*********************************************************************************************\
* Get values from Domoticz using http/json
\*********************************************************************************************/
boolean Domoticz_getData(int idx, float *data)
{
boolean success = false;
boolean success=false;
char host[20];
sprintf(host, "%u.%u.%u.%u", Settings.Controller_IP[0], Settings.Controller_IP[1], Settings.Controller_IP[2], Settings.Controller_IP[3]);
sprintf(host,"%u.%u.%u.%u",Settings.Controller_IP[0],Settings.Controller_IP[1],Settings.Controller_IP[2],Settings.Controller_IP[3]);
Serial.print(F("HTTP : Connecting to "));
Serial.print(F("connecting to "));
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, Settings.ControllerPort))
{
connectionFailures++;
Serial.println(F("HTTP : Connection failed"));
Serial.println(F("connection failed"));
return false;
}
// We now create a URI for the request
String url = "/json.htm?type=devices&rid=";
String url = F("/json.htm?type=devices&rid=");
url += idx;
Serial.print(F("HTTP : Requesting URL: "));
Serial.print(F("Requesting URL: "));
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timer = millis() + 200;
while (!client.available() && millis() < timer)
delay(1);
unsigned long timer=millis()+200;
while(!client.available() && millis()<timer)
delay(1);
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
while(client.available()){
String line = client.readStringUntil('\n');
if (line.substring(10, 14) == "Data")
{
String strValue = line.substring(19);
byte pos = strValue.indexOf(' ');
strValue = strValue.substring(0, pos);
strValue.trim();
float value = strValue.toFloat();
*data = value;
Serial.println("Succes!");
success = true;
}
if (line.substring(10,14) == "Data")
{
String strValue=line.substring(19);
byte pos=strValue.indexOf(' ');
strValue=strValue.substring(0,pos);
strValue.trim();
float value = strValue.toFloat();
*data=value;
Serial.println(F("Succes!"));
success=true;
}
}
Serial.println(F("HTTP : Closing connection"));
Serial.println(F("closing connection"));
return success;
}
//#ifdef ESP_EASY
//********************************************************************************
// Interface for Sending to Controllers
//********************************************************************************
boolean sendData(byte sensorType, int idx, byte varIndex)
{
switch(Settings.Protocol)
{
case 1:
Domoticz_sendData(sensorType, idx, varIndex);
break;
case 2:
Domoticz_sendDataMQTT(sensorType, idx, varIndex);
break;
}
}
//#endif
/*********************************************************************************************\
* Send data to Domoticz using http url querystring
\*********************************************************************************************/
boolean Domoticz_sendData(byte sensorType, int idx, byte varIndex)
{
boolean success = false;
char log[80];
boolean success=false;
char host[20];
sprintf(host, "%u.%u.%u.%u", Settings.Controller_IP[0], Settings.Controller_IP[1], Settings.Controller_IP[2], Settings.Controller_IP[3]);
Serial.print(F("HTTP : Connecting to "));
Serial.println(host);
sprintf(host,"%u.%u.%u.%u",Settings.Controller_IP[0],Settings.Controller_IP[1],Settings.Controller_IP[2],Settings.Controller_IP[3]);
sprintf(log,"%s%s","connecting to ",host);
addLog(log);
if (printToWeb)
{
printWebString += log;
printWebString += "<BR>";
}
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, Settings.ControllerPort))
{
connectionFailures++;
Serial.println(F("HTTP : Connection failed"));
addLog((char*)"connection failed");
if (printToWeb)
printWebString += F("connection failed<BR>");
return false;
}
// We now create a URI for the request
String url = F("/json.htm?type=command&param=udevice&idx=");
url += idx;
switch(sensorType)
{
case 1: // single value sensor, used for Dallas, BH1750, etc
@@ -97,7 +125,7 @@ boolean Domoticz_sendData(byte sensorType, int idx, byte varIndex)
url += UserVar[varIndex];
url += ";0";
break;
case 10: // single value sensor, used for Dallas, BH1750, etc
case 10: // switch
url = F("/json.htm?type=command&param=switchlight&idx=");
url += idx;
url += "&switchcmd=";
@@ -108,29 +136,39 @@ boolean Domoticz_sendData(byte sensorType, int idx, byte varIndex)
break;
}
Serial.print(F("HTTP : Requesting URL: "));
Serial.println(url);
url.toCharArray(log,79);
addLog(log);
if (printToWeb)
{
printWebString += log;
printWebString += "<BR>";
}
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timer = millis() + 200;
while (!client.available() && millis() < timer)
delay(1);
unsigned long timer=millis()+200;
while(!client.available() && millis()<timer)
delay(1);
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
while(client.available()){
String line = client.readStringUntil('\n');
if (line.substring(0, 15) == "HTTP/1.1 200 OK")
{
Serial.println("HTTP : Succes!");
success = true;
}
if (line.substring(0,15) == "HTTP/1.1 200 OK")
{
addLog((char*)"Succes!");
if (printToWeb)
printWebString += F("Success<BR>");
success=true;
}
}
Serial.println(F("HTTP : Closing connection"));
addLog((char*)"closing connection");
if (printToWeb)
printWebString += F("closing connection<BR>");
#ifdef ESP_EASY
if (Settings.UDPPort != 0)
{
IPAddress broadcastIP(255,255,255,255);
@@ -142,11 +180,406 @@ boolean Domoticz_sendData(byte sensorType, int idx, byte varIndex)
char str[80];
str[0]=0;
message.toCharArray(str, 79);
Serial.print("SYSLG: ");
Serial.print("UDP >: ");
Serial.println(str);
portTX.write(str);
portTX.endPacket();
}
#endif
return success;
}
/*********************************************************************************************\
* Syslog client
\*********************************************************************************************/
void syslog(char *message)
{
if (Settings.Syslog_IP[0] != 0)
{
IPAddress broadcastIP(Settings.Syslog_IP[0],Settings.Syslog_IP[1],Settings.Syslog_IP[2],Settings.Syslog_IP[3]);
portTX.beginPacket(broadcastIP,514);
char str[80];
str[0]=0;
sprintf(str,"<7>ESP Unit: %u : %s",Settings.Unit,message);
Serial.print("SYSLG > ");
Serial.println(str);
portTX.write(str);
portTX.endPacket();
}
}
/*********************************************************************************************\
* Handle incoming MQTT messages
\*********************************************************************************************/
// handle MQTT messages
void callback(const MQTT::Publish& pub) {
String message = pub.payload_string();
MQTTMessage(&message);
}
/*********************************************************************************************\
* Connect to MQTT message broker
\*********************************************************************************************/
void MQTTConnect()
{
IPAddress MQTTBrokerIP(Settings.Controller_IP);
MQTTclient.set_server(MQTTBrokerIP,1883);
MQTTclient.set_callback(callback);
// MQTT needs a unique clientname to subscribe to broker
String clientid = "ESPClient";
clientid += Settings.Unit;
for (byte x=1; x < 3; x++)
{
if (MQTTclient.connect(clientid))
{
Serial.println(F("MQTT : Connected to broker"));
MQTTclient.subscribe("domoticz/out");
break;
}
else
Serial.println(F("MQTT : Failed to connected to broker"));
delay(500);
}
}
/*********************************************************************************************\
* Parse incoming MQTT message
\*********************************************************************************************/
void MQTTMessage(String *message)
{
char json[512];
json[0]=0;
message->toCharArray(json,511);
// if (Settings.Debug == 3)
// Serial.println(json);
StaticJsonBuffer<512> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
//for (JsonObject::iterator it=root.begin(); it!=root.end(); ++it)
//{
// Serial.println(it->key);
// Serial.println(it->value.asString());
//}
if (root.success())
{
long idx = root["idx"];
float nvalue = root["nvalue"];
long nvaluealt = root["nvalue"];
const char* name = root["name"];
const char* svalue = root["svalue"];
const char* svalue1 = root["svalue1"];
const char* svalue2 = root["svalue2"];
const char* svalue3 = root["svalue3"];
if (nvalue == 0)
nvalue = nvaluealt;
Serial.print(F("MQTT : idx="));
Serial.print(idx);
Serial.print(" name=");
Serial.print(name);
Serial.print(" nvalue=");
Serial.print(nvalue);
Serial.print(" svalue=");
Serial.print(svalue);
Serial.print(" svalue1=");
Serial.print(svalue1);
Serial.print(" svalue2=");
Serial.println(svalue2);
Serial.print(" svalue3=");
Serial.println(svalue3);
}
else
Serial.println(F("MQTT : json parse error"));
}
/*********************************************************************************************\
* Send data to Domoticz using MQTT message
\*********************************************************************************************/
boolean Domoticz_sendDataMQTT(byte sensorType, int idx, byte varIndex)
{
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["idx"] = idx;
String values;
char str[80];
switch(sensorType)
{
case 1: // single value sensor, used for Dallas, BH1750, etc
root["nvalue"] = 0;
values = UserVar[varIndex-1];
values.toCharArray(str,79);
root["svalue"] = str;
break;
case 2: // temp + hum + hum_stat, used for DHT11
root["nvalue"] = 0;
values = UserVar[varIndex-1];
values += ";";
values += UserVar[varIndex];
values += ";0";
values.toCharArray(str,79);
root["svalue"] = str;
break;
case 3: // temp + hum + hum_stat + bar + bar_fore, used for BMP085
root["nvalue"] = 0;
values = UserVar[varIndex-1];
values += ";0;0;";
values += UserVar[varIndex];
values += ";0";
values.toCharArray(str,79);
root["svalue"] = str;
break;
case 10: // switch
root["command"] = "switchlight";
if (UserVar[varIndex-1] == 0)
root["switchcmd"] = "Off";
else
root["switchcmd"] = "On";
break;
}
// JsonArray& data = root.createNestedArray("data");
// data.add(48.756080, 6); // 6 is the number of decimals to print
// data.add(2.302038, 6); // if not specified, 2 digits are printed
// test drive mqtt
//String json = "{\"idx\": 161, \"nvalue\": 1, \"svalue\": \"";
//json += millis()/1000;
//json += "\" }";
//Serial.println(json);
char json[256];
root.printTo(json, sizeof(json));
Serial.print("MQTT : ");
Serial.println(json);
addLog(json);
if (!MQTTclient.publish("domoticz/in", json))
{
Serial.println(F("MQTT publish failed"));
MQTTConnect();
connectionFailures++;
}
}
struct NodeStruct
{
byte ip[4];
byte age;
}Nodes[32];
/*********************************************************************************************\
* Send data to other ESP node
\*********************************************************************************************/
boolean nodeVariableCopy(byte var, byte unit)
{
float value = UserVar[var-1];
char log[80];
boolean success=false;
char host[20];
if(Nodes[unit].ip[0] == 0)
{
strcpy(log,"Remote Node unknown");
addLog(log);
if (printToWeb)
{
printWebString += log;
printWebString += "<BR>";
}
return false;
}
sprintf(host,"%u.%u.%u.%u",Nodes[unit].ip[0],Nodes[unit].ip[1],Nodes[unit].ip[2],Nodes[unit].ip[3]);
sprintf(log,"%s%s","connecting to ",host);
addLog(log);
if (printToWeb)
{
printWebString += log;
printWebString += "<BR>";
}
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, 80))
{
connectionFailures++;
addLog((char*)"connection failed");
if (printToWeb)
printWebString += F("connection failed<BR>");
return false;
}
// We now create a URI for the request
String url = F("/?cmd=variableset%20");
url += var;
url += ",";
url += value;
url.toCharArray(log,79);
addLog(log);
if (printToWeb)
{
printWebString += log;
printWebString += "<BR>";
}
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timer=millis()+200;
while(!client.available() && millis()<timer)
delay(1);
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\n');
if (line.substring(0,15) == "HTTP/1.1 200 OK")
{
addLog((char*)"Succes!");
if (printToWeb)
printWebString += F("Success<BR>");
success=true;
}
}
addLog((char*)"closing connection");
if (printToWeb)
printWebString += F("closing connection<BR>");
return success;
}
/*********************************************************************************************\
* Check UDP messages
\*********************************************************************************************/
void checkUDP()
{
// UDP events
int packetSize = portRX.parsePacket();
if (packetSize)
{
char packetBuffer[128];
Serial.print("UDP " );
Serial.print(packetSize);
Serial.print(" < ");
int len = portRX.read(packetBuffer, 128);
if (packetBuffer[0] != 255)
{
packetBuffer[len] = 0;
Serial.println(packetBuffer);
#ifdef ESP_CONNEXIO
ExecuteLine(packetBuffer,VALUE_SOURCE_SERIAL);
#endif
#ifdef ESP_EASY
ExecuteCommand(packetBuffer);
#endif
}
else
{
// binary data!
switch(packetBuffer[1])
{
case 1: // sysinfo message
{
byte mac[6];
byte ip[4];
byte unit = packetBuffer[12];
for (byte x=0; x < 6; x++)
mac[x]=packetBuffer[x+2];
for (byte x=0; x < 4; x++)
ip[x]=packetBuffer[x+8];
if (unit < 31)
{
for (byte x=0; x < 4; x++)
Nodes[unit].ip[x]=packetBuffer[x+8];
Nodes[unit].age=0; // reset 'age counter'
}
char macaddress[20];
sprintf(macaddress,"%02x:%02x:%02x:%02x:%02x:%02x",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
char ipaddress[16];
sprintf(ipaddress,"%u.%u.%u.%u",ip[0],ip[1],ip[2],ip[3]);
Serial.print(macaddress);
Serial.print(",");
Serial.print(ipaddress);
Serial.print(",");
Serial.println(unit);
}
}
}
}
}
void refreshNodeList()
{
for (byte counter=0; counter<32; counter++)
{
if(Nodes[counter].ip[0] != 0)
{
Nodes[counter].age++; // increment age counter
if (Nodes[counter].age > 10) // if entry to old, clear this node ip from the list.
for (byte x=0; x < 4; x++)
Nodes[counter].ip[x]=0;
}
}
}
void sendSysInfoUDP(byte repeats)
{
// 1 byte 'binary token 255'
// 1 byte id
// 6 byte mac
// 4 byte ip
// 1 byte unit
// ??? build
// ??
// send my info to the world...
for (byte counter=0; counter < repeats; counter++)
{
uint8_t mac[] = {0,0,0,0,0,0};
uint8_t* macread = WiFi.macAddress(mac);
byte data[20];
data[0]=255;
data[1]=1;
for (byte x=0; x < 6; x++)
data[x+2]=macread[x];
IPAddress ip = WiFi.localIP();
for (byte x=0; x < 4; x++)
data[x+8]=ip[x];
data[12]=Settings.Unit;
IPAddress broadcastIP(255,255,255,255);
portTX.beginPacket(broadcastIP,Settings.UDPPort);
portTX.write(data,20);
portTX.endPacket();
if (counter < (repeats-1))
delay(500);
}
// store my own info also in the list...
IPAddress ip = WiFi.localIP();
for (byte x=0; x < 4; x++)
Nodes[Settings.Unit].ip[x]=ip[x];
Nodes[Settings.Unit].age=0;
}
+11 -220
View File
@@ -19,8 +19,7 @@ void pulseinit(byte Par1)
boolean analog(byte Par1)
{
boolean success = false;
//int value = analogRead(A0); // crashes on latest release...
int value = millis()/1000;
int value = analogRead(A0);
UserVar[Par1 - 1] = (float)value;
Serial.print("ADC : Analog value: ");
Serial.println(value);
@@ -323,7 +322,6 @@ byte read_dht_dat(void)
{
byte i = 0;
byte result = 0;
noInterrupts();
for (i = 0; i < 8; i++)
{
while (!digitalRead(DHT_Pin)); // wait for 50us
@@ -332,7 +330,6 @@ byte read_dht_dat(void)
result |= (1 << (7 - i));
while (digitalRead(DHT_Pin)); // wait '1' finish
}
interrupts();
return result;
}
@@ -349,12 +346,15 @@ boolean dht(byte type, byte Par1, byte Par2)
{
pinMode(DHT_Pin, OUTPUT);
// DHT start condition, pull-down i/o pin for 18ms
digitalWrite(DHT_Pin, HIGH); // Pull high
delay(250);
digitalWrite(DHT_Pin, LOW); // Pull low
delay(18);
delay(20);
noInterrupts();
digitalWrite(DHT_Pin, HIGH); // Pull high
delayMicroseconds(40);
pinMode(DHT_Pin, INPUT); // change pin to input
delayMicroseconds(40);
//delayMicroseconds(40);
dht_in = digitalRead(DHT_Pin);
if (!dht_in)
@@ -367,6 +367,8 @@ boolean dht(byte type, byte Par1, byte Par2)
for (i = 0; i < 5; i++)
dht_dat[i] = read_dht_dat();
interrupts();
// Checksum calculation is a Rollover Checksum by design!
byte dht_check_sum = dht_dat[0] + dht_dat[1] + dht_dat[2] + dht_dat[3]; // check check_sum
@@ -395,6 +397,9 @@ boolean dht(byte type, byte Par1, byte Par2)
}
}
}
interrupts();
if (!success)
{
delay(2000);
@@ -613,219 +618,5 @@ boolean bmp085(byte Par1)
}
}
/*********************************************************************************************\
* LCD I2C Display
\*********************************************************************************************/
#define LCD_I2C_ADDRESS 0x27
#define PLUGIN_021_ROWS 4
#define PLUGIN_021_COLS 20
#define LCD_CLEARDISPLAY 0x01
#define LCD_RETURNHOME 0x02
#define LCD_ENTRYMODESET 0x04
#define LCD_DISPLAYCONTROL 0x08
#define LCD_CURSORSHIFT 0x10
#define LCD_FUNCTIONSET 0x20
#define LCD_SETCGRAMADDR 0x40
#define LCD_SETDDRAMADDR 0x80
// flags for display entry mode
#define LCD_ENTRYRIGHT 0x00
#define LCD_ENTRYLEFT 0x02
#define LCD_ENTRYSHIFTINCREMENT 0x01
#define LCD_ENTRYSHIFTDECREMENT 0x00
// flags for display on/off control
#define LCD_DISPLAYON 0x04
#define LCD_DISPLAYOFF 0x00
#define LCD_CURSORON 0x02
#define LCD_CURSOROFF 0x00
#define LCD_BLINKON 0x01
#define LCD_BLINKOFF 0x00
// flags for display/cursor shift
#define LCD_DISPLAYMOVE 0x08
#define LCD_CURSORMOVE 0x00
#define LCD_MOVERIGHT 0x04
#define LCD_MOVELEFT 0x00
// flags for function set
#define LCD_8BITMODE 0x10
#define LCD_4BITMODE 0x00
#define LCD_2LINE 0x08
#define LCD_1LINE 0x00
#define LCD_5x10DOTS 0x04
#define LCD_5x8DOTS 0x00
// flags for backlight control
#define LCD_BACKLIGHT 0x08
#define LCD_NOBACKLIGHT 0x00
#define En B00000100 // Enable bit
#define Rw B00000010 // Read/Write bit
#define Rs B00000001 // Register select bit
void LCD_I2C_init();
void LCD_I2C_printline(byte row, byte col, char* message);
inline size_t LCD_I2C_write(uint8_t value);
void LCD_I2C_display();
void LCD_I2C_clear();
void LCD_I2C_home();
void LCD_I2C_setCursor(uint8_t col, uint8_t row);
inline void LCD_I2C_command(uint8_t value);
void LCD_I2C_send(uint8_t value, uint8_t mode);
void LCD_I2C_write4bits(uint8_t value);
void LCD_I2C_expanderWrite(uint8_t _data);
void LCD_I2C_pulseEnable(uint8_t _data);
uint8_t _displayfunction;
uint8_t _displaycontrol;
uint8_t _displaymode;
uint8_t _numlines;
uint8_t _backlightval=LCD_BACKLIGHT;
boolean lcdinit=false;
boolean lcd(byte Par1, byte Par2, char *text)
{
Serial.print("LCD : ");
Serial.println(text);
if (!lcdinit)
{
LCD_I2C_init();
lcdinit=true;
}
if (Par1 >= 0 && Par1 <= PLUGIN_021_ROWS)
{
LCD_I2C_printline(Par1-1, Par2-1, text);
}
Wire.endTransmission(true);
}
/*********************************************************************/
void LCD_I2C_init()
/*********************************************************************/
{
_displayfunction = LCD_2LINE;
_numlines = PLUGIN_021_ROWS;
delay(50);
// Now we pull both RS and R/W low to begin commands
LCD_I2C_expanderWrite(_backlightval); // reset expander and turn backlight off (Bit 8 =1)
delay(1000);
//put the LCD into 4 bit mode, this is according to the hitachi HD44780 datasheet, figure 24, pg 46
LCD_I2C_write4bits(0x03 << 4); // we start in 8bit mode, try to set 4 bit mode
delayMicroseconds(4500); // wait min 4.1ms
LCD_I2C_write4bits(0x03 << 4); // second try
delayMicroseconds(4500); // wait min 4.1ms
LCD_I2C_write4bits(0x03 << 4); // third go!
delayMicroseconds(150);
LCD_I2C_write4bits(0x02 << 4); // finally, set to 4-bit interface
LCD_I2C_command(LCD_FUNCTIONSET | _displayfunction); // set # lines, font size, etc.
_displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; // turn the display on with no cursor or blinking default
LCD_I2C_display();
LCD_I2C_clear(); // clear it off
_displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; // Initialize to default text direction (for roman languages)
LCD_I2C_command(LCD_ENTRYMODESET | _displaymode); // set the entry mode
LCD_I2C_home();
}
/*********************************************************************/
void LCD_I2C_printline(byte row, byte col, char* message)
/*********************************************************************/
{
LCD_I2C_setCursor(col,row);
byte maxcol = PLUGIN_021_COLS-col;
//clear line if empty message
if (message[0]==0)
for (byte x=0; x<PLUGIN_021_COLS; x++) LCD_I2C_write(' ');
else
for (byte x=0; x < maxcol; x++)
{
if (message[x] != 0) LCD_I2C_write(message[x]);
else break;
}
}
/*********************************************************************/
inline size_t LCD_I2C_write(uint8_t value)
/*********************************************************************/
{
LCD_I2C_send(value, Rs);
return 0;
}
/*********************************************************************/
void LCD_I2C_display() {
/*********************************************************************/
_displaycontrol |= LCD_DISPLAYON;
LCD_I2C_command(LCD_DISPLAYCONTROL | _displaycontrol);
}
/*********************************************************************/
void LCD_I2C_clear(){
/*********************************************************************/
LCD_I2C_command(LCD_CLEARDISPLAY);// clear display, set cursor position to zero
delayMicroseconds(2000); // this command takes a long time!
}
/*********************************************************************/
void LCD_I2C_home(){
/*********************************************************************/
LCD_I2C_command(LCD_RETURNHOME); // set cursor position to zero
delayMicroseconds(2000); // this command takes a long time!
}
/*********************************************************************/
void LCD_I2C_setCursor(uint8_t col, uint8_t row){
/*********************************************************************/
int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 };
if ( row > _numlines ) {
row = _numlines-1; // we count rows starting w/0
}
LCD_I2C_command(LCD_SETDDRAMADDR | (col + row_offsets[row]));
}
/*********************************************************************/
inline void LCD_I2C_command(uint8_t value) {
/*********************************************************************/
LCD_I2C_send(value, 0);
}
/*********************************************************************/
void LCD_I2C_send(uint8_t value, uint8_t mode) {
/*********************************************************************/
uint8_t highnib=value&0xf0;
uint8_t lownib=(value<<4)&0xf0;
LCD_I2C_write4bits((highnib)|mode);
LCD_I2C_write4bits((lownib)|mode);
}
/*********************************************************************/
void LCD_I2C_write4bits(uint8_t value) {
/*********************************************************************/
LCD_I2C_expanderWrite(value);
LCD_I2C_pulseEnable(value);
}
/*********************************************************************/
void LCD_I2C_expanderWrite(uint8_t _data){
/*********************************************************************/
Wire.beginTransmission(LCD_I2C_ADDRESS);
Wire.write((int)(_data) | _backlightval);
Wire.endTransmission(false);
yield();
}
/*********************************************************************/
void LCD_I2C_pulseEnable(uint8_t _data){
/*********************************************************************/
LCD_I2C_expanderWrite(_data | En); // En high
delayMicroseconds(1); // enable pulse must be >450ns
LCD_I2C_expanderWrite(_data & ~En); // En low
delayMicroseconds(50); // commands need > 37us to settle
}
+95 -144
View File
@@ -30,22 +30,26 @@
// You can allways change these during runtime and save to eeprom
// After loading firmware, issue a 'reset' command to load the defaults.
#define DEFAULT_SSID "ssid" // Enter your network SSID
#define DEFAULT_KEY "wpakey" // Enter your network WPA key
#define DEFAULT_SERVER "192.168.0.8" // Enter your Domoticz Server IP address
#define DEFAULT_PORT 8080 // Enter your Domoticz Server port value
#define DEFAULT_DELAY 60 // Enter your Send delay in seconds
#define DEFAULT_AP_KEY "configesp" // Enter network WPA key for AP (config) mode
#define DEFAULT_DALLAS_IDX 0 // Enter IDX of your virtual temperature device
#define DEFAULT_DHT_IDX 0 // Enter IDX of your virtual Humidity device
#define DEFAULT_DHT_TYPE 11 // Enter Type of your virtual Humidity device
#define DEFAULT_BMP_IDX 0 // Enter IDX of your virtual Barometric Pressure device
#define DEFAULT_LUX_IDX 0 // Enter IDX of your virtual LUX device
#define DEFAULT_RFID_IDX 0 // Enter IDX of your virtual RFID device
#define DEFAULT_ANALOG_IDX 0 // Enter IDX of your virtual Analog device
#define DEFAULT_PULSE1_IDX 0 // Enter IDX of your virtual Pulse counter
#define DEFAULT_NAME "newdevice" // Enter your device friendly name
#define DEFAULT_SSID "ssid" // Enter your network SSID
#define DEFAULT_KEY "wpakey" // Enter your network WPA key
#define DEFAULT_SERVER "192.168.0.8" // Enter your Domoticz Server IP address
#define DEFAULT_PORT 8080 // Enter your Domoticz Server port value
#define DEFAULT_DELAY 60 // Enter your Send delay in seconds
#define DEFAULT_AP_KEY "configesp" // Enter network WPA key for AP (config) mode
#define DEFAULT_DALLAS_IDX 0 // Enter IDX of your virtual temperature device
#define DEFAULT_DHT_IDX 0 // Enter IDX of your virtual Humidity device
#define DEFAULT_DHT_TYPE 11 // Enter Type of your virtual Humidity device
#define DEFAULT_BMP_IDX 0 // Enter IDX of your virtual Barometric Pressure device
#define DEFAULT_LUX_IDX 0 // Enter IDX of your virtual LUX device
#define DEFAULT_RFID_IDX 0 // Enter IDX of your virtual RFID device
#define DEFAULT_ANALOG_IDX 0 // Enter IDX of your virtual Analog device
#define DEFAULT_PULSE1_IDX 0 // Enter IDX of your virtual Pulse counter
#define DEFAULT_SWITCH1_IDX 0 // Enter IDX of your switch device
#define UNIT 1
#define DEFAULT_PROTOCOL 1 // Protocol used for controller communications
// 1 = Domoticz HTTP
// 2 = Domoticz MQTT
#define UNIT 1
// ********************************************************************************
// DO NOT CHANGE ANYTHING BELOW THIS LINE
@@ -62,11 +66,17 @@
// 10 DomoticzSend Serial in
// 11 Switch
// sensor types
// 1 = single value, general purpose (Dallas, LUX, counters, etc)
// 2 = temp + hum (DHT)
// 3 = temp + hum + baro (BMP085)
// 10 = switch
#define ESP_PROJECT_PID 2015050101L
#define ESP_EASY
#define VERSION 1
#define BUILD 8
#define BUILD 9
#define UDP_LISTEN_PORT 65500
#define REBOOT_ON_MAX_CONNECTION_FAILURES 30
#include <ESP8266WiFi.h>
@@ -74,12 +84,20 @@
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <Wire.h>
#include <stdio.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <LiquidCrystal_I2C.h>
ESP8266WebServer server(80);
// MQTT client
PubSubClient MQTTclient("");
// LCD
LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display
// WebServer
ESP8266WebServer WebServer(80);
// syslog stuff
char packetBuffer[255];
WiFiUDP portRX;
WiFiUDP portTX;
@@ -113,8 +131,24 @@ struct SettingsStruct
byte Syslog_IP[4];
unsigned int UDPPort;
unsigned int Switch1;
byte Protocol;
byte IP[4];
byte Gateway[4];
byte Subnet[4];
byte Debug;
char Name[26];
} Settings;
struct LogStruct
{
unsigned long timeStamp;
char Message[80];
}Logging[10];
int logcount=-1;
boolean printToWeb = false;
String printWebString = "";
float UserVar[15];
unsigned long timer;
unsigned long timer100ms;
@@ -130,13 +164,14 @@ unsigned long wdcounter=0;
unsigned long pulseCounter1=0;
byte switch1state=0;
void setup()
{
Serial.begin(9600);
Serial.print(F("\nINIT : Booting Build nr:"));
Serial.println(BUILD);
EEPROM.begin(4096);
EEPROM.begin(1024);
LoadSettings();
// if different version, eeprom settings structure has changed. Full Reset needed
@@ -150,110 +185,48 @@ void setup()
ResetFactory();
}
// configure hardware pins according to eeprom settings.
if (Settings.Pin_i2c_sda != -1)
{
Serial.println(F("INIT : I2C"));
Wire.begin(Settings.Pin_i2c_sda, Settings.Pin_i2c_scl);
}
hardwareInit();
if (Settings.Pin_wired_in_1 != -1)
{
Serial.println(F("INIT : Input 1"));
pinMode(Settings.Pin_wired_in_1, INPUT_PULLUP);
}
if (Settings.Pin_wired_in_2 != -1)
{
Serial.println(F("INIT : Input 2"));
pinMode(Settings.Pin_wired_in_2, INPUT_PULLUP);
}
WifiAPconfig();
WifiConnect();
if (Settings.Pin_wired_out_1 != -1)
{
Serial.println(F("INIT : Output 1"));
pinMode(Settings.Pin_wired_out_1, OUTPUT);
}
if (Settings.Pin_wired_out_2 != -1)
{
Serial.println(F("INIT : Output 2"));
pinMode(Settings.Pin_wired_out_2, OUTPUT);
}
// create unique AP SSID
ap_ssid[0] = 0;
strcpy(ap_ssid, "ESP_");
sprintf(ap_ssid, "%s%u", ap_ssid, Settings.Unit);
// setup ssid for AP Mode when needed
WiFi.softAP(ap_ssid, Settings.WifiAPKey);
// We start in STA mode
WiFi.mode(WIFI_STA);
server.on("/", handle_root);
server.on("/config", handle_config);
server.on("/devices", handle_devices);
server.on("/hardware", handle_hardware);
server.on("/json.htm", handle_json);
server.begin();
WebServerInit();
// setup UDP
if (Settings.UDPPort != 0)
portRX.begin(Settings.UDPPort);
// Setup timers
timer = millis() + 30000; // startup delay 30 sec
timer100ms = millis() + 100; // timer for periodic actions 10 x per/sec
timer1s = millis() + 1000; // timer for periodic actions once per/sec
timerwd = millis() + 30000; // timer for watchdog once per 30 sec
if (Settings.RFID > 0)
rfidinit(Settings.Pin_wired_in_1, Settings.Pin_wired_in_2);
if (Settings.Pulse1 > 0)
pulseinit(Settings.Pin_wired_in_1);
// if a SSID is configured, try to connect to Wifi network
if (strcasecmp(Settings.WifiSSID, "ssid") != 0)
{
WifiConnect();
// check if we got an ip address.
IPAddress ip = WiFi.localIP();
if (ip[0]==0) // dhcp issue ?
{
Serial.println(F("No IP!"));
delayedReboot(60);
}
}
else
{
// Start Access Point for first config steps...
AP_Mode = true;
WifiAPMode(true);
}
Serial.println(F("INIT : Boot OK"));
// Setup LCD display
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.print("ESP Easy");
// Setup MQTT Client
MQTTConnect();
syslog((char*)"Boot");
sendSysInfoUDP(3);
Serial.println(F("INIT : Boot OK"));
addLog((char*)"Boot");
}
void loop()
{
server.handleClient();
WebServer.handleClient();
MQTTclient.loop();
if (Serial.available())
serial();
// upd events
int packetSize = portRX.parsePacket();
if (packetSize)
{
Serial.print("UDP : " );
int len = portRX.read(packetBuffer, 255);
if (len > 0) packetBuffer[len] = 0;
{
Serial.println(packetBuffer);
ExecuteCommand(packetBuffer);
}
}
checkUDP();
if (cmd_disconnect == true)
{
cmd_disconnect = false;
@@ -267,9 +240,12 @@ void loop()
timerwd = millis() + 30000;
char str[40];
str[0]=0;
sprintf(str,"WD %u CF %u FM %u", wdcounter/2, connectionFailures, FreeMem());
Serial.print("WD : ");
sprintf(str,"Uptime %u ConnectFailures %u FreeMem %u", wdcounter/2, connectionFailures, FreeMem());
Serial.println(str);
syslog(str);
sendSysInfoUDP(1);
refreshNodeList();
}
// Perform regular checks, 10 times/sec
@@ -301,12 +277,13 @@ void loop()
if (Settings.Switch1 != 0)
{
byte state1 = digitalRead(0);
byte state1 = digitalRead(Settings.Pin_wired_in_1);
if (state1 != switch1state)
{
switch1state = state1;
UserVar[11 - 1] = state1;
Domoticz_sendData(10, Settings.Switch1, 11);
sendData(10, Settings.Switch1, 11);
delay(100);
}
}
delay(10);
@@ -322,7 +299,7 @@ void inputCheck()
Serial.print("RFID : Tag : ");
Serial.println(rfid_id);
UserVar[8 - 1] = rfid_id;
Domoticz_sendData(1, Settings.RFID, 8);
sendData(1, Settings.RFID, 8);
}
}
}
@@ -332,31 +309,32 @@ void SensorSend()
if (Settings.Dallas > 0)
{
dallas(1, 1); // read ds18b20 on wiredout 1, store to var 1
Domoticz_sendData(1, Settings.Dallas, 1);
sendData(1, Settings.Dallas, 1);
}
if (Settings.DHT > 0)
{
dht(Settings.DHTType, 2, 2); // readd dht on wiredout 2, store to var 2 (and 3)
Domoticz_sendData(2, Settings.DHT, 2);
dht(Settings.DHTType, 2, 2); // read dht on wiredout 2, store to var 2 (and 3)
if (!isnan(UserVar[2-1]) && (UserVar[3-1] > 0))
sendData(2, Settings.DHT, 2);
}
if (Settings.BMP > 0)
{
bmp085(4); // read bmp085 (i2c) and store to vars 4 and 5
Domoticz_sendData(3, Settings.BMP, 4);
sendData(3, Settings.BMP, 4);
}
if (Settings.LUX > 0)
{
lux(6); // read BH1750 LUX sensor and store to var 6
Domoticz_sendData(1, Settings.LUX, 6);
sendData(1, Settings.LUX, 6);
}
if (Settings.Analog > 0)
{
analog(7); // read ADC and store to var 7
Domoticz_sendData(1, Settings.Analog, 7);
sendData(1, Settings.Analog, 7);
}
if (Settings.Pulse1 > 0)
@@ -373,37 +351,10 @@ void SensorSend()
Serial.print(F("New Value:"));
Serial.println(value);
UserVar[9 - 1] = value; // store pulsecount to var 9
Domoticz_sendData(1, Settings.Pulse1, 9);
sendData(1, Settings.Pulse1, 9);
}
}
}
void syslog(char *message)
{
if (Settings.Syslog_IP[0] != 0)
{
IPAddress broadcastIP(Settings.Syslog_IP[0],Settings.Syslog_IP[1],Settings.Syslog_IP[2],Settings.Syslog_IP[3]);
portTX.beginPacket(broadcastIP,514);
char str[80];
str[0]=0;
sprintf(str,"<7>ESP Unit: %u : %s",Settings.Unit,message);
Serial.print("SYSLG: ");
Serial.println(str);
portTX.write(str);
portTX.endPacket();
}
}
void delayedReboot(int rebootDelay)
{
while (rebootDelay !=0 )
{
Serial.print(F("Delayed Reset "));
Serial.println(rebootDelay);
rebootDelay--;
delay(1000);
}
ESP.reset();
}
+41
View File
@@ -0,0 +1,41 @@
void hardwareInit()
{
// configure hardware pins according to eeprom settings.
if (Settings.Pin_i2c_sda != -1)
{
Serial.println(F("INIT : I2C"));
Wire.begin(Settings.Pin_i2c_sda, Settings.Pin_i2c_scl);
}
if (Settings.Pin_wired_in_1 != -1)
{
Serial.println(F("INIT : Input 1"));
pinMode(Settings.Pin_wired_in_1, INPUT_PULLUP);
}
if (Settings.Pin_wired_in_2 != -1)
{
Serial.println(F("INIT : Input 2"));
pinMode(Settings.Pin_wired_in_2, INPUT_PULLUP);
}
if (Settings.Pin_wired_out_1 != -1)
{
Serial.println(F("INIT : Output 1"));
pinMode(Settings.Pin_wired_out_1, OUTPUT);
}
if (Settings.Pin_wired_out_2 != -1)
{
Serial.println(F("INIT : Output 2"));
pinMode(Settings.Pin_wired_out_2, OUTPUT);
}
if (Settings.RFID > 0)
rfidinit(Settings.Pin_wired_in_1, Settings.Pin_wired_in_2);
if (Settings.Pulse1 > 0)
pulseinit(Settings.Pin_wired_in_1);
}
+41
View File
@@ -0,0 +1,41 @@
/********************************************************************************************\
* Een float en een unsigned long zijn beide 4bytes groot. Deze zijn niet te casten naar
* elkaar. Onderstaande twee funkties converteren de unsigned long
* en de float.
\*********************************************************************************************/
unsigned long float2ul(float f)
{
unsigned long ul;
memcpy(&ul, &f,4);
return ul;
}
float ul2float(unsigned long ul)
{
float f;
memcpy(&f, &ul,4);
return f;
}
void addLog(char *line)
{
Serial.println(line);
logcount++;
if (logcount > 9)
logcount=0;
Logging[logcount].timeStamp = millis();
strcpy(Logging[logcount].Message,line);
Logging[logcount].Message[79]=0;
}
void delayedReboot(int rebootDelay)
{
while (rebootDelay !=0 )
{
Serial.print(F("Delayed Reset "));
Serial.println(rebootDelay);
rebootDelay--;
delay(1000);
}
ESP.reset();
}
+56 -2
View File
@@ -25,7 +25,7 @@ void ExecuteCommand(char *Line)
if (GetArgv(Line, TmpStr1, 4))
{
UserVar[10 - 1] = atof(TmpStr1);
Domoticz_sendData(Par1, Par2, 10);
sendData(Par1, Par2, 10);
}
}
@@ -64,9 +64,40 @@ void ExecuteCommand(char *Line)
for (byte x = 0; x < 25; x++)
if (TmpStr1[x] == '_')
TmpStr1[x] = ' ';
lcd(Par1, Par2, TmpStr1);
lcd.setCursor(Par2-1,Par1-1);
lcd.print(TmpStr1);
}
if (strcasecmp(Command, "IOTest") == 0)
{
if (Par1 == 255)
{
Serial.print("Analog:");
Serial.println(analogRead(A0));
if (printToWeb)
{
printWebString += "Analog: ";
printWebString += analogRead(A0);
printWebString += "<BR>";
}
}
else
{
pinMode(Par1, OUTPUT);
for (byte x=0; x < 10; x++)
{
digitalWrite(Par1,HIGH);
delay(100);
digitalWrite(Par1,LOW);
delay(100);
if (printToWeb)
{
printWebString += "Did the LED Flash? <BR>";
}
}
}
}
// ****************************************
// configure settings commands:
// ****************************************
@@ -100,6 +131,12 @@ void ExecuteCommand(char *Line)
if (strcasecmp(Command, "Pulse") == 0)
Settings.Pulse1 = Par1;
if (strcasecmp(Command, "Switch") == 0)
Settings.Switch1 = Par1;
if (strcasecmp(Command, "Debug") == 0)
Settings.Debug = Par1;
if (strcasecmp(Command, "ControllerIP") == 0)
{
if (GetArgv(Line, TmpStr1, 2))
@@ -204,6 +241,7 @@ void ExecuteCommand(char *Line)
Serial.print(" RFID : "); Serial.println(Settings.RFID);
Serial.print(" Analog : "); Serial.println(Settings.Analog);
Serial.print(" Pulse : "); Serial.println(Settings.Pulse1);
Serial.print(" Switch : "); Serial.println(Settings.Switch1);
}
if (strcasecmp(Command, "Freemem") == 0)
@@ -389,6 +427,21 @@ void ResetFactory(void)
Settings.Syslog_IP[3] = 0;
Settings.UDPPort = 0;
Settings.Switch1 = DEFAULT_SWITCH1_IDX;
Settings.Protocol = DEFAULT_PROTOCOL;
Settings.IP[0] = 0;
Settings.IP[1] = 0;
Settings.IP[2] = 0;
Settings.IP[3] = 0;
Settings.Gateway[0] = 0;
Settings.Gateway[1] = 0;
Settings.Gateway[2] = 0;
Settings.Gateway[3] = 0;
Settings.Subnet[0] = 0;
Settings.Subnet[1] = 0;
Settings.Subnet[2] = 0;
Settings.Subnet[3] = 0;
Settings.Debug = 0;
strcpy(Settings.Name, DEFAULT_NAME);
Save_Settings();
WifiDisconnect();
ESP.reset();
@@ -403,4 +456,5 @@ unsigned long FreeMem(void)
{
return system_get_free_heap_size();
}
+378 -46
View File
@@ -1,9 +1,28 @@
//********************************************************************************
// Web Interface init
//********************************************************************************
void WebServerInit()
{
// Prepare webserver pages
WebServer.on("/", handle_root);
WebServer.on("/config", handle_config);
WebServer.on("/devices", handle_devices);
WebServer.on("/hardware", handle_hardware);
WebServer.on("/json.htm", handle_json);
#ifdef ESP_CONNEXIO
WebServer.on("/eventlist", handle_eventlist);
#endif
WebServer.on("/log", handle_log);
WebServer.on("/debug", handle_debug);
WebServer.begin();
}
//********************************************************************************
// Web Interface root page
//********************************************************************************
void handle_root() {
Serial.print(F("HTTP : Webrequest : "));
String webrequest = server.arg("cmd");
String webrequest = WebServer.arg("cmd");
webrequest.replace("%20", " ");
Serial.println(webrequest);
char command[80];
@@ -12,23 +31,50 @@ void handle_root() {
if (strcasecmp(command, "wifidisconnect") != 0)
{
ExecuteCommand(command);
String reply = F("<body><form>Welcome to ESP Easy");
String reply = "";
printToWeb=true;
printWebString = "";
#ifdef ESP_CONNEXIO
ExecuteLine(command,VALUE_SOURCE_SERIAL);
#endif
#ifdef ESP_EASY
ExecuteCommand(command);
#endif
reply += printWebString;
reply += F("<body><form>Welcome to ESP ");
#ifdef ESP_CONNEXIO
reply += F("Connexio : ");
#endif
#ifdef ESP_EASY
reply += F("Easy : ");
#endif
reply += Settings.Name;
reply += F("<BR><a href='/config'>Config</a>");
reply += F("<BR><a href='/devices'>Devices</a>");
reply += F("<BR><a href='/hardware'>Hardware</a>");
reply += F("<BR><a href='/?cmd=reboot'>Reboot</a>");
reply += F("<BR><a href='/?cmd=wifidisconnect'>Disconnect</a>");
reply += F("<BR><a href='/?cmd=wificonnect'>Connect</a>");
#ifdef ESP_CONNEXIO
reply += F("<BR><a href='/eventlist'>Eventlist</a>");
#endif
reply += F("<BR><a href='/log'>Log</a>");
reply += F("<BR><a href='/debug'>Debug</a>");
reply += F("<BR><BR>System Info");
IPAddress ip = WiFi.localIP();
IPAddress gw = WiFi.gatewayIP();
reply += F("<BR><BR>Uptime : ");
reply += wdcounter/2;
reply += F(" minutes");
char str[20];
sprintf(str, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
reply += "<BR><BR>IP : ";
reply += F("<BR>IP : ");
reply += str;
sprintf(str, "%u.%u.%u.%u", gw[0], gw[1], gw[2], gw[3]);
@@ -41,8 +87,52 @@ void handle_root() {
reply += F("<BR>Unit : ");
reply += Settings.Unit;
reply += F("<BR>STA MAC: ");
uint8_t mac[] = {0,0,0,0,0,0};
uint8_t* macread = WiFi.macAddress(mac);
char macaddress[20];
sprintf(macaddress,"%02x:%02x:%02x:%02x:%02x:%02x",macread[0],macread[1],macread[2],macread[3],macread[4],macread[5]);
reply +=macaddress;
reply += F("<BR>AP MAC: ");
macread = WiFi.softAPmacAddress(mac);
sprintf(macaddress,"%02x:%02x:%02x:%02x:%02x:%02x",macread[0],macread[1],macread[2],macread[3],macread[4],macread[5]);
reply +=macaddress;
reply += F("<BR>ESP Chip ID: ");
reply += ESP.getChipId();
reply += F("<BR>ESP Flash Size: ");
reply += ESP.getFlashChipSize();
reply += F("<BR>Free Mem: ");
reply += ESP.getFreeHeap();
reply += F("<BR><BR>Node List:<BR>");
for (byte x=0; x<32;x++)
{
if(Nodes[x].ip[0] != 0)
{
if (x==Settings.Unit)
reply += "<font color='blue'>";
char url[80];
sprintf(url,"<a href='http://%u.%u.%u.%u'>%u.%u.%u.%u</a>",Nodes[x].ip[0],Nodes[x].ip[1],Nodes[x].ip[2],Nodes[x].ip[3],Nodes[x].ip[0],Nodes[x].ip[1],Nodes[x].ip[2],Nodes[x].ip[3]);
reply += "Unit ";
reply += x;
reply += " : ";
reply += url;
reply += " (age=";
reply += Nodes[x].age;
reply += ")<BR>";
if (x==Settings.Unit)
reply += "</font color>";
}
}
reply += F("</form></body>");
server.send(200, "text/html", reply);
WebServer.send(200, "text/html", reply);
printWebString = "";
printToWeb=false;
delay(100);
}
else
@@ -51,6 +141,7 @@ void handle_root() {
// because the webconnection is still active at this point
// disconnect would result into a crash/reboot...
Serial.println(F("WIFI : Disconnecting..."));
WebServer.send(200, "text/html", "OK");
cmd_disconnect = true;
}
}
@@ -63,18 +154,26 @@ void handle_config() {
Serial.println(F("HTTP : Webconfig : "));
String ssid = server.arg("ssid");
String key = server.arg("key");
String controllerip = server.arg("controllerip");
String controllerport = server.arg("controllerport");
String ip = server.arg("ip");
String unit = server.arg("unit");
String apkey = server.arg("apkey");
String syslogip = server.arg("syslogip");
String udpport = server.arg("udpport");
String name = WebServer.arg("name");
String ssid = WebServer.arg("ssid");
String key = WebServer.arg("key");
String controllerip = WebServer.arg("controllerip");
String controllerport = WebServer.arg("controllerport");
String protocol = WebServer.arg("protocol");
String ip = WebServer.arg("ip");
String espip = WebServer.arg("espip");
String espgateway = WebServer.arg("espgateway");
String espsubnet = WebServer.arg("espsubnet");
String unit = WebServer.arg("unit");
String apkey = WebServer.arg("apkey");
String syslogip = WebServer.arg("syslogip");
String udpport = WebServer.arg("udpport");
if (ssid[0] != 0)
{
name.replace("+", " ");
name.toCharArray(tmpstring, 25);
strcpy(Settings.Name, tmpstring);
ssid.toCharArray(tmpstring, 25);
strcpy(Settings.WifiSSID, tmpstring);
key.toCharArray(tmpstring, 25);
@@ -82,7 +181,14 @@ void handle_config() {
controllerip.toCharArray(tmpstring, 25);
str2ip(tmpstring, Settings.Controller_IP);
Settings.ControllerPort = controllerport.toInt();
Settings.Protocol = protocol.toInt();
Settings.IP_Octet = ip.toInt();
espip.toCharArray(tmpstring, 25);
str2ip(tmpstring, Settings.IP);
espgateway.toCharArray(tmpstring, 25);
str2ip(tmpstring, Settings.Gateway);
espsubnet.toCharArray(tmpstring, 25);
str2ip(tmpstring, Settings.Subnet);
Settings.Unit = unit.toInt();
apkey.toCharArray(tmpstring, 25);
strcpy(Settings.WifiAPKey, tmpstring);
@@ -93,12 +199,21 @@ void handle_config() {
LoadSettings();
}
String reply = F("<body>");
reply += F("<form>SSID:<BR><input type='text' name='ssid' value='");
String reply = F("<body><form>");
reply += F("Name:<BR><input type='text' name='name' value='");
Settings.Name[25]=0;
reply += Settings.Name;
reply += F("'><BR>SSID:<BR><input type='text' name='ssid' value='");
reply += Settings.WifiSSID;
reply += F("'><BR>WPA Key:<BR><input type='text' name='key' value='");
reply += Settings.WifiKey;
reply += F("'><BR>WPA AP Mode Key:<BR><input type='text' name='apkey' value='");
reply += Settings.WifiAPKey;
reply += F("'><BR>Unit nr:<BR><input type='text' name='unit' value='");
reply += Settings.Unit;
reply += F("'><BR>Controller IP:<BR><input type='text' name='controllerip' value='");
char str[20];
sprintf(str, "%u.%u.%u.%u", Settings.Controller_IP[0], Settings.Controller_IP[1], Settings.Controller_IP[2], Settings.Controller_IP[3]);
@@ -106,14 +221,41 @@ void handle_config() {
reply += F("'><BR>Controller Port:<BR><input type='text' name='controllerport' value='");
reply += Settings.ControllerPort;
reply += F("'><BR>Fixed IP Octet: (Optional)<BR><input type='text' name='ip' value='");
reply +=F("'><BR>Protocol");
byte choice = Settings.Protocol;
String options[3];
options[0]=F("");
options[1]=F("Domoticz HTTP");
options[2]=F("Domoticz MQTT");
reply +=F("<BR><select name='protocol'>");
for (byte x=0; x<3;x++)
{
reply +=F("<option value='");
reply +=x;
reply +="'";
if (choice==x)
reply +=" selected";
reply +=">";
reply +=options[x];
reply+="</option>";
}
reply +=F("</select>");
reply += F("<BR><BR>Optional<BR><BR>Fixed IP Octet:<BR><input type='text' name='ip' value='");
reply += Settings.IP_Octet;
reply += F("'><BR>Unit nr:<BR><input type='text' name='unit' value='");
reply += Settings.Unit;
reply += F("'><BR>ESP IP:<BR><input type='text' name='espip' value='");
sprintf(str, "%u.%u.%u.%u", Settings.IP[0], Settings.IP[1], Settings.IP[2], Settings.IP[3]);
reply += str;
reply += F("'><BR>WPA AP Mode Key:<BR><input type='text' name='apkey' value='");
reply += Settings.WifiAPKey;
reply += F("'><BR>ESP GW:<BR><input type='text' name='espgateway' value='");
sprintf(str, "%u.%u.%u.%u", Settings.Gateway[0], Settings.Gateway[1], Settings.Gateway[2], Settings.Gateway[3]);
reply += str;
reply += F("'><BR>ESP Subnet:<BR><input type='text' name='espsubnet' value='");
sprintf(str, "%u.%u.%u.%u", Settings.Subnet[0], Settings.Subnet[1], Settings.Subnet[2], Settings.Subnet[3]);
reply += str;
reply += F("'><BR>Syslog IP:<BR><input type='text' name='syslogip' value='");
str[0]=0;
@@ -125,7 +267,7 @@ void handle_config() {
reply += F("'><BR><input type='submit' value='Submit'>");
reply += F("</form></body>");
server.send(200, "text/html", reply);
WebServer.send(200, "text/html", reply);
delay(1000);
}
@@ -137,17 +279,17 @@ void handle_devices() {
Serial.println(F("HTTP : Webdevices : "));
String boardtype = server.arg("boardtype");
String sensordelay = server.arg("delay");
String dallas = server.arg("dallas");
String dht = server.arg("dht");
String dhttype = server.arg("dhttype");
String bmp = server.arg("bmp");
String lux = server.arg("lux");
String rfid = server.arg("rfid");
String analog = server.arg("analog");
String pulse1 = server.arg("pulse1");
String switch1 = server.arg("switch1");
String boardtype = WebServer.arg("boardtype");
String sensordelay = WebServer.arg("delay");
String dallas = WebServer.arg("dallas");
String dht = WebServer.arg("dht");
String dhttype = WebServer.arg("dhttype");
String bmp = WebServer.arg("bmp");
String lux = WebServer.arg("lux");
String rfid = WebServer.arg("rfid");
String analog = WebServer.arg("analog");
String pulse1 = WebServer.arg("pulse1");
String switch1 = WebServer.arg("switch1");
if (sensordelay.toInt() != 0)
{
@@ -162,6 +304,45 @@ void handle_devices() {
Settings.Pulse1 = pulse1.toInt();
Settings.Switch1 = switch1.toInt();
Save_Settings();
#ifdef ESP_CONNEXIO
struct NodoEventStruct TempEvent;
ClearEvent(&TempEvent);
for (byte x=1; x<50;x++)
Eventlist_Write(x,&TempEvent,&TempEvent);
EEPROM.commit();
char cmd[80];
sprintf(cmd,"eventlistwrite; boot %u; TimerSet 1,%u",Settings.Unit,Settings.Delay);
ExecuteLine(cmd,VALUE_SOURCE_SERIAL);
sprintf(cmd,"eventlistwrite; Timer 1; TimerSet 1,%u",Settings.Delay);
ExecuteLine(cmd,VALUE_SOURCE_SERIAL);
if (Settings.Dallas != 0)
{
eventAddTimer((char*)"DallasRead 1,1");
eventAddVarSend(1, 1, Settings.Dallas);
}
if (Settings.DHT != 0)
{
eventAddTimer((char*)"DHTRead 2,2");
eventAddVarSend(2, 2, Settings.DHT);
}
if (Settings.BMP != 0)
{
eventAddTimer((char*)"BMP085Read 4");
eventAddVarSend(4, 3, Settings.BMP);
}
if (Settings.LUX != 0)
{
eventAddTimer((char*)"LuxRead 6");
eventAddVarSend(6, 1, Settings.LUX);
}
if (Settings.Analog != 0)
{
eventAddTimer((char*)"VariableWiredAnalog 7");
eventAddVarSend(7, 1, Settings.Analog);
}
#endif
}
String reply = F("<body><form>");
@@ -188,9 +369,30 @@ void handle_devices() {
reply += F("'><BR><input type='submit' value='Submit'>");
reply += F("</form></body>");
server.send(200, "text/html", reply);
WebServer.send(200, "text/html", reply);
delay(100);
}
#ifdef ESP_CONNEXIO
void eventAddVarSend(byte var, byte sensortype, int idx)
{
char cmd[80];
char strProtocol[5];
if (Settings.Protocol == 1)
strcpy(strProtocol,"HTTP");
if (Settings.Protocol == 2)
strcpy(strProtocol,"MQTT");
sprintf(cmd,"eventlistwrite; Timer 1; VariableSend %u,%s,%u,%u",var,strProtocol,sensortype,idx);
ExecuteLine(cmd,VALUE_SOURCE_SERIAL);
}
void eventAddTimer(char* event)
{
char cmd[80];
sprintf(cmd,"eventlistwrite; Timer 1; %s",event);
ExecuteLine(cmd,VALUE_SOURCE_SERIAL);
}
#endif
//********************************************************************************
// Web Interface hardware page
@@ -199,7 +401,7 @@ void handle_hardware() {
Serial.println(F("HTTP : Hardware : "));
String boardtype = server.arg("boardtype");
String boardtype = WebServer.arg("boardtype");
if (boardtype.length() != 0)
{
@@ -321,13 +523,15 @@ void handle_hardware() {
reply += F("<BR><input type='submit' value='Submit'>");
reply += F("</form></body>");
server.send(200, "text/html", reply);
WebServer.send(200, "text/html", reply);
delay(100);
}
//********************************************************************************
// Nodo proof of concept. send json query as nodo event on I2C to mega
// Compatible with Nodo 3.8 only, tested on R818
// set used variables to global on the Mega.
//********************************************************************************
#define NODO_VERSION_MAJOR 3
#define TARGET_NODO 5
@@ -348,9 +552,9 @@ struct TransmissionStruct
};
void handle_json() {
Serial.print("HTTP : Web json : idx: ");
String idx = server.arg("idx");
String svalue = server.arg("svalue");
Serial.print(F("HTTP : Web json : idx: "));
String idx = WebServer.arg("idx");
String svalue = WebServer.arg("svalue");
Serial.print(idx);
Serial.print(" svalue: ");
Serial.println(svalue);
@@ -392,15 +596,143 @@ void handle_json() {
Wire.write(data[x]);
Wire.endTransmission();
server.send(200, "text/html", "OK");
WebServer.send(200, "text/html", "OK");
delay(100);
}
unsigned long float2ul(float f)
{
unsigned long ul;
memcpy(&ul, &f, 4);
return ul;
#ifdef ESP_CONNEXIO
//********************************************************************************
// Web Interface eventlist page
//********************************************************************************
void handle_eventlist() {
Serial.print(F("HTTP : Eventlist request : "));
char *TempString=(char*)malloc(80);
String reply =F("Eventlist<BR><BR>");
if (WebServer.args() ==1)
{
struct NodoEventStruct TempEvent;
ClearEvent(&TempEvent);
for (byte x=1; x<50;x++)
Eventlist_Write(x,&TempEvent,&TempEvent);
EEPROM.commit();
String eventlist = WebServer.arg("eventlist");
eventlist.replace("%0D%0A", "\n");
int NewLineIndex = eventlist.indexOf('\n');
byte limit=0;
byte messagecode=0;
while (NewLineIndex > 0 && limit < 10)
{
limit++;
String line=eventlist.substring(0,NewLineIndex);
line.replace("%3B", ";");
line.replace("%2C", ",");
line.replace("+", " ");
//int SemiColonIndex = line.indexOf(';');
//line = line.substring(SemiColonIndex+1);
String strCommand = F("eventlistwrite;");
strCommand += line;
Serial.println(strCommand);
strCommand.toCharArray(TempString,79);
messagecode=ExecuteLine(TempString,VALUE_SOURCE_SERIAL);
if (messagecode > 0)
{
reply += TempString;
reply += " : ";
reply += MessageText_tabel[messagecode];
reply += "<BR>";
}
eventlist = eventlist.substring(NewLineIndex+1);
NewLineIndex = eventlist.indexOf('\n');
}
}
reply += F("<body><form method='post'>");
reply += F("<textarea name='eventlist' rows='15' cols='80' wrap='on'>");
byte x=1;
while(EventlistEntry2str(x++,0,TempString,false))
if(TempString[0]!=0)
{
reply += TempString;
reply += '\n';
}
reply += F("</textarea>");
reply += F("<BR><input type='submit' value='Submit'>");
reply += F("</form></body>");
WebServer.send(200, "text/html", reply);
free(TempString);
}
#endif
//********************************************************************************
// Web Interface log page
//********************************************************************************
void handle_log() {
Serial.println(F("HTTP : Log request : "));
char *TempString=(char*)malloc(80);
String reply = F("<script language='JavaScript'>function RefreshMe(){window.location = window.location}setTimeout('RefreshMe()', 3000);</script>Log<BR><BR>");
byte counter=logcount;
do
{
counter++;
if (counter > 9)
counter=0;
if (Logging[counter].timeStamp > 0)
{
reply += Logging[counter].timeStamp;
reply +=" : ";
reply += Logging[counter].Message;
reply +="<BR>";
}
} while (counter != logcount);
WebServer.send(200, "text/html", reply);
free(TempString);
}
//********************************************************************************
// Web Interface debug page
//********************************************************************************
void handle_debug() {
Serial.print(F("HTTP : Webrequest : "));
String webrequest = WebServer.arg("cmd");
webrequest.replace("%3B", ";");
webrequest.replace("%2C", ",");
webrequest.replace("+", " ");
Serial.println(webrequest);
char command[80];
command[0] = 0;
webrequest.toCharArray(command, 79);
String reply = "";
reply += F("<body><form>Command:<BR>");
reply += F("<input type='text' name='cmd' value='");
reply += webrequest;
reply += F("'><BR><input type='submit' value='Submit'>");
printToWeb=true;
printWebString = "<BR>";
#ifdef ESP_CONNEXIO
ExecuteLine(command,VALUE_SOURCE_SERIAL);
#endif
#ifdef ESP_EASY
ExecuteCommand(command);
#endif
reply += printWebString;
reply += F("</form></body>");
WebServer.send(200, "text/html", reply);
printWebString = "";
printToWeb=false;
}
+59 -7
View File
@@ -1,26 +1,50 @@
//********************************************************************************
// Set Wifi AP Mode config
//********************************************************************************
void WifiAPconfig()
{
// create and store unique AP SSID/PW to prevent ESP from starting AP mode with default SSID and No password!
ap_ssid[0] = 0;
strcpy(ap_ssid, "ESP_");
sprintf(ap_ssid, "%s%u", ap_ssid, Settings.Unit);
// setup ssid for AP Mode when needed
WiFi.softAP(ap_ssid, Settings.WifiAPKey);
// We start in STA mode
WiFi.mode(WIFI_STA);
}
//********************************************************************************
// Set Wifi AP Mode
//********************************************************************************
void WifiAPMode(boolean state)
{
if (state)
{
AP_Mode=true;
Serial.println(F("WIFI : Starting AP Mode"));
WiFi.softAP(ap_ssid, Settings.WifiAPKey);
WiFi.mode(WIFI_AP_STA);
}
else
{
AP_Mode=false;
Serial.println(F("WIFI : Ending AP Mode"));
WiFi.mode(WIFI_STA);
}
}
//********************************************************************************
// Connect to Wifi AP
//********************************************************************************
boolean WifiConnect()
{
Serial.println(F("WIFI : Connecting..."));
if (WiFi.status() != WL_CONNECTED)
{
if (Settings.WifiSSID[0] != 0)
if ((Settings.WifiSSID[0] != 0) && (strcasecmp(Settings.WifiSSID, "ssid") != 0))
{
//WiFi.mode(WIFI_STA);
WiFi.begin(Settings.WifiSSID, Settings.WifiKey);
for (byte x = 0; x < 10; x++)
{
@@ -44,17 +68,42 @@ boolean WifiConnect()
Serial.println(ip);
WiFi.config(ip, gw, subnet);
}
if (Settings.IP[0] != 0 && Settings.IP[0] != 255)
{
Serial.print(F("IP : Static IP :"));
char str[20];
sprintf(str, "%u.%u.%u.%u", Settings.IP[0], Settings.IP[1], Settings.IP[2], Settings.IP[3]);
Serial.println(str);
IPAddress ip = Settings.IP;
IPAddress gw = Settings.Gateway;
IPAddress subnet = Settings.Subnet;
WiFi.config(ip,gw,subnet);
}
}
else
Serial.println(F("WIFI : No SSID!"));
{
Serial.println(F("WIFI : No SSID!"));
NC_Count=1;
WifiAPMode(true);
}
}
}
//********************************************************************************
// Disconnect from Wifi AP
//********************************************************************************
boolean WifiDisconnect()
{
WiFi.disconnect();
}
//********************************************************************************
// Scan all Wifi Access Points
//********************************************************************************
void WifiScan()
{
Serial.println(F("WIFI : SSID Scan start"));
@@ -85,6 +134,10 @@ void WifiScan()
Serial.println("");
}
//********************************************************************************
// Check if we are still connected to a Wifi AP
//********************************************************************************
void WifiCheck()
{
if (WiFi.status() != WL_CONNECTED)
@@ -93,7 +146,6 @@ void WifiCheck()
if (NC_Count > 10 && !AP_Mode)
{
C_Count=0;
AP_Mode=true;
WifiAPMode(true);
}
}
@@ -102,13 +154,13 @@ void WifiCheck()
if (NC_Count !=0) // there was a disconnect before...
{
C_Count++;
if (C_Count > 30)
if (C_Count > 60)
{
Serial.println(F("WIFI : Return to STA mode"));
NC_Count=0;
AP_Mode=false;
WifiAPMode(false);
}
}
}
}
}
+10
View File
@@ -48,4 +48,14 @@
// UDP listening port web configurable
// If UDP port enabled, also send IDX events to this UDP port
// Added Domotics lightswitch option, input on GPIO-0 pin.
// R009 26-06-2015
// Changed switch pin from GPIO-0 to wired input pin 1
// Added config options for static IP/gateway/subnet
// Using LCD library instead of local functions
// Added MQTT library
// Added JSON parse library
// Needs Domoticz 2560 and Mosquitto 3.1.1 or higher
// Reduced EEPROM from 4096->1024 (needs a RAM buffer from same size!)
// Added basic logging to web interface