Skip to content

Instantly share code, notes, and snippets.

@aparedero
Last active June 21, 2020 11:26
Show Gist options
  • Save aparedero/b849ce7ba0812bc2c8f8ebeda588ea5e to your computer and use it in GitHub Desktop.
Save aparedero/b849ce7ba0812bc2c8f8ebeda588ea5e to your computer and use it in GitHub Desktop.
Extended Raspberry Pi example code from Ubidots ( https://help.ubidots.com/en/articles/513309-connect-the-raspberry-pi-with-ubidots )
import time
import requests
import math
import random
TOKEN = "..." # Just put your TOKEN here (API Credentials --> On left side)
DEVICE_LABEL = "mbit-iot-simulator" # Put name of DEVICE here
VARIABLE_LABEL_1 = "temperature" # Name of first variable: Temperature
VARIABLE_LABEL_2 = "humidity" # Name of second var: Humidity
VARIABLE_LABEL_3 = "position" # Name of third var: Position
VARIABLE_LABEL_4 = "speed" # Name of fourth var: Speed
VARIABLE_LABEL_5 = "switch" # Name of fifth var: Switch
def build_payload(variable_1, variable_2, variable_3, variable_4, variable_5):
# Creates random values for sending data
value_1 = random.randint(10, 37)
value_2 = random.randint(15, 85)
value_4 = random.randint(0,30)
value_5 = bool(random.getrandbits(1))
# Creates a random gps coordinates
lat = random.randrange(40, 41, 1) + \
random.randrange(1, 1000, 1) / 1000.0
lng = random.randrange(-3, -4, -1) + \
random.randrange(1, 1000, 1) / 1000.0
payload = {variable_1: value_1,
variable_2: value_2,
variable_4: value_4,
variable_5: value_5,
variable_3: {"value": 1, "context": {"lat": lat, "lng": lng}}}
return payload
def post_request(payload):
# Creates the headers for the HTTP requests
url = "http://industrial.api.ubidots.com"
url = "{}/api/v1.6/devices/{}".format(url, DEVICE_LABEL)
headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
# Makes the HTTP requests
status = 400
attempts = 0
while status >= 400 and attempts <= 5:
req = requests.post(url=url, headers=headers, json=payload)
status = req.status_code
attempts += 1
time.sleep(1)
# Processes results
if status >= 400:
print("[ERROR] Could not send data after 5 attempts, please check \
your token credentials and internet connection")
return False
print(payload)
print("[INFO] request made properly, your device is updated")
return True
def main():
payload = build_payload(
VARIABLE_LABEL_1, VARIABLE_LABEL_2, VARIABLE_LABEL_3, VARIABLE_LABEL_4, VARIABLE_LABEL_5)
print("[INFO] Attemping to send data")
post_request(payload)
print("[INFO] finished")
if __name__ == '__main__':
while (True):
main()
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment