11local INTERVAL = 50 -- in 1/100th seconds
2- local MSP_API_VERSION = 1
2+
33local MSP_TX_INFO = 186
4- local MSP_SET_RTC = 246
54
65local lastRunTS
76local sensorId = - 1
8- local apiVersionReceived = false
9- local timeIsSet = false
7+ local dataInitialised = false
8+ local data_init = nil
109
1110local function getSensorValue ()
1211 if sensorId == - 1 then
@@ -26,64 +25,25 @@ local function init()
2625 lastRunTS = 0
2726end
2827
29- local function processMspReply (cmd ,rx_buf )
30- if cmd == nil or rx_buf == nil then
31- return
32- end
33- if cmd == MSP_API_VERSION and # (rx_buf ) >= 3 then
34- apiVersion = rx_buf [2 ] + rx_buf [3 ] / 1000
35-
36- apiVersionReceived = true
37- end
38- end
39-
4028local function run_bg ()
4129 -- run in intervals
4230 if lastRunTS == 0 or lastRunTS + INTERVAL < getTime () then
4331 local sensorValue = getSensorValue ()
4432 if modelActive (sensorValue ) then
4533 -- Send data when the telemetry connection is available
4634 -- assuming when sensor value higher than 0 there is an telemetry connection
47- if not apiVersionReceived then
48- protocol .mspRead (MSP_API_VERSION )
49-
50- processMspReply (mspPollReply ())
51- elseif apiVersionReceived and not timeIsSet then
52- -- only send datetime one time after telemetry connection became available
53- -- or when connection is restored after e.g. lipo refresh
54-
55- if apiVersion >= 1.041 then
56- -- format: seconds after the epoch (32) / milliseconds (16)
57- local now = getRtcTime ()
58-
59- values = {}
35+ if not dataInitialised then
36+ if data_init == nil then
37+ data_init = assert (loadScript (SCRIPT_HOME .. " /data_init.lua" ))()
38+ end
6039
61- for i = 1 , 4 do
62- values [i ] = bit32.band (now , 0xFF )
63- now = bit32.rshift (now , 8 )
64- end
40+ dataInitialised = data_init .init ();
6541
66- values [5 ] = 0 -- we don't have milliseconds
67- values [6 ] = 0
68- else
69- -- format: year (16) / month (8) / day (8) / hour (8) / min (8) / sec (8)
70- local now = getDateTime ()
71- local year = now .year ;
42+ if dataInitialised then
43+ data_init = nil
7244
73- values = {}
74- values [1 ] = bit32.band (year , 0xFF )
75- year = bit32.rshift (year , 8 )
76- values [2 ] = bit32.band (year , 0xFF )
77- values [3 ] = now .mon
78- values [4 ] = now .day
79- values [5 ] = now .hour
80- values [6 ] = now .min
81- values [7 ] = now .sec
45+ collectgarbage ()
8246 end
83-
84- protocol .mspWrite (MSP_SET_RTC , values )
85-
86- timeIsSet = true
8747 else
8848 local rssi , alarm_low , alarm_crit = getRSSI ()
8949 -- Scale the [0, 85] (empirical) RSSI values to [0, 255]
@@ -98,8 +58,7 @@ local function run_bg()
9858 protocol .mspWrite (MSP_TX_INFO , values )
9959 end
10060 else
101- apiVersionReceived = false
102- timeIsSet = false
61+ dataInitialised = false
10362 end
10463
10564 lastRunTS = getTime ()
0 commit comments