NodeMCU温度读取的MQTT搭建使用

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

概要

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

固件的更新

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

具体流程

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

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

图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()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,165评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,503评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,295评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,589评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,439评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,342评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,749评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,397评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,700评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,740评论 2 313
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,523评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,364评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,755评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,024评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,297评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,721评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,918评论 2 336

推荐阅读更多精彩内容