Skip to content

Instantly share code, notes, and snippets.

@giljr
Last active April 25, 2020 22:59
Show Gist options
  • Select an option

  • Save giljr/6f857c063e86734a2955f46df428581d to your computer and use it in GitHub Desktop.

Select an option

Save giljr/6f857c063e86734a2955f46df428581d to your computer and use it in GitHub Desktop.
# # Python mqtt_sub_temp.py
# This program access Mysql inside PhpMyAdmin Application on my Raspberry PI
# It subscribe (as admin) to a Topic 'temp' the value 25 ° C
# Please create a User named user1, password 321 in your Pi
import paho.mqtt.client as mqtt
import requests
import sys
import mysql.connector
from datetime import date, datetime, timedelta
import time
# Mosquitto MQTT
username = "admin"
password = "123"
hostname = "localhost"
port = 1883
# Banco de dados MySql
user_mysql = "pi"
pwd_mysql = "root"
db_mysql = "mydb"
# Callback event functions
# on_connect = function called when the connection between the client and the MQTT broker occurs
# on_message = function called when a message from a subscribed topic is received
# on_publish = function called when a message is published
# on_subscribe = function called when a topic is subscribed to by the MQTT client
# on_log = function for debugging Paho
def on_connect(client, userdata, flags, rc):
print("Method-> on_connect: " + str(rc))
def on_message(client, obj, msg):
# Print the message content
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload) )
# Connection to Mysql database
# All configuration parameters of the Mysql Connector can be found
# Here: https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
cnx = mysql.connector.connect(user=user_mysql, password=pwd_mysql, database=db_mysql)
cursor = cnx.cursor()
query = ("INSERT INTO sensors "
"(name, value, timestamp) "
"VALUES (%s, %s, %s)")
# msg.topico = stores the topic
# msg.payload = stores the message content
# time.time = timestamp (UTC).
dados_recebidos = (msg.topic, msg.payload, str(int(time.time())))
# Load and run the query.
cursor.execute(query, dados_recebidos)
cnx.commit()
# Terminates the connection to the database
cursor.close()
cnx.close()
def on_publish(client, obj, mid):
print("Method-> on_publish: " + str(mid))
def on_subscribe(client, obj, mid, granted_qos):
print("Method-> Subscribe: " + str(mid) + " " + str(granted_qos))
def on_log(client, obj, level, string):
print(string)
#------------------------------------------------
mqttc = mqtt.Client()
# Sign the callback functions
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
# Connects to the MQTT Mosquitto
# Enter the username and password
mqttc.username_pw_set(username, password)
# Load the TLS certificate.
#mqttc.tls_set("/etc/mosquitto/certs/ca.crt")
# Enter the IP or DNS address of the Mosquitto server
# Use 1883 for WITHOUT TLS connection, and 8883 for secure TLS connection
mqttc.connect(hostname, port)
# Sign the topic, with QoS level 0 (can be 0, 1 or 2
mqttc.subscribe("temp", 0)
# To post to a topic, use the following function
mqttc.publish("temp", "25")
# It remains in a loop even if there are errors
while True:
try:
rc = 0
while rc == 0:
rc = mqttc.loop()
print("Mosquitto is running!: " + str(rc))
except OtherExceptions:
print("Exceptions Error Occurred!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment