[PORADNIK] Arduino IDE

Awatar użytkownika
slawek
Posty: 2465
Rejestracja: pn mar 14, 2016 11:48 pm
Lokalizacja: Biała Podlaska

Może niezbyt suplowo wygląda, ale działa ;)
Do pełni szczęścia przydałoby się automatyczne generowanie GUID, bo trzeba zmieniać za każdą kompilacją (może użyć odczytanego MAC jako część GUID?)
TEORIA jest wtedy gdy wszystko wiemy i nic nie działa
PRAKTYKA jest wtedy gdy wszystko działa a my nie wiemy dlaczego
My łączymy teorię z praktyką czyli nic nie działa i nikt nie wie dlaczego
elmaya
Posty: 1482
Rejestracja: śr cze 27, 2018 5:48 pm
Lokalizacja: El Saucejo - Sevilla

Dobre pytanie, jestem też zainteresowany.
Awatar użytkownika
wojtas567
Posty: 2209
Rejestracja: ndz kwie 03, 2016 7:16 pm
Lokalizacja: Olsztyn

Dodałem jeszcze linijkę żeby AP się wyłączyło jak już jest połączony z suplą.
Nie wiem czy w dobrym miejscu ale u mnie działa a jak kliknie się config to sieć się pojjawia

Kod: Zaznacz cały

}
      WiFi.softAPdisconnect(true); // wyłączenie rozgłaszania sieci ESP 
  } else {
    Serial.println("failed to mount FS");
  }
  //end read
  //Serial.println(Location_id);
  //Serial.println(Location_Pass);
  //Serial.println(Supla_server);
 
 
   char GUID[SUPLA_GUID_SIZE] ={0x1
przydałoby się jeszcze ustawić wejście w cobfig po przytrzymaniu przycisku przez 10 s lub 10 kliknięć :).
Ostatnio zmieniony ndz lip 08, 2018 9:19 pm przez wojtas567, łącznie zmieniany 1 raz.
Pozdrawiam
Wojtek
Awatar użytkownika
slawek
Posty: 2465
Rejestracja: pn mar 14, 2016 11:48 pm
Lokalizacja: Biała Podlaska

Aby uzyskać 10s wystarczy zamiast

Kod: Zaznacz cały

int timeout           = 120; // seconds to run for
wpisać

Kod: Zaznacz cały

int timeout           = 10000; // seconds to run for
TEORIA jest wtedy gdy wszystko wiemy i nic nie działa
PRAKTYKA jest wtedy gdy wszystko działa a my nie wiemy dlaczego
My łączymy teorię z praktyką czyli nic nie działa i nikt nie wie dlaczego
elmaya
Posty: 1482
Rejestracja: śr cze 27, 2018 5:48 pm
Lokalizacja: El Saucejo - Sevilla

jeśli masz rację
} else {
Serial.println("failed to mount FS");
}
//end read
//Serial.println(Location_id);
//Serial.println(Location_Pass);
//Serial.println(Supla_server);

WiFi.mode(WIFI_STA); // Force to station mode because if device was switched off while in access point mode it will start up next time in access point mode.
-------------
int timeout = 120; // seconds to run for


time this is the open configuration
if you reset AP is still open
Awatar użytkownika
wojtas567
Posty: 2209
Rejestracja: ndz kwie 03, 2016 7:16 pm
Lokalizacja: Olsztyn

slawek pisze: ndz lip 08, 2018 8:28 pm Aby uzyskać 10s wystarczy zamiast

Kod: Zaznacz cały

int timeout           = 120; // seconds to run for
wpisać

Kod: Zaznacz cały

int timeout           = 10000; // seconds to run for
To chyba jest za mało bo u mnie nie działa :(, od razu wskakuje w tryb konfig AP.
Pozdrawiam
Wojtek
Awatar użytkownika
slawek
Posty: 2465
Rejestracja: pn mar 14, 2016 11:48 pm
Lokalizacja: Biała Podlaska

Faktycznie - działa natychmiast...
TEORIA jest wtedy gdy wszystko wiemy i nic nie działa
PRAKTYKA jest wtedy gdy wszystko działa a my nie wiemy dlaczego
My łączymy teorię z praktyką czyli nic nie działa i nikt nie wie dlaczego
cino111
Posty: 714
Rejestracja: pn maja 07, 2018 8:00 pm

Dodałem do kodu jeszcze termometry i przycisk, ale nie kompiluje mi się. @Slawek, @wojtas567 mozecie zerknąć co jest nie tak?
Wywala mi sekcji void loop () na DynamicJsonBuffer jsonBuffer;
exit status 1
'DynamicJsonBuffer' was not declared in this scope

Kod: Zaznacz cały

#include <FS.h>  

#include <ESP8266WiFi.h>
#define SUPLADEVICE_CPP
#include <SuplaDevice.h>

#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h> 
#include <ArduinoJson.h>

#include <OneWire.h>
#include <DallasTemperature.h>
int button1 = 0; //wartosc początkowa dla przycisku 1

WiFiClient client;

OneWire oneWire(4); //  (D2) - Pin number
DallasTemperature sensors(&oneWire);

DeviceAddress garaz = { 0x28, 0xFF, 0x2E, 0xFB, 0xC1, 0x17, 0x1, 0xD3 };       // odczytany adres 28FF2EFBC11701D3  
DeviceAddress zewnatrz = { 0x28, 0xFF, 0xEC, 0xFE, 0xC1, 0x17, 0x1, 0xF3 };     //Odczytany adres 28FFECFEC11701F3 

//define your default values here, if there are different values in config.json, they are overwritten.
//length should be max size + 1 
char Supla_server[40];
char Location_id[15];
char Location_Pass[20];
byte mac[6];

//flag for saving data
bool shouldSaveConfig = false;
bool initialConfig = false;

#define TRIGGER_PIN D3
int timeout           = 120; // szas otwarica config po resecie ESP


int measurePin = A0;
int ledPower = 5;

int samplingTime = 280;
int deltaTime = 40;
int sleepTime = 9680;

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}
void ondemandwifiCallback () {
// The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_Supla_server("server", "supla server", Supla_server, 40);
  WiFiManagerParameter custom_Location_id("ID", "Location_id", Location_id, 15);
  WiFiManagerParameter custom_Location_Pass("Password", "Location_Pass", Location_Pass, 20);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);
  
  //add all your parameters here
  wifiManager.addParameter(&custom_Supla_server);
  wifiManager.addParameter(&custom_Location_id);
  wifiManager.addParameter(&custom_Location_Pass);

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  wifiManager.setMinimumSignalQuality();

  // set configportal timeout
    wifiManager.setConfigPortalTimeout(timeout);

    if (!wifiManager.startConfigPortal("OnDemandAP")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      //reset and try again, or maybe put it to deep sleep
      ESP.restart();
      delay(5000);
    }
    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
    
    //read updated parameters
    strcpy(Supla_server, custom_Supla_server.getValue());
    strcpy(Location_id, custom_Location_id.getValue());
    strcpy(Location_Pass, custom_Location_Pass.getValue());
  
}

// DS18B20 Sensor read implementation
double get_temperature(int channelNumber, double last_val) {

    
    
    digitalWrite(ledPower,LOW); // power on the LED
    delayMicroseconds(samplingTime);

    voMeasured = analogRead(measurePin); // read the dust value
  
    delayMicroseconds(deltaTime);
    digitalWrite(ledPower,HIGH); // turn the LED off
    delayMicroseconds(sleepTime);

    // 0 - 5.0V mapped to 0 - 1023 integer values 
    calcVoltage = voMeasured * (5.0 / 1024); 
  
    dustDensity = (0.17 * calcVoltage - 0.1)*1000; 
  
    Serial.print("Raw Signal Value (0-1023): ");
    Serial.print(voMeasured);
  
    Serial.print(" - Voltage: ");
    Serial.print(calcVoltage);
  
    Serial.print(" - Dust Density [ug/m3]: ");
    Serial.println(dustDensity);    
    
    
    
    
      
    double t = -275;
    
    if ( sensors.getDeviceCount() > 0 )
      {
         sensors.requestTemperatures();
         switch(channelNumber)

          {
            case 0:
                   
                    t = sensors.getTempC(garaz);
                    break;
            case 1:
                    t = sensors.getTempC(zewnatrz);
                    break;
            
            
              
          
             };
      };

    
    return t;  
}

void setup() {

  Serial.begin(115200);
  //sensors.begin();

 pinMode (16, INPUT_PULLUP); //ustawiamy Pin 16 (D0) na przycisk
   // Init DS18B20 library 
  sensors.begin();
  
    // Set temperature callback
  SuplaDevice.setTemperatureCallback(&get_temperature);
  
  

  pinMode(TRIGGER_PIN, INPUT);
  
  if (WiFi.SSID()==""){
    //Serial.println("We haven't got any access point credentials, so get them now");   
    initialConfig = true;
  }
  
  //read configuration from FS json
  Serial.println("mounting FS...");
  
  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    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);
        if (json.success()) {
         // Serial.println("\nparsed json");

          strcpy(Supla_server, json["Supla_server"]);
          strcpy(Location_id, json["Location_id"]);
          strcpy(Location_Pass, json["Location_Pass"]);

        } else {
          Serial.println("failed to load json config");
          
        }
      }
    }
    WiFi.softAPdisconnect(true); // wyłączenie rozglaszania Wifi ESP po połaczeniu do lokalnego WIFI
  } else {
    Serial.println("failed to mount FS");
  }
  //end read
  //Serial.println(Location_id);
  //Serial.println(Location_Pass);
  //Serial.println(Supla_server);
 
 delay(10);
 
   char GUID[SUPLA_GUID_SIZE] ={0x53,0x9C,0x2D,0x21,0x2F,0xB2,0xB9,0x40,0x71,0xAD,0xA8,0xCD,0x39,0xC7,0x34,0x4D}; 
   // with GUID that you can retrieve from https://www.supla.org/arduino/get-guid.
   WiFi.macAddress(mac);

  
  // CHANNEL0 - Thermometer DS18B20
  SuplaDevice.addDS18B20Thermometer();

   // CHANNEL1 - Thermometer DS18B20
  SuplaDevice.addDS18B20Thermometer();


  
  
  // CHANNEL2 - RELAY
  SuplaDevice.addRelay(D5, true);          

  // CHANNEL3 - RELAY
  SuplaDevice.addRelay(D6, true);            

   // CHANNEL4 - RELAY
  SuplaDevice.addRelay(D7, true);  

 

  
  // CHANNEL5 - Opening sensor (Normal Open)
  SuplaDevice.addSensorNO(A0); // A0 - Pin number where the sensor is connected
                               // Call SuplaDevice.addSensorNO(A0, true) with an extra "true" parameter
                               // to enable the internal pull-up resistor





  // CHANNEL6 - DHT22 Sensor
  // SuplaDevice.addDHT11();
  // SuplaDevice.addAM2302();
  // SuplaDevice.addDHT22();

  int LocationID = atoi(Location_id);
  SuplaDevice.begin(GUID,              // Global Unique Identifier 
                    mac,               // Ethernet MAC address
                    Supla_server,  // SUPLA server address
                    LocationID,                 // Location ID 
                    Location_Pass);               // Location Password
    
}

void loop() {

   // is configuration portal requested?
  if ( digitalRead(TRIGGER_PIN) == LOW|| (initialConfig))  {
    ondemandwifiCallback () ;
    initialConfig = false; 
  }
  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["Supla_server"] = Supla_server;
    json["Location_id"] = Location_id;
    json["Location_Pass"] = Location_Pass;

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
    json.prettyPrintTo(Serial);
    json.printTo(configFile);
    configFile.close();
    Serial.println("config saved");
    shouldSaveConfig = false;
    //end save
  }
  
  if (WiFi.status() != WL_CONNECTED) 
  {
    WiFi_up();
  }
 SuplaDevice.iterate();
 
   TSD_SuplaChannelNewValue przycisk1; //ustaw nazwe dla przycisku
  przycisk1.SenderID = 0; // Powiadom clouda, że załączasz recznie. W przypadku siłowników ma być 0
  przycisk1.ChannelNumber = 4; // nr kanału przekaźnika
  przycisk1.DurationMS = 0; //czas wlaczenia

button1 = digitalRead(16); 
if(digitalRead(16)==LOW){ // tu dodajemy jeszcze raz zeby nie pstrykalo samo czyli przerwa i ponowne zapytanie
  delay(100);
if(digitalRead(16)==LOW){
przycisk1.value[0] = !przycisk1.value[0]; 
SuplaDevice.channelSetValue(&przycisk1);
while(digitalRead(16)==LOW);
delay(20);
}
  
}}
}


// Supla.org ethernet layer
    int supla_arduino_tcp_read(void *buf, int count) {
        _supla_int_t size = client.available();
       
        if ( size > 0 ) {
            if ( size > count ) size = count;
            return client.read((uint8_t *)buf, size);
        };
    
        return -1;
    };
    
    int supla_arduino_tcp_write(void *buf, int count) {
        return client.write((const uint8_t *)buf, count);
    };
    
    bool supla_arduino_svr_connect(const char *server, int port) {
          return client.connect(server, 2015);
    }
    
    bool supla_arduino_svr_connected(void) {
          return client.connected();
    }
    
    void supla_arduino_svr_disconnect(void) {
         client.stop();
    }
    
    void supla_arduino_eth_setup(uint8_t mac[6], IPAddress *ip) {

       WiFi_up();
    }
SuplaDeviceCallbacks supla_arduino_get_callbacks(void) {
          SuplaDeviceCallbacks cb;
          
          cb.tcp_read = &supla_arduino_tcp_read;
          cb.tcp_write = &supla_arduino_tcp_write;
          cb.eth_setup = &supla_arduino_eth_setup;
          cb.svr_connected = &supla_arduino_svr_connected;
          cb.svr_connect = &supla_arduino_svr_connect;
          cb.svr_disconnect = &supla_arduino_svr_disconnect;
          cb.get_temperature = &get_temperature;
           cb.get_temperature_and_humidity = NULL;
          cb.get_rgbw_value = NULL;
          cb.set_rgbw_value = NULL;
          
          return cb;
}

void WiFi_up() // Procedimiento de conexión para redes WiFi
{
  Serial.print("Conexión a la red ");
 // Serial.println(ssid);

  WiFi.begin(); // Intentar conectarse a la red


  for (int x = 60; x > 0; x--) 
  {
    if (WiFi.status() == WL_CONNECTED) 
    {
      break;                           
    }
    else                                 
    {
      Serial.print(".");                
      delay(500);                      
    }

  }

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("");
    Serial.println("Conexión hecha");
    Serial.println("Adres IP: ");
    Serial.print(WiFi.localIP());
    Serial.print(" / ");
    Serial.println(WiFi.subnetMask());
    Serial.print("puerta: ");
    Serial.println(WiFi.gatewayIP());
    long rssi = WiFi.RSSI();
    Serial.print("Fuerza de la señal (RSSI): ");
    Serial.print(rssi);
    Serial.println(" dBm");
  }
  else    
  {
    Serial.println("");
    Serial.println("La conexión no pudo hacerse");
  }
}
elmaya
Posty: 1482
Rejestracja: śr cze 27, 2018 5:48 pm
Lokalizacja: El Saucejo - Sevilla

3 przyciski, 3 przekaźniki, ntc10k dla temperatury w ADC
Awatar użytkownika
wojtas567
Posty: 2209
Rejestracja: ndz kwie 03, 2016 7:16 pm
Lokalizacja: Olsztyn

cino111 pisze: pn lip 09, 2018 6:59 am Dodałem do kodu jeszcze termometry i przycisk, ale nie kompiluje mi się. @Slawek, @wojtas567 mozecie zerknąć co jest nie tak?
Wywala mi sekcji void loop () na DynamicJsonBuffer jsonBuffer;
brakuje Ci biblioteki <ArduinoJson.h>
poprawiłem też termometry bo miałeś za dużo kodu :) chyba, że będziesz używał czujnika pyłu ale to i tak by nie działał jeszcze.

Kod: Zaznacz cały

#include <FS.h>  

#include <ESP8266WiFi.h>
#define SUPLADEVICE_CPP
#include <SuplaDevice.h>

#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h> 
#include <ArduinoJson.h>

#include <OneWire.h>
#include <DallasTemperature.h>
int button1 = 0; //wartosc początkowa dla przycisku 1

WiFiClient client;

OneWire oneWire(4); //  (D2) - Pin number
DallasTemperature sensors(&oneWire);

DeviceAddress garaz = { 0x28, 0xFF, 0x2E, 0xFB, 0xC1, 0x17, 0x1, 0xD3 };       // odczytany adres 28FF2EFBC11701D3  
DeviceAddress zewnatrz = { 0x28, 0xFF, 0xEC, 0xFE, 0xC1, 0x17, 0x1, 0xF3 };     //Odczytany adres 28FFECFEC11701F3 

//define your default values here, if there are different values in config.json, they are overwritten.
//length should be max size + 1 
char Supla_server[40];
char Location_id[15];
char Location_Pass[20];
byte mac[6];

//flag for saving data
bool shouldSaveConfig = false;
bool initialConfig = false;

#define TRIGGER_PIN D3
int timeout           = 120; // szas otwarica config po resecie ESP

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}
void ondemandwifiCallback () {
// The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_Supla_server("server", "supla server", Supla_server, 40);
  WiFiManagerParameter custom_Location_id("ID", "Location_id", Location_id, 15);
  WiFiManagerParameter custom_Location_Pass("Password", "Location_Pass", Location_Pass, 20);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);
  
  //add all your parameters here
  wifiManager.addParameter(&custom_Supla_server);
  wifiManager.addParameter(&custom_Location_id);
  wifiManager.addParameter(&custom_Location_Pass);

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  wifiManager.setMinimumSignalQuality();

  // set configportal timeout
    wifiManager.setConfigPortalTimeout(timeout);

    if (!wifiManager.startConfigPortal("SuplaAP")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      //reset and try again, or maybe put it to deep sleep
      ESP.restart();
      delay(5000);
    }
    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
    
    //read updated parameters
    strcpy(Supla_server, custom_Supla_server.getValue());
    strcpy(Location_id, custom_Location_id.getValue());
    strcpy(Location_Pass, custom_Location_Pass.getValue());
  
}

// DS18B20 Sensor read implementation
double get_temperature(int channelNumber, double last_val) {
      
    double t = -275;
    
    if ( sensors.getDeviceCount() > 0 )
      {
         sensors.requestTemperatures();
         switch(channelNumber)

          {
            case 0:
                   
                    t = sensors.getTempC(garaz);
                    break;
            case 1:
                    t = sensors.getTempC(zewnatrz);
                    break;
          
             };
      };

    
    return t;  
}

void setup() {

  Serial.begin(115200);

 pinMode (16, INPUT_PULLUP); //ustawiamy Pin 16 (D0) na przycisk

   // Init DS18B20 library 
  sensors.begin();
  
    // Set temperature callback
  SuplaDevice.setTemperatureCallback(&get_temperature);
  
  

  pinMode(TRIGGER_PIN, INPUT);
  
  if (WiFi.SSID()==""){
    //Serial.println("We haven't got any access point credentials, so get them now");   
    initialConfig = true;
  }
  
  //read configuration from FS json
  Serial.println("mounting FS...");
  
  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    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);
        if (json.success()) {
         // Serial.println("\nparsed json");

          strcpy(Supla_server, json["Supla_server"]);
          strcpy(Location_id, json["Location_id"]);
          strcpy(Location_Pass, json["Location_Pass"]);

        } else {
          Serial.println("failed to load json config");
          
        }
      }
    }
    WiFi.softAPdisconnect(true); // wyłączenie rozglaszania Wifi ESP po połaczeniu do lokalnego WIFI
  } else {
    Serial.println("failed to mount FS");
  }
  //end read
  //Serial.println(Location_id);
  //Serial.println(Location_Pass);
  //Serial.println(Supla_server);
 
 delay(10);
 
   char GUID[SUPLA_GUID_SIZE] ={0x53,0x9C,0x2D,0x21,0x2F,0xB2,0xB9,0x40,0x71,0xAD,0xA8,0xCD,0x39,0xC7,0x34,0x4D}; 
   // with GUID that you can retrieve from https://www.supla.org/arduino/get-guid.
   WiFi.macAddress(mac);

  
  // CHANNEL0 - Thermometer DS18B20
  SuplaDevice.addDS18B20Thermometer();

   // CHANNEL1 - Thermometer DS18B20
  SuplaDevice.addDS18B20Thermometer();


  
  
  // CHANNEL2 - RELAY
  SuplaDevice.addRelay(D5, true);          

  // CHANNEL3 - RELAY
  SuplaDevice.addRelay(D6, true);            

   // CHANNEL4 - RELAY
  SuplaDevice.addRelay(D7, true);  

 

  
  // CHANNEL5 - Opening sensor (Normal Open)
  SuplaDevice.addSensorNO(A0); // A0 - Pin number where the sensor is connected
                               // Call SuplaDevice.addSensorNO(A0, true) with an extra "true" parameter
                               // to enable the internal pull-up resistor





  // CHANNEL6 - DHT22 Sensor
  // SuplaDevice.addDHT11();
  // SuplaDevice.addAM2302();
  // SuplaDevice.addDHT22();

  int LocationID = atoi(Location_id);
  SuplaDevice.begin(GUID,              // Global Unique Identifier 
                    mac,               // Ethernet MAC address
                    Supla_server,  // SUPLA server address
                    LocationID,                 // Location ID 
                    Location_Pass);               // Location Password
    
}

void loop() {

   // is configuration portal requested?
  if ( digitalRead(TRIGGER_PIN) == LOW|| (initialConfig))  {
    ondemandwifiCallback () ;
    initialConfig = false; 
  }
  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["Supla_server"] = Supla_server;
    json["Location_id"] = Location_id;
    json["Location_Pass"] = Location_Pass;

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
    json.prettyPrintTo(Serial);
    json.printTo(configFile);
    configFile.close();
    Serial.println("config saved");
    shouldSaveConfig = false;
    //end save
  }
  
  if (WiFi.status() != WL_CONNECTED) 
  {
    WiFi_up();
  }
 SuplaDevice.iterate();
 
   TSD_SuplaChannelNewValue przycisk1; //ustaw nazwe dla przycisku
  przycisk1.SenderID = 0; // Powiadom clouda, że załączasz recznie. W przypadku siłowników ma być 0
  przycisk1.ChannelNumber = 4; // nr kanału przekaźnika
  przycisk1.DurationMS = 0; //czas wlaczenia

button1 = digitalRead(16); 
if(digitalRead(16)==LOW){ // tu dodajemy jeszcze raz zeby nie pstrykalo samo czyli przerwa i ponowne zapytanie
  delay(100);
if(digitalRead(16)==LOW){
przycisk1.value[0] = !przycisk1.value[0]; 
SuplaDevice.channelSetValue(&przycisk1);
while(digitalRead(16)==LOW);
delay(20);
    }
  }
}


// Supla.org ethernet layer
    int supla_arduino_tcp_read(void *buf, int count) {
        _supla_int_t size = client.available();
       
        if ( size > 0 ) {
            if ( size > count ) size = count;
            return client.read((uint8_t *)buf, size);
        };
    
        return -1;
    };
    
    int supla_arduino_tcp_write(void *buf, int count) {
        return client.write((const uint8_t *)buf, count);
    };
    
    bool supla_arduino_svr_connect(const char *server, int port) {
          return client.connect(server, 2015);
    }
    
    bool supla_arduino_svr_connected(void) {
          return client.connected();
    }
    
    void supla_arduino_svr_disconnect(void) {
         client.stop();
    }
    
    void supla_arduino_eth_setup(uint8_t mac[6], IPAddress *ip) {

       WiFi_up();
    }
SuplaDeviceCallbacks supla_arduino_get_callbacks(void) {
          SuplaDeviceCallbacks cb;
          
          cb.tcp_read = &supla_arduino_tcp_read;
          cb.tcp_write = &supla_arduino_tcp_write;
          cb.eth_setup = &supla_arduino_eth_setup;
          cb.svr_connected = &supla_arduino_svr_connected;
          cb.svr_connect = &supla_arduino_svr_connect;
          cb.svr_disconnect = &supla_arduino_svr_disconnect;
          cb.get_temperature = &get_temperature;
           cb.get_temperature_and_humidity = NULL;
          cb.get_rgbw_value = NULL;
          cb.set_rgbw_value = NULL;
          
          return cb;
}

void WiFi_up() // Procedimiento de conexión para redes WiFi
{
  Serial.print("Conexión a la red ");
 // Serial.println(ssid);

  WiFi.begin(); // Intentar conectarse a la red


  for (int x = 60; x > 0; x--) 
  {
    if (WiFi.status() == WL_CONNECTED) 
    {
      break;                           
    }
    else                                 
    {
      Serial.print(".");                
      delay(500);                      
    }

  }

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("");
    Serial.println("Conexión hecha");
    Serial.println("Adres IP: ");
    Serial.print(WiFi.localIP());
    Serial.print(" / ");
    Serial.println(WiFi.subnetMask());
    Serial.print("puerta: ");
    Serial.println(WiFi.gatewayIP());
    long rssi = WiFi.RSSI();
    Serial.print("Fuerza de la señal (RSSI): ");
    Serial.print(rssi);
    Serial.println(" dBm");
  }
  else    
  {
    Serial.println("");
    Serial.println("La conexión no pudo hacerse");
  }
}
Pozdrawiam
Wojtek
ODPOWIEDZ

Wróć do „FAQ / Jak to zrobić”