Skip to content

Instantly share code, notes, and snippets.

@dwblair
Last active August 19, 2019 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwblair/280d1394e99e5cdd064561d5ed54bb41 to your computer and use it in GitHub Desktop.
Save dwblair/280d1394e99e5cdd064561d5ed54bb41 to your computer and use it in GitHub Desktop.
Simple code for posting dummy values to FarmOS using an ESP32 with Micropython
import ujson as json
import urequests as requests
import time
import machine
from machine import Pin
from machine import SPI
# set up FARMOS params
public_key='[PUBLIC KEY]'
private_key='[PRIVATE KEY]'
# set up WIFI parameters
WIFI_NET = '[ESSID]'
WIFI_PASSWORD = '[PASSWORD]'
base_url='https://wolfesneck.farmos.net/farm/sensor/listener/'
url = base_url+public_key+'?private_key='+private_key
headers = {'Content-type':'application/json', 'Accept':'application/json'}
# function for posting data
def post_data():
try:
r = requests.post(url,data=json.dumps(payload),headers=headers)
except Exception as e:
print(e)
#r.close()
return "timeout"
else:
r.close()
print('Status', r.status_code)
return "posted"
# function for connecting to wifi
def do_connect():
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(False)
sta_if.active(True)
sta_if.connect(WIFI_NET, WIFI_PASSWORD)
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
index=0
# main loop
while True:
print ("iteration #"+str(index)+":")
temp=23.2
humidity=45.5
# form the payload
payload ={"temp": t,"humidity":h}
print(payload)
# connect to network
do_connect()
# post the data
post_data()
print("Posted!\n")
index+=1
time.sleep(5)
@dwblair
Copy link
Author

dwblair commented Aug 19, 2019

Using latest release of Micropython, here: http://micropython.org/download#esp32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment