Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //ESP-WROOM-02 WiFi Joystick WebSocket版
- //ESPAsyncWebServer,ESPAsyncTCP Library needed
- //
- //ESP8266 Boards v2.7.4推奨(v3ではWiFiセーブバグあるため…
- //CPU 80Mhz,Crystal 26Mhz
- //Flash 4MB(FS3MB
- //Flash 40Mhz
- //Reset no dtr
- //ESP32 v2.0.0
- //Library
- //AsyncTCP
- //https://github.com/me-no-dev/AsyncTCP/archive/master.zip
- //ESPAsyncWebServer
- //https://github.com/me-no-dev/ESPAsyncWebServer/archive/master.zip
- //RGB LED
- //FastLED Library
- #ifdef ESP32
- #include <WiFi.h>
- #include <AsyncTCP.h>
- #include <ESPmDNS.h>
- #elif defined(ESP8266)
- #include <ESP8266WiFi.h>
- #include <ESPAsyncTCP.h>
- #include <ESP8266mDNS.h>
- #endif
- #include <ESPAsyncWebServer.h>
- #define LED_BUILTIN 13
- //#define debug//コメントを外すとデバッグメッセージをシリアルに流す
- //#define RGBLED
- #ifdef RGBLED
- #include <FastLED.h>
- #define NUM_LEDS 1
- #define DATA_PIN 27
- CRGB leds[NUM_LEDS];
- #endif
- AsyncWebServer server(80);
- AsyncWebSocket ws("/ws");
- int8_t x = 0;
- int8_t y = 0;
- //gzip compressed arry
- //https://www.mischianti.org/online-converter-file-to-cpp-gzip-byte-array-3/
- //File: joystick.html.gz, Size: 1189
- #define joystick_html_gz_len 1189
- const uint8_t joystick_html_gz[] PROGMEM = {
- 0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x9D, 0x56, 0x4D, 0x6F, 0xE3, 0x44,
- 0x18, 0x3E, 0x1B, 0x89, 0xFF, 0x30, 0x78, 0x17, 0xD9, 0xA1, 0xB1, 0x9D, 0x82, 0x58, 0xA1, 0x34,
- 0x29, 0xDA, 0xAE, 0x8A, 0x58, 0xD4, 0x0A, 0xA4, 0x56, 0xD0, 0xDC, 0x76, 0x62, 0xBF, 0x8D, 0x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9, 0x31, 0x8C, 0x48, 0x4B, 0xC9, 0x8E, 0xA3, 0xE5, 0x5E, 0xF7, 0x5D, 0x93, 0x61, 0xCF, 0xED,
- 0xCE, 0xEC, 0x72, 0xD4, 0xF6, 0x67, 0x0F, 0x9A, 0xD3, 0xEE, 0x95, 0x46, 0x1D, 0x2C, 0x4D, 0x23,
- 0x6B, 0x6A, 0xEA, 0xB8, 0xED, 0x92, 0xFD, 0xE8, 0xA3, 0x1E, 0xB6, 0xBB, 0xDF, 0x8C, 0xA9, 0x95,
- 0xFB, 0x0E, 0x6F, 0xD2, 0xE6, 0x1B, 0x00, 0xBF, 0x0A, 0xF4, 0xA7, 0xEF, 0x3F, 0xB9, 0xA7, 0x0A,
- 0x67, 0x01, 0x0B, 0x00, 0x00
- };
- //File: virtualjoystick.js.gz, Size: 2945
- #define virtualjoystick_js_gz_len 2945"text/plain", "Not found");
- }
- void SoftAPmode(){
- WiFi.mode(WIFI_AP);
- WiFi.softAP("ESP-WROOM-02");
- WiFi.begin();
- }
- void setup() {
- pinMode(LED_BUILTIN, OUTPUT);
- pinMode(0, INPUT_PULLUP);//書き込みボタンをボタンとして使えるように。
- digitalWrite(LED_BUILTIN, LOW);
- Serial.begin(9600);
- Serial.println("");
- #ifdef RGBLED
- FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
- leds[0] = CRGB::Green;
- FastLED.show();
- #endif
- boolean SoftAP = false;
- if(WiFi.SSID() != NULL){
- WiFi.mode(WIFI_STA);
- WiFi.begin();
- }else{
- SoftAP = true;
- }
- unsigned int cnt = 0;
- while (WiFi.status() != WL_CONNECTED) {
- cnt++;
- delay(100);
- led_toggle();//LED点滅
- //Wifiアクセスポイントに接続できない場合Soft APモードに変更する
- if(cnt >= 100 || digitalRead(0) == LOW || SoftAP == true){//接続トライ100カウント以上もしくは書き込みボタンを押すとSoft APモードに変更
- SoftAP = true;
- digitalWrite(LED_BUILTIN, LOW);
- SoftAPmode();
- //dnsServer.start(53, "*", WiFi.softAPIP());
- #ifdef ESP8266
- WiFi.setSleepMode(WIFI_NONE_SLEEP);
- #endif
- break;//Soft APにしてもbreakしないと抜けられない
- }
- #ifdef debug
- Serial.print(".");
- #endif
- }
- /*if (WiFi.waitForConnectResult() != WL_CONNECTED) {
- Serial.printf("WiFi Failed!\n");
- return;
- }
- */
- #ifdef debug
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- if(SoftAP == false){
- Serial.println(WiFi.localIP());
- }else{
- Serial.println(WiFi.softAPIP());
- }
- #endif
- //mDNS初期化
- if (!MDNS.begin("esp")) {
- #ifdef debug
- Serial.println("Error setting up MDNS responder!");
- #endif
- }
- MDNS.addService("http", "tcp", 80);
- initWebSocket();
- server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
- AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", joystick_html_gz, joystick_html_gz_len);
- response->addHeader(F("Content-Encoding"), F("gzip"));
- request->send(response);
- });
- server.on("/virtualjoystick.js", HTTP_GET, [](AsyncWebServerRequest *request){
- AsyncWebServerResponse *response = request->beginResponse_P(200, "text/javascript", virtualjoystick_js_gz, virtualjoystick_js_gz_len);
- response->addHeader(F("Content-Encoding"), F("gzip"));
- request->send(response);
- });
- wifiMgr();
- //server.on("/update", HTTP_GET, [](AsyncWebServerRequest *request){handleUpdate(request);});
- server.on("/doUpdate", HTTP_POST,
- [](AsyncWebServerRequest *request) {},
- [](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data,
- size_t len, bool final) {handleDoUpdate(request, filename, index, data, len, final);}
- );
- server.onNotFound(notFound);
- server.begin();
- }
- void loop() {
- #ifdef ESP8266
- MDNS.update();
- #endif
- ws.cleanupClients();
- if(Serial.available() > 0){
- char serData = Serial.read();
- if(serData == 'c'){
- led_toggle();
- Serial.print("c");
- Serial.write(x);
- Serial.write(y);
- }else if(serData == '&'){
- led_toggle();
- ws.textAll(Serial.readStringUntil(';'));
- }else{
- Serial.flush();
- while(!Serial.available()){
- Serial.read();
- }
- }
- }
- }
- void led_toggle(){
- static boolean ledtoggle = false;
- ledtoggle = !ledtoggle;
- digitalWrite(LED_BUILTIN,ledtoggle);
- #ifdef RGBLED
- if(ledtoggle == false){
- leds[0] = CRGB::Green;
- FastLED.show();
- }else{
- leds[0] = CRGB::Black;
- FastLED.show();
- }
- #endif
- }
- //WebSocket
- /*void notifyClients() {
- ws.textAll(String(ledState));
- }*/
- void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
- AwsFrameInfo *info = (AwsFrameInfo*)arg;
- if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
- data[len] = 0;
- /*if (strcmp((char*)data, "toggle") == 0) {
- ledState = !ledState;
- notifyClients();
- }
- */
- //Serial.println((char*)data);
- uint8_t ypos = 0;
- char strx[4];
- char stry[4];
- if(data[0] == 'x'){
- for (int i=2; i <= len; i++){
- if(data[i] == 'y'){
- ypos = i + 2;
- break;
- }else{
- strx[i-2] = data[i];
- }
- }
- for (int i=ypos; i <= len; i++){
- stry[i-ypos] = data[i];
- }
- //Serial.println(ypos);
- x = atoi(strx);
- y = atoi(stry);
- #ifdef debug
- Serial.print("x:");
- Serial.print(x);
- Serial.print(",y:");
- Serial.println(y);
- #endif
- }
- }
- }
- void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
- void *arg, uint8_t *data, size_t len) {
- switch (type) {
- case WS_EVT_CONNECT:
- #ifdef debug
- Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
- #endif
- break;
- case WS_EVT_DISCONNECT:
- #ifdef debug
- Serial.printf("WebSocket client #%u disconnected\n", client->id());
- #endif
- x = 0;
- y = 0;
- break;
- case WS_EVT_DATA:
- handleWebSocketMessage(arg, data, len);
- break;
- case WS_EVT_PONG:
- case WS_EVT_ERROR:
- break;
- }
- }
- void initWebSocket() {
- ws.onEvent(onEvent);
- server.addHandler(&ws);
- }
- //以下Wifi設定画面用
- #define SSIDLIMIT 30
- String ssid_rssi_str[SSIDLIMIT];
- String ssid_str[SSIDLIMIT];
- String ssid;
- String passwd;
- String maskpasswd(String passwd){
- String maskpasswd = "";
- for (int i=0; i<passwd.length(); i++) maskpasswd = maskpasswd + "*";
- if (passwd.length() == 0) maskpasswd = "(null)";
- return maskpasswd;
- }
- String Headder_str() {
- String html = "";
- html += "<!DOCTYPE html><html><head>";
- html += "<meta name='viewport' content='width=device-width, initial-scale=1.3'>";
- html += "<meta http-equiv='Pragma' content='no-cache'>";
- html += "<meta http-equiv='Cache-Control' content='no-cache'></head>";
- html += "<meta http-equiv='Expires' content='0'>";
- html += "<style>";
- html += "a:link, a:visited { background-color: #009900; color: white; padding: 5px 15px;";
- html += "text-align: center; text-decoration: none; display: inline-block;}";
- html += "a:hover, a:active { background-color: green;}";
- html += "bo32{ background-color: #EEEEEE;}";
- html += "input[type=button], input[type=submit], input[type=reset] {";
- html += "background-color: #000099; border: none; color: white; padding: 5px 20px;";
- html += "text-decoration: none; margin: 4px 2px;";
- html += "</style>";
- html += "<body>";
- html += "<h2>Setup</h2>";
- return html;
- }
- void wifiMgr() {
- server.on("/setup", HTTP_GET, [] (AsyncWebServerRequest *request) {
- String html = Headder_str();
- html += "<a href='/wifiinput'>WIFI setup</a>";
- html += "<hr><h3>Current Settings</h3>";
- html += "SSID: " + WiFi.SSID() + "<br>";
- html += "passwd: " + maskpasswd(passwd) + "<br>";
- html += "<hr><h3>Firmware Update</h3>";
- html += "<form method='POST' action='/doUpdate' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
- html += "<hr><p><center><a href='/reboot'>Reboot</a></center>";
- html += "</body></html>";
- request->send(200, "text/html", html);
- });
- server.on("/wifiinput", HTTP_GET, [] (AsyncWebServerRequest *request) {
- String html = Headder_str();
- html += "<a href='/'>TOP</a> ";
- html += "<hr><p>";
- html += "<h3>WiFi Selector</h3>";
- html += "<form action='/wifiset' method='get'>";
- html += "<select name='ssid' id ='ssid'>";
- html += "</select><br>\r\n";
- html += "Password<br><input type='password' name='passwd' value='" + passwd + "'>";
- html += "<br><input type='submit' value='set'>";
- html += "</form><br>";
- html += "<script type='text/javascript'>\n";
- html += "const selectName = document.getElementById('ssid');\n";
- html += "let xhr = new XMLHttpRequest();\n";
- html += "xhr.open('GET', 'scan');\n";
- html += "xhr.onload = () => {\n";
- html += "let responseJson = JSON.parse(xhr.response);\n";
- html += "for(var i=0;i<responseJson.length;i++){\n";
- html += "let op = document.createElement('option');\n";
- html += "op.value = responseJson[i].ssid;\n";
- html += "op.textContent = responseJson[i].ssid;\n";
- html += "selectName.appendChild(op);}}\n";
- html += "xhr.send();\n</script>\n";
- html += "<br><hr><p><center><a href='/'>Cancel</a></center>";
- html += "</body></html>";
- request->send(200, "text/html", html);
- });
- server.on("/wifiset", HTTP_GET, [] (AsyncWebServerRequest *request) {
- AsyncWebServerResponse *response = request->beginResponse(302, "text/plain", "");
- //ssid = server.arg("ssid");
- //passwd = server.arg("passwd");
- ssid = request->arg("ssid");
- passwd = request->arg("passwd");
- ssid.trim();
- passwd.trim();
- #ifdef debug
- Serial.println(ssid);
- #endif
- response->addHeader("Location", String("http://esp.local"));
- request->send(response);
- MDNS.end();
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid.c_str(), passwd.c_str());
- unsigned int cnt = 0;
- while (WiFi.status() != WL_CONNECTED) {
- cnt++;
- delay(100);
- led_toggle();//LED点滅
- if(cnt >= 100){//接続トライ100カウントで戻る
- digitalWrite(LED_BUILTIN, LOW);
- //WiFi.mode(WIFI_AP);
- //WiFi.softAP("ESP-WROOM-02");
- //WiFi.begin();
- SoftAPmode();
- break;
- }
- #ifdef debug
- Serial.print(".");
- #endif
- }
- if (!MDNS.begin("esp")) {
- #ifdef debug
- Serial.println("Error setting up MDNS responder!");
- #endif
- }
- MDNS.addService("http", "tcp", 80);
- if(WiFi.status() == WL_CONNECTED){
- digitalWrite(LED_BUILTIN, HIGH);
- }
- });
- server.on("/reboot", HTTP_GET, [] (AsyncWebServerRequest *request) {
- String html = Headder_str();
- html += "<hr><p>";
- html += "<h3>reboot confirmation</h3><p>";
- html += "Are you sure to reboot?<p>";
- html += "<center><a href='/doreboot'>YES</a> <a href='/'>no</a></center>";
- html += "<p><hr>";
- html += "</body></html>";
- request->send(200, "text/html", html);
- });
- server.on("/doreboot", HTTP_GET, [] (AsyncWebServerRequest *request) {
- String html = Headder_str();
- html += "<hr><p>";
- html += "<h3>rebooting</h3><p>";
- html += "The setting WiFi connection will be disconnected...<p>";
- html += "<hr>";
- html += "</body></html>";
- request->send(200, "text/html", html);
- // reboot
- #ifdef debug
- Serial.println("reboot now.");
- #endif
- //digitalWrite(LED_BUILTIN, LOW);
- delay(2000); // hold 2 sec
- ESP.restart(); // restart
- });
- server.on("/scan", HTTP_GET, [](AsyncWebServerRequest *request){
- String json = "[";
- int n = WiFi.scanComplete();
- if(n == -2){
- WiFi.scanNetworks(true);
- } else if(n){
- for (int i = 0; i < n; ++i){
- if(i) json += ",";
- json += "{";
- json += "\"rssi\":"+String(WiFi.RSSI(i));
- json += ",\"ssid\":\""+WiFi.SSID(i)+"\"";
- json += ",\"bssid\":\""+WiFi.BSSIDstr(i)+"\"";
- json += ",\"channel\":"+String(WiFi.channel(i));
- json += ",\"secure\":"+String(WiFi.encryptionType(i));
- json += ",\"hidden\":"+String(WiFi.isHidden(i)?"true":"false");
- json += "}";
- }
- WiFi.scanDelete();
- if(WiFi.scanComplete() == -2){
- WiFi.scanNetworks(true);
- }
- }
- json += "]";
- //CORS対策
- AsyncWebServerResponse *response = request->beginResponse(200, "application/json", json);
- response->addHeader(F("Access-Control-Allow-Origin"), F("*"));
- response->addHeader(F("Access-Control-Max-Age"), F("600"));
- response->addHeader(F("Access-Control-Allow-Methods"), F("PUT,POST,GET,OPTIONS"));
- response->addHeader(F("Access-Control-Allow-Headers"), F("*"));
- request->send(response);
- //request->send(200, "application/json", json);
- json = String();
- });
- }
- //以下WebUpdate用
- /*
- void handleUpdate(AsyncWebServerRequest *request) {
- char* html = "<form method='POST' action='/doUpdate' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
- request->send(200, "text/html", html);
- }
- */
- size_t content_len;
- void handleDoUpdate(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) {
- if (!index){
- Serial.println("Update");
- content_len = request->contentLength();
- // if filename includes spiffs, update the spiffs partition
- //int cmd = (filename.indexOf("spiffs") > -1) ? U_PART : U_FLASH;
- #ifdef ESP8266
- Update.runAsync(true);
- if (!Update.begin(content_len, U_FLASH)) {
- #else
- if (!Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH)) {
- #endif
- Update.printError(Serial);
- }
- }
- if (Update.write(data, len) != len) {
- Update.printError(Serial);
- #ifdef ESP8266
- } else {
- Serial.printf("Progress: %d%%\n", (Update.progress()*100)/Update.size());
- #endif
- }
- if (final) {
- AsyncWebServerResponse *response = request->beginResponse(302, "text/plain", "Please wait while the device reboots");
- response->addHeader("Refresh", "20");
- response->addHeader("Location", "/");
- request->send(response);
- if (!Update.end(true)){
- Update.printError(Serial);
- } else {
- Serial.println("Update complete");
- Serial.flush();
- ESP.restart();
- }
- }
- }
- void printProgress(size_t prg, size_t sz) {
- Serial.printf("Progress: %d%%\n", (prg*100)/content_len);
- }
Advertisement
Add Comment
Please, Sign In to add comment