Skip to content

Instantly share code, notes, and snippets.

@f41ardu
Created January 27, 2024 07:52
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 f41ardu/ac521a69a90fffa18f733e2e573f201d to your computer and use it in GitHub Desktop.
Save f41ardu/ac521a69a90fffa18f733e2e573f201d to your computer and use it in GitHub Desktop.
Simple client to put data via get request t
# esp rest client with authentification
# this will be the new energy monitoring esp client
# this is the testversion
# network
import urequests
import ujson as json
import ubinascii
import time
# bmp and dht hardware
from machine import Pin
from machine import I2C
import dht
import math
from libraries.bmp180 import BMP180
sda=Pin(4)
scl=Pin(5)
dhtPin=Pin(0,Pin.IN)
i2c=I2C(scl,sda)
bmp = BMP180(i2c)
bmp.oversample = 3
bmp.sealevel = 1024
bmp.absaltitude = 513
d = dht.DHT22(dhtPin)
def make_authenticated_request(host, port, endpoint, params, username, password):
url = f'http://{host}:{port}{endpoint}?{params}'
print(f'Sending request to: {url}')
# Add Basic Authentication header
credentials = f"{username}:{password}"
encoded_credentials = ubinascii.b2a_base64(credentials.encode('utf-8')).decode('utf-8')
headers = {'Authorization': f'Basic {encoded_credentials}'}
try:
response = urequests.get(url, headers=headers)
except Exception as e:
print(f"Error making request: {e}")
return None
return response.json()
if __name__ == '__main__':
host = 'server.fritz.box'
port = 8599
endpoint = '/api'
led = Pin(2, Pin.OUT)
d.measure()
# Set your parameters
temperature=str(d.temperature())
humidity=str(d.humidity())
params = 'TempDHT='+temperature+'&humidityDHT='+humidity
print(params)
# Set your authentication credentials
username = 'user1'
password = 'password'
while True:
response = make_authenticated_request(host, port, endpoint, params, username, password)
if response:
print(response)
else:
print("Failed to get a response. Retrying in 5 seconds...")
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment