Skip to content

ZerynthApp Library

This module provides access to the Zerynth App functionalities.

The Zerynth App is an innovative mobile app designed to make interaction with Zerynth programs easy. A Zerynth App can be tought as a bidirectional communication channel between a Zerynth script running on a device and some HTML+Javascript template running on the mobile app.

A program using the ZerynthApp module must provide some components:

  • an UI template, responsible of the Javascript part
  • a set of remotely callable functions representing the channel from Javascript to Python
  • a set of events representing the channel from Python to Javascript

When the ZerynthApp class, defined in this module, is instantiated and run, it waits for messages coming from the mobile app through the Zerynth Advanced Device Manager.

ZerynthApp Step by Step

Using the “zerynthapp” module is easy.

  • First, a device template must be defined by creating the needed HTL and javascript files. The template must be uploaded to the ADM directly from Zerynth Studio or through the Zerynth Toolchain.
  • A “zerynthapp” instance must be created
  • The “zerynthapp” instance must be configured with credentials
  • The “zerynthapp” callable functions must be defined
  • The “zerynthapp” instance must be run

HTML templates

HTML templates reside on the ADM servers and are transferred from it to the mobile app where they are rendered. Javascript is needed to add some logic to the template. The task is made easier by using the Zerynth ADM Javascript library.

Templates are better explained with examples:

<!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>Zerynth</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>

  </head>
  <body>
    <div style="text-align:center">
      <p id="status" style="background:#ddd;font-weight:bold"></p>
      <h1>Hello, Zerynth!</h1>
      <div style="margin-left: 20px;margin-right: 20px">
        <button class="btn btn-primary btn-xs" onclick="Z.call('random',[0,20],random_callback)">Random!</button>
      </div>
      <div id="number"></div>
    </div>
    <script>

    //callback for remote random method
    function random_callback(msg){
        $("#number").html(msg.res)
    }


    $(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));
        }
      })
    });
    </script>
  </body>
</html>

In the body section, the html scaffolding is layed out and logic is inserted to link the template events with the functions running on the device. For example, in the onclick part of the button a RPC to the method “random” is generated by using the construct Z.call(method,parameters,callback). All the parameters are encoded, sent to the device, and used as arguments of the corresponding Python function. The Z.call function is the channel from Javascript to Python.

Everytime the device will send an event, such event will be passed to the on_event callback of the Z object. Parameters can be passed to the event function and transmitted to the mobile app. The event method of the ZerynthApp instance is the channel from Python to Javascript.

Zerynth App Instances

A template must be coupled with a Zerynth script running on a device. Here it is an example:

from wireless import wifi
# this example is based on Particle Photon
# change the following line to use a different wifi driver
from broadcom.bcm43362 import bcm43362 as wifi_driver
import streams

# Import the Zerynth APP library
from zerynthapp import zerynthapp

streams.serial()

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

# define a RPC function: generate a random number
def do_random(a,b):
    return random(a,b)

# send events on button pressed
def on_btn():
    zapp.event({"my_button":"pressed"})

onPinFall(BTN0,on_btn,debounce=1000)

zapp = zerynthapp.ZerynthApp("DEVICE UID HERE", "DEVICE TOKEN HERE", log=True)

# link "random" to do_random
zapp.on("random",do_random)

try:
    # connect to the wifi network (Set your SSID and password below)
    wifi_driver.auto_init()
    for i in range(0,5):
        try:
            wifi.link("NETWORK SSID",wifi.WIFI_WPA2,"NETWORK PASSWORD")
            break
        except Exception as e:
            print("Can't link",e)
    else:
        print("Impossible to link!")
        while True:
            sleep(1000)

    # Start the Zerynth app instance!
    zapp.run()

    # Do whatever you need here
    while True:
        print(".")
        sleep(5000)

except Exception as e:
    print(e)

This simple script connects to the local Wifi network, configures and runs a ZerynthApp instance. The method on is called to configure the Javascript-to-Python channel: everytime a call to “random” is remotely requested from Javascript, the function do_random is called in the Zerynth script. When the device button is pressed, the event method is called, and the event is transferred to the mobile app, where Javascript, configured in the template, updates a label.

The ZerynthApp class

class ZerynthApp(uid, token, ip=None, address="things.zerynth.com", log=False)

Creates a ZerynthApp instance or the device with uid uid and token token. If log is True, some debug messages are printed. If ip is given, it tries to connect to the ADM instance hosted at ip (default ip is 178.22.65.123). If address is given, it tries to connect to the ADM instance hosted ad address url (default address is “things.zerynth.com”).

on(method, fn)

Associates the method name method to the callable fn. Everytime the ZerynthApp instance receives a request for method from the mobile app, the callable fn is executed (possibly with arguments).

event(payload)

Sends an event with payload payload to the mobile app.

notify(title, text)

Sends a push notification to connected apps with title title and text text.

run()

Starts the ZerynthApp instance on a separate thread and returns immediately.