mqtt.js和python paho-mqtt,python编写通过mqtt服务器和网页之间收发数据的程序,将数据存入sqlite3数据库...

mqtt

mosquitto -v

8、修改配置文件,使其支持websocket协议,
建立配置文件/etc/mosquitto/mosquitto.conf 把mosquitto源码目录下提供的默认配置文件复制到/etc/mosquitto目录
cp mosquitto.conf /etc/mosquitto
cd /etc/mosquitto

然后,修改配置文件mosquitto.conf,
vi /etc/mosquitto/mosquitto.conf

在/etc/mosquitto/mosquitto.conf 的“Default listener” 一节添加如下几行:
port 1883
listener 9001
protocol websockets

9、指定默认配置文件启动运行,使其支持websocket协议

mosquitto -v -c /etc/mosquitto/mosquitto.conf 


二、MQTT测试运行

一个完整的MQTT示例包括一个代理器,一个发布者和一个订阅者。测试分为以下几个步骤:

【1】启动服务mosquitto。

【2】订阅者通过mosquitto_sub订阅指定主题的消息。

【3】发布者通过mosquitto_pub发布指定主题的消息。

【4】代理服务器把该主题的消息推送到订阅者。

在线安装的服务器默认启动了,如果没有启动

1.1 启动代理服务
mosquitto -v -c /etc/mosquitto/mosquitto.conf 
    【-v】打印更多的调试信息
    【-c】指定配置文件

1.2 订阅主题
mosquitto_sub -v -t sensor
    【-t】指定主题,此处为sensor
    【-v】打印更多的调试信息
    【-h】指定mqtt服务器地址,缺省指连接到本机127.0.0.1
1.3 发布内容
mosquitto_pub -t sensor  -m 12
    【-t】指定主题
    【-m】指定消息内容
    【-h】指定mqtt服务器地址,缺省指连接到本机127.0.0.1
1.4 运行结果

    当发布者推送消息之后,订阅者获得以下内容
sensor 12


 mosquitto客户端操作Shell命令例子
1)、在192.168.1.200上开启一个终端运行MQTT服务器
mosquito -v -c /etc/mosquitto/mosquitto.conf 

2)、开启另外一个终端执行订阅主题的shell命令,程序运行后进入等待状态;
mosquitto_sub -d -h 192.168.1.200 -t msg
3)、在开启一个新终端,执行发布指定主题与消息的shell命令
mosquitto_pub -d -h 192.168.1.200 -t msg -m "hello"

发布消息命令执行完毕后,切换到订阅消息的终端窗口,将看到订阅的消息内容,切换到服务器运行的终端,可以看到两客户端连接到服务器的信息。

image

image

安装libwebsocket

image

image

image

(63条消息) 最新libwebsockets库的编译与测试方法_点点滴滴-CSDN博客_libwebsockets编译

image

让mqtt支持websocket,将68行改为yes

make

make prefix=/usr install

image

image

image

配置结束后需要重启

image

image

image

image

image

image

image

python paho-mqtt

image

image

# -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
from random import random

import paho.mqtt.client as mqtt
import time
import json
broker = '192.168.118.134'
port = 1883
topic = "sensor/photosensitive"
client_id = f'python-mqtt-{1}'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
    # Set Connecting Client ID
    client = mqtt.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))


def publish(client):
    i = 0
    while True:
        x = {'photosensitive': i}
        i = i + 1
        time.sleep(1)
        msg = json.dumps(x)
        result = client.publish(topic, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")






def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)

if __name__ == '__main__':
    run()

image

用1883

9001用于websocket

(63条消息) mosquitto与web连接_JavaEE菜鸟-CSDN博客_mosquitto 连接

image

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <!-- Load c3.css -->
    <link type="text/css" href="../static/css/c3.css" rel="stylesheet">
</head>

<body>
    <div id="real-chart"></div>

    <!-- Load d3.js and c3.js -->
    <script type="text/javascript" src="../static/js/d3.v4.min.js" charset="utf-8"></script>
    <script type="text/javascript" src="../static/js/c3.min.js"></script>

    <script type="text/javascript" src="../static/js/paho-mqtt.js"></script>

    <script>
        // 初始化图表
        var chart = c3.generate({
            bindto: '#real-chart',
            data: {
                json: [],
                type: 'area-spline', // line,spline,step,area,area-spline,area-step,bar,scatter,pie,donut,gauge
                labels: true,
            },
            axis: {
                x: {
                    type: 'timeseries',
                    tick: { // 设置刻度轴
                        count: 12,
                        culling: {
                            max: 12
                        },
                        format: '%Y-%m-%d %H:%M:%S',
                    }
                }
            },
        });

        // 生成图表数据
        var metrics = ['光强'];
        var addData = (function() {
            var datas = [];
            return function(data) {
                datas.push(data);
                if (datas.length < 12) {
                    chart.load({
                        json: datas,
                        keys: {
                            x: 'date',
                            value: metrics,
                        },
                    });
                } else {
                    chart.flow({
                        json: [data],
                        keys: {
                            x: 'date',
                            value: metrics,
                        },
                        duration: 1000,
                    });
                }
            }
        })();

        // Create a client instance
        client = new Paho.MQTT.Client("192.168.118.134", Number(9001), "clientId-sub");

        // set callback handlers
        client.onConnectionLost = onConnectionLost;
        client.onMessageArrived = onMessageArrived;

        // connect the client
        client.connect({
            onSuccess: onConnect
        });


        // called when the client connects
        function onConnect() {
            // Once a connection has been made, make a subscription and send a message.
            console.log("onConnect");
            client.subscribe("sensor/photosensitive");
        }

        // called when the client loses its connection
        function onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                console.log("onConnectionLost:" + responseObject.errorMessage);
            }
        }

        // called when a message arrives
        function onMessageArrived(message) {
            console.log("onMessageArrived:" + message.payloadString);
            var obj = JSON.parse(message.payloadString);
            var data = {
                date: new Date(),
                光强: Math.floor(obj.photosensitive),
            };
            addData(data);
        }
    </script>
</body>

</html>

image

从网页获取数据存入sqlite3数据库

# -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
import datetime
from random import random

import paho.mqtt.client as mqtt
import time
import json
from mqtt.DBControl import DBControl
broker = '192.168.118.134'
port = 1883
topic = "sensor/photosensitive"
client_id = f'python-mqtt-{1}'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
    # Set Connecting Client ID
    client = mqtt.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))


# def publish(client):
#     i = 0
#     while True:
#         x = {'photosensitive': i}
#         i = i + 1
#         time.sleep(1)
#         msg = json.dumps(x)
#         result = client.publish(topic, msg)
#         # result: [0, 1]
#         status = result[0]
#         if status == 0:
#             print(f"Send `{msg}` to topic `{topic}`")
#         else:
#             print(f"Failed to send message to topic {topic}")
def sub(client):
    def on_message(client, userdata, msg):
        # print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        sqldata = msg.payload.decode()
        sqldata = json.loads(sqldata)
        # print(sqldata)
        print(sqldata['photosensitive'])
        mydb = DBControl('sensordatas.db')
        nowdate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        mydb.insert_data('pht',sqldata['photosensitive'], nowdate)
        print(mydb.query_data('pht'))

    client.subscribe(topic)
    client.on_message = on_message


def run():
    client = connect_mqtt()
    # client.loop_start()
    sub(client)
    client.loop_forever()
if __name__ == '__main__':
    run()
import sqlite3
import datetime


class DBControl(object):
    def __init__(self, dbpath):
        try:
            # 打开数据库连接
            self.db = sqlite3.connect(dbpath)
            self.cursor = self.db.cursor()  # 创建一个游标对象
            self.table_name = "phtdatas"    # 数据库表名
            self.init_db()
        except Exception as e:
            print(e)
    '''
    初始化数据库,不存在的表格则创建
    '''
    def init_db(self):
        re = self.is_exist_table(self.table_name)
        if  re[0][0] < 1:
            self.create_table('''create table ''' + self.table_name + '''(
                    id integer not null primary key autoincrement,
                    pht integer,
                    time datetime )''')


    '''
    是否存在名为table_name的表格,不存在返回0
    '''
    def is_exist_table(self, table_name):
        re = 0
        sql = '''select count(*)  from sqlite_master where type='table' and name = '%s';''' % table_name

        try:
            re = self.cursor.execute(sql)
        except Exception as e:
            print(e)

        return self.cursor.fetchall()


    '''
    创建表格
    '''
    def create_table(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            print(e)


    '''
    数据插入
    '''
    def insert_data(self, data_type, data, time):
        sql = '''insert into '''

        if data_type == "pht":
            sql = sql + self.table_name+'''(pht, time) 
            values(%d, '%s')'''%(data, time)

        # 插入数据库的操作
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except Exception as e:
            print(e)
            if self.db:
                self.db.rollback()


    '''
    查询数据库数据
    '''
    def query_data(self, data_type, numbers=10):
        sql = '''select * from '''
        result = []

        if data_type == "pht":
            sql = sql + self.table_name + ''' order by id desc 
                                        limit %d''' %(numbers)

        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()  # 获取查询的数据
        except Exception as e:
            print(e)

        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值