TOI - Things on Internet
Published © GPL3+

Remote Controlled Relays Using ESP32, Python And Javascript

How to remotely control the relays integrated on 4zerobox (industrial board based on ESP32) using Zerynth (Python + JS).

IntermediateFull instructions provided2 hours5,096
Remote Controlled Relays Using ESP32, Python And Javascript

Things used in this project

Hardware components

ESP32S
Espressif ESP32S
×1
Relay (generic)
×1
4zerobox
×1

Software apps and online services

Zerynth Studio
Zerynth Studio

Story

Read more

Schematics

feature_tAQ1rRj3Sz.png

Code

main.py

Python
# DEMO relay

import streams
from wireless import wifi

from espressif.esp32net import esp32wifi as wifi_driver
from zerynthapp import zerynthapp

streams.serial()

sleep(1000)
print("STARTING...")

relay_1 = D23
relay_2 = D22

pinMode(relay_1,OUTPUT)
pinMode(relay_2,OUTPUT)

digitalWrite(relay_1,0)
digitalWrite(relay_2,0)

# define a function to control relay
def set_relay(relay,status):
    if relay == 1:
        pin = relay_1
    else:
        pin = relay_2
    print("relay:",relay,"status:",status)
    digitalWrite(pin,status)
        

try:
    device_uid = 'bK1-MP0eTY-D3-N_13Jw5w'
    device_tkn = '8KH18QopQg2E3sKlBWTU6w'
    zapp = zerynthapp.ZerynthApp(device_uid, device_tkn, log=True)
except Exception as e:
    print(e)

# link "control" to set_relay
zapp.on("control",set_relay)

try:
    
    ssid = 'Zerynth'
    pwd = 'zerynthwifi'
    
    wifi_driver.auto_init()
    for i in range(0,5):
        try:
            wifi.link(ssid,wifi.WIFI_WPA2,pwd)
            break
        except Exception as e:
            print("Can't link",e)
    else:
        print("Impossible to link!")
        while True:
            sleep(1000)

    # Start the Zerynth app instance!
    # Remember to create a template with the files under the "template" folder you just cloned
    # upload it to the ADM and associate it with the connected device
    zapp.run()
    
    while True:
        print("4ZeroBox DEMO RELAY running...")
        sleep(5000)
        
except Exception as e:
    print(e)

index.html

HTML
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <title>4ZeroBox</title>
    <!-- LOAD JQUERY AND BOOTSTRAP -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <!-- LOAD THE ZERYNTH ADM JS LIBRARY -->
    <script src="https://api.zerynth.com/zadm/latest/z.js"></script> 
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/css/bootstrap3/bootstrap-switch.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/js/bootstrap-switch.js"></script>
  <style>
      .led-box {
          height: 30px;
          width: 25%;
          margin: 10px 0;
          float: left;
        }
        
        .led-box p {
          font-size: 12px;
          text-align: center;
          margin: 1em;
        }
        .led-yellow {
          margin: 0 auto;
          width: 24px;
          height: 24px;
          background-color: #FF0;
          border-radius: 50%;
          box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 7px 1px, inset #808002 0 -1px 9px, #FF0 0 2px 12px;
}
  </style>
  </head>
  <body>
    <div style="text-align:center">
      <p id="status" style="background:#ddd;font-weight:bold"></p>
      <img src="img/logo_4zerobox_payoff.png" style="width:50%">
      <h2>DEMO RELAY</h2>
      <center>
      <br>
      <table style="width:40%">
          <tr style="height:120px">
              <td>
                <center>
                <div class="led-box" style="width:100%">
                  <div class="led-yellow" style="background-color:#AAAA00" id="ly1"></div>
                  <p style="font-size:15px;">Lamp 1</p>
                </div>
                </center>
              </td>
              <td>
                <div class="led-box" style="width:100%">
                  <center>
                  <div class="led-yellow" style="background-color:#AAAA00" id="ly2"></div>
                  <p style="font-size:15px;">Lamp 2</p>
                  </center>
                </div>
              </td>
          </tr>
          <tr>
              <td>
                  <center>
                  <input type="checkbox" name="relay1">
                  </center>
              </td>
              <td>
                  <center>
                  <input type="checkbox" name="relay2">
                  </center>
              </td>
          </tr>
      </table>
      </center>
    </div>
    
    <script>

    //callback for remote random method
    function control_callback(msg){
        $("#number").html(msg.res)
    }
    
    $("[name='relay1']").bootstrapSwitch();
    $("[name='relay2']").bootstrapSwitch();

    $(document).ready(function() {
      // initialize the Z object
      Z.init({
        on_connected:  function(){$("#status").html("CONNECTED")},
        on_error:  function(){$("#status").html("ERROR")},
        on_disconnected:  function(){$("#status").html("DISCONNECTED"); return true},
        on_online:  function(evt){$("#status").html("ONLINE");},
        on_offline:  function(evt){$("#status").html("OFFLINE");},
        on_event:  function(evt){
            //display received event
            $("#status").html("EVENT!"+JSON.stringify(evt)); 
        }
      })
    });
    
    $('input[name="relay1"]').on('switchChange.bootstrapSwitch', function(event, state) {
      console.log(state); // true | false
      if (state == false) {
          var led = document.getElementById( "ly1" );
          led.style.backgroundColor = '#AAAA00';
          Z.call('control',[1,0],control_callback);
      }
      else{
          var led = document.getElementById( "ly1" );
          led.style.backgroundColor = '#FFFF00';
          Z.call('control',[1,1],control_callback);
      }
    });
    $('input[name="relay2"]').on('switchChange.bootstrapSwitch', function(event, state) {
      console.log(state); // true | false
      if (state == false) {
          var led = document.getElementById( "ly2" );
          led.style.backgroundColor = '#AAAA00';
          Z.call('control',[2,0],control_callback);
      }
      else{
          var led = document.getElementById( "ly2" );
          led.style.backgroundColor = '#FFFF00';
          Z.call('control',[2,1],control_callback);
      }
    });
    
    </script>
  </body>
</html>

Credits

TOI - Things on Internet
4 projects • 20 followers
TOI is the creator of 4zerobox: the Industrial Toolkit for IoT Solution Providers. Live now on Kickstarter: https://bit.ly/get-4zerobox
Contact

Comments

Please log in or sign up to comment.