Skip to content

Instantly share code, notes, and snippets.

@prabindh
Last active April 10, 2020 02:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save prabindh/f8bac87189949e877f97a26666d062ab to your computer and use it in GitHub Desktop.
Station-side Python code
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