Last active
October 29, 2020 14:53
-
-
Save totomz/8abc630888229d68e677c5dd52de1007 to your computer and use it in GitHub Desktop.
Python script to colelct humidity and temperature from a DHT22 sensor and an ipmi server
This file contains 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
#! /usr/bin/python3 | |
import statsd | |
import Adafruit_DHT | |
import time | |
import boto3 | |
import sys | |
import subprocess | |
import socket | |
from timeit import default_timer as timer | |
DHT_SENSOR = Adafruit_DHT.DHT22 | |
DHT_PIN = 4 | |
statsd = statsd.StatsClient(STATSD_ENDPOINT, 8125, prefix='totomz.homelab') | |
def str2float(string, default=0.0): | |
res = default | |
try: | |
res = float(string) | |
except Exception: | |
res = default | |
return res | |
def collect_and_send(hostname, ip): | |
try: | |
out = subprocess.check_output("ipmitool -P root -U root -H {ip} sensor".format(ip=ip), | |
stderr=subprocess.STDOUT, | |
shell=True) | |
stdout = str(out.decode('utf-8')) | |
metrics = stdout.split("\n") | |
for line in metrics: | |
metric_line = line.lower() | |
if "temp" not in metric_line: | |
continue | |
p = metric_line.split("|") | |
metric_name = str.lower(str.strip(str.strip(p[0]))).replace(" ", "_") | |
metric_value = str2float(str.strip(p[1]), 0) | |
statsd.gauge("bmc.{host}.{metric_name}".format(host=hostname, metric_name=metric_name), metric_value) | |
except Exception as e: | |
# do nothing | |
print(e) | |
print("Starting temperature and humidity monitoring service....") | |
sys.stdout.flush() | |
while True: | |
#################### | |
# Environment data # | |
#################### | |
start = timer() | |
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN) | |
if humidity is not None and temperature is not None: | |
print("{2} Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity, time.strftime("%Y-%m-%d %H:%M:%S"))) | |
sys.stdout.flush() | |
statsd.gauge('rack.temp', temperature) | |
statsd.gauge('rack.humidity', humidity) | |
else: | |
print("Failed to retireve temp {0} or humidity {1}".format(temperature,humidity)) | |
sys.stdout.flush() | |
end = timer() | |
print("temp & humidity: {}".format(end - start)) | |
################ | |
# IPMI Metrics # | |
################ | |
start = timer() | |
collect_and_send(hostname="ziobob", ip="192.168.10.30") | |
end = timer() | |
print("ziocharlie: {}".format(end - start)) | |
start = timer() | |
collect_and_send(hostname="ziocharlie", ip="192.168.10.31") | |
end = timer() | |
print("ziocharlie: {}".format(end - start)) | |
time.sleep(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment