Last active
October 20, 2021 10:59
-
-
Save farshidtz/3131dda8997be63e1dcc2a716f7cd5cf to your computer and use it in GitHub Desktop.
Read from DHT22 and submit to edgex-device-rest
This file contains hidden or 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
# Original script from https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/python-setup | |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries | |
# SPDX-License-Identifier: MIT | |
# RUN: | |
# REST_SERVER=http://myserver:59986 python3 read.py | |
import time | |
import board | |
import adafruit_dht | |
import requests | |
import json | |
import os | |
rest_server = os.environ['REST_SERVER'] | |
# Initial the dht device, with data pin connected to: | |
dhtDevice = adafruit_dht.DHT22(board.D4) | |
# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio. | |
# This may be necessary on a Linux single board computer like the Raspberry Pi, | |
# but it will not work in CircuitPython. | |
# dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) | |
while True: | |
try: | |
print("----------------------------") | |
# Print the values to the serial port | |
temperature = dhtDevice.temperature | |
humidity = dhtDevice.humidity | |
print("Temp: {:.1f}C Humidity: {}% ".format(temperature, humidity)) | |
url = '%s/api/v2/resource/DHT11Sensor/temperature' % rest_server | |
payload = temperature | |
headers = {'content-type': 'application/json'} | |
response = requests.post(url, data=json.dumps(payload), headers=headers) | |
print("Posting temperature: {} {}".format(response.status_code, response.text)) | |
url = '%s/api/v2/resource/DHT11Sensor/humidity' % rest_server | |
payload = humidity | |
headers = {'content-type': 'application/json'} | |
response = requests.post(url, data=json.dumps(payload), headers=headers) | |
print("Posting humidity: {} {}".format(response.status_code, response.text)) | |
except requests.exceptions.RequestException as error: | |
print(error) | |
time.sleep(10.0) | |
continue | |
except RuntimeError as error: | |
# Errors happen fairly often, DHT's are hard to read, just keep going | |
print(error.args[0]) | |
time.sleep(2.0) | |
continue | |
except Exception as error: | |
dhtDevice.exit() | |
raise error | |
time.sleep(10.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment