NodeMCU温度读取的MQTT搭建使用

前言:本文是另一篇文章《NodeMCU的使用记录》的后续。在前一篇文章中,主要是在大流程上说明了如何来使用NodeMCU,并没有深入完成一个示例,而NodeMCU最主要被用于物联网,所以本文主要以实现一个温度采集器为核心思路进行介绍,在此过程中涉及了固件程序的更新,传感器的读取,MQTT的搭建使用。

概要

为了能够清晰的介绍整个过程,我将本文分为三个部分,固件的更新、传感器数据的读取、MQTT的搭建使用,每个部分独立为一个大章节。在每个主要部分,都采用大章节进行概要介绍,然后通过小章节对细节进行说明。

固件的更新

固件的更新是最简单的过程,因为有一个在线的编译网站,选择编译的模块就可以了,编译完成后会发送下载连接到指定邮箱。

具体流程

编译网页链接:https://nodemcu-build.com/index.php

在该页面中,首先填入接收下载链接的邮箱地址。然后再选择需要的模块进行编译。因为我使用了DHT温度传感器,并且希望通过MQTT来进行数据的传输,所以最终模块的选择如下:

NodeMCU温度读取的MQTT搭建使用_第1张图片
图1  编译模块选择

注意:编译大概在5分钟内就能完成,可以刷新下邮箱获取结果邮件。

传感器数据的读取

传感器数据读取这个问题,最关键的地方并不是如何来读取,而是你如何知道别人如何知道怎么读取这个传感器数据的?就像前一篇文章中提到了GPIO的操控,但换一个其他接口,可能就不会了。所以,一定要知道这些接口在那里能够被找到,然后才是如何去使用这些接口。

模块的帮助页面

https://nodemcu.readthedocs.io/en/master/modules/mqtt/#mqttclientconnect

这个页面是NodeMCU的帮助页面,左侧列出了该目标板支持的模块,以及这些模块的操控API。

DHT传感器的数据读取

以DHT传感器模块为例,列出的API有:

dht.read()    Read all kinds of DHT sensors, including DHT11, 21, 22, 33, 44 humidity temperature combosensor.

dht.read11()   Read DHT11 humidity temperature combo sensor.

dht.readxx()    Read all kinds of DHT sensors, except DHT11.

我的传感器就是DHT11,所以通过这里来看,直接使用对应read11接口读取数据即可,代码如下:

re,t,s,x = dht.read11(1);

硬件连接

本来硬件连接应该放在更前章节进行说明,但由于这个硬件太简单,大部分人都不需要详细说明,所以就放在了本章末尾。

在DHT11传感器上,有三个引脚,一个电源输入,一个地输入,另一个就是数据输出引脚。在本例中,数据输出引脚与NodeMCU的D1引脚相连接。

MQTT的搭建使用

MQTT的搭建主要有三个部分,一个是服务器的搭建,另一个是NodeMCU程序的编写实现,最后是一个MQTT客户端的实现。

MQTT服务器搭建

这个部分主要参考了https://www.jianshu.com/p/37f7ee7ead65,基本按这个命令执行就可以。

NodeMCU的MQTT实现

这个部分主要参考了NodeMCU的模块手册,在模块手册中有一个示例代码,基于该示例代码进行了一些修改。修改后代码如下:

function mqttConnect()

    -- init mqtt client without logins, keepalive timer 120s

    m = mqtt.Client("clientid", 120)

    mqtt_client = m;

    -- setup Last Will and Testament (optional)

    -- Broker will publish a message with qos = 0, retain = 0, data = "offline"

    -- to topic "/lwt" if client don't send keepalive packet

    m:lwt("/lwt", "offline", 0, 0)


    m:on("connect", function(client) print ("mqtt connected") mqtt_connected=1; end)

    m:on("offline", function(client) print ("mqtt offline") mqtt_connected=0; end)

    -- on publish message receive event

    m:on("message", function(client, topic, data)

      print(topic .. ":" )

      if data ~= nil then

        print(data)

      end

    end)

    -- on publish overflow receive event

    m:on("overflow", function(client, topic, data)

      print(topic .. " partial overflowed message: " .. data )

    end)

    -- for TLS: m:connect("192.168.11.118", secure-port, 1)

    m:connect("192.168.1.213", 1883, 0, function(client)

      print("mqtt connected")

      mqtt_connected=1;

      -- Calling subscribe/publish only makes sense once the connection

      -- was successfully established. You can do that either here in the

      -- 'connect' callback or you need to otherwise make sure the

      -- connection was established (e.g. tracking connection status or in

      -- m:on("connect", function)).


      -- subscribe topic with qos = 0

      client:subscribe("mqtt", 0, function(client) print("subscribe success") end)

      -- publish a message with data = hello, QoS = 0, retain = 0

      --client:publish("/topic", "hello", 0, 0, function(client) print("sent") end)

    end,

    function(client, reason)

      print("failed reason: " .. reason)

    end)

end

function sendData(data)

    if (mqtt_connected == 1) then

        mqtt_client:publish("mqtt", data, 0, 0, function(client) print("sent:"..data) end)

    else

        print("mqtt is not ready!");

    end

end

NodeMCU最终整体代码如下:

local connected = 0;

local mqtt_connected = 0;

local mqtt_client = 0;

function onConnect()

    print("Connected!");

    connected = 1;

end

function mqttConnect()

    -- init mqtt client without logins, keepalive timer 120s

    m = mqtt.Client("clientid", 120)

    mqtt_client = m;

    -- setup Last Will and Testament (optional)

    -- Broker will publish a message with qos = 0, retain = 0, data = "offline"

    -- to topic "/lwt" if client don't send keepalive packet

    m:lwt("/lwt", "offline", 0, 0)


    m:on("connect", function(client) print ("mqtt connected") mqtt_connected=1; end)

    m:on("offline", function(client) print ("mqtt offline") mqtt_connected=0; end)

    -- on publish message receive event

    m:on("message", function(client, topic, data)

      print(topic .. ":" )

      if data ~= nil then

        print(data)

      end

    end)

    -- on publish overflow receive event

    m:on("overflow", function(client, topic, data)

      print(topic .. " partial overflowed message: " .. data )

    end)

    -- for TLS: m:connect("192.168.11.118", secure-port, 1)

    m:connect("192.168.1.213", 1883, 0, function(client)

      print("mqtt connected")

      mqtt_connected=1;

      -- Calling subscribe/publish only makes sense once the connection

      -- was successfully established. You can do that either here in the

      -- 'connect' callback or you need to otherwise make sure the

      -- connection was established (e.g. tracking connection status or in

      -- m:on("connect", function)).


      -- subscribe topic with qos = 0

      client:subscribe("mqtt", 0, function(client) print("subscribe success") end)

      -- publish a message with data = hello, QoS = 0, retain = 0

      --client:publish("/topic", "hello", 0, 0, function(client) print("sent") end)

    end,

    function(client, reason)

      print("failed reason: " .. reason)

    end)

end

function sendData(data)

    if (mqtt_connected == 1) then

        mqtt_client:publish("mqtt", data, 0, 0, function(client) print("sent:"..data) end)

    else

        print("mqtt is not ready!");

    end

end

--connect to Access Point (DO NOT save config to flash)

station_cfg={}

station_cfg.ssid="HiWiFi_XXXXX"

station_cfg.pwd="xxxxxxxxxxxx"

station_cfg.save=false

re = wifi.sta.config(station_cfg)

print(re)

wifi.sta.connect(onConnect)

--local mytimer = tmr.create()

--mytimer:register(10000, tmr.ALARM_SINGLE, function (t) print("expired"); t:unregister() end)

--mytimer:start()

local mytimer = tmr.create()

local times = 0;

if not mytimer:alarm(5000, tmr.ALARM_AUTO, function()

  if connected == 1 then

    if (wifi.sta.getip()) then

        connected = 2;

        print(wifi.sta.getip())

        mqttConnect();

    end

  end

  if connected == 2 then

    re,t,s,x = dht.read11(1);

    sendData(re.." "..t.." "..s.." "..x);

    --print("Send:"..re.." "..t.." "..s.." "..x);

  else

    print("read:"..dht.read11(1));

  end

end)

then

  print("whoopsie")

end

MQTT客户端实现

MQTT客户端使用Python实现,因为主要是用于进行测试,不需要很复杂的界面,安全等等机制。最终实现代码如下:

import paho.mqtt.client as mqtt

MQTTHOST = "www.xxxxx.com"

MQTTPORT = 1883

TITLE = "mqtt"

mqttClient = mqtt.Client()

# 连接MQTT服务器

def on_mqtt_connect():

    mqttClient.connect(MQTTHOST, MQTTPORT, 60)

    mqttClient.loop_start()


# 消息处理函数

def on_message_come(lient, userdata, msg):

    print(msg.topic + ":" + str(msg.payload.decode("utf-8")))

    # 消息处理开启多进程

    #p = Process(target=talk, args=("/camera/person/num/result", msg.payload.decode("utf-8")))

    #p.start()

# subscribe 消息订阅

def on_subscribe():

    mqttClient.subscribe(TITLE, 1)  # 主题为"test"

    mqttClient.on_message = on_message_come  # 消息到来处理函数

# publish 消息发布

def on_publish(topic, msg, qos):

    mqttClient.publish(topic, msg, qos);

# 多进程中发布消息需要重新初始化mqttClient

def talk(topic, msg):

    cameraPsersonNum = camera_person_num.CameraPsersonNum(msg)

    t_max, t_mean = cameraPsersonNum.personNum()

    mqttClient = mqtt.Client()

    mqttClient.connect(MQTTHOST, MQTTPORT, 60)

    mqttClient.loop_start()

    mqttClient.publish(topic, '{"max":' + str(t_max) + ',"mean:"' + str(t_mean) + '}', 1)

def main():

    on_mqtt_connect()

    on_subscribe()

    while True:

        pass

if __name__ == '__main__':

    main()

你可能感兴趣的:(NodeMCU温度读取的MQTT搭建使用)