ESP01 a Virtuino se POMOC POMOC

Odpovědět
Cermy
Příspěvky: 16
Registrován: 01 úno 2019, 11:23

ESP01 a Virtuino se POMOC POMOC

Příspěvek od Cermy » 21 lis 2019, 12:59

Ahoj mám problém Prosím POMOC POMOC
Hraji si s aplikací Virtuino se, kde vyčítám hodnoty z thingspeak ale potřeboval bych rychlejší odezvy teplot než 15s.
Virtuino umí vytvořit vlastní server ze kterého mohu do paměti zapsat a číst hodnoty přes ESP01.
Potřebuji pomoci s tím jak mu říct:
1) že na GPI00 mám relé které bych chtěl ovládat přes vmemory2
2) na GPI02 mám čidlo DS18B20 ze kterého bych chtěl posílat teploty každou sekundu na vmemory3

Je možné že s ESP01 to nepůjde? V řádku 2 má napsáno ESP32
Ve VIRTUINO mám na výběr kódy Json API nebo Http API jaký bych měl mít zvolený podle zdrojáku?

Kód: Vybrat vše

[code]
/* Virtuino SE Json example: Read - Write variables  (VARIABLES SIZE=256);
 * Supported boards: ESP32
 * Created by Ilias Lamprou
 * Updated Feb 27 2019
 * More examples: https://virtuino.com/index.php/virtuino-se/20-virtuino-se-code-examples
 */
// ------ VirtuinoSE V Memory Table
//  V0 memory -> variable1 
//  V1 memory -> variable2
//  V2 memory -> Sensor value 1 
//  V3 memory -> Sensor value 2 
//  V4 memory -> Analog A0
//  V6 ... V255 memory -> reserved


#ifdef ESP8266
 #include <ESP8266WiFi.h>  // Pins for board ESP8266 Wemos-NodeMCU
 #else
 #include <WiFi.h>    // Pins for board ESP32
 #endif


//------------------- USER SETTINGS ---------------------------------
const char* ssid = "Barca";           // The name of your WiFi network (SSID)
const char* password = "Boulevard";           // WIFI network PASSWORD

WiFiServer wifiServer(8000);                  // Virtuino default Server port: 8000

const char* ssid_AP = "Virtuino network";     // Access point network SSID
const char* password_AP = "1234567890";       // Access point network PASSWORD

#define VIRTUINO_KEY  "1234"      // Virtuino KEY, only the requests that include this key will be acceptable. // disable the line if you don't want to use a key                          

#define V_memory_count 256         // the size of V memory. You can change it to a number <256
//-------------------------------------------------------------------

float V_memory[V_memory_count];    // This array is synchronized with Virtuino SE V memory

boolean debug = true;              // set this variable to false on the finale code to decrease the request duration

//--- VARIABLES for this demo example
float   variable1 = 0;
float   variable2 = 0;
                                  
unsigned long timeStrored=0;


//============================================================== connectToWiFiNetwork
void connectToWiFiNetwork(){
  Serial.println("Connecting to "+String(ssid));
  
   // If you don't want to config IP manually disable the next four lines
  IPAddress ip(192, 168, 0, 150);            // where 150 is the desired IP Address   
  IPAddress gateway(192, 168, 0, 254);         // set gateway to match your network
  IPAddress subnet(255, 255, 255, 0);        // set subnet mask to match your network
  WiFi.config(ip, gateway, subnet);          // If you don't want to config IP manually disable this line
 
  WiFi.mode(WIFI_STA);                       // Configure the module as station only.
   WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.print(".");
    }
   Serial.println("");
   Serial.println("WiFi connected");
   Serial.println(WiFi.localIP());
}

//================================================================= initAccessPoint
void initAccessPoint(){
  Serial.print("Setting soft-AP ... ");                   // Default IP: 192.168.4.1
   WiFi.mode(WIFI_AP);                                     // Config module as Access point only.  Set WiFi.mode(WIFI_AP_STA); to config module as Acces point and station
   boolean result = WiFi.softAP(ssid_AP,password_AP);      // set the Access point SSID and password
   if(result == true)  {
    Serial.println("Server Ready");
    Serial.println(WiFi.softAPIP());
   }
   else Serial.println("Failed!");
}

//============================================================== setup
//==============================================================
void setup() {
  if (debug) {
    Serial.begin(9600);
    while (!Serial) continue;
  }

  //initAccessPoint();               //enable this line to use the esp board as AP  
  connectToWiFiNetwork();      //enable this line to connect the module to your wifi network  
  
  wifiServer.begin();
  
  }




//============================================================== loop
//==============================================================
void loop() {
virtuinoRun();        //Necessary function to communicate with Virtuino. Client handler


  //--- How to read a variable from Virtuino SE
  float v=vMemoryRead(0);
  if (variable1!=v) {        // Read the V0 memory.  On Virtuino panel add a regulator  to virtual memory V0  
      variable1=v;
      Serial.println("Variable1="+String(variable1));
  }
  
  //--- How to send to Virtuino SE sensor values
   if (millis()-timeStrored>5000) {       // read sensor value every 5 seconds. Avoid to use delay on your code
      vMemoryWrite(2,random(100));           // copy the sensor value to V2
      vMemoryWrite(3,random(100));
      vMemoryWrite(4,random(100));
      timeStrored=millis();               // On Virtuino panel add value displays or instrument  to virtual memories V2,V3,V4
  }


}

//===========================================================
float vMemoryRead(int memoryIndex){
  if ((memoryIndex>=0) & (memoryIndex<256)) return V_memory[memoryIndex];
  else return 0;
}
//===========================================================
void vMemoryWrite(int memoryIndex, double value){
  V_memory[memoryIndex]=value;
}

//============================================================== onCommandReceived
//==============================================================
/* This function is called every time Virtuino SE app sends a request to server 
 * The 'variableIndex' is the V memory index of Virtuino app
 * The 'valueAsText' is the value that has sent from the app
 * If the 'valueAsText" is ? you have to return the value that you want to be displayed on Virtuino panel
 */
 String onCommandReceived(int variableIndex, String valueAsJson){     
   String valueAsText = getJsonValue(valueAsJson,"value");    // read the value from the received Json string 
   if (debug) Serial.println("New value received: V"+String(variableIndex)+"  value="+valueAsText);
 if (valueAsText=="?") return (String(vMemoryRead(variableIndex)));   // return the value of the arduino V memory array
  else {
    float value = valueAsText.toFloat();        // convert the value to float. The valueAsText have to be numerical
    vMemoryWrite(variableIndex,value);
 }
 return "";
  
}


//================== Virtuino Library (included in sketch) ===============
//==============================================================
//==============================================================
/* Only the next functions are nedded to communicate with Virtuino 
 * Avoid to make changes to the code below  
 */


#define WRONG_KEY_MESSAGE  "Wrong Key"  
#define WELLCOME_MESSAGE  "Hello Virtuino"  


//============================================================== virtuinoRun
//==============================================================
  void virtuinoRun(){
  WiFiClient client = wifiServer.available();
  if (client) {
    if (debug) Serial.println("Client connected");
    while(!client.available())delay(1);    // Wait until the client sends some data
    String data="";
    while (client.connected()) {
      while (client.available()>0) {
        char c = client.read();
        data+=c;
        if (debug) Serial.write(c);
      }
     client.flush(); 
     if (debug) Serial.println("\nReceived data: "+data);
     String response= getResponseAsJson(data);
      client.print(response);
     if (debug) Serial.println("Response : "+response);
     client.stop();
    }
     
    if (debug) Serial.println("Client disconnected");
  }
 }



//============================================================== prepareResponse
//==============================================================
String getResponseAsJson(String data){
    //---check the KEY
   #ifdef VIRTUINO_KEY 
      String key = getJsonValue(data, "key");
      if (debug) Serial.println("Key="+key);
      if (!key.equals(VIRTUINO_KEY)) return "{\"status\":\"-1\",\"message\":\""+String(WRONG_KEY_MESSAGE)+"\"}";
   #endif

    //---check connection status
    String statusInfo = getJsonValue(data, "status");
    if (debug) Serial.println("statusInfo="+statusInfo);
    if (statusInfo.equals("0")) return "{\"status\":\"2\",\"message\":\""+String(WELLCOME_MESSAGE)+"\"}";
  
   String response="{\"status\":\"1\"";
   for (int i=0;i<V_memory_count;i++){
      // easy way to read a Json object without installing extra json libraries
      String jsonTag="V"+String(i)+"_";
      int pos = data.indexOf(jsonTag);
      if (pos>0) {
        int startPos= data.indexOf("{",pos+1);
        if (startPos>pos) {
          int endPos= data.indexOf("}", startPos+2);
          if (endPos>startPos) {
            String variableAsJson = data.substring(startPos,endPos+1);
            String variableValue=onCommandReceived(i,variableAsJson);
          if (variableValue.length()>0) response+=",\""+jsonTag+"\":{\"value\":\""+urlencode(&variableValue)+"\"}";
          }
        }
      }
      
   } //for
   response+="}";
  return response;
}

//==============================================================
// easy way to read a Json text value without installing extra json libraries
  String getJsonValue(String jsonAsText, String jsonTag){
    int pos = jsonAsText.indexOf(jsonTag);
    if (pos>0) {
      int startPos=jsonAsText.indexOf(":\"",pos);
      int lastPos = jsonAsText.indexOf("\"",startPos+2);
      String value=jsonAsText.substring(startPos+2,lastPos);
      value=urldecode(&value);
      if (lastPos>startPos) return value;
    }
    return "";
 }


  //=================== ENCODE - DECODE Library (included in sketch) ==========
  //=================================================================
  
  //================================================================ urldecode
String urldecode(String* str){
   String encodedString="";
    char c;
    char code0;
    char code1;
    for (int i =0; i < str->length(); i++){
        c=str->charAt(i);
      if (c == '+'){
        encodedString+=' ';  
      }else if (c == '%') {
        i++;
        code0=str->charAt(i);
        i++;
        code1=str->charAt(i);
        c = (h2int(code0) << 4) | h2int(code1);
        encodedString+=c;
      } else{
         encodedString+=c;  
      }
      yield();
    }
    
   return encodedString;
}
//================================================================ urlencode
String urlencode(String* str){
   String encodedString="";
    char c;
    char code0;
    char code1;
    char code2;
    for (int i =0; i < str->length(); i++){
      c=str->charAt(i);
      if (c == ' '){
        encodedString+= '+';
      } else if (isalnum(c)){
        encodedString+=c;
      } else{
        code1=(c & 0xf)+'0';
        if ((c & 0xf) >9){
            code1=(c & 0xf) - 10 + 'A';
        }
        c=(c>>4)&0xf;
        code0=c+'0';
        if (c > 9){
            code0=c - 10 + 'A';
        }
        code2='\0';
        encodedString+='%';
        encodedString+=code0;
        encodedString+=code1;
        //encodedString+=code2;
      }
      yield();
    }
    return encodedString;
}
//================================================================ h2int
unsigned char h2int(char c){
    if (c >= '0' && c <='9'){
        return((unsigned char)c - '0');
    }
    if (c >= 'a' && c <='f'){
        return((unsigned char)c - 'a' + 10);
    }
    if (c >= 'A' && c <='F'){
        return((unsigned char)c - 'A' + 10);
    }
    return(0);
}

Odpovědět

Kdo je online

Uživatelé prohlížející si toto fórum: Žádní registrovaní uživatelé a 0 hostů