void wsSend(const char* _str) { if (sizeof(_str)<=1) return; // don't send blank messages if (wsConcount>0) { for (int x=0; x<wsConcount; x++) { webSocket.sendTXT(x, _str); } } }
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) { 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] Connection 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"); break; case WStype_BIN: USE_SERIAL.printf("[%u] get binary length: %u\n", num, length); hexdump(payload, length); // send message to client webSocket.sendBIN(num, payload, length); break; } }
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) { switch(type) { case WStype_DISCONNECTED: Serial.printf("[WSc] Disconnected!\n"); break; case WStype_CONNECTED: { IPAddress ip = webSocket.remoteIP(num); 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 server when Connected webSocket.sendTXT(num, "Connected"); } break; case WStype_TEXT: webSocket.sendTXT(num, payload); Serial.printf("[%u] get Text: %s\n", num, payload); // send message to server // webSocket.sendTXT("message here"); break; case WStype_BIN: Serial.printf("[WSc] get binary lenght: %u\n", length); // send data to server // webSocket.sendBIN(payload, lenght); break; } }
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) { switch(type) { case WStype_DISCONNECTED: //USE_SERIAL.printf("[%u] Disconnected!\n", num); wsConcount--; sprintf(str,"ws disconnect count=%d",wsConcount); if (useMQTT) mqtt.publish(mqttpub,str); break; case WStype_CONNECTED: { IPAddress ip = webSocket.remoteIP(num); sprintf(str,"[%u] connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload); //USE_SERIAL.println(); // send message to client sprintf(str,"Connection #%d.", num); webSocket.sendTXT(num, str); sprintf(str, "name=%s", nodename); webSocket.sendTXT(num, str); //webSocket.sendTXT(num, mqttpub); //webSocket.sendTXT(num, mqttsub); if (timeStatus() == timeSet) webSocket.sendTXT(num, "Time is set."); else webSocket.sendTXT(num, "Time not set."); //mqtt.publish(mqttpub, str); //wsSendlabels(); newWScon = num + 1; wsConcount++; sprintf(str,"ws connect count=%u new=%u",wsConcount,newWScon); if (useMQTT) mqtt.publish(mqttpub,str); } break; case WStype_TEXT: payload[length] = '\0'; // null terminate handleMsg((char *)payload); break; case WStype_BIN: // USE_SERIAL.printf("[%u] get binary lenght: %u\n", num, length); hexdump(payload, length); // send message to client // webSocket.sendBIN(num, payload, lenght); break; } }
void Wifi::wifiWriteLoop() { char buff[180]; webSocket.sendTXT(0,"FUUUUUCK"); /*sprintf (buff, "%d plus %d is %d", 5, 5, 5+5); _s->print("C**t!\n"); if (_s->available() > 0){ webSocket.sendTXT(0,_s->readString()); _s->flush(); }*/ }
void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length){ switch(type) { case WStype_DISCONNECTED: Serial.println("Websocket Disconnected..."); break; case WStype_CONNECTED: Serial.println("Websocket Connected!"); break; case WStype_TEXT: String text = String((char *) &payload[0]); Serial.println("Received text:"); Serial.println(text); // process the text however you want if (text.startsWith("on:")) { ws.sendTXT(num, "ack: on"); String outletNumber = text.substring(3, 4); if (outletNumber.equals("1")) { turnOn(OUTLET_1); } else if (outletNumber.equals("2")) { turnOn(OUTLET_2); } } else if (text.startsWith("off:")) { ws.sendTXT(num, "ack: off"); String outletNumber = text.substring(4, 5); if (outletNumber.equals("1")) { turnOff(OUTLET_1); } else if (outletNumber.equals("2")) { turnOff(OUTLET_2); } } break; } }
void setup() { // USE_SERIAL.begin(921600); USE_SERIAL.begin(115200); //Serial.setDebugOutput(true); 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); } WiFiMulti.addAP("WiFi2", "4328646518"); while(WiFiMulti.run() != WL_CONNECTED) { delay(100); } webSocket.begin(); webSocket.onEvent(webSocketEvent); }
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) { 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] Message: %s\n", num, payload); //webSocket.sendTXT(num,payload); //_s->printf("%s",payload); break; } }
void loop() { if (safeMode) { // safeMode engaged, enter blocking loop wait for an OTA update int safeDelay=30000; // five minutes in 100ms counts while (safeDelay--) { ArduinoOTA.handle(); delay(100); } ESP.reset(); // restart, try again delay(5000); // give esp time to reboot } if(wifiMulti.run() != WL_CONNECTED) { // reboot if wifi connection drops ESP.reset(); delay(5000); } if (!mqtt.connected()) { mqttreconnect(); // check mqqt status } doTick(); if (hasRSSI) doRSSI(); if (hasTout) doTout(); if (hasVout) doVout(); if (hasIout) doIout(); if (getRGB) doRGBout(); if (hasSpeed) doSpeed(); if ( (doUpdate) || (updateCnt>= 60 / ((updateRate * 20) / 1000) ) ) runUpdate(); // check for config update as requested or every 60 loops if (wsConcount>0) wsData(); if (useMQTT) mqttData(); // regular update for non RGB controllers if (prtConfig) printConfig(); // config print was requested sprintf(str,"Sleeping in %u seconds.", (updateRate*20/1000)); if ((!skipSleep) && (sleepEn)) { if (useMQTT) mqtt.publish(mqttpub, str); } int cnt = 30; if (updateRate>30) cnt=updateRate; while(cnt--) { ArduinoOTA.handle(); if (useMQTT) mqtt.loop(); #ifndef _MINI httpd.handleClient(); #endif webSocket.loop(); if (getTime) updateNTP(); // update time if requested by command if (scanI2C) i2c_scan(); if (hasRGB) doRGB(); // rgb updates as fast as possible if (rgbTest) testRGB(); #ifndef _MINI if (doUpload) { // upload file to spiffs by command doUpload = false; fileSet = false; int stat = uploadFile(fileName, fileURL); sprintf(str, "Upload complete: %s %d bytes.",fileName,stat); if (useMQTT) mqtt.publish(mqttpub, str); } #endif if (setPolo) { setPolo = false; // respond to an mqtt 'ping' of sorts if (useMQTT) mqtt.publish(mqttpub, "Polo"); } if (doReset) { // reboot on command if (useMQTT) { mqtt.publish(mqttpub, "Rebooting!"); mqtt.loop(); } delay(50); ESP.reset(); delay(5000); // allow time for reboot } if (!hasRGB) delay(20); // don't delay for rgb controller } if ((!skipSleep) && (sleepEn)) { if ((sleepPeriod<60) || (sleepPeriod>43200)) sleepPeriod=900; // prevent sleeping for less than 1 minute or more than 12 hours sprintf(myChr,"Back in %d minutes", sleepPeriod/60); if (useMQTT) { mqtt.publish(mqttpub, myChr); mqtt.loop(); } ESP.deepSleep(1000000 * sleepPeriod, WAKE_RF_DEFAULT); // sleep for 15 min delay(5000); // give esp time to fall asleep } skipSleep = false; updateCnt++; }
void setup() { memset(voltsChr,0,sizeof(voltsChr)); memset(amps0Chr,0,sizeof(amps0Chr)); memset(amps1Chr,0,sizeof(amps1Chr)); memset(tmpChr,0,sizeof(tmpChr)); // if the program crashed, skip things that might make it crash String rebootMsg = ESP.getResetReason(); if (rebootMsg=="Exception") safeMode=true; else if (rebootMsg=="Hardware Watchdog") safeMode=true; else if (rebootMsg=="Unknown") safeMode=true; else if (rebootMsg=="Software Watchdog") safeMode=true; if (sw1>=0) { pinMode(sw1, OUTPUT); } if (sw2>=0) { pinMode(sw2, OUTPUT); } if (sw3>=0) { pinMode(sw3, OUTPUT); } if (sw4>=0) { pinMode(sw4, OUTPUT); } // "mount" the filesystem bool success = SPIFFS.begin(); if (!success) SPIFFS.format(); if (!safeMode) fsConfig(); // read node config from FS #ifdef _TRAILER wifiMulti.addAP("DXtrailer", "2317239216"); #else wifiMulti.addAP("Tell my WiFi I love her", "2317239216"); #endif int wifiConnect = 240; while ((wifiMulti.run() != WL_CONNECTED) && (wifiConnect-- > 0)) { // spend 2 minutes trying to connect to wifi // connecting to wifi delay(1000); } if (wifiMulti.run() != WL_CONNECTED ) { // still not connected? reboot! ESP.reset(); delay(5000); } if (hasHostname) { // valid config found on FS, set network name WiFi.hostname(String(nodename)); // set network hostname ArduinoOTA.setHostname(nodename); // OTA hostname defaults to esp8266-[ChipID] MDNS.begin(nodename); // set mDNS hostname } WiFi.macAddress(mac); // get esp mac address, store it in memory, build fw update url sprintf(macStr,"%x%x%x%x%x%x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); sprintf(theURL,"/iotfw?mac=%s", macStr); // request latest config from web api if (!safeMode) getConfig(); // check web api for new firmware if (!safeMode) httpUpdater(); // start UDP for ntp client udp.begin(localPort); updateNTP(); setSyncProvider(getNtptime); // use NTP to get current time setSyncInterval(600); // refresh clock every 10 min #ifndef _MINI // start the webserver httpd.onNotFound(handleNotFound); httpd.begin(); // Add service to MDNS-SD MDNS.addService("http", "tcp", 80); #endif // start websockets server webSocket.begin(); webSocket.onEvent(webSocketEvent); // setup other things setupOTA(); setupMQTT(); // setup i2c if configured, basic sanity checking on configuration if (hasI2C && iotSDA>=0 && iotSCL>=0 && iotSDA!=iotSCL) { sprintf(str,"I2C enabled, using SDA=%u SCL=%u", iotSDA, iotSCL); mqtt.publish(mqttpub, str); Wire.begin(iotSDA, iotSCL); // from api config file //Wire.begin(12, 14); // from api config file i2c_scan(); printConfig(); if (hasRGB) setupRGB(); if (hasIout) setupADS(); if (hasSpeed) setupSpeed(); } // OWDAT = 4; if (OWDAT>0) { // setup onewire if data line is using pin 1 or greater sprintf(str,"Onewire Data OWDAT=%u", OWDAT); mqtt.publish(mqttpub, str); oneWire.begin(OWDAT); if (hasTout) { ds18b20 = DallasTemperature(&oneWire); ds18b20.begin(); // start one wire temp probe } if (hasTpwr>0) { pinMode(hasTpwr, OUTPUT); // onewire power pin as output digitalWrite(hasTpwr, LOW); // ow off } } if (useMQTT) { String rebootReason = String("Last reboot cause was ") + rebootMsg; rebootReason.toCharArray(str, rebootReason.length()+1); mqtt.publish(mqttpub, str); } }
void loop() { ws.loop(); }
void setupWebsocketServer() { ws.begin(); ws.onEvent(webSocketEvent); Serial.println("Websocket Server setup complete"); }
void Wifi::begin(Stream &s) { _s = &s; //USE_SERIAL.begin(921600); USE_SERIAL.begin(115200); //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); } int n = WiFi.scanNetworks(); Serial.println("[SETUP] SCANNING..."); Serial.println(""); if (n == 0) USE_SERIAL.println("no networks found"); else { USE_SERIAL.print(n); USE_SERIAL.println(" networks found"); for (int i = 0; i < n; ++i) { // Print SSID and RSSI for each network found USE_SERIAL.print(i + 1); USE_SERIAL.print(": "); USE_SERIAL.print(WiFi.SSID(i)); USE_SERIAL.print(" ("); USE_SERIAL.print(WiFi.RSSI(i)); USE_SERIAL.print(")"); USE_SERIAL.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*"); delay(10); } } Serial.println(""); WiFiMulti.addAP(NETWORKNAME, NETWORKPASS); while(WiFiMulti.run() != WL_CONNECTED) { delay(100); } USE_SERIAL.print("IP address: "); USE_SERIAL.println(WiFi.localIP()); USE_SERIAL.flush(); // start webSocket server webSocket.begin(); webSocket.onEvent(webSocketEvent); if(MDNS.begin("esp8266")) { USE_SERIAL.println("MDNS responder started"); } // handle index server.on("/", []() { // send index.html server.send(200, "text/html", "<html><head><script>var connection = new WebSocket('ws://'+location.hostname+':8899/', ['arduino']);connection.onopen = function () { connection.send('Connect ' + new Date()); }; connection.onerror = function (error) { console.log('WebSocket Error ', error);};connection.onmessage = function (e) { console.log('Server: ', e.data);};function sendRGB() { var r = parseInt(document.getElementById('r').value).toString(16); var g = parseInt(document.getElementById('g').value).toString(16); var b = parseInt(document.getElementById('b').value).toString(16); if(r.length < 2) { r = '0' + r; } if(g.length < 2) { g = '0' + g; } if(b.length < 2) { b = '0' + b; } var rgb = '#'+r+g+b; console.log('RGB: ' + rgb); connection.send(rgb); }</script></head><body>LED Control:<br/><br/>R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/></body></html>"); }); server.begin(); // Add service to MDNS MDNS.addService("http", "tcp", 80); MDNS.addService("ws", "tcp", 8899); }
void Wifi::wifiLoop() { webSocket.loop(); server.handleClient(); }
void loop() { webSocket.loop(); }