MQTT 介绍
什么是MQTT?
MQTT代表MQ遥测传输。它是一种发布/订阅,极其简单和轻量级的消息传递协议,专为受限设备和低带宽,高延迟或不可靠的网络而设计。设计原则是最小化网络带宽和设备资源要求,同时还试图确保可靠性和一定程度的交付保证。这些原则也使该协议成为新兴的“机器到机器”(M2M)或“物联网”世界的连接设备,以及带宽和电池功率非常高的移动应用的理想选择。
MQTT 官网
MQTT wiki
MQTT 和 Android
是否有使用MQTT的标准端口?
是。IANA保留TCP / IP端口1883以与MQTT 一起使用。TCP / IP端口8883也已注册,用于通过SSL使用MQTT。
使用 paho-mqtt 软件进行实验
环境搭建
Linux 系统(安装 python3 以及 paho-mqtt 的python库)
配置mqtt服务器请参考 linux 基本使用、新建用户、emqtt 的基本使用 中的 emqtt配置
示例代码
- Consumer.py 文件
- 功能: mqtt 主题的订阅以及接收主题中发布的信息。
- 代码如下
#!/usr/bin/python3
#以上是指定运行的软件路径
import paho.mqtt.client as mqtt
# 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))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
#订阅主题 1234
client.subscribe("1234")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
# 打印主题名字 + 指定字符串内容 + 生产者发布的内容
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60) # 客户端连接到指定的 ip 地址和端口
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever() #客户端一直运行
- Producer.py 文件
- 功能: 往 mqtt 中指定的主题发布信息。
- 代码如下
#!/usr/bin/python3
#以上是指定运行的软件路径
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client:mqtt.Client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
# 往 Consumer 订阅的主题发送信息
client.publish("1234","i send a message")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60) # 客户端连接到指定的 ip 地址和端口
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever() #客户端一直运行
print("end")
更简洁的发布方法:
主题名: 1234
服务器地址:iot.eclipse.org
发送内容: hello mqtt
$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import paho.mqtt.publish as publish
>>> publish.single("1234", " hello mqtt", hostname="iot.eclipse.org")
mqtt 接收并且存储数据
参考教程:
Python3 MySQL 数据库连接 - PyMySQL 驱动
介绍如何使用python3 连接mysql 数据库
介绍如何使用 数据库
pymysql 的 GitHub 项目地址
mysql数据库安装
sudo apt-get install mysql-server mysql-client libmysqlclient-dev
- 安装过程中会提示设置密码
sudo netstat -tap | grep mysql
- 登陆mysql数据库可以通过如下命令:
mysql -u root -p
-u 表示选择登陆的用户名, -p 表示登陆的用户密码,上面命令输入之后会提示输入密码,输入密码就可以登录到mysql。
退出命令
quit
读取数据表
#!/usr/bin/python3
# 以上代码指定 python 版本
import pymysql
# 打开数据库连接
# 输入 地址 用户名 密码 数据库名字
db = pymysql.connect("localhost","root","password","database")
# 使用 cursor() 方法创建一个游标对象 cursor
cur = db.cursor()
# 使用 execute() 方法执行 SQL
table = "pitable" # 设置数据表名字
# cur.execute("select * from pitable")
cur.execute("select * from %s" % (table))
try:
# 使用 fetchone() 方法获取单条数据
#data = cur.fetchone()
#print("数据表的单行内容是: \n", data)
# 使用 fetchall() 接收全部的返回结果行
dataAll = cur.fetchall()
print("数据表的全部内容是: \n", dataAll)
db.commit()
except:
# 如果发送错误则回滚
print("--------------error!-----------------")
db.rollback()
# 关闭数据库连接
db.close()
插入数据到数据表
#!/usr/bin/python3
# 以上代码指定 python 版本
import pymysql
# 打开数据库链接
# 输入 地址 用户名 密码 数据库名字
db = pymysql.connect("localhost","root","password","database")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
try:
#sql_insert="insert into pitable values('Java','30')"
value_name = 'python36'
value = '36'
sql_insert="insert into pitable values(%s,%s)"
# 使用 execute() 方法执行 SQL
cursor.execute(sql_insert,(value_name,value))
print("/-------- insert successfully ---------/")
print(sql_insert)
# 执行sql语句
db.commit()
except:
# 如果发送错误则回滚
print("/-------------- error! ----------------/")
db.rollback()
# 关闭数据库连接
db.close()
mqtt 消费者接收数据并且存到数据表
# !/usr/bin/python3
# 以上是指定运行的软件路径
import paho.mqtt.client as mqtt # mqtt协议
import pymysql # python mysql
# 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))
if rc == 0:
print ("connetced MQTT server successfuly!")
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
# 订阅主题 topic_test
client.subscribe("topic_test")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
# 打印主题名字 + 指定字符串内容 + 生产者发布的内容
print("Topic is ", msg.topic) # debug
print(msg.topic+"\n get the messages \n"+str(msg.payload))
# 输入 地址 用户名 密码 数据库名字
db = pymysql.connect("localhost","root","password","database")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
try:
sql_insert="insert into dataTable values(%s,%s)"
# 使用 execute() 方法执行 SQL
cursor.execute(sql_insert, (msg.topic, msg.payload))
print("/-------- insert successfully ---------/")
print(sql_insert)
# 执行sql语句
db.commit()
except:
# 如果发送错误则回滚
print("/-------------- error! ----------------/")
db.rollback()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# 客户端连接到指定的 ip 地址和端口
client.connect("47.xxx.251.xxx", 1883, 60)
# client.connect("iot.eclipse.org", 1883, 60) # paho-mqtt 提供的一个 mqtt 服务器
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever() #客户端一直运行