def connectToLocalNetwork():
    wifi_driver.auto_init()
    try:
        wifi.link(WIFI_SSID, wifi.WIFI_WPA2, WIFI_PASS)
    except Exception as e:
        print("Can't connect to WiFi - Check network name and password", e)
        while True:
            sleep(1000)
示例#2
0
def wifi_connect():
    print("Establishing wifi Link...")
    try:
        wifi.link("TP-LINK_5D60C9", wifi.WIFI_WPA2, "69303050")
        print("wifi Link Established")
    except Exception as e:
        print("ooops, something wrong while linking :-(", e)
        while True:
            sleep(1000)
示例#3
0
def init_wifi():
    wifi_driver.auto_init()
    for _ in range(5):
        try:
            print("connect wifi")
            wifi.link("your_wifi_id", wifi.WIFI_WPA2, "your_wifi_pass")
            print("connect wifi done")
            break
        except Exception as e:
            print("wifi connect err", e)
示例#4
0
def link(ssid, password, sec=WPA2, attempts=5, delay=2000):
    exc = None
    for _ in range(attempts):
        try:
            wifi.link(ssid, sec, password)
            break
        except Exception as e:
            exc = e
            sleep(delay)
    else:
        raise exc
示例#5
0
def init_rtc():
    while True:
        try:
            wifi.link(SSID, wifi.WIFI_WPA2, PASSWORD)

            timestamp = int(json.loads(requests.get("http://now.zerynth.com/").content)['now']['epoch'])
            rtc.set_utc(timestamp)

            wifi.unlink()
            break
        except Exception as e:
            mcu.reset()
示例#6
0
def f_state_wifi_configure():
    """ ### ### ### ###
    # WIFI_CONFIGURE: if wifi connection settings 
    # are unknown then try to connect to a 
    # predifined network that allows the storage
    # of updated wifi connection params
    # it opens a server listening at 87246
    # it expect a MessageConfig with the new
    # settings. If everything goes right then a 
    # new config file is stored in flash memory
    # and the state machine is re-set to CONFIG
    # it accesses the global variables so 
    # include the following in your file:
    # from memory_context include *
    ### ### ### ### """
    print("STATE WIFI_CONFIGURE")
    # connect to the standard wifi to configure
    # wifi settings
    for retry in range(10):
        try:
            wifi.link(mem.my_config.wifi_net, wifi.WIFI_WPA2, mem.my_config.wifi_pwd)
            
        except Exception as e:
            print(e)

    
    if wifi.is_linked():
        test_socket = socket.socket()
        test_socket.bind(('', WiDCCProtocol.SERVER_PORT))
        test_socket.listen(1)
        test_client, _ = test_socket.accept()
        msg = ''
        while 1:
            data = test_client.recv(64)
            msg += data
            if not data:
                break
        test_client.close()
        test_socket.close()
        try:
            message = WiDCCProtocol.read_message(msg)
            if message.msg_type == WiDCCProtocol.MsgTypes.WIFI_CONFIG:
                #mem.my_config.loco_id = message.loco_id
                mem.my_config.wifi_net = message.wifi_net
                mem.my_config.wifi_pwd = message.wifi_pwd
                mem.my_config.save()
                mem.my_state = mem.States.CONFIG            
        except:
            pass         
        wifi.unlink()
        
    else:
        sleep(500)
def connectWifi(SSID, PASSWORD):
    print("Connecting to Wi-Fi router...")

    for i in range(0, 5):
        try:
            wifi.link(SSID, wifi.WIFI_WPA2, PASSWORD)
            break
        except Exception as e:
            print("Error: ", e)
        else:
            print("Cannot connect.")
            while True:
                sleep(1000)
示例#8
0
 def loop_failure(self):
     print("Loop Failure!")
     while True:
         try:
             if not wifi.is_linked():
                 print("WiFi was not linked. Relinking...")
                 wifi.link(SSID, wifi.WIFI_WPA2, PASSWORD)
             print("Attempting to reconnect...")
             self.reconnect()
             break
         except Exception as e:
             pass
         sleep(5000)
     return mqtt.RECOVERED
示例#9
0
def wifi_connect():
    for retry in range(10):
        try:
            print("Establishing Link...")
            wifi.link(wifi_ssid, wifi_secu, wifi_pass)
            print("Link Established")
            digitalWrite(GREEN, HIGH)
            break
        except Exception as e:
            print("ooops, something wrong while linking :(", e)
            digitalWrite(GREEN, LOW)
            digitalWrite(RED, HIGH)
            sleep(1000)
            digitalWrite(RED, LOW)
            sleep(1000)
示例#10
0
def connectWifi(SSID, PASSWORD):
    print("Connecting to Wi-Fi router...")
    
    for i in range(0,5):
    try:
        wifi.link(SSID,wifi.WIFI_WPA2,PASSWORD)
        break
    except Exception as e:
        print("Error: ", e)
    else:
        print("Cannot connect.")
        while True:
            sleep(1000)
            


def on_switch():
    digitalWrite(D5,LOW)
    print("ON")

def off_switch():
    digitalWrite(D5,HIGH)
    print("OFF")
    




# Intialize APP
pinMode(RELAY_PIN, OUTPUT)
wifi_driver.auto_init()
connectWifi(SSID,PASSWORD)
info = wifi.link_info()
print("Connected to WiFI IP:",info[0])

zapp = zerynthapp.ZerynthApp(UID, TOKEN, log=True)
zapp.on("on_switch", on_switch)
zapp.on("off_switch",off_switch)
zapp.run()

while True:
    try:
        sleep(1000)
    except Exception as e:
        print("Error: ",e)
示例#11
0
def connect():
    from espressif.esp32net import esp32wifi as wifi_driver
    wifi_driver.auto_init()

    print("Establishing Link...")
    while True:
        try:
            return wifi.link(SSID, wifi.WIFI_WPA2, PASSWORD)
        except Exception as e:
            print("Wifi Linking failed. Attempting to reconnect...")
        sleep(5000)
示例#12
0
def f_state_wifi_start():
    """ ### ### ### ###
    # WIFI START: if wifi connection settings are
    # are known then try to connect to the network
    # it accesses the global variables so 
    # include the following in your file:
    # from memory_context include *
    ### ### ### ### """
    print("STATE WIFI_START")
    
    for retry in range(10):
        try:
            wifi.link(mem.my_config.wifi_net, mem.wifi.WIFI_WPA2, mem.my_config.wifi_pwd)
            
        except Exception as e:
            mem.my_state = mem.States.WIFI_CONFIGURE
            print(e)

    sleep(250)
    if wifi.is_linked():
        mem.my_state = mem.States.WIFI_TCP_LINK
示例#13
0
def connect():
    """
    Connects the board to the wifi.
    """
    if WIFI_PASSWORD == "WIFI_PASSWORD":
        print("CHANGE WIFI NAME AND PASSWORD VALUES IN SOURCES/WIFI_CONNECTION.PY")
        return False

    wifi_driver.auto_init()

    try:
        num_tries = 3
        for i in range(num_tries):
            print("connecting to WIFI... " + str(i+1) + "/" + str(num_tries))
            wifi.link(WIFI_NAME, wifi.WIFI_WPA2, WIFI_PASSWORD)
            print("done")
            return True
        else:
            print("Could not connect.")
            return False
    except Exception as e:
        print("Could not connect to WIFI. Error:", e)
        return False
示例#14
0
from zerynthapp import zerynthapp

streams.serial()

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

try:
    # Device UID and TOKEN can be created in the ADM panel
    zapp = zerynthapp.ZerynthApp("DEVICE UID", "DEVICE TOKEN", log=True)

    # connect to the wifi network (Set your SSID and password below)
    wifi_driver.auto_init()
    for i in range(0,5):
        try:
            wifi.link("SSID",wifi.WIFI_WPA2,"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!
    # 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()
    
    # Read ADC and send values to the ADM
    while True:
示例#15
0
# use the wifi interface to link to the Access Point
# change network name, security and password as needed

relay = D17

pinMode(relay, OUTPUT)
digitalWrite(relay, 1)

while True:

    print("Establishing Link...")
    try:
        # FOR THIS EXAMPLE TO WORK, "Network-Name" AND "Wifi-Password" MUST BE SET
        # TO MATCH YOUR ACTUAL NETWORK CONFIGURATION
        wifi.link("WIFI-SSID", wifi.WIFI_WPA2, "WIFI-PW")
    except Exception as e:
        print("ooops, something wrong while linking :(", e)

    ## let's try to connect to timeapi.org to get the current UTC time
    for i in range(3):
        try:
            print("Trying to connect...")
            # go get that time!
            # url resolution and http protocol handling are hidden inside the requests module
            response = requests.get(
                "http://worldtimeapi.org/api/timezone/Europe/Budapest")
            # let's check the http response status: if different than 200, something went wrong
            #print("Http Status:",response.status)
            # if we get here, there has been no exception, exit the loop
            break
示例#16
0
#################################################################
#################################################################

# BEGIN
print(' LOG | BOARD | Start')
try:
    global port
    my_init()  # START OF HTU21
    init_HTU21D(port)
    wifi_driver.auto_init()
    sleep(3000)

    for retry in range(20):
        print(' LOG | BOARD | Connecting...')
        try:
            wifi.link('iPhone', wifi.WIFI_WPA2, 'ciaociao')
            print(' LOG | BOARD | Connected to wifi')
            break
        except IOError:
            sleep(1000)
    sleep(1000)
    print(' LOG | BOARD | Connecting to Zerynth App...')
    zapp = zerynthapp.ZerynthApp(uid, token)
    print(' LOG | BOARD | zapp object created!')

    # ZERYNTH APP ASSOCIATION FUNCTION

    zapp.on('event', event_receiver)
    zapp.on('is_saved', is_plant_saved)

    print(' LOG | BOARD | Start the app instance...')
示例#17
0
                "DEVICE-TOKEN-HERE",
                log=False,
                fota_callback=fota_callback)

try:
    # Get information about the currently running configuration
    # Check documentation here: https://docs.zerynth.com/latest/official/core.zerynth.stdlib/docs/official_core.zerynth.stdlib_fota.html
    rec = fota.get_record()
    bcslot = rec[4]
    valid_runtime = rec[0]

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

    # Start the device instance!
    # It immediately returns while a background thread keeps trying to connect and receive messages
    z.start()

    # Do whatever you need here
    if valid_runtime:
        msg = "Hello, this is Bytecode running on slot " + str(bcslot)
示例#18
0
from drivers.wifi.cc3000 import cc3000_tiny as cc3000
# and also import the viperapp module
from libs.apps import viperapp


streams.serial()

# save the template.html in the board flash with new_resource
new_resource("template.html")

# connect to a wifi network
try:
    cc3000.auto_init()

    print("Establishing Link...")
    wifi.link("Network-Name",wifi.WIFI_WPA2,"Wifi-Password")
    print("Ok!")        
except Exception as e:
    print(e)

    
#### ViperApp Setup    
    
# :: Javascript to Python ::
# the following function will be called when the template button is pressed
def show_message(msg):
    print(msg)

# :: Python to Javascript ::
# the following function sends messages to the mobile app
# labelling them as "btn" events
示例#19
0
    config.led_start_transaction()
    temp, hum = sensor.get_temp(), sensor.get_hum()
    thing.mqtt.publish(config.config['TOPIC'], {'touch': True})
    send_eth_transaction(temp, hum)
    config.led_end_transaction()
    tx_mutex.release()


ser_ch = streams.serial()
config.led_init()

wifi_driver.init()
for _ in range(3):
    try:
        print("> Establishing Link...")
        wifi.link(config.config['SSID'], wifi.WIFI_WPA2, config.config['PSW'])
        break
    except Exception as e:
        print("> ooops, something wrong while linking :(")
else:
    mcu.reset()
print("> linked!")

tx_mutex = threading.Lock()
endpoint, thingname, clicert, pkey = default_credentials.load()
mqtt_id = ''.join(['%02x' % byte
                   for byte in mcu.uid()])  # derive unique id from mcu uid
thing = iot.Thing(endpoint, mqtt_id, clicert, pkey, thingname=thingname)

print("> connecting to mqtt broker...")
thing.mqtt.connect()
示例#20
0
from espressif.esp32net import esp32wifi as wifi_driver

streams.serial()

# init the wifi driver!
# The driver automatically registers itself to the wifi interface
# with the correct configuration for the selected board
wifi_driver.auto_init()

# use the wifi interface to link to the Access Point
# change network name, security and password as needed
print("Establishing Link...")
try:
    # FOR THIS EXAMPLE TO WORK, "Network-Name" AND "Wifi-Password" MUST BE SET
    # TO MATCH YOUR ACTUAL NETWORK CONFIGURATION
    wifi.link("Zerynth",wifi.WIFI_WPA2,"zerynthwifi")
except Exception as e:
    print("ooops, something wrong while linking :(", e)
    while True:
        sleep(1000)

url = "http://httpbin.org/"

tests = [
    {
        "title": "Testing GET Method...",
        "method": requests.get,
        "url": url+"get",
        "params": {"test": "query_string"}
    },
    {
示例#21
0
文件: main.py 项目: tkaden4/ricebot
def clean_value(value):
    return (value - 4095 / 2) * 3.3 / 4095


def on_error(delay):
    while True:
        digitalWrite(LED0, HIGH)
        sleep(delay)
        digitalWrite(LED0, LOW)
        sleep(delay)


for retry in range(10):
    try:
        wifi.link(wifi_config.SSID, wifi.WIFI_WPA2, wifi_config.PASSWORD)
        break
    except Exception as e:
        on_error(100)

if not wifi.is_linked():
    on_error(200)
else:
    digitalWrite(LED0, HIGH)
    while True:
        try:
            values = []
            for i in range(200):
                values.append(clean_value(adc.read(A3)))
            requests.post(wifi_config.HOST,
                          json={
示例#22
0
for pin in LED.values():
    pinMode(pin, OUTPUT)

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

try:
    # Wifi 4 Click on slot A(specify which serial port will be used and which RST pin)
    wifi_driver.init(SERIAL2, D24, baud=9600)
except Exception as e:
    print(e)

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

try:
    # Device UID and TOKEN can be created in the ADM panel
    zapp = zerynthapp.ZerynthApp("DEVICE UID", "DEVICE TOKEN", log=True)
except Exception as e:
    print(e)

# Start the Zerynth app instance!
示例#23
0
        print('requested sampling period:', config['sampling_period'])
        sampling_period = config['sampling_period']
    if 'led_state' in config:
        digitalWrite(LED0, LOW if config['led_state'] == 'on' else HIGH)
    return config


pinMode(LED0, OUTPUT)
digitalWrite(LED0, HIGH)

streams.serial()
new_resource('device.conf.json')
device_conf = helpers.load_device_conf()

wifi_driver.auto_init(ext=1)
wifi.link(device_conf['wifi_ssid'], wifi.WIFI_WPA2,
          device_conf['wifi_password'])
print('> linked')

sampling_period = 2000
ateccx08a.hwcrypto_init(
    I2C0,
    2,
    i2c_addr=device_conf['i2caddr'],
    dev_type=helpers.conf2atecctype[device_conf['devtype']])

# create a google cloud device instance, connect to mqtt broker, set config callback and start mqtt reception loop
device = iot.Device(device_conf['project_id'],
                    device_conf['cloud_region'],
                    device_conf['registry_id'],
                    device_conf['device_id'],
                    '',
示例#24
0
# Created: 2016-07-27 11:00:55.020628
#
################################################################################

import streams

# import the wifi interface
from wireless import wifi

# import wifi support
from espressif.esp8266wifi import esp8266wifi as wifi_driver

streams.serial()

# init the wifi driver!
# The driver automatically registers itself to the wifi interface
# with the correct configuration for the selected device
wifi_driver.auto_init()

# use the wifi interface to link to the Access Point
# change network name, security and password as needed
print("Establishing Link...")
try:
    # FOR THIS EXAMPLE TO WORK, "Network-Name" AND "Wifi-Password" MUST BE SET
    # TO MATCH YOUR ACTUAL NETWORK CONFIGURATION
    wifi.link("Network-name", wifi.WIFI_WPA2, "password")
    print("Link Established")
except Exception as e:
    print("ooops, something wrong while linking :(", e)
    while True:
        sleep(1000)
示例#25
0
from drivers.wifi.cc3000 import cc3000_tiny as cc3000
# and also import the viperapp module
from libs.apps import viperapp
p = thermalprinter.ThermalPrinter(SERIAL1,19200)

s=streams.serial()

# save the template.html in the board flash with new_resource
new_resource("template.html")

# connect to a wifi network
try:
    cc3000.auto_init()

    print("Establishing Link...")
    wifi.link("SSID_WiFi",wifi.WIFI_WPA2,"PWD_WiFi")
    print("Ok!")        
except Exception as e:
    print(e)

def printMessage(msg):
    p.print_text("VIPER\n",justification="c", style="b")
    p.print_text("www.viperize.it\n\n",justification="c", style="b")
    p.print_text("Take me!\n",justification="c", style="b")
    p.print_text(msg)
    p.print_text("\n"*2+"*"*20+"\n"*3,justification="c")    
    
#### ViperApp Setup    
    
# :: Javascript to Python ::
# the following function will be called when the template button is pressed
示例#26
0
try:
    streams.serial()

    # init the wifi driver!
    # The driver automatically registers itself to the wifi interface
    # with the correct configuration for the selected board
    wifi_driver.auto_init()

    # use the wifi interface to link to the Access Point
    # change network name, security and password as needed
    print("Establishing WiFi Link...")
    for retry in range(5):
        try:
            # FOR THIS EXAMPLE TO WORK, "Network-Name" AND "Wifi-Password" MUST BE SET
            # TO MATCH YOUR ACTUAL NETWORK CONFIGURATION
            wifi.link("Network-Name",wifi.WIFI_WPA2,"Wifi-Password")
            print("...done!")
            break
        except Exception as e:
            pass
    else:
        print(":( can't connect to wifi")
        raise IOError

    # create an UDP socket and set a timeout of 1 second
    sock = socket.socket(type=socket.SOCK_DGRAM)
    sock.settimeout(1000)

    # create an NTP request packet
    pkt = bytearray([0]*48)
    pkt[0] = 0x1B
示例#27
0
new_resource('device.conf.json')


# define a callback for config updates
def config_callback(config):
    global publish_period
    print('requested publish period:', config['publish_period'])
    publish_period = config['publish_period']
    return {'publish_period': publish_period}


streams.serial()
wifi_driver.auto_init()

# place here your wifi configuration
wifi.link("SSID", wifi.WIFI_WPA2, "PSW")

pkey = helpers.load_key('private.hex.key')
device_conf = helpers.load_device_conf()
publish_period = 5000


# choose an appropriate way to get a valid timestamp (may be available through hardware RTC)
def get_timestamp():
    user_agent = {"user-agent": "curl/7.56.0"}
    return json.loads(
        requests.get('http://now.httpbin.org',
                     headers=user_agent).content)['now']['epoch']


# create a google cloud device instance, connect to mqtt broker, set config callback and start mqtt reception loop
示例#28
0
token = "BBFF-FZEcZCMX7zB8mUz6dJjJzQzmMv8w0H"

streams.serial()

#Servomotor Marrone -> GND Rosso -> 5V  Arancione --> D25
MyServo = servo.Servo(D25.PWM,
                      min_width=1000,
                      max_width=2000,
                      default_width=1000)
MyServo.attach()

wifi_driver.auto_init()

print("Establishing connection..")
try:
    wifi.link("Vodafone-26184725", wifi.WIFI_WPA, "kfmu9axt2m9udca")
    print("Connected!")
except Exception as e:
    print("Something went wrong.. ", e)
    while True:
        sleep(1000)


#build JSON directory
def build_json(variable, value):
    try:
        data = {variable: {"value": value}}
        return data
    except Exception as e:
        print("Exception catched.. ", e)
        return None
示例#29
0
onPinFall(BTN0,on_btn,debounce=1000)


# Device UID and TOKEN can be created in the ADM panel
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!
    # 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()
    
    # Do whatever you need here
    while True:
示例#30
0
#constantes do termistor usado
A = 0.001129148
B = 0.000234125
C = 0.0000000876741

#habilita o uso de fluxo de dados através da UART do microcontrolador
streams.serial()

# use the wifi interface to link to the Access Point
# change network name, security and password as needed
print("Establishing Link...")
try:
    # FOR THIS EXAMPLE TO WORK, "Network" AND "Password" MUST BE SET
    # TO MATCH YOUR ACTUAL NETWORK CONFIGURATION
    wifi.link("Network", wifi.WIFI_WPA2, "Password")
except Exception as e:
    print("ooops, something wrong while linking :(", e)
    while True:
        sleep(1000)


# define MQTT callbacks
def is_sample(data):
    if ('message' in data):
        return (data['message'].qos == 1
                and data['message'].topic == "desktop/samples")
    return False


def print_sample(client, data):
示例#31
0
from espressif.esp8266wifi import esp8266wifi as wifidriver
from wireless import wifi

NETWORK_SSID = "dediosnet"
NETWORK_KEY = "DeD!os24180501"
SERVER_IP = "192.168.1.5"
SERVER_PORT = 55555
SOCKET_STREAM = None

streams.serial()

wifidriver.auto_init()

for retries in range(10):
    try:
        wifi.link(NETWORK_SSID, wifi.WIFI_WPA2, NETWORK_KEY)
        print("Connected to Wi-Fi")
        break
    except Exception:
        print("Can't connect to Wi-Fi")
        sleep(1000)
else:
    mcu.reset()
for retries in range(10):
    try:
        SOCKET_STREAM = socket.socket()
        SOCKET_STREAM.connect((SERVER_IP, SERVER_PORT))
        print("Connected to server")
        break
    except Exception:
        print("Can't connect to server")
示例#32
0
# Viper Example Code

# import streams & socket
import streams
import socket

# import the broadcom 43362 wifi driver
from drivers.wifi.bcm43362 import bcm43362 as bcm
# import the wifi interface
from wireless import wifi

streams.serial()

# init the broadcom driver: works on the Photon and Broadcom based boards
# The driver automatically registers itself to the wifi interface
# so the wifi module can use the Broadcom chip without your intervention
bcm.auto_init()

print("establishing link...")
try:
    wifi.link("", wifi.WIFI_WPA2, "")
except Exception as e:
    print ("oops, something went wrong while linking :(", e)
    sleep(5000)

print ("Linked!")

info = wifi.link_info()
print("My IP is: ", info[0])
示例#33
0

onPinFall(BTN0, on_btn, debounce=1000)

# Device UID and TOKEN can be created in the ADM panel
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!
    # 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()

    # Do whatever you need here
    while True:
示例#34
0

# define a callback for shadow updates
def shadow_callback(requested):
    global publish_period
    print('requested publish period:', requested['publish_period'])
    publish_period = requested['publish_period']
    return {'publish_period': publish_period}


streams.serial()
wifi_driver.auto_init()

print('connecting to wifi...')
# place here your wifi configuration
wifi.link("JoeyCat", wifi.WIFI_WPA2, "joeylovesfood")

pkey, clicert = helpers.load_key_cert('private.pem.key', 'certificate.pem.crt')
thing_conf = helpers.load_thing_conf()
publish_period = 1000  #decreased from 5 secs to one sec

# create aws iot thing instance, connect to mqtt broker, set shadow update callback and start mqtt reception loop
thing = iot.Thing(thing_conf['endpoint'],
                  thing_conf['mqttid'],
                  clicert,
                  pkey,
                  thingname=thing_conf['thingname'])
print('connecting to mqtt broker...')
thing.mqtt.connect()
thing.on_shadow_request(shadow_callback)
thing.mqtt.loop()
示例#35
0
digitalWrite(water_pin, LOW)
pinMode(light_pin, OUTPUT)
digitalWrite(light_pin, LOW)
pinMode(light_test_pin, OUTPUT)
digitalWrite(light_test_pin, LOW)
pinMode(photoresistor, INPUT_ANALOG)
onPinFall(btn_pin, button_press) #quando BTN0 viene premuto tutto viene spento
    
try:
    sleep(5000)
    print('Initialize wifi')
    spwf01sa.init(SERIAL2, wifi_reset_pin)
    sleep(3000)
    
    print('Connecting...')
    wifi.link('Vodafone2.4GHz-33915375', wifi.WIFI_WPA2, 'Rosato65wifi95')
    print('Connected to wifi')
    sleep(1000)
    zapp = zerynthapp.ZerynthApp(uid, token)
    print('zapp object created!')
    #############################################
    #Associate the method calls to Python funcs
    zapp.on('set_desired_temp', set_desired_temp) #gestione della temperatura desiderata
    zapp.on('heating_switch', heating_switch)       #gestione on/off riscaldamento
    zapp.on('water_switch', water_switch)           #gestion on/off acqua
    zapp.on('light_switch', light_switch)           #gestion on/off luce
    zapp.on('set_delay', set_delay)                 #gestion on/off "doccia automatica"
    zapp.on('set_state', set_state)                 #var bool che tiene traccia dell'effettivo on/off del sistema automatico 
    zapp.on('get_initial_state', get_initial_state) #invia lo stato iniziale di tutte le variabili
    
    print('Start the app instance...')
示例#36
0

class ConfigurationSimulator:
    def __init__(self, value):
        self.value = value


# Connect to WiFi network
try:
    print("Initializing WiFi driver..")
    # This setup refers to spwf01sa wi-fi chip mounted on flip n click device slot A
    # For other wi-fi chips auto_init method is available, wifi_driver.auto_init()
    wifi_driver.auto_init()

    print("Establishing connection with WiFi network...")
    wifi.link(network_SSID, network_SECURITY, network_password)
    print("Done")
except Exception as e:
    print("Something went wrong while linking to WiFi network: ", e)

try:
    device = iot.Device(device_key, device_password, actuator_references)
except Exception as e:
    print("Something went wrong while creating the device: ", e)

try:
    wolk = iot.Wolk(
        device,
        host="api-demo.wolkabout.com",
        port=1883,
        actuation_handler=ActuationHandlerImpl(),
示例#37
0
import streams

import helper
import ssl

from liveintersect.iot import iot

new_resource('asset.config.json')

streams.serial()

print("Initializing wifi_driver")
wifi_driver.auto_init()
print("Establishing wifi_connection")
wifi.link("SSID", wifi.WIFI_WPA2, "PWD")

cacert = __lookup(SSL_CACERT_COMODO_RSA_CERTIFICATION_AUTHORITY)
ctx = ssl.create_ssl_context(cacert=cacert,
                             options=ssl.CERT_REQUIRED | ssl.SERVER_AUTH)

print("> Connected")

try:
    asset_config = helper.load_asset_conf()
    my_asset = iot.Asset(asset_config["baseUrl"],
                         asset_config["apiKey"],
                         asset_config["srNo"],
                         asset_config["assetName"],
                         assetTypeCode=asset_config["assetTypeCode"],
                         ssl_ctx=ctx)
示例#38
0
# load the Photon wifi driver
# change the following import to use another network driver
from bcm43362 import bcm43362 as wifi_driver

streams.serial()

# init the wifi driver!
wifi_driver.auto_init()

# use the wifi interface to link to the Access Point
# change network name, security and password as needed
print("Establishing Link...")
try:
    # FOR THIS EXAMPLE TO WORK, "Network-Name" AND "Wifi-Password" MUST BE SET
    # TO MATCH YOUR ACTUAL NETWORK CONFIGURATION
    wifi.link("Network-Name",wifi.WIFI_WPA2,"Network-Pass")
except Exception as e:
    print("ooops, something wrong while linking :(", e)
    while True:
        sleep(1000)

# FOR THIS EXAMPLE TO WORK YOU NEED TO FOLLOW THE STEPS AT:
# ------> http://library.123go.it/twitter/   <-------
# and get your public token and your secret code!

public_token = "...here goes your public token..."
secret_code = "...here goes your secret code..."
tweet = "How cool is tweeting with a @particle Photon and @VIPER_IoT? :P"

try:
    twitter.tweet(public_token,secret_code,tweet)