kakopappa / sinric

Amazon Alexa Smart home skill / Google Home Action for ESP8266 / ESP32 / Arduino
https://sinric.com
287 stars 166 forks source link

ESP 8266 V3 <FS.h> WiFiManager.h #329

Closed arduino-nour closed 5 years ago

arduino-nour commented 5 years ago

0 1 2 //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// arduinou.nour@gmai.com ////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////

0.0.txt /////////////////////////////////////////////////////////////////

include //this needs to be first, or it all crashes and burns...

include

include

include

include

include // get it from https://github.com/Links2004/arduinoWebSockets/releases

include // get it from https://arduinojson.org/ or install via Arduino library manager

include "WiFiManager.h" //https://github.com/tzapu/WiFiManager

// Issue #18 https://github.com/kakopappa/sinric/issues/18 // If you receive an error like multi_nav_wifi:51: error: 'class WiFiManager' has no member named 'addAP' use // https://github.com/the-real-orca/WiFiManager

WebSocketsClient webSocket; WiFiClient client;

define MyApiKey "xxxxxxxxxxxxxxxxxxxxxxx" // TODO: Change to your sinric API Key. Your API Key is displayed on sinric.com dashboard

define HEARTBEAT_INTERVAL 300000 // 5 Minutes

define lamp1 "5d344e1b56393964a3c9ba0b"

uint64_t heartbeatTimestamp = 0; bool isConnected = false;

void load(WiFiManager &wifiManager) { //clean FS, for testing // SPIFFS.format();

//read configuration from FS json Serial.println("mounting FS...");

if (SPIFFS.begin()) { if (SPIFFS.exists("/config.json")) { //file exists, reading and loading Serial.println("reading config file"); File configFile = SPIFFS.open("/config.json", "r");

  if (configFile) {
    Serial.println("opened config file...");
    size_t size = configFile.size();
    // Allocate a buffer to store contents of the file.
    std::unique_ptr<char[]> buf(new char[size]);

    configFile.readBytes(buf.get(), size);
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.parseObject(buf.get());
    json.printTo(Serial); // debug output to console

    if (json.success()) {
      Serial.println("\nparsed json");
      if ( json["Networks"].is<JsonArray>() ) {
        for (int i=0; i < json["Networks"].size(); i++) {
          auto obj = json["Networks"][i];

          // add existing networks and credentials
          wifiManager.addAP(obj["SSID"], obj["Password"]);
        }
      }
    } else {
      Serial.println("failed to load json config");
      return;
    }
  }
}
SPIFFS.end();

} else { Serial.println("failed to mount FS -> format"); SPIFFS.format(); } }

void save(WiFiManager &wifiManager) { //save the custom parameters to FS if (SPIFFS.begin()) { Serial.println("saving config..."); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); JsonArray& networks = json.createNestedArray("Networks");

// encode known networks to JSON
for (int i = 0; auto ap = wifiManager.getAP(i); i++ ) {
  JsonObject& obj = jsonBuffer.createObject();
  obj["SSID"] = ap->ssid;
  obj["Password"] = ap->pass;
  networks.add(obj);
}

File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
  Serial.println("failed to open config file for writing");
  return;
}

json.printTo(Serial); Serial.println(); // debug output to console
json.printTo(configFile);
configFile.close();
SPIFFS.end();

} }

//flag for saving data bool shouldSaveConfig = false; //callback notifying us of the need to save config void saveConfigCallback () { shouldSaveConfig = true; }

void turnOn(String deviceId) { if (deviceId == "lamp1") // Device ID of first device {
Serial.print("Turn on device id: "); Serial.println(deviceId); digitalWrite (16,HIGH); } else if (deviceId == "5xxxxxxxxxxxxxxxxxxxxxxxx") // Device ID of second device { Serial.print("Turn on device id: "); Serial.println(deviceId); } else { Serial.print("Turn on for unknown device id: "); Serial.println(deviceId);
}
}

void turnOff(String deviceId) { if (deviceId == "lamp1") // Device ID of first device {
Serial.print("Turn off Device ID: "); Serial.println(deviceId); //digitalWrite (16,LOW);
} else if (deviceId == "5xxxxxxxxxxxxxxxxxxxxxxxx") // Device ID of second device { Serial.print("Turn off Device ID: "); Serial.println(deviceId); } else { Serial.print("Turn off for unknown device id: "); Serial.println(deviceId);
} }

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) { switch(type) { case WStype_DISCONNECTED: isConnected = false;
Serial.printf("[WSc] Webservice disconnected from sinric.com!\n"); break; case WStype_CONNECTED: { isConnected = true; Serial.printf("[WSc] Service connected to sinric.com at url: %s\n", payload); Serial.printf("Waiting for commands from sinric.com ...\n");
} break; case WStype_TEXT: { Serial.printf("[WSc] get text: %s\n", payload); // Example payloads

    // For Light device type
    // {"deviceId": xxxx, "action": "setPowerState", value: "ON"} // https://developer.amazon.com/docs/device-apis/alexa-powercontroller.html
    // {"deviceId": xxxx, "action": "AdjustBrightness", value: 3} // https://developer.amazon.com/docs/device-apis/alexa-brightnesscontroller.html
    // {"deviceId": xxxx, "action": "setBrightness", value: 42} // https://developer.amazon.com/docs/device-apis/alexa-brightnesscontroller.html
    // {"deviceId": xxxx, "action": "SetColor", value: {"hue": 350.5,  "saturation": 0.7138, "brightness": 0.6501}} // https://developer.amazon.com/docs/device-apis/alexa-colorcontroller.html
    // {"deviceId": xxxx, "action": "DecreaseColorTemperature"} // https://developer.amazon.com/docs/device-apis/alexa-colortemperaturecontroller.html
    // {"deviceId": xxxx, "action": "IncreaseColorTemperature"} // https://developer.amazon.com/docs/device-apis/alexa-colortemperaturecontroller.html
    // {"deviceId": xxxx, "action": "SetColorTemperature", value: 2200} // https://developer.amazon.com/docs/device-apis/alexa-colortemperaturecontroller.html

    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.parseObject((char*)payload); 
    String deviceId = json ["deviceId"];     
    String action = json ["action"];

    if(action == "setPowerState") { // Switch or Light
        String value = json ["value"];
        if(value == "ON") {
            turnOn(deviceId);
        } else {
            turnOff(deviceId);
        }
    }
    else if(action == "setBrightness") {

    }
    else if(action == "AdjustBrightness") {

    }
    else if (action == "test") {
        Serial.println("[WSc] received test command from sinric.com");
    }
  }
  break;
case WStype_BIN:
  Serial.printf("[WSc] get binary length: %u\n", length);
  break;

} }

void setup() { Serial.begin(115200); pinMode (16,OUTPUT); //digitalWrite (16,HIGH);

//WiFiManager //Local intialization. Once its business is done, there is no need to keep it around WiFiManager wifiManager; //reset settings - for testing wifiManager.resetSettings();

// load known access points load(wifiManager);

//set config save notify callback wifiManager.setSaveConfigCallback(saveConfigCallback);

//fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration if(!wifiManager.autoConnect()) { Serial.println("failed to connect and hit timeout"); //reset and try again, or maybe put it to deep sleep ESP.reset(); delay(1000); }

// save known access points if ( shouldSaveConfig ) save(wifiManager);

//if you get here you have connected to the WiFi Serial.println(); Serial.print("connected to: "); Serial.println(WiFi.SSID()); Serial.print("local ip: "); Serial.println(WiFi.localIP());

// server address, port and URL webSocket.begin("iot.sinric.com", 80, "/");

// event handler webSocket.onEvent(webSocketEvent); webSocket.setAuthorization("apikey", MyApiKey);

// try again every 5000ms if connection has failed webSocket.setReconnectInterval(5000); // If you see 'class WebSocketsClient' has no member named 'setReconnectInterval' error update arduinoWebSockets }

void loop() { webSocket.loop();

if(isConnected) { uint64_t now = millis();

  // Send heartbeat in order to avoid disconnections during ISP resetting IPs over night. Thanks @MacSass
  if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
      heartbeatTimestamp = now;
      webSocket.sendTXT("H");          
  }

}
}

//////////////////////////////////////////////////////////

Lod does not work Even the ESP 8266 V3 does not light up when you press the key What is the problem? Is it in the code? The connection is correct Thank you for your attention /////////////////////////////////////////

arduino-nour commented 5 years ago

????

kakopappa commented 5 years ago

in the serial terminal pic, I can see the on/off commands coming in, looks like your Sinric integration si fine.

If the LED is not working, it's likely to do with the PIN mapping is wrong.

try the on.off on a new sketch with the same pins and check whether it's working

arduino-nour commented 5 years ago

Thank you for your comment All connections are correct You changed the esp 8266 v3 It's working on ESP8266WebServer library Also on the WiFiManager.h library But does not work with Alexa Everything works successfully even if you log on Serial Monitor Gives the code On and OFF and it sends the status of keys on On the mobile, it also gives On and Off from within the Alexa program

Is the code correct?

kakopappa commented 5 years ago

if (deviceId == "lamp1") <-- wrong

this should be device id. device id is like 5xxxxxxxxxxxxxx

arduino-nour commented 5 years ago

It worked like this

define lamp1 "5xxxxxxxxxxxxxxxxxxxxxxxx"

const int ligh1= 16;

void turnOn(String deviceId) { if (deviceId == "lamp1") // Device ID of first device {
Serial.print("Turn on device id: "); Serial.println(deviceId); digitalWrite (ligh1,HIGH); } void setup() { Serial.begin(115200); pinMode (ligh1,OUTPUT); ////////////////////////////////////////////////

Do you mean work?

oid turnOn(String deviceId) { if (deviceId == "5xxxxxxxxxxxxxxxx") // Device ID of first device {
Serial.print("Turn on device id: "); Serial.println(deviceId); digitalWrite (ligh1,HIGH); }

//////////////////////////////////////////////// All thanks to you my friend

kakopappa commented 5 years ago

device id is not device name. I hope you got it to work now

arduino-nour commented 5 years ago

kakopappa thank you very much I will work it out and give you the result

arduino-nour commented 5 years ago

@kakopappa thank you my friend The problem has been resolved Now I can call Alexa

oid turnOn(String deviceId) { if (deviceId == "5xxxxxxxxxxxxxxxx") // Device ID of first device { Serial.print("Turn on device id: "); Serial.println(deviceId); digitalWrite (16,HIGH); }