-
Notifications
You must be signed in to change notification settings - Fork 19
/
mqttcam.xlua
77 lines (67 loc) · 2.42 KB
/
mqttcam.xlua
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
-- The following code creates a CAM object and publishes images to the
-- 'broker'. You must at a minimum change the 'topic' and the CAM
-- settings in 'cfg' to the settings required by your CAM board.
-- WARNING:
-- Make sure to test the CAM cfg settings in camtest.lsp prior to running this program.
-- Tutorial:
-- https://realtimelogic.com/articles/Streaming-ESP32CAM-Images-to-Multiple-Browsers-via-MQTT
-- The following two settings must correspond with settings in mqtcam.html
-- Change the topic to your address
local topic = "/xedge32/espcam/USA/92629"
-- We use the public HiveMQ broker
local broker = "broker.hivemq.com"
-- Settings for 'FREENOVE ESP32-S3 WROOM' CAM board
-- Details: https://realtimelogic.com/ba/ESP32/source/cam.html
local cfg={
d0=11, d1=9, d2=8, d3=10, d4=12, d5=18, d6=17, d7=16,
xclk=15, pclk=13, vsync=6, href=7, sda=4, scl=5, pwdn=-1,
reset=-1, freq="20000000", frame="HD"
}
-- Open the cam
local cam,err=esp32.cam(cfg)
assert(cam, err) -- Throws error if 'cfg' incorrect
local timer -- Timer object; set below.
-- MQTT connect/disconnect callback
local function onstatus(type,code,status)
-- If connecting to broker succeeded
if "mqtt" == type and "connect" == code and 0 == status.reasoncode then
timer:set(300,false,true) -- Activate timer every 300 milliseconds
trace"Connected"
return true -- Accept connection
end
timer:cancel()
trace("Disconnect or connect failed",type,code)
return true -- Keep trying
end
-- Create MQTT client
local mqtt=require("mqttc").create(broker,onstatus)
-- Timer coroutine function activated every 300 millisecond
function publishImage()
local busy=false
while true do
--trace(mqtt:status(), busy)
-- Flow control: If less than 2 queued MQTT messages
if mqtt:status() < 2 and not busy then
busy=true
-- Delegating to a thread is not required but makes the app smoother
-- Ref: https://realtimelogic.com/ba/doc/?url=auxlua.html#thread_lib
ba.thread.run(function()
local image,err=cam:read()
if image then
mqtt:publish(topic,image)
else
trace("cam:read()",err)
end
busy=false
end)
end
coroutine.yield(true) -- sleep
end
end
timer = ba.timer(publishImage)
-- Run by Xedge32 when terminating this xlua script.
function onunload()
timer:cancel()
mqtt:close()
cam:close()
end