#include #include #include #include using namespace websockets; #define __NAME__ "DC Motor" #define PWM_PIN 5 static double f = 0; int wifi_connect(const char *ssid, const char *password, unsigned int timeout) { WiFi.begin(ssid, password); for (unsigned int i = timeout; WiFi.status() != WL_CONNECTED; --timeout) // wait for wifi to connect { delay(1000); Serial.printf("%u... ", timeout); } Serial.println(); return WiFi.status() == WL_CONNECTED; } int mdns_start(const char *mdsn) { return MDNS.begin(mdsn); } /* ESP8266WebServer *http_server = nullptr; int http_start(unsigned int port) { http_server = new ESP8266WebServer(port); if (http_server == nullptr) { return 0; } http_server->onNotFound([](){ http_server->send(404, "text/plain", "404 Not found"); }); http_server->on("/", HTTP_GET, []() { http_server->send(200, "text/html", "" "" "" "" ""); }); http_server->begin(); return 1; } */ WebsocketsServer ws_server; int ws_start(unsigned int port) { ws_server.listen(port); return ws_server.available(); } void setup() { Serial.begin(115200); Serial.setTimeout(2000); while (!Serial) { delay(1000); } // wait serial to initialize Serial.println(); Serial.println(__NAME__ " " __DATE__ " " __TIME__); pinMode(PWM_PIN, OUTPUT); analogWrite(PWM_PIN, (int)(f * PWMRANGE)); // 1. connect to wifi static const char *wifi_ssid = "OpenWrt"; static const char *wifi_psk = "3JGJXC3R"; Serial.printf("connecting to %s, using password %s\n", wifi_ssid, wifi_psk); if (wifi_connect(wifi_ssid, wifi_psk, 16)) { Serial.printf("connected to %s, ip: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str()); } else { Serial.println("failed to connect"); // ap_begin() } // 2. start mdns responder static const char *mdsn_name = "ds18b20"; if (mdns_start(mdsn_name)) { Serial.printf("mdns responder started: http://%s.local\n", mdsn_name); } else { Serial.println("MDNS.begin() failed"); } /* // 3. start http server unsigned int http_port = 80; if (http_start(http_port)) { Serial.printf("Serve HTTP at :%u\n", http_port); } */ // 4. start ws server unsigned int ws_port = 80; if (ws_start(ws_port)) { Serial.printf("Serve WebSocket at :%u\n", ws_port); } } void loop() { /* if (http_server != nullptr) { http_server->handleClient(); } */ if (ws_server.available()) { if (ws_server.poll()) { WebsocketsClient ws_client = ws_server.accept(); if (ws_client.available()) { static char buffer[24]; int length = snprintf(buffer, 24, "%.2f", f); ws_client.send(buffer, length); // send initial data } while (ws_client.available()) { WebsocketsMessage message = ws_client.readBlocking(); if (message.isText()) { f = atof(message.data().c_str()); f = max(0.0, min(f, 1.0)); // clamp input data in [ 0.0, 1.0 ] analogWrite(PWM_PIN, (int)(f * PWMRANGE)); } } } } delay(2000); //ESP.deepSleep(2e6); // sleep for 2 sec }