Instantly share code, notes, and snippets.
Created
August 8, 2017 08:38
-
Save anonymous/ac1e8194b292b1f5048e1e9a2ece9707 to your computer and use it in GitHub Desktop.
Fauxmo Static IP WebSocket ToggleButton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* PIN CONNECTIONS | |
* GND --- RESISTOR ---- [LED] --- PIN 0 (D3) | |
* VCC --- RESISTOR ---- PIN 2 (D4) --- [BUTTON] --- GND | |
*/ | |
#include <Arduino.h> | |
#include <ESP8266WiFi.h> | |
#include "fauxmoESP.h" | |
#include <WebSocketsServer.h> | |
// Start User Information --------------- | |
const char* deviceName1 = "SHOP LED"; //device name for alexa | |
// start static ip | |
IPAddress ip(192, 168, 1, 121); | |
IPAddress gateway(192, 168, 1, 1); | |
IPAddress subnet(255, 255, 255, 0); | |
IPAddress DNS(192, 168, 1, 1); | |
#define PORT 61211 //just pick any port number you like | |
#define WS_PORT 61212 //just pick any port number you like (Websocket Port) | |
WiFiServer server(PORT); | |
#define MY_ESP_NAME "ESP121" // The name of the device in the network NO SPACES!!! | |
// end static ip | |
#define WIFI_SSID "SSID" // wifi of the router | |
#define WIFI_PASS "wifiPassword" // wifi pasword | |
/* | |
#define WIFI_SSID "ZTE" // wifi of the router | |
#define WIFI_PASS "12345678" // wifi pasword | |
*/ | |
#define LED_PIN1 2 //0 | |
#define BUTTON_PIN1 0 //2 | |
//End User Information ----------------------- | |
#define USE_SERIAL Serial | |
#define SERIAL_BAUDRATE 115200 | |
fauxmoESP fauxmo; | |
int ledState1 = LOW; // the current state of the output pin | |
int buttonState1; // the current reading from the input pin | |
int lastButtonState1 = LOW; // the previous reading from the input pin | |
unsigned long lastDebounceTime1 = 0; // the last time the output pin was toggled | |
unsigned long debounceDelay1 = 50; // the debounce time; increase if the output flickers | |
int websockMillis=50; // SocketVariables are sent to client every 50 milliseconds | |
String Time=""; // for counting time in the websocket | |
unsigned long ss; | |
byte mm,hh; | |
String webSite,javaScript,JSONtxt; | |
unsigned long websockCount=0UL,wait000=0UL; | |
String LEDswitch1="OFF"; | |
//WebSocketsServer webSocket=WebSocketsServer(88); | |
WebSocketsServer webSocket=WebSocketsServer(WS_PORT); | |
void buildWebsite(){ | |
buildJavascript(); | |
webSite = "HTTP/1.1 200 OK\r\n"; | |
webSite += "Content-Type: text/html\r\n\r\n"; | |
webSite += "\r\n"; | |
webSite += " <!DOCTYPE HTML><HTML>\n"; //I Add the + | |
webSite += "<META name='viewport' content='width=device-width, initial-scale=1'>\n"; | |
webSite += javaScript; | |
webSite += "<BODY>\n"; | |
webSite += "<BR><B>This is the "; | |
webSite += MY_ESP_NAME; | |
webSite += " website ...</B><BR><BR>\n"; | |
webSite += "<BR><B>IP Address:Port : "; | |
webSite += WiFi.localIP().toString().c_str(); | |
webSite += ":"; | |
webSite += PORT; | |
webSite += "</B><BR>\n"; | |
webSite += "<BR><B>WebSocket IP Address:Port : "; | |
webSite += WiFi.localIP().toString().c_str(); | |
webSite += ":"; | |
webSite += WS_PORT; | |
webSite += "</B><BR><BR>\n"; | |
webSite += "Runtime = <A ID='runtime'></A><BR>\n"; | |
webSite += "websockCount = <A ID='websockCount'></A><BR><BR>\n"; | |
webSite += "<B>"; | |
webSite += deviceName1; | |
webSite += " Status = <A ID='ledstate1'></A><BR><BR>"; | |
webSite += "</B>"; | |
webSite += "<TR><TD><BUTTON ID='buttonOn1' ONCLICK='buttonOn1()' STYLE='width:120px;height:50px'>"; | |
webSite += deviceName1; | |
webSite += " ON</BUTTON></TD></TR>\n"; | |
webSite += "<TR><TD><BUTTON ID='buttonOff1' ONCLICK='buttonOff1()' STYLE='width:120px;height:50px'>"; | |
webSite += deviceName1; | |
webSite += " OFF</BUTTON></TD></TR>\n"; | |
webSite += "</BODY>\n"; | |
webSite += "</HTML>\n"; | |
} | |
void buildJavascript(){ | |
javaScript = "<SCRIPT>\n"; | |
javaScript += "InitWebSocket();\n"; | |
javaScript += "function InitWebSocket(){\n"; | |
//javaScript += " websock=new WebSocket('ws://'+window.location.hostname+':88/');\n"; | |
javaScript += " websock=new WebSocket('ws://'+window.location.hostname+':"; | |
javaScript += WS_PORT; | |
javaScript += "/');\n"; | |
javaScript += " websock.onmessage=function(evt){\n"; | |
javaScript += " JSONobj=JSON.parse(evt.data);\n"; | |
javaScript += " document.getElementById('runtime').innerHTML=JSONobj.runtime;\n"; | |
javaScript += " document.getElementById('websockCount').innerHTML=JSONobj.websockCount;\n"; | |
javaScript += " document.getElementById('ledstate1').innerHTML=JSONobj.ledstate1;\n"; | |
javaScript += " console.log(evt);\n"; | |
javaScript += " var e = document.getElementById('ledstate1');\n"; | |
javaScript += " if (JSONobj.ledstate1 === 'ON') {\n"; | |
javaScript += " e.style.color = 'red';\n"; | |
javaScript += " }\n"; | |
javaScript += " else if (JSONobj.ledstate1 === 'OFF') {\n"; | |
javaScript += " e.style.color = 'black';\n"; | |
javaScript += " }\n"; | |
javaScript += " else {\n"; | |
javaScript += " console.log('unknown event');\n"; | |
javaScript += " }\n"; | |
javaScript += " }\n"; | |
javaScript += "}\n"; | |
javaScript += "\n"; | |
javaScript += "function buttonOn1(){\n"; | |
javaScript += " btn='LEDonoff1=LED1 = ON';\n"; | |
javaScript += " websock.send(btn);\n"; | |
javaScript += "}\n"; | |
javaScript += "\n"; | |
javaScript += "function buttonOff1(){\n"; | |
javaScript += " btn='LEDonoff1=LED1 = OFF';\n"; | |
javaScript += " websock.send(btn);\n"; | |
javaScript += "}\n"; | |
javaScript += "\n"; | |
javaScript += "</SCRIPT>\n"; | |
} | |
String millis2time(){ | |
Time = ""; | |
ss=millis()/1000; | |
hh=ss/3600; | |
mm=(ss-hh*3600)/60; | |
ss=(ss-hh*3600)-mm*60; | |
if(hh<10)Time+="0"; | |
Time+=(String)hh+":"; | |
if(mm<10)Time+="0"; | |
Time+=(String)mm+":"; | |
if(ss<10)Time+="0"; | |
Time+=(String)ss; | |
return Time; | |
} | |
void websocketResponse() { | |
if(millis()>wait000){ | |
websockCount++; | |
JSONtxt = "{\"runtime\":\""+millis2time()+"\","; // JSON requires double quotes | |
JSONtxt += "\"websockCount\":\""+(String)websockCount+"\","; | |
JSONtxt += "\"ledstate1\":\""+LEDswitch1+"\"}"; | |
webSocket.broadcastTXT(JSONtxt); | |
wait000=millis()+websockMillis; | |
} | |
} | |
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t wslength){ | |
String payloadString=(const char *)payload; | |
USE_SERIAL.println(" "); | |
USE_SERIAL.println("WEBSOCKET Received..."); | |
USE_SERIAL.println("payload: '"+payloadString+"', channel: "+(String)num);//comment | |
switch(type) { | |
case WStype_DISCONNECTED: | |
USE_SERIAL.printf("[%u] Disconnected!\n", num); | |
break; | |
case WStype_CONNECTED: | |
{ | |
IPAddress ip = webSocket.remoteIP(num); | |
USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload); | |
// send message to client | |
webSocket.sendTXT(num, "Connected"); | |
} | |
break; | |
case WStype_TEXT: | |
{ | |
USE_SERIAL.printf("[%u] get Text: %s\n", num, payload); | |
// send message to client | |
// webSocket.sendTXT(num, "message here"); | |
// send data to all connected clients | |
// webSocket.broadcastTXT("message here"); | |
/////// | |
USE_SERIAL.println(payloadString);//new | |
byte separator=payloadString.indexOf('='); | |
String var=payloadString.substring(0,separator); | |
String val=payloadString.substring(separator+1); | |
USE_SERIAL.println(var);//new | |
USE_SERIAL.println(val);//new | |
if(var=="LEDonoff1"){ | |
//LEDonoff=false; | |
if(val=="LED1 = ON") { | |
writeLED1("1"); | |
} | |
else if(val=="LED1 = OFF") { | |
writeLED1("0"); | |
} | |
} | |
} | |
///////////// | |
break; | |
case WStype_BIN: | |
{ | |
//USE_SERIAL.printf("[%u] get binary length: %u\n", num, length); | |
//hexdump(payload, length); | |
USE_SERIAL.printf("BIN TYPE"); | |
// send message to client | |
// webSocket.sendBIN(num, payload, length); | |
} | |
break; | |
default: | |
// if nothing else matches, do the default | |
// default is optional | |
USE_SERIAL.printf("No TYPE match!"); | |
break; | |
} | |
} | |
void htmlReading() { | |
// Check if a client has connected | |
WiFiClient client = server.available(); | |
if (!client) { | |
return; | |
} | |
USE_SERIAL.println("New Client");//new | |
/* | |
String s; | |
s = ""; | |
while (client.connected()) { | |
if (client.available()) { | |
char c = client.read(); | |
s += c; | |
Serial.println(c); | |
Serial.println(s); | |
} | |
} | |
*/ | |
buildWebsite(); | |
// Send the response to the client | |
client.print(webSite); | |
delay(1); | |
} | |
///// Callback From FAUXMO | |
void callback(uint8_t device_id, const char * device_name, bool state) { | |
//Serial.printf("[MAIN] %s state: %s\n", device_name, state ? "ON" : "OFF"); | |
//if ( (strcmp(device_name, "lamp") == 0) ) { | |
USE_SERIAL.println(" "); | |
USE_SERIAL.println("FAUXMO Received..."); | |
if ( (strcmp(device_name, deviceName1) == 0) ) { | |
USE_SERIAL.print("Device "); Serial.print(device_name); | |
USE_SERIAL.print(" state: "); | |
if (state) { | |
USE_SERIAL.println("ON"); | |
writeLED1("1"); | |
} else {; | |
USE_SERIAL.println("OFF"); | |
writeLED1("0"); | |
} | |
} | |
} | |
////Push Button1 Reading | |
void buttonReading1() { | |
int reading1 = digitalRead(BUTTON_PIN1); | |
if (reading1 != lastButtonState1) { | |
// reset the debouncing timer | |
lastDebounceTime1 = millis(); | |
} | |
if ((millis() - lastDebounceTime1) > debounceDelay1) { | |
if (reading1 != buttonState1) { | |
buttonState1 = reading1; | |
USE_SERIAL.println(" "); | |
USE_SERIAL.println("BUTTON1 Received..."); | |
if (buttonState1 == LOW) { | |
if (ledState1 == HIGH) { | |
writeLED1("0"); | |
} | |
else { | |
writeLED1("1"); | |
} | |
//ledState1 = !ledState1; | |
USE_SERIAL.print("Button 1 State: "); | |
USE_SERIAL.println(ledState1); | |
} | |
} | |
} | |
lastButtonState1 = reading1; | |
} | |
///Function for LED1 State Change | |
static void writeLED1(String LEDWrite1) { | |
if (LEDWrite1 == "0") { | |
LEDswitch1="OFF"; | |
ledState1 = LOW; | |
digitalWrite(LED_PIN1, ledState1); | |
USE_SERIAL.println("LED1 You Selected OFF"); | |
USE_SERIAL.print(deviceName1); | |
USE_SERIAL.println(" is OFF"); | |
} | |
else if (LEDWrite1 == "1") { | |
LEDswitch1="ON"; | |
ledState1 = HIGH; | |
digitalWrite(LED_PIN1, ledState1); | |
USE_SERIAL.println("LED1 You Selected ON"); | |
USE_SERIAL.print(deviceName1); | |
USE_SERIAL.println(" is ON"); | |
} | |
else if (LEDWrite1 == "3") { | |
LEDswitch1="STA"; | |
USE_SERIAL.println("LED1 You Selected STATE"); | |
USE_SERIAL.print("LED1 State: "); | |
USE_SERIAL.println(ledState1); | |
USE_SERIAL.print(deviceName1); | |
USE_SERIAL.println(" State"); | |
} | |
else { | |
LEDswitch1="INV"; | |
USE_SERIAL.println("LED1 You clicked INVALID"); | |
USE_SERIAL.print(deviceName1); | |
USE_SERIAL.println(" is Invalid"); | |
} | |
} | |
//WiFi.hostname(MY_ESP_NAME); | |
///// Wifi Init | |
void wifiSetup() { | |
WiFi.config(ip, gateway, subnet, DNS); //for static ip | |
delay(100); // for static ip | |
// Set WIFI module to STA mode | |
WiFi.mode(WIFI_STA); | |
// Connect | |
USE_SERIAL.printf("[WIFI] Connecting to %s ", WIFI_SSID); | |
WiFi.hostname(MY_ESP_NAME); | |
WiFi.begin(WIFI_SSID, WIFI_PASS); | |
// Wait | |
while (WiFi.status() != WL_CONNECTED) { | |
USE_SERIAL.print("."); | |
delay(200); | |
} | |
USE_SERIAL.println(); | |
while (WiFi.waitForConnectResult() != WL_CONNECTED) { | |
USE_SERIAL.println("Fail connecting"); | |
delay(5000); | |
ESP.restart(); | |
} | |
// Connected! | |
USE_SERIAL.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str()); | |
USE_SERIAL.print(":"); | |
USE_SERIAL.println(PORT); | |
USE_SERIAL.printf("WebSocket at IP address: %s", WiFi.localIP().toString().c_str()); | |
USE_SERIAL.print(":"); | |
USE_SERIAL.println(WS_PORT); | |
// Start the server for udp port | |
server.begin(); | |
USE_SERIAL.println("Server started"); | |
} | |
//// SETUP | |
void setup() { | |
// Init serial port and clean garbage | |
//Serial.begin(SERIAL_BAUDRATE); | |
USE_SERIAL.begin(SERIAL_BAUDRATE); | |
//USE_SERIAL.setDebugOutput(true); | |
USE_SERIAL.println(); | |
USE_SERIAL.println(); | |
USE_SERIAL.println(); | |
/* | |
for(uint8_t t = 4; t > 0; t--) { | |
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t); | |
USE_SERIAL.flush(); | |
delay(1000); | |
} | |
*/ | |
USE_SERIAL.println(); | |
USE_SERIAL.println("FauxMo - Push Button - Websockets - Static IP - Static Port sketch"); | |
USE_SERIAL.print("After connection, ask Alexa/Echo to 'TURN "); | |
USE_SERIAL.print(deviceName1); | |
USE_SERIAL.print(" ON' or 'TURN "); | |
USE_SERIAL.print(deviceName1); | |
USE_SERIAL.println(" OFF'"); | |
pinMode(LED_PIN1, OUTPUT); | |
pinMode(BUTTON_PIN1, INPUT); | |
//// Wifi | |
wifiSetup(); | |
//// Fauxmo | |
fauxmo.addDevice(deviceName1); | |
fauxmo.onMessage(callback); | |
////Websockets | |
webSocket.begin(); | |
webSocket.onEvent(webSocketEvent); | |
} | |
//// LOOP | |
void loop() { | |
buttonReading1(); | |
webSocket.loop(); | |
websocketResponse(); | |
htmlReading(); | |
fauxmo.handle(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment