Virtuino ESP32

127486
Offline
Зарегистрирован: 15.02.2018

Всем добра. 
Помогите разобрать кусочек кода, не могу понять его алгоритм работы, день потратил, ни чего толком не нагуглил(

 

Есть связка ESP32+Virtuino. 

После старта устанавливает TCP соединение и держит его. А вот как клиент после каждого опроса отключается и подключается заново и так по циклу. 

Вот что видно в терминале 

WiFi connected
192.168.1.150
Connected
!Q23=?$!V03=?$!V04=?$!V07=?$!V08=?$!V09=?$
Received data: !Q23=?$!V03=?$!V04=?$!V07=?$!V08=?$!V09=?$
Response : !Q23=0$!V3=0.00$!V4=0.00$!V7=0.00$!V8=0.00$!V9=0.00$
Disconnected
Connected
!Q23=?$!V03=?$!V04=?$!V07=?$!V08=?$!V09=?$
Received data: !Q23=?$!V03=?$!V04=?$!V07=?$!V08=?$!V09=?$
Response : !Q23=0$!V3=0.00$!V4=0.00$!V7=0.00$!V8=0.00$!V9=0.00$
Disconnected
 
Как сделать так чтобы он постоянно подключен был?
 
 
/* Example: ESP32 - Control PWM pins
 * Created by Ilias Lamprou
 * Modified: Sep/22/2019
 */

#include <WiFi.h>


//--- SETTINGS ------------------------------------------------
const char* ssid = "GK+1";         // enter the name (SSID) of your WIFI network
const char* password = "1274861234";         // enter your WIFI network PASSWORD
WiFiServer server(8000);                   // Default Virtuino Server port 
IPAddress ip(192, 168, 1, 150);            // where 150 is the desired IP Address. The first three numbers must be the same as the router IP
IPAddress gateway(192, 168, 1, 1);         // set gateway to match your network. Replace with your router IP
//---

//---VirtuinoCM  Library settings --------------
#include "VirtuinoCM.h"
VirtuinoCM virtuino;               
#define V_memory_count 32          // the size of V memory. You can change it to a number <=255)
float V[V_memory_count];           // This array is synchronized with Virtuino V memory. You can change the type to int, long etc.
//---


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

//-- PWM settings
const int channel_pin_17 = 0;   //  (enter a value between 0-15)
const int channel_pin_23 = 1;

int lastValuePWM_17=0;
int lastValuePWM_23=0;

//============================================================== setup
//==============================================================
void setup() {
  if (debug) {
    Serial.begin(9600);
    while (!Serial) continue;
  }
 
  virtuino.begin(onReceived,onRequested,512);  //Start Virtuino. Set the buffer to 512. With this buffer Virtuino can control about 50 pins (1 command >= 9bytes) The T(text) commands with 20 characters need 20+6 bytes
  //virtuino.key="1234";                       //This is the Virtuino password. Only requests the start with this key are accepted from the library

  connectToWiFiNetwork();
  server.begin();
  
//  pinMode(LED_BUILTIN,OUTPUT);    // On Virtuino panel add a button to control this pin
  pinMode(17, OUTPUT);            // On Virtuino panel add a regulator to control this pin
  pinMode(23, OUTPUT);            // On Virtuino panel add a regulator to control this pin
  pinMode(4, INPUT);              // On Virtuino panel add a led to get the state of this pin
  pinMode(19, INPUT);             // On Virtuino panel add a led to get the state of this pin

  //---- setup for PWM pin 17
  ledcSetup(channel_pin_17,5000,8);  // channel setup:  channel=0  freq=5000   resolution=8
  ledcAttachPin(17, channel_pin_17);  // attach the channel 0 to the pin 17

  //---- setup for PWM pin 23
  ledcSetup(channel_pin_23,5000,8);  // channel setup:  channel=1  freq=5000   resolution=8(8 bits = 0-255)
  ledcAttachPin(23,channel_pin_23);  // attach the channel 1 to the pin 23
 
  }

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

  // enter your code below. Avoid to use delays on this loop. Instead of the default delay function use the vDelay that is located on the bottom of this code
  // You don't need to add code to read or write to the pins. Just enter the  pinMode of each Pin you want to use on void setup

  //--- example to control the PWM pin 17. The virtual pin V0 contains the PWM value
  if (V[0]!=lastValuePWM_17) {           // control the PWM pin every time the V0 is changed
    ledcWrite(channel_pin_17, V[0]);     // write the value to the channel of pin 17
    lastValuePWM_17=V[0];                // store the V0 value
  }
  
  
 //--- example to control the PWM pin 23. The virtual pin V1 contains the PWM value
  if (V[1]!=lastValuePWM_23) {           // control the PWM pin every time the V0 is changed
    ledcWrite(channel_pin_23, V[1]);     // write the value to the channel of pin 17
    lastValuePWM_23=V[1];                // store the V0 value
  }
  

  //vDelay(1000);     // This is an example of the recommended delay function. Remove this if you don't need
}






/*================= Virtuino Code ==============================
You don't need to make changes to the code bellow

*/

//============================================================== connectToWiFiNetwork
void connectToWiFiNetwork(){
  Serial.println("Connecting to "+String(ssid));
   // If you don't want to config IP manually disable the next two lines
   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);                       // Config 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());
}


//============================================================== onCommandReceived
//==============================================================
/* This function is called every time Virtuino app sends a request to server to change a Pin value
 * The 'variableType' can be a character like V, T, O  V=Virtual pin  T=Text Pin    O=PWM Pin 
 * The 'variableIndex' is the pin number index of Virtuino app
 * The 'valueAsText' is the value that has sent from the app   */
 void onReceived(char variableType, uint8_t variableIndex, String valueAsText){     
    if (variableType=='V'){
        float value = valueAsText.toFloat();        // convert the value to float. The valueAsText have to be numerical
        if (variableIndex<V_memory_count) V[variableIndex]=value;              // copy the received value to arduino V memory array
    }
}

//==============================================================
/* This function is called every time Virtuino app requests to read a pin value*/
String onRequested(char variableType, uint8_t variableIndex){     
    if (variableType=='V') {
    if (variableIndex<V_memory_count) return  String(V[variableIndex]);   // return the value of the arduino V memory array
  }
  return "";
}


 //==============================================================
  void virtuinoRun(){
   WiFiClient client = server.available();
   if (!client) return;
   if (debug) Serial.println("Connected");
   unsigned long timeout = millis() + 3000;
   while (!client.available() && millis() < timeout) delay(1);
   if (millis() > timeout) {
    Serial.println("timeout");
    client.flush();
    client.stop();
    return;
  }
    virtuino.readBuffer="";    // clear Virtuino input buffer. The inputBuffer stores the incoming characters
      while (client.available()>0) {        
        char c = client.read();         // read the incoming data
        virtuino.readBuffer+=c;         // add the incoming character to Virtuino input buffer
        if (debug) Serial.write(c);
      }
     client.flush();
     if (debug) Serial.println("\nReceived data: "+virtuino.readBuffer);
     String* response= virtuino.getResponse();    // get the text that has to be sent to Virtuino as reply. The library will check the inptuBuffer and it will create the response text
     if (debug) Serial.println("Response : "+*response);
     client.print(*response);
     client.flush();
     delay(10);
     client.stop(); 
    if (debug) Serial.println("Disconnected");
}


 //============================================================== vDelay
  void vDelay(int delayInMillis){long t=millis()+delayInMillis;while (millis()<t) virtuinoRun();}

 

 
 
 
127486
Offline
Зарегистрирован: 15.02.2018

Судя по всему что весь ребус вот в этом куске кода

client.flush();
     if (debug) Serial.println("\nReceived data: "+virtuino.readBuffer);
     String* response= virtuino.getResponse();    // get the text that has to be sent to Virtuino as reply. The library will check the inptuBuffer and it will create the response text
     if (debug) Serial.println("Response : "+*response);
     client.print(*response);
     client.flush();
     delay(10);
     client.stop(); 
    if (debug) Serial.println("Disconnected");

 

Kakmyc
Offline
Зарегистрирован: 15.01.2018

Строки 150 и 166 ни на какие мысли не наводит ?

127486
Offline
Зарегистрирован: 15.02.2018

Я понимаю что они как раз разрывают соединение.
Если их закоментировать, то вообще не работает.

Про 150 логика работы ясна.

А вот про 166 я как раз и залип.

sadman41
Offline
Зарегистрирован: 19.10.2016

Вообще не работает - это как?

127486
Offline
Зарегистрирован: 15.02.2018

Не работает, это не соединяется с виртуиной, в терминале пусто. 

Собственно решил вопрос установив false в 025 строке. 
В самой виртуине поставил 0 в параметре периодичность опроса. 

Но интуиция подсказывает что это костыль.