-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtelemetry.lua
96 lines (81 loc) · 2.52 KB
/
telemetry.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
--[[
Telemetry implementation for MQTT.
]]
telemetry_channel_node = telemetry_channel .. nodeid
mqtt_topic = telemetry_channel_node .. "/csvlog"
printv(2,"mqtt_topic: ", mqtt_topic)
function mqtt_publish(broker)
local data
if (broker.short) then
data=csvs[#csvs]
else
data=csvlog
end
broker.m:publish(mqtt_topic, data, 1, 0, function(client)
printv(2,"########## Success: MQTT message sent.")
if (broker.close) then
broker.m=nil
end
end)
end
function mqtt_connect(broker)
--[[
MQTT telemetry
Encode telemetry data as JSON and publish message to
MQTT broker at topic configured within "config.lua".
]]
local m
printv(2,"Submitting telemetry data to MQTT broker.")
-- JSON payload
-- https://nodemcu.readthedocs.io/en/master/modules/sjson/
-- https://github.com/ISEMS/isems-data-collector/blob/926eb4a3/test_importer.py
printv(2,"Creating CSV payload.")
printv(2,"########## MQTT broker host:", broker.host)
m = mqtt.Client("isems-" .. nodeid, 120)
broker.m=m
m:on("connect", function(client) printv(2,"########## Connected to MQTT broker") end)
m:on("offline", function(client) printv(1,"########## MQTT broker " .. broker.host .. " offline") ; broker.m=nil end)
-- on publish message receive event
m:on("message", function(client, topic, message)
print("######## Topic", topic .. ":" )
if message ~= nil then
print("######## The MQTT server has received this message:", message)
end
end)
m:connect(broker.host, broker.port, 0,
function(client)
-- subscribe topic with qos = 0
-- client:subscribe(mqtt_topic, 0, function(client) print("subscribe success") end)
mqtt_publish(broker)
end,
function(client, reason)
print("########### MQTT connect failed. Reason: " .. reason)
end
)
end
local function get_config()
mqtt_brokers={}
for i=1,2 do
local broker={}
for _,k in ipairs{'host','port','close','short'} do
broker[k]=_G['mqtt_broker'..i..'_'..k]
end
if (broker.host ~= nil and broker.host ~= '') then
table.insert(mqtt_brokers,broker)
end
end
end
if mqtt_enabled then
printv(2,"Sending csv log mqtt data.")
printv(2,'csvlog',csvlog)
if (mqtt_brokers == nil) then
get_config()
end
for i,broker in ipairs(mqtt_brokers) do
if (broker.m) then
mqtt_publish(broker)
else
mqtt_connect(broker)
end
end
end