您的位置:首页 > 娱乐 > 八卦 > 在LUAT中使用MQTT客户端,游戏脚本,办公脚本自动操作

在LUAT中使用MQTT客户端,游戏脚本,办公脚本自动操作

2024/10/5 20:26:40 来源:https://blog.csdn.net/xiaoyao961/article/details/139554096  浏览:    关键词:在LUAT中使用MQTT客户端,游戏脚本,办公脚本自动操作

本文将介绍在LUAT中工程化使用MQTT客户端的方法及注意事项。实验平台为合宙AIR724UG,其固件版本为Luat_V4001_RDA8910_FLOAT_TMP

面向对象

使用middleclass库为脚本提供基础面向对象支持,将此repo中的middleclass.lua文件添加到项目中即可使用。middleclass库典型用法如下:

-- file: test.lua
local class = require 'middleclass'
local Test = class 'Test' -- 创建Test类-- Test对象初始化函数, 其形参个数可以是任意的
function Test:initialize(initA)self.a = initA -- 初始化成员变量
end-- Test对象成员函数
function Test:inc()self.a = self.a + 1
endfunction Test:getA()return self.a
endreturn Test
-- file: app.lua
local Test = require 'test'local test = Test:new(5) -- 创建Test对象-- 调用成员函数
test:inc()
print(test:getA()) -- 输出6
print(test.class.name) -- 输出对象类名'Test'

此外,通过middleclass还可实现继承及多态。

LUAT MQTT库介绍

使用mqtt库前,须先引入对应模块

require 'mqtt'

mqtt库相关函数如下:

local mqttc = mqtt.client('clientId') -- 创建mqtt客户端
mqttc:connect('host.com', PORT) --  连接mqtt服务器
mqttc:subscribe('/topic') -- 订阅MQTT主题
mqttc:publish('/topic', 'payload') -- 发布MQTT主题
mqttc:receive(TIMEOUT, 'EVENT_NAME') -- 接收消息

详情请参阅官方文档。

LUAT MQTT库用法

由于socket库的限制,subscribepublishreceive函数仅可在调用了connect函数的协程被调用,但对于一个完整的MQTT客户端应用,发布、订阅主题都是必不可少的环节。如何在同一协程中发布、订阅、接收MQTT主题?mqtt库对此也提供了所需接口,其中mqttc:receive的返回值是解决此问题的关键。

local TIMEOUT = 60000
local EVENT_NAME = 'CUSTOM_MQTT_EVENT'
local res, data, param = mqttc:receive(TIMEOUT, EVENT_NAME)
if res then-- 正确接收到MQTT消息,此时 type(res) == 'table'-- res.topic为消息主题、res.payload为消息负载
elseif data == 'timeout' then-- 超时错误,此时应当重新调用mqttc:receive函数
elseif data == EVENT_NAME then-- mqttc:receive所指定的名为EVENT_NAME的系统事件被发布-- 此时param为发布事件时所携带的参数-- <== 我们将在这里根据param变量进行实际的MQTT主题发布、订阅工作 ==>handleMqttAct(params) -- 此函数的实现将在下文给出
else-- 未知MQTT错误, 此时应当尝试重新连接MQTT
end

通过调用sys.publish函数,即可发布可中断mqttc:receive函数调用堵塞的系统消息。
由于socket库的限制,一般只允许在调用sys.publish时携带额外的string型参数,否则socket库内部会在接收系统事件时发生错误。通过修改socket库的源码,还可以令其允许发布对应名称系统事件时携带任意类型的参数。

--- a/lib/socket.lua
+++ b/lib/socket.lua
@@ -336,7 +336,12 @@ function mt:recv(timeout, msg, msgNoResume)if r == nil thenreturn false, "timeout"elseif r == 0xAA then
-                local dat = table.concat(self.output)
+                local dat
+                if #self.output > 0 and type(self.output[1]) ~= 'string' then
+                    dat = self.output[1]
+                else
+                    dat = table.concat(self.output)

接着,定义subscribepublish的包装函数:

function subscribe(topic)sys.publish(EVENT_NAME, {type = 'sub',topic = topic,})
endfunction publish(topic, payload)sys.publish(EVENT_NAME, {type = 'pub',topic = topic,payload = payload,})
end

外部代码通过这两个包装函数以发布、订阅MQTT主题,而实际的发布、订阅逻辑发生在handleMqttAct函数中:

function handleMqttAct(param)local sels = {sub = function()mqttc:subscribe(param.topic)end,pub = function()mqttc:publish(param.topic, param.payload)end,}local found = sels[param.type]if found ~= nil thenfound()end
end

MQTT初始化及断线重连流程

为保证程序健壮性,实际应用时常常需要涉及程序自动从错误状态恢复的逻辑,MQTT的断线重连便是其中一种:

开始套接字 就绪?连接MQTT服务器成功?获取消息处理消息延时yesnoyesnoyesno

对MQTT库进行OOP封装

最后,给出基本的Cloud类实现:

-- file: cloud.lua
require 'mqtt'
local class = require 'middleclass'
local Cloud = class 'Cloud'-- 自定义事件名
local M_MQTT_ACT = 'M_MATT_ACT'
local TIMEOUT = 60000function Cloud:initialize(host, port, clientId)self.ready = falsesys.taskInit(function()while true dowhile not socket.isReady() do sys.wait() endself.mqttc = mqtt.client(clientId)if self.mqttc:connect(host, port) thenself.ready = trueself:onConn()while true dolocal res, data, param = self.mqttc:receive(TIMEOUT, M_MQTT_ACT)if res thenself:handleMqttMsg(res.topic, res.payload)elseif data == 'timeout' then-- DO NOTHINGelseif data == M_MQTT_ACT thenself:handleMqttAct(param)elsebreak -- 断线重连endendself.ready = falseendendend)
endfunction Cloud:onConn()-- 由派生类重写
endfunction Cloud:subscribe(topic)sys.publish(M_MQTT_ACT, {type = 'sub',topic = topic,})
endfunction Cloud:publish(topic, payload)sys.publish(M_MQTT_ACT, {type = 'pub',topic = topic,payload = payload,})
endfunction Cloud:handleMqttMsg(topic, payload)-- TODO: MQTT消息处理
endfunction Cloud:handleMqttAct(param)local sels = {sub = function()self.mqttc:subscribe(param.topic)end,pub = function()self.mqttc:publish(param.topic, param.payload)end,}local found = sels[param.type]if found ~= nil thenfound()end
endreturn Cloud

Cloud,还可以拓展出自动在恢复连接后重注册已订阅主题的子类

-- file: cloudAutoReSub.lua
require 'mqtt'
local class = require 'middleclass'
local Cloud = require'cloud'
local CloudAutoReSub = class('CloudAutoReSub', Cloud)function CloudAutoReSub:initialize(host, port, clientId)self.subscribedTopics = {}self.class.super.initialize(self, host, port, clientId)
endfunction CloudAutoReSub:onConn()for _, v in ipairs(self.subscribedTopics) doself.mqttc:subscribe(v)end
endfunction CloudAutoReSub:subscribe(topic)table.insert(self.subscribedTopics, topic)self.class.super.subscribe(self, topic)
endreturn CloudAutoReSub