Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By Def
#51605 I'm trying to do a simple pannel where u can select to which AP you can connect. To get ssid, rssi and encryption type I'm using scanNetworks() from WiFi library, then encode it into json and send it though websockets. After one for loop iteration in scanNet() I get my data about only one network and websockets disconnects. I did a lot of debugging and find out that WiFi.scanNetworks() causes Websockets to disconnect. Have somebody tried that combo and run into same problem?

I'm running this on ESP-12F

Code: Select all#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <Ticker.h>
#include <FS.h>
#include <ArduinoJson.h>
#include <SPI.h>

const char* ssid = "********";
const char* password = "********";

//text/plain

ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
Ticker timer;
int value = 200;


void scanNet(){
  StaticJsonBuffer<200> jsonBuffer;
  int n = 0;
  n = WiFi.scanNetworks();
  if (n == 0){
    Serial.println("no networks found");
  }
   else
   {
     JsonObject& json = jsonBuffer.createObject();
     json["action"] = "getNet"; // action name
     for (int i = 0; i < n; ++i)
     {
       char buffer[81] = "";
       // Print SSID and RSSI for each network found
       json["ssid"] = WiFi.SSID(i);
       json["rssi"] = WiFi.RSSI(i);
       json["enc"] = WiFi.encryptionType(i);
       json.printTo(buffer, sizeof(buffer));
       // cant pass buffer directly to broadcast, server doesnt get any data
       //bcos of quatation marks maybe?
       String strn = String(buffer);
       webSocket.broadcastTXT(strn);
       //Serial.print(buffer);
    }
  }
}


void broadcastINT(int *value){
  //
  String string = String(*value);
  //char string[17];
  //itoa(value, string, 10);
  webSocket.broadcastTXT(string);
  (*value)+=1;
}


void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[%u] Disconnected!\n", num);
            break;
            timer.detach();
        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);
                scanNet();
                timer.attach_ms(5000, scanNet);
            }
            break;
        case WStype_TEXT:
            Serial.printf("[%u] get Text: %s\n", num, payload);
//            // echo data back to browser
          //broadcastINT(value);
      //webSocket.sendTXT(num, payload, lenght);
//
//            // send data to all connected clients
      //webSocket.broadcastTXT(payload, lenght);
            break;
        case WStype_BIN:
            Serial.printf("[%u] get binary lenght: %u\n", num, lenght);
//            hexdump(payload, lenght);
//
//            // echo data back to browser
      //webSocket.sendBIN(num, payload, lenght);
            break;
    }

}


void sendFile(String name, String type){
     bool result = SPIFFS.begin();
  Serial.println("SPIFFS opened: " + result);

  // this opens the file in read-mode
  File f = SPIFFS.open("/" + name, "r");

  if (!f) {
    Serial.println("File open failed" + name );
    return;
  }
  server.streamFile(f, type);
  f.close();
}

void handleRoot() {
  sendFile("index.html", "text/html");
}

void handleAdmin() {
  sendFile("admin.html", "text/html");
}

void handleAdminJS (){
    sendFile("admin.js", "application/javascript");
}

void handleJquery (){
    sendFile("jquery.js.gz", "application/javascript");
}

void handleChart (){
    sendFile("highcharts.js.gz", "application/javascript");
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
    if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);
  server.on("/admin", handleAdmin);
  server.on("/admin.js",handleAdminJS);
  server.on("/jquery.js",handleJquery);
  server.on("/highcharts.js", handleChart);
  //server.on("/", handleJS);

  server.begin();
  Serial.println("HTTP server started");
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
  Serial.println("WebSocket init");
  // always use this to "mount" the filesyste
}

void loop() {
  server.handleClient();
  webSocket.loop();

}
User avatar
By Leonas
#51697
Def wrote:Have somebody tried that combo and run into same problem?
Yes, same combo and no, not the same problem. I do not broadcast per line, though, but create one big string with all SSIDs and then broadcast that in one go.

In webSocketEvent
webSocket.broadcastTXT(wlanList());

Code: Select allString wlanList() {
  String wlanRow = "";
  uint16_t n = WiFi.scanNetworks();
  if (n) {
    for (uint16_t i = 0; i < n; ++i) {
      uint8_t quality = 0;
      if (WiFi.RSSI(i) <= -100) {
        quality = 0;
      }
      else if (WiFi.RSSI(i) >= -50) {
        quality = 100;
      }
      else {
        quality = 2 * (WiFi.RSSI(i) + 100);
      }
      if (quality < 20) { continue; } // Skip bad quality networks
      wlanRow += "^" + String(WiFi.SSID(i)) + "^" + String(quality) + "^" + String((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? "0" : "1");
    }
    return wlanRow;
  }

On the web page side:
Code: Select all    else if (evt.data.charAt(0) == "^") {
      var wlanArray = evt.data.substr(1).split('^');
    }
so the string is parsed by the ^ separator and all elements can be put and displayed in a html table.