/* VirtuinoSE example: Turn On-Off the onboard led
* Supported boards: ESP8266 & ESP32
* Created by Ilias Lamprou
* Updated Oct 27 2018
* More examples:
http://virtuino.com/index.php/virtuino- ... e-examples
*/
// ------ VirtuinoSE V Memory Table
// V1 memory -> PIN = LED_BUILTIN onboard led
#ifdef ESP8266
#include <ESP8266WiFi.h>
#else
#include <WiFi.h>
#endif
//------------------- USER SETTINGS ---------------------------------
const char* ssid = "WIFI NETWORK"; // WIFI network SSID
const char* password = "PASSWORD"; // WIFI network PASSWORD
WiFiServer wifiServer(8000); // Server port
#define VIRTUINO_KEY "1234" // Virtuino KEY, only the requests that include this key will be acceptable
//============================================================== 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, 1, 150); // where 150 is the desired IP Address
IPAddress gateway(192, 168, 1, 1); // 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());
}
//============================================================== setup
//==============================================================
void setup() {
Serial.begin(9600);
while (!Serial) {;}
connectToWiFiNetwork(); //enable this line to connect the module your wifi network
wifiServer.begin();
pinMode(LED_BUILTIN, OUTPUT);
}
//============================================================== по команде получено
//==============================================================
/ * Эта функция вызывается каждый раз, когда приложение Virtuino отправляет запрос на сервер
* «VariableIndex» - это V-память приложения Virtuino
* 'ValueAsText' - это значение, отправленное из приложения.
* Если 'valueAsText' равен?, Вы должны вернуть значение, которое вы хотите отобразить на панели Virtuino.
* /
String onCommandReceived(int variableIndex, String valueAsText){
Serial.println("=== onCommandReceived variableIndex="+String(variableIndex)+" valueAsText="+valueAsText);
// --- код для включения или выключения встроенного светодиода
if (variableIndex==1){ // Virtuino V1 memory -> бортовой свет
if (valueAsText=="?") return String(digitalRead(LED_BUILTIN)); // вернуть состояние LED_BUILTIN как текст
int v=valueAsText.toInt();
if (v==1) digitalWrite(LED_BUILTIN,HIGH); // change the state of pin LED_BUILTIN
else if (v==0) digitalWrite(LED_BUILTIN,LOW);
}
return "";ф
}
//============================================================== loop
//==============================================================
void loop() {
virtuinoRun();
}
//================== Virtuino Library (included) ===============
//==============================================================
//==============================================================
/* Для связи с Virtuino необходимы только следующие две функции * Избегайте внесения изменений в приведенный ниже код
*/
#define WRONG_KEY_MESSAGE "Wrong Key"
#define WELLCOME_MESSAGE "Hello Virtuino"
boolean debug=true;
//============================================================== virtuinoRun
//==============================================================
void virtuinoRun(){
WiFiClient client = wifiServer.available(); // Check if a client has connected
if (client) {
if (debug) Serial.println("New client");
while(!client.available())delay(1); // Wait until the client sends some data
String req = client.readStringUntil('\r'); // Read the first line of the request
if (debug) Serial.println(req);
//-- check request
int pos = req.indexOf("GET /");
if (pos!=-1){ // We have a GET message
req.remove(0,pos+5); // Clear the characters GET /
int k= req.indexOf(" HTTP/");
if (k>0) req.remove(k); // Clear the tail of the line
//---the variable req contains the Virtuino command string.
String commandResponse = prepareResponse(&req); //Prepare the text that the server has to return to app
String responseHttp= "HTTP/1.1 200 OK\r\n Content-Type: text/html\r\nConnection: close\r\n\r\n";
responseHttp+=commandResponse; // add the commandResponse to request response
responseHttp+="\r\n\r\n";
if (debug) Serial.println("ResponseHttp="+responseHttp);
client.print(responseHttp);
client.print("status:0");
delay(1);
if (debug) Serial.println("Client disonnected");
client.flush();
}
else {
Serial.println("invalid request");
client.stop();
}
}
}
//============================================================== prepareResponse
//==============================================================
String prepareResponse(String* commands){
//---check the KEY
#ifdef VIRTUINO_KEY
String virtuinoKey="";
int keyPosStart = commands->indexOf("&KEY=");
if (keyPosStart!=-1) {
int keyPosEnd = commands->indexOf('&',keyPosStart+5);
if (keyPosEnd!=-1) virtuinoKey= commands->substring(keyPosStart+5,keyPosEnd);
else virtuinoKey= commands->substring(keyPosStart);
}
if (!virtuinoKey.equals(VIRTUINO_KEY)) return WRONG_KEY_MESSAGE;
#endif
//--- read all virtuino commands from request
String commandResponse="";
boolean checkNext=true;
int cStart=-1;
while (checkNext){
cStart=commands->indexOf('&',cStart+1);
if (cStart!=-1) {
int cEnd=commands->indexOf('&',cStart+1);
String oneCommand="";
if (cEnd<0) oneCommand=commands->substring(cStart+1);
else oneCommand=commands->substring(cStart+1,cEnd);
if (debug) Serial.println("cmd: "+oneCommand);
char commandType = oneCommand.charAt(0);
if (commandType=='C') return "&CNT="+String(WELLCOME_MESSAGE); // Virtuino sends the command &C=? to check the connection status
if ((commandType=='V') || (commandType=='T')) {
int equalCharPosition = oneCommand.indexOf('=');
int variableIndex = oneCommand.substring(1,equalCharPosition).toInt();
String valueString = oneCommand.substring(equalCharPosition+1);
String returnedValue = onCommandReceived(variableIndex,valueString);
if (returnedValue.length()>0) {
commandResponse+='&';
commandResponse+=commandType;
commandResponse+=String(variableIndex);
commandResponse+='=';
commandResponse+=returnedValue;
}
}
}
else checkNext=false; // the last command has checked
}
if (debug) Serial.println("Response="+commandResponse );
if (commandResponse.length()==0) commandResponse="OK";
return commandResponse;
}