From df81ee662a36740c2e829c60101531b9bfe56f55 Mon Sep 17 00:00:00 2001 From: Pierrick C Date: Wed, 26 Jul 2017 15:51:58 +0200 Subject: [PATCH] Ajout des scripts MQTT --- python/mqtt2papirus.py | 84 +++++++++++++++++++++++++++++++++ python/mqtt2sql.py | 92 +++++++++++++++++++++++++++++++++++++ python/papirus-lm752mqtt.py | 63 +++++++++++++++++++++++++ python/picam+mqtt.py | 59 ++++++++++++++++++++++++ 4 files changed, 298 insertions(+) create mode 100755 python/mqtt2papirus.py create mode 100755 python/mqtt2sql.py create mode 100755 python/papirus-lm752mqtt.py create mode 100755 python/picam+mqtt.py diff --git a/python/mqtt2papirus.py b/python/mqtt2papirus.py new file mode 100755 index 0000000..c0f64c8 --- /dev/null +++ b/python/mqtt2papirus.py @@ -0,0 +1,84 @@ +#!/usr/bin/python2 +# -*- coding: utf8 -*- + +# Get data from MQTT broker and print them to +# Papirus ePaper display + +from papirus import Papirus +from papirus import PapirusTextPos + +import paho.mqtt.client as mqtt + +import datetime +import decimal + +# MQTT settings +mqtt_server = 'localhost' +mqtt_port= 1883 +mqtt_auth= {'username':'cameteo', + 'password':'CaMeteo'} +mqtt_client_id= 'mqtt2papirus' + +topic="pi/papirus_zero_hat/temperature/#" + +# Papirus display settings +disp_rotation = 0 +font_path = '/usr/share/fonts/truetype/freefont/FreeMono.ttf' +font_path_bold = '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf' +text_size = 15 + +date = datetime.datetime.now().replace(microsecond=0).isoformat() +temp = "-" +unit_temp = "\u00B0C" + +#Set the dispaly and position of text +text = PapirusTextPos(False, rotation=disp_rotation) +#text.Clear() +text.AddText(date, 0, 0, text_size, Id="Date", font_path=font_path_bold) +text.AddText("Connecting to MQTT...", 5, 15, text_size, Id="Temperature", font_path=font_path) +text.WriteAll() + +# The callback for when the client receives a CONNACK response from the server. +def on_connect(client, userdata, flags, rc): + print("Connected with result code "+str(rc)) + date = datetime.datetime.now().replace(microsecond=0).isoformat() + text.UpdateText("Date", date, font_path=font_path_bold) + text.UpdateText("Temperature", "Connected to MQTT !") + text.WriteAll() + # Subscribing in on_connect() means that if we lose the connection and + # reconnect then subscriptions will be renewed. + client.unsubscribe("$SYS/#") + client.subscribe(topic) + +# The callback for when a PUBLISH message is received from the server. +def on_message(client, userdata, msg): + global unit_temp + top=msg.topic[len(topic)-1:].strip() + print(top+" : "+str(msg.payload)) + + if top == "date" : + text.UpdateText("Date", msg.payload, font_path=font_path_bold) + + if top == "unit" : + unit_temp = msg.payload + + if top == "value" : + val = decimal.Decimal(msg.payload) + txt = "T= %.1f" % val + unit_temp.decode("utf-8") + text.UpdateText("Temperature", txt) + text.WriteAll() + +######## +# Main # +######## + +#Connect to MQTT broker and loop... +mqtt_client = mqtt.Client(mqtt_client_id, clean_session=False) +mqtt_client.username_pw_set(mqtt_auth['username'], mqtt_auth['password']) +mqtt_client.on_connect = on_connect +mqtt_client.on_message = on_message +mqtt_client.connect(mqtt_server, mqtt_port, 60) + +mqtt_client.loop_forever() + + diff --git a/python/mqtt2sql.py b/python/mqtt2sql.py new file mode 100755 index 0000000..7d51585 --- /dev/null +++ b/python/mqtt2sql.py @@ -0,0 +1,92 @@ +#!/usr/bin/python3 + +# Pérenisation de données arrivant sur un MQTT +# vers une base de données MariaDb/MySQL +# Auteur : Arofarn +# v0.1 + +################# +# Configuration # +################# + +#MQTT Broker +mqtt_host = "aro-yuno" +mqtt_port = 1883 +mqtt_client_id = "mqtt2sql" +#mqtt_auth = { 'username' : 'arofarn', 'password' : 'xxx' } +qos=1 +topic = "huzzah0/#" + +#MySQL database + +sql_host = "localhost" +#sql_port = +sql_base = "iot_test" +sql_user = "arofarn" +#sql_pass = "password" + +######## +# MAIN # +######## + +import paho.mqtt.client as mqtt +from datetime import datetime +import json +import pymysql.cursors + +def on_connect(client, userdata, flags, rc): + print("Connected with result code "+str(rc)) + client.subscribe(topic) + +def on_message(client, userdata, msg): + top=msg.topic[len(topic)-1:].strip() + + subtopics = top.split("/") + payload = msg.payload.decode() + + val = json.loads(payload) + print("%s : %s %s (%s)" % (val['type'], val['value'], val['unit'], subtopics[0])) + + with connection.cursor() as cursor: + sql = "INSERT INTO `data` (`valdate`, `value`, `type_id`, `sensor_id`) VALUES (%s, %s, %s, %s)" + cursor.execute(sql, (datetime.strptime(val['date'], "%d/%m/%Y %H:%M:%S"), float(val['value']), val['type'], subtopics[0])) + + connection.commit() + +def on_message_date(client, userdata, msg): + payload = msg.payload.decode() + try: + d = datetime.strptime(payload, "%d/%m/%Y %H:%M:%S") + print("Date : %s" % d) + except: + print("Date mal formatée : %s" % payload) + + +def on_disconnect(client, userdata, msg): + if msg != 0: + print("Déconnexion imprévu : %s" % msg) + connection.close() + +connection = pymysql.connect(host=sql_host, + user=sql_user, + #password=sql_pass, + db=sql_base, + charset='utf8mb4', + cursorclass=pymysql.cursors.DictCursor) + +######## +# Main # +######## + +#Connect to MQTT broker and loop... +mqtt_client = mqtt.Client(mqtt_client_id, clean_session=False) +#mqtt_client.username_pw_set(mqtt_auth['username'], mqtt_auth['password']) +mqtt_client.on_connect = on_connect +mqtt_client.on_message = on_message +mqtt_client.on_disconnect = on_disconnect + +mqtt_client.message_callback_add("huzzah0/NTP/date", on_message_date) + +mqtt_client.connect(mqtt_host, mqtt_port, 60) + +mqtt_client.loop_forever() diff --git a/python/papirus-lm752mqtt.py b/python/papirus-lm752mqtt.py new file mode 100755 index 0000000..9106bee --- /dev/null +++ b/python/papirus-lm752mqtt.py @@ -0,0 +1,63 @@ +#!/usr/bin/python3 +# -*- coding: utf8 -*- + +#Get LM75 temperature value and send it to MQTT broker + +import smbus +import paho.mqtt.publish as mqtt +import datetime + +# MQTT settings +mqtt_server = 'localhost' +mqtt_port= 1883 +mqtt_auth= {'username':'cameteo', + 'password':'CaMeteo'} +mqtt_client_id= 'papirus_temp2mqtt' +mqtt_qos=2 + +mqtt_topic="pi/papirus_zero_hat/temperature/" + +#LM75B settings +LM75B_ADDRESS = 0x48 +LM75B_TEMP_REGISTER = 0 +LM75B_CONF_REGISTER = 1 +LM75B_THYST_REGISTER = 2 +LM75B_TOS_REGISTER = 3 +LM75B_CONF_NORMAL = 0 + +class LM75B(object): + def __init__(self, address=LM75B_ADDRESS, busnum=1): + self._address = address + self._bus = smbus.SMBus(busnum) + self._bus.write_byte_data(self._address, LM75B_CONF_REGISTER, LM75B_CONF_NORMAL) + + def getTempC(self): + """Return temperature in degrees Celsius""" + raw = self._bus.read_word_data(self._address, LM75B_TEMP_REGISTER) & 0xFFFF + raw = (((raw << 8) & 0xFF00) + (raw >> 8) +128 ) /256 + return raw + +######## +# Main # +######## + +#Get and print data +date = datetime.datetime.now().replace(microsecond=0).isoformat() +print(date) + +sens = LM75B() +lm75_temp = sens.getTempC() +print("Temperature (Papirus HAT LM75b) : %s °C" % lm75_temp) + + +#Send data to MQTT broker +mqtt_data = [{'topic':mqtt_topic + "value", 'payload':lm75_temp, 'qos':mqtt_qos, 'retain':True}, + {'topic':mqtt_topic + "date", 'payload':date, 'qos':mqtt_qos, 'retain':True}, + {'topic':mqtt_topic + "unit", 'payload':"\u00B0C", 'qos':mqtt_qos, 'retain':True}, + {'topic':mqtt_topic + "desc", 'payload':"LM75b sensor", 'qos':mqtt_qos, 'retain':True}] + +mqtt.multiple(mqtt_data, + hostname= mqtt_server , + port= mqtt_port , + auth= mqtt_auth , + client_id= mqtt_client_id ) diff --git a/python/picam+mqtt.py b/python/picam+mqtt.py new file mode 100755 index 0000000..02f25ff --- /dev/null +++ b/python/picam+mqtt.py @@ -0,0 +1,59 @@ +#!/usr/bin/python3 + +# Take a picture with the Pi Camera module and publish the path +# and name of the file on a MQTT broker + +import picamera +import paho.mqtt.publish as mqtt +from time import sleep +import datetime + + +# Camera settings +camera_resolution=(2592, 1944) +camera_warmup_time=2 #in seconds +#camera_iso=800 + +# MQTT settings +mqtt_server = 'localhost' +mqtt_port= 1883 +mqtt_auth= {'username':'cameteo', + 'password':'CaMeteo'} +mqtt_client_id= 'picamera2mqtt' +mqtt_qos=2 + +# Photo parameters +photo_path = '/home/pi/photos/' +photo_format = 'jpg' +photo_mqtt_topic = 'pi/picamera/' + +######## +# Main # +######## + +file_date = datetime.datetime.now().replace(microsecond=0).isoformat() +file_name = file_date + "." + photo_format + +# Taking a photo +################# +cam = picamera.PiCamera(resolution = camera_resolution) + +# Warm-up +cam.start_preview() +sleep(camera_warmup_time) + +print(photo_path+file_name) + +cam.capture(photo_path+file_name) + +# MQTT publication +################### +mqtt_data = [{'topic':photo_mqtt_topic+"path", 'payload':photo_path, 'qos':mqtt_qos, 'retain':False}, + {'topic':photo_mqtt_topic+"last_photo_name", 'payload':file_name, 'qos':mqtt_qos, 'retain':False}, + {'topic':photo_mqtt_topic+"last_photo_date", 'payload':file_date, 'qos':mqtt_qos, 'retain':False}] + +mqtt.multiple(mqtt_data, + hostname= mqtt_server , + port= mqtt_port , + client_id= mqtt_client_id , + auth= mqtt_auth )