arduino-libraries / WiFiNINA

140 stars 106 forks source link

Can't connect to server after Wifi reconnect #66

Closed hesorensen closed 5 years ago

hesorensen commented 5 years ago

To save battery I want to end my WiFi connection and then reconnect when next message has to be send. It works fine the first time; and after I call WiFi.End I can connect to wifi again with WiFi.begin but I can't talk to any servers. Is that a feature or a bug?

Board: MKR Wifi 1010 Wifinina library: 1.4.0

Example:

#include <WiFiNINA.h>
#include "arduino_secrets.h"

char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;
WiFiSSLClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }
}

void loop() {
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    if (status != WL_CONNECTED)
      delay(10000);
  }
  Serial.println("Connected to wifi");

  makeRequest();

  Serial.println("Disconnecting from Wifi");
  WiFi.end();

  delay(10000);
}

void makeRequest(){
  Serial.println("Starting connection to server...");
  if (client.connect("www.arduino.cc", 443)) {
    Serial.println("connected to server");

    client.println("GET /asciilogo.txt HTTP/1.1");
    client.println("Host: www.arduino.cc");
    client.println();

    while (client.connected() && !client.available()) {
      delay(100);
    }

    if (client.connected()){
      while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }
    }

    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();
  }
  else {
    Serial.println("Could not connect to server");
  }
}
hesorensen commented 5 years ago

That was a stupid user exception :-(