Last active
April 10, 2020 02:26
Star
You must be signed in to star a gist
Station-side Python code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import network | |
import urequests | |
import ujson | |
import machine | |
import time | |
def do_post(url, data): | |
headers = {'Content-Type': 'application/json'} | |
r = urequests.post(url, data=data, headers=headers) | |
#print(r) | |
results = r.json() | |
#print(results) | |
def do_connect_as_ap(ap_ssid, ap_pwd): | |
ap = network.WLAN(network.AP_IF) | |
ap.active(True) | |
sta_if = network.WLAN(network.STA_IF) | |
sta_if.active(False) | |
ap.config(essid=ap_ssid, password=ap_pwd) | |
while ap.active() == False: | |
pass | |
print('network config:', ap.ifconfig()) | |
def do_connect_as_station(sta_ssid, sta_pwd): | |
ap = network.WLAN(network.AP_IF) | |
ap.active(False) | |
sta_if = network.WLAN(network.STA_IF) | |
if not sta_if.isconnected(): | |
print('connecting to network...') | |
sta_if.active(True) | |
sta_if.connect(sta_ssid, sta_pwd) | |
while not sta_if.isconnected(): | |
pass | |
print('network config:', sta_if.ifconfig()) | |
### Main config parameters | |
kelvi_host_ip = "http://10.41.2.37:8000/" | |
WHICH_PIN = 0 ## GPIO 0 - config button in wiolink | |
key_val = 0 | |
self_id = 100 # Some unique id for this station | |
ap_ssid = "MicroPython-abba" | |
ap_pwd = "abba" | |
sta_ssid = "" | |
sta_pwd = "" | |
# Connect to target host | |
do_connect_as_station(sta_ssid, sta_pwd); | |
data = {} | |
data["station-id"] = str(self_id) | |
data["counter"] = 0 | |
# DEMO - Loop for 50 presses at this time | |
press_count = 0 | |
while press_count < 50: | |
time.sleep_ms(50) | |
key_val = machine.Pin(WHICH_PIN).value() | |
if int(key_val) == 0: # default pulled high | |
press_count = press_count + 1 | |
data["value"] = int(1) | |
data["counter"] = press_count | |
json_data = ujson.dumps(data) | |
# POST to target host | |
try: | |
do_post(kelvi_host_ip, json_data) | |
except: | |
print('Error posting') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment