Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
outside the Wi-Fi network
#1
hello good I wanted to know what code to use to activate the signals from outside the house from another place thanks a greeting. 
that is from outside the Wi-Fi network with the GSM.
I forgot to tell you that I work with a Wemos D1 mini Pro.
I don't want to put an ethernet card to make it Wi-Fi. thanks for your help i'm stuck. 
the code used is websockets not if I have to open ports in the router what is the best option

Code:
I have done the project with Arduino WS. I don't want to put an ethernet card to make it Wi-Fi. thanks for your help i'm stuck



/* Virtuino Iot example: ESP8266 Read/Write to digital pins
* Supported boards: all ESP8266 boards
*
* This example contains the following features
* 1. How to read enable an Arduino led from Virtuino dashboard
* 2. How to send the state of an arduino pin to Virtuino dashboard

* Created by Ilias Lamprou
* Updated Apr 11 2022
*/
/*Los pines utilizados son:
* D0 GPIO 16 sensor magnetico que regitra la entrada de un intruso en caso de que se abra la puerta estando activada
* D1 GPIO 5 abre portal 3 seg
* D2 GPIO 4 detecta el pin manual y regula la señal envia a arduino si no se abriria y cerraria debido al tiempo de manualizado del boton
* D3 GPIO 0 oesta libre para usar con señal de TENSION en un futuro se pone en alto al reiniciar el modulo
* D4 GPIO 2 esta salida manda la señal de apertura de puerta de entrada a casa
* D5 GPIO 14 este pin esta puenteado con el D2 y registra el alto de boton manualizado D2 para contar cuando esta alto y bajo uno si y uno no se pone en alt
* D6 GPIO 12 rele activa la larma sonora. tambien se puede forzar su activacion con un boton en el telefono
* D7 GPIO 13 asociado a señal de telefono para activar la apertura o cierre de puerta (este pin es virtual solo registra los pulsos )
* D8 GPIO 15 testigo de pinpuerta para mantener el pin activo o no activo para contar el pulso
*/
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h> // Download the library WebSockets by Markus Sattler from arduino library manager (ver 2.3.5)

//--- SETTINGS ----------------------------------------
  const char* ssid = "xxxxxxxx";                      // WIFI network SSID
  const char* password = "xxxxxxx";              // WIFI network PASSWORD
  WebSocketsServer webSocket = WebSocketsServer(8000); // Default Virtuino Server port = 8000
  IPAddress ip(192, 168, 1, 145);                    // 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

//---- Enter all the Tags here. You have to use the same Tags on Virtuino variables
  const char* pin0_tag= "V0";        // tag for digital input sensor magnetico
  const char* pin1_tag= "V1";        // tag for digital output apertura portal
  const char* pin2_tag= "V2";        // tag for digital output señal arduino
  const char* pin3_tag= "V3";        // señal para mandar correo alarma
  const char* pin4_tag= "V4";
  const char* pin6_tag= "V6";        // tag for digital output manual alarma
  const int senspuer = 16;    //D0 GIOP 16 sensor magnetico
  const int coalarma = 0;    //D3 GPIO5 correo alarma
  const int relealarm = 12; //D6 GPIO12 rele activa la larma sonora
  const int abrircasa = 13;  //D7 GPIO13 asociado a señal de telefono para activar la apertura o cierre de puerta
  const int pinse = 15;    //D8 testigo de pinpuerta para mantener el pin activo o no activo para contar el pulso
  const int copuab= 2;      //D4 GPIO2 correo puerta abierta

unsigned long tiempoasignado1/*se va sumando al anterior*/ = 0;       

  // add more here like the next lines...
  // const char* pin2_tag= "V2";
  // const char* pin8_tag= "V8";

//---- Enter some variables to hold the last state of the inputs.
  uint8_t pin0_lastValue=0;
  uint8_t pin1_lastValue=0;
  uint8_t pin2_lastValue=0;
  uint8_t pin3_lastValue=0;
  uint8_t pin4_lastValue=0;
  uint8_t pin6_lastValue=0;

  // add more here like the next lines...
  // uint8_t pin2_lastValue=0;
  // uint8_t pin8_lastValue=0;


//===================================================== sendPinStatus
// It is called every time a new client is connected.
// The void informs Virtuino app about the current pin states and variable values.

void sendPinsStatus(){
  sendValue(pin0_tag, String(digitalRead(D0)));    // send the digital input D0 state
  sendValue(pin1_tag, String(digitalRead(D1)));    // send the digital input D1 state
  sendValue(pin2_tag, String(digitalRead(D2)));    // send the digital input D2 state
  sendValue(pin3_tag, String(digitalRead(D3)));    // send the digital input D3 state
  sendValue(pin4_tag, String(digitalRead(D4)));    // send the digital input D4 state   
  sendValue(pin6_tag, String(digitalRead(D6)));    // send the digital ouput D6 state


  // add more here like the next lines...
  // sendValue(pin2_tag, String(digitalRead(D2)));
  // sendValue(pin8_tag, String(digitalRead(D8)));
  }

//===================================================== onValueReceived
// It is called every time a new value received
  void onValueReceived(String tag, String value){
    Serial.println("Received: tag="+tag+ "  value="+value);

    if (tag== pin0_tag) {                    // write to digital pin D1
      int v=value.toInt();
      if (v==1) digitalWrite(D0,HIGH); else digitalWrite(D0,LOW);
    }
    if (tag== pin1_tag) {                    // write to digital pin D1
      int v=value.toInt();
      if (v==1) digitalWrite(D1,HIGH); else digitalWrite(D1,LOW);
    }
    if (tag== pin2_tag) {                    // write to digital pin D2
      int v=value.toInt();
      if (v==1) digitalWrite(D2,HIGH); else digitalWrite(D2,LOW);
    }
    if (tag==pin3_tag) {                    // write to digital Output D3
     
      int v=value.toInt();
      if (v==1) digitalWrite(D3,HIGH); else digitalWrite(D3,LOW);
    }
    if (tag==pin4_tag) {                    // write to digital Output D4
     
      int v=value.toInt();
      if (v==1) digitalWrite(D4,HIGH); else digitalWrite(D4,LOW);
    }
    if (tag== pin6_tag) {                    // write to digital pin D6
      int v=value.toInt();
      if (v==1) digitalWrite(D6,HIGH); else digitalWrite(D6,LOW);
    }
   

    }

//===================================================== setup
//=====================================================
  void setup() {
      Serial.begin(115200);
      while (!Serial) delay(1);
      //pinMode(D0,INPUT);                  // entrada sensor magnetico D0
      pinMode(D1,OUTPUT);                // salida abrir portal
      pinMode(D2,OUTPUT);                // señal abrir puerta casa
      //pinMode(D3,INPUT);                // señal para correo de alarma
      //pinMode(D4,INPUT);                // señal para correo puerta abierta
      pinMode(D6,OUTPUT);                // manual alarma
      pinMode(coalarma,OUTPUT);
      pinMode(senspuer, INPUT);    //pin D0(gpio16)sensor de puerta magnetico
      pinMode(relealarm, OUTPUT);  //pin D6(gpio12)rele activa la larma sonora
      pinMode(abrircasa, OUTPUT);  //asociado a señal de telefono para activar la apertura o cierre de puerta
      pinMode(pinse, OUTPUT);
      pinMode(copuab, OUTPUT);    //D3 pin activacion correo puerta

      connectToWiFiNetwork();
      webSocket.begin();
      webSocket.onEvent(webSocketEvent);
  }

//===================================================== loop
//=====================================================
  void loop() {
      webSocket.loop();   

      //---Example: How to send a Digital Input state to Virtuino app every time it changes
    int pin0= digitalRead(D0);            // read the new state
      if (pin0_lastValue != pin0) {        // compare with the previous input state
        sendValue(pin0_tag, String(pin0));  // send the new state
        pin0_lastValue=pin0;                // copy the new state to variable pin7_lastValue
      }


      //---Example: How to send a Digital Input state to Virtuino app every time it changes
/*    int pin8= digitalRead(D8);            // read the new state
      if (pin8_lastValue != pin8) {        // compare with the previous input state
        sendValue(pin8_tag, String(pin8));  // send the new state
        pin8_lastValue=pin8;                // copy the new state to variable pin8_lastValue
      }
*/
      //--- Attention: Don't add a line like the next. It will send values to Virtuino app on each loop circle.
      // sendValue(pinD0_tag, digitalRead(D0));

      // avoid to use the void Delay() in your code. This causes communication delays
      // vDelay(1000);  // Use the vDelay() instead of Delay() or better none of them

      // add your code here...
unsigned long tiempoahora1 = millis();
  int pinstate3 =0;
  int pinstate = 0;
  pinstate3=digitalRead(4);//D2
  pinstate=digitalRead(14);//pin D5

  if(pinstate==HIGH)
  {
      int estadoanterior = 0;
      int estado = 0;  //guardar el estado del boton
      estado = digitalRead(abrircasa);
      delay(400);   
      digitalWrite(abrircasa,HIGH);
      int salida = 0;  //0= led esta apagado, 1=led encendido
    if ((estado == HIGH) && (estadoanterior == LOW)) //lee el estado del led si encendido ejecuta este ciclo
    {
       
      salida = 1 - salida;          //si esta encendido le resta 1 queda en apagado
     
        if(pinstate3==HIGH)//detecta el pin manual y regula la señal envia a arduino si no se abriria y cerraria debido al tiempo de manualizado del boton
        {
          digitalWrite(D2, HIGH);
          delay(50);
          digitalWrite(D2, LOW);
          delay(2000);
        Serial.println("se ejecutaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ");
          int senspuer1=0;
          senspuer1 = digitalRead(16);
          if(senspuer1==LOW)
          {
            digitalWrite(copuab, HIGH);
            int pin4= digitalRead(D4);            // read the new state
            if (pin4_lastValue != pin4) {        // compare with the previous input state
            sendValue(pin4_tag, String(pin4));  // send the new state
            pin4_lastValue=pin4;// copy the new state to variable pin7_lastValue
         
            }
         
            digitalWrite(copuab, LOW);
            Serial.println("puerta abierta!!!!!! ");
          }
        }
      digitalWrite(pinse, LOW);
      delay(100);
      digitalWrite(relealarm, LOW);
      digitalWrite(abrircasa,LOW);
      Serial.println("desactivando alarma!!!!!! ");
      delay(100);
      Serial.println(salida);
    }

  else
    {
      if(pinstate3==HIGH)
      {
      digitalWrite(D2, HIGH);
      delay(50);
      digitalWrite(D2, LOW);
      Serial.println("se ejjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj ");
      }
   
      Serial.println("activando alarma¡¡¡¡¡¡¡ ");
      digitalWrite(pinse, HIGH);
      delay(2000);
    }

  }
   
  int pupor=0;
  pupor= digitalRead(D1);
  if(pupor == HIGH)
    {
    Serial.println("abriendo puerta portal");
   

    digitalWrite(D1,HIGH);
    delay(3000);
    digitalWrite(D1,LOW);
    }
    int i=0;
    int estad = 0;
    int pinstate2 = 0;
    pinstate2=digitalRead (16);
    estad=digitalRead(pinse);
  if((estad==HIGH) && (pinstate2 == LOW))
  {
    if (tiempoahora1 - tiempoasignado1 >= 20000)

    {
   
     
    Serial.println("puerta abierta robo");
    Serial.println(millis());
    digitalWrite(coalarma,HIGH);   
      int pin3= digitalRead(D3);            // read the new state
      if (pin3_lastValue != pin3) {        // compare with the previous input state
        sendValue(pin3_tag, String(pin3));  // send the new state
        pin3_lastValue=pin3;                // copy the new state to variable pin7_lastValue
      delay(100);
      }
     

    digitalWrite(coalarma,LOW);
    tiempoasignado1=tiempoahora1;
     
     
    }


  }
      delay(100);
      int pin3= digitalRead(D3);            // read the new state
      if (pin3_lastValue != pin3) {        // compare with the previous input state
        sendValue(pin3_tag, String(pin3));  // send the new state
        pin3_lastValue=pin3;                // copy the new state to variable pin7_lastValue
      }
       
      int pin4= digitalRead(D4);            // read the new state
      if (pin4_lastValue != pin4) {        // compare with the previous input state
        sendValue(pin4_tag, String(pin4));  // send the new state
        pin4_lastValue=pin4;                // copy the new state to variable pin7_lastValue
      }

     
  }









/*=====================================================
  ======================  UTILS =======================
  =====================================================
  You don't need to make changes to the code below
*/
//===================================================== connectToWiFiNetwork
void connectToWiFiNetwork(){
  Serial.println("Connecting to "+String(ssid));
  // If you don't want to config IP manually disable the next two lines and the disables IPAddress variables  at the top of the code
  //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("\nWiFi connected");
  Serial.println(WiFi.localIP());              // Insert this IP on Virtuino IoT server settings
}


//===================================================== sendValue
// This function sends a value to a Tag.
// The tag and the value are converted to a json message before sending

bool sendValue(const char* tag, String value){
  String json = "{\"";
  json+=tag;
  json+="\":\"";
  json+=value;
  json+="\"}";
  Serial.println("Send: "+json);
  return webSocket.broadcastTXT(json);    // This function sends the message to all connected clients.
}

//===================================================== webSocketEvent
//This is the server handler. It receives all the messages

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[%u] Disconnected!\n", num);
            break;
        case WStype_CONNECTED:{
            IPAddress ip = webSocket.remoteIP(num);
            Serial.printf("[%u] New client connected - IP: %d.%d.%d.%d \n", num, ip[0], ip[1], ip[2], ip[3]);
            sendPinsStatus();        // send the initial pin and variable values to the connected clients
            break;
        }
        case WStype_TEXT:  // a new message received
            Serial.printf("[%u] Received: %s\n", num, payload);
            //-- The incoming payload is a json message. The following code extracts the value from json without extra library
            String str = (char*)payload;
            int p1 = str.indexOf("{\"");
            if (p1==0) {
              int p2 = str.indexOf("\":");
              if (p2>p1) {
                String tag = str.substring(p1+2,p2);
                p1 = str.indexOf(":\"",p2);
                if (p1>0) {
                  p2 = str.lastIndexOf("\"}");
                  if (p2>0){
                      String value = str.substring(p1+2,p2);
                      onValueReceived(tag,value);       
                    }
                  }
                }
            }
            break;
    }
}


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


Reply
#2
Hi,

you don't need to make changes on the arduino code

1. you have to enable the port forward for the server port 8000 in your router settings
2. On Virtuino app the only thing you have to do, is to replace the internal ip with you external router ip in the connection settings

This is an article about these settings for the older app Virtuino 6.
https://virtuino.com/index.php/virtuino/...connection
Reply
#3
Good morning, your solution has not worked for me but I keep trying, thank you very much for your help first of all,
with the IP inside my house it works perfectly. The problem comes when I try to do it from outside my network.
I can't even do it with the tutorial you provided.
As you can see, I also configure the ports in the router, but even so,
I still do not connect with GSM and disabled the antivirus and the firewall the Windows Defender and there is no way to connect it either.
I have also tried to do it with the ip that you provide me on the phone from your browser but it does not connect either. I don't know what else to do, please, since I bought the application, I would like it to work.
Thank you for your help and good morning.
Let's see if we all manage to make it work for me. Greetings and I hope your help. Thank you.
                   
Reply
#4
Hi, the settings seems to be correct.

There are too many tools in the internet that they can help you to check if the port 8000 is open.
You have to be sure for this before you test the project.

The phone has to be connected to the "data connection" before you test the external ip address.
Reply
#5
ok, it's solved, thank you very much, it was a CG NAT problem, it wasn't open, so thank you very much for your help and I'm sorry for the inconvenience, greetings
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)