Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create mcp9808_average temp+mqtt #34

Merged
merged 2 commits into from
Mar 7, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions examples/mcp9808_average temp+mqtt
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
FoamyGuy marked this conversation as resolved.
Show resolved Hide resolved
# SPDX-License-Identifier: MIT

import time
import board
import adafruit_mcp9808
import paho.mqtt.client as mqtt
import numpy as np
import json
i2c = board.I2C() # uses board.SCL and board.SDA

# To initialise using the default address:
mcp = adafruit_mcp9808.MCP9808(i2c)

broker_address="Broker IP"
port = 1883
user = "mqttuser"
password = "mqttpassword"
client = mqtt.Client("P1") #create new instance
client.username_pw_set(user, password=password)
client.connect(broker_address, port=port)
client.loop_start()
# To initialise using a specified address:
# Necessary when, for example, connecting A0 to VDD to make address=0x19
# mcp = adafruit_mcp9808.MCP9808(i2c_bus, address=0x19)
from array import *
from decimal import Decimal
#Create autodiscovery topic for Home assistant
#"ha" is autodiscovery prefix in home assistant
send_msg = {
"state_topic": "ha/sensor/sensorLivingroom/state",
"device_class": "temperature",
"unit_of_measurement": "°C",
"value_template": "{{ value_json.temperature }}",
"device": {
"identifiers": [
"rpisensorgatewayn01"
],
"manufacturer": "Raspberry",
"model": "RPI 3B",
"name": "Livingroom temperature",
"sw_version": "MCU9808"
},
"name": "Livingroom temperature",
"unique_id": "rpisensorgateway_0x01"
}
client.publish("ha/sensor/sensorLivingroom/config", payload=json.dumps(send_msg), qos=0, retain=True) #publish
temp1m = array('d',[0,0,0,0,0,0,0,0,0] ) #using array to aproximate 10 temperature readings
avgtemp = 0
while True:
print(len(temp1m))
for count in range (0,9):
temp1m[count] = mcp.temperature
print("Temperature: {} C ".format(mcp.temperature))
avgtemp = round(np.average(temp1m), 1)
print("avgtemp {} C".format(avgtemp))
time.sleep(10)
send_msg = {
'temperature': avgtemp
}
client.publish("ha/sensor/sensorLivingroom/state",payload=json.dumps(send_msg)) #publish result in mqtt