-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy path.preload
More file actions
69 lines (58 loc) · 2.54 KB
/
.preload
File metadata and controls
69 lines (58 loc) · 2.54 KB
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
-- A simple MQTT Sparkplug Explorer
-- The broker. The public HiveMQ broker typically has many connected Sparkplug clients
local mqttServer = "broker.hivemq.com"
local mqttVer="mqttc" -- V5
--local mqttVer="mqtt3c" -- V3
local username,password="admin","admin"
local mqtt,sp,serpent -- forward declarations, see runExplorer()
local fmt=string.format
-- MQTT connect/disconnect callback
local function onstatus(type,code,status)
-- If a successful MQTT connect
if "mqtt" == type and "connect" == code and 0 == status.reasoncode then
-- Subscribe to the Sparkplug wildcard topic 'spBv1.0/#'
mqtt:subscribe"spBv1.0/#"
tracep(false,0,"MQTT connection established; Waiting for messages")
return true -- Accept connection
end
tracep(false,0,"MQTT broker disconnected or connect failed:",type,code)
return 0 -- reconnect with zero timeout
end
-- MQTT on publish callback
local function onpublish(topic,payload,prop)
tracep(false,0,fmt("Sparkplug topic: %s",topic))
local t,err = sp.decode(payload)
if t then
tracep(false,0,serpent.block(t,{comment=false}),"\n")
else
trace("Decode err",err)
end
end
-- Load the complete Sparkplug protobuf schema from the ZIP file mako.zip
local function loadSchema()
-- Open the file mako.zip:.lua/sparkplug_b.proto
local fp <close> = ba.openio"vm":open".lua/sparkplug_b.proto"
assert(fp, "\nsparkplug_b.proto not found")
return fp:read"*a" -- Return schema
end
-- The runExplorer function is the core of the script that sets up and
-- starts the Sparkplug Explorer.
local function runExplorer()
local ok
-- Load the 'protoc' Lua module, which is used for parsing the protobuf
-- schema. If the module is not found, an error message is printed.
local ok,protoc = pcall(require,"protoc")
assert(ok, "\nThe Lua module 'protoc' is not included in the server's resource file")
assert(protoc:load(loadSchema()), "Cannot parse schema")
-- Load the Serpent Lua module, a Lua serializer and pretty
-- printer. It is used for pretty printing Lua tables in
-- onpublish() above.
-- Docs: https://github.com/pkulchenko/serpent
serpent=require"serpent"
tracep(false,0,fmt("\nConnecting to broker %s",mqttServer))
-- Load and create instance: https://realtimelogic.com/ba/doc/?url=MQTT.html
mqtt=require(mqttVer).create(mqttServer,onstatus,onpublish,{recbta=false,username=username,password=password})
sp=require"SparkplugB"
tracep(false,0,"Sparkplug Explorer started")
end
ba.thread.run(runExplorer) -- Run after Mako completes the startup process