Repository navigation
Expand file tree
/
Copy pathArgumentLogger_For_PythonGUI.lua
More file actions
895 lines (822 loc) · 27 KB
/
Copy pathArgumentLogger_For_PythonGUI.lua
File metadata and controls
895 lines (822 loc) · 27 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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
--====================================================================
-- DCS Export Arguments
--
-- Logs everything the DCS export environment can see for the player
-- aircraft. Each category can be switched on/off from the control
-- file written by Helios_Argument_Logger_GUI.py:
--
-- GENERATED by the aircraft
-- ARGS cockpit arguments (device 0)
-- INDICATIONS list_indication() text displays
-- FLIGHT LoGet* flight data (speeds, attitude, position...)
-- SYSTEMS LoGet* engine / mechanical / payload / nav data
-- DRAWARGS external model draw arguments
-- DEVICES radio / avionics device getters (frequency, power)
-- PROBE also call every get_*/is_* getter on every device
-- RECEIVED by the aircraft
-- SENSORS RWR/TWS emitters, targets, radio beacons
-- COMMANDS LoSetCommand / performClickableAction / SetCommand
-- calls made by export scripts (Helios, DCS-BIOS...)
--====================================================================
local lfs = require "lfs"
local firstRun = true
local prevArgs = {}
local prevDrawArgs = {}
local prevIndications = {}
local prevData = {}
local prevDeviceData = {}
local loggerDirectory = HELIOS_ARGUMENT_LOGGER_DIR
if type(loggerDirectory) ~= "string" or loggerDirectory == "" then
error("Helios Argument Logger folder was not set by Export.lua")
end
loggerDirectory = loggerDirectory:gsub("\\", "/")
local logDirectory = loggerDirectory .. "/Logs"
local controlFilePath = loggerDirectory .. "/ArgumentLogger_For_PythonGUI.control"
local logFile = nil
local logDirty = false
local loggingEnabled = false
local ThisExport = {}
local PrevExport = {}
PrevExport.LuaExportStart = LuaExportStart
PrevExport.LuaExportStop = LuaExportStop
PrevExport.LuaExportBeforeNextFrame = LuaExportBeforeNextFrame
PrevExport.LuaExportAfterNextFrame = LuaExportAfterNextFrame
PrevExport.LuaExportActivityNextEvent = LuaExportActivityNextEvent
local DCSInfo = LoGetSelfData()
local LOG_ARGUMENT_CHANGES = true
----------------------------------------------------------------------
-- Configuration
----------------------------------------------------------------------
local MAX_COCKPIT_ARG = 8316 -- cockpit arguments scanned on device 0
local MAX_DRAW_ARG = 1500 -- external model draw arguments scanned
local MAX_INDICATION = 64 -- list_indication ids scanned
local MAX_DEVICE_ID = 256 -- device ids probed with GetDevice()
local MAX_TABLE_DEPTH = 6 -- nesting limit when flattening LoGet* tables
local MIN_INTERVAL = 0.2
local MAX_INTERVAL = 60
-- Defaults used when the control file does not mention an option.
local DEFAULT_OPTIONS = {
INTERVAL = 5, -- seconds between scans
ARGS = true,
INDICATIONS = true,
FLIGHT = true,
SYSTEMS = true,
SENSORS = true,
DEVICES = true,
PROBE = false,
DRAWARGS = false,
COMMANDS = true,
}
local OPTION_ORDER = {
"ARGS", "INDICATIONS", "FLIGHT", "SYSTEMS", "SENSORS",
"DEVICES", "PROBE", "DRAWARGS", "COMMANDS",
}
local opts = {}
for k, v in pairs(DEFAULT_OPTIONS) do opts[k] = v end
local nextTickTime = 0
local nextScanTime = 0
-- LoGet* functions polled each scan. Missing functions are skipped and
-- every call is protected, so the lists can safely name functions that
-- only exist for some aircraft.
local FLIGHT_FUNCTIONS = {
"LoGetSelfData", "LoGetIndicatedAirSpeed", "LoGetTrueAirSpeed", "LoGetMachNumber",
"LoGetAltitudeAboveSeaLevel", "LoGetAltitudeAboveGroundLevel", "LoGetVerticalVelocity",
"LoGetAngleOfAttack", "LoGetAccelerationUnits", "LoGetADIPitchBankYaw", "LoGetMagneticYaw",
"LoGetSlipBallPosition", "LoGetGlideDeviation", "LoGetSideDeviation", "LoGetAngularVelocity",
"LoGetVectorVelocity", "LoGetVectorWindVelocity", "LoGetBasicAtmospherePressure",
"LoGetShakeAmplitude",
}
local SYSTEMS_FUNCTIONS = {
"LoGetEngineInfo", "LoGetMechInfo", "LoGetMCPState", "LoGetPayloadInfo", "LoGetSnares",
"LoGetControlPanel_HSI", "LoGetNavigationInfo", "LoGetRoute", "LoGetFMData",
"LoGetHelicopterFMData", "LoGetPilotName", "LoGetPlayerPlaneId",
}
local SENSOR_FUNCTIONS = {
"LoGetTWSInfo", "LoGetTargetInformation", "LoGetLockedTargetInformation",
"LoGetF15_TWS_Contacts", "LoGetSightingSystemInfo", "LoGetWingInfo",
"LoGetRadioBeaconsStatus",
}
-- Device getters that are known to take no arguments.
local SAFE_DEVICE_GETTERS = { get_frequency = true, is_on = true }
-- Getters that are never probed (they need arguments or are handled elsewhere).
local PROBE_EXCLUDE = { get_argument_value = true, is_frequency_in_range = true }
----------------------------------------------------------------------
-- Utility: control file state
----------------------------------------------------------------------
local function isTruthy(value)
return value == "1" or value == "on" or value == "true" or value == "yes" or value == "start"
end
-- Returns enabled(boolean), options(table); or nil when the file is
-- missing/empty (for example while the GUI is rewriting it).
local function readControl()
local f = io.open(controlFilePath, "r")
if not f then
return nil
end
local text = f:read("*a") or ""
f:close()
if not string.find(text, "%S") then
return nil
end
local enabled = false
local newOpts = {}
for k, v in pairs(DEFAULT_OPTIONS) do newOpts[k] = v end
for line in string.gmatch(text, "[^\r\n]+") do
local trimmed = (line:gsub("^%s+", ""):gsub("%s+$", ""))
local key, value = trimmed:match("^([%w_]+)%s*=%s*(.-)$")
if key then
key = string.upper(key)
value = string.lower(value)
if key == "INTERVAL" then
local n = tonumber(value)
if n then
if n < MIN_INTERVAL then n = MIN_INTERVAL end
if n > MAX_INTERVAL then n = MAX_INTERVAL end
newOpts.INTERVAL = n
end
elseif key == "STATE" then
enabled = isTruthy(value)
elseif DEFAULT_OPTIONS[key] ~= nil then
newOpts[key] = isTruthy(value)
end
else
local word = string.lower(trimmed)
if word == "on" or word == "start" or word == "1" then
enabled = true
elseif word == "off" or word == "stop" or word == "0" then
enabled = false
end
end
end
return enabled, newOpts
end
local function optionsSummary()
local parts = { string.format("INTERVAL=%g", opts.INTERVAL) }
for _, key in ipairs(OPTION_ORDER) do
parts[#parts + 1] = key .. "=" .. (opts[key] and "1" or "0")
end
return table.concat(parts, " ")
end
----------------------------------------------------------------------
-- Utility: append to log
----------------------------------------------------------------------
local function logLine(text)
if logFile then
logFile:write(text .. "\n")
logDirty = true
end
end
local function flushLog()
if logFile and logDirty then
logFile:flush()
logDirty = false
end
end
local function openNewLogFile()
if not lfs.attributes(logDirectory) then
assert(lfs.mkdir(logDirectory))
end
local aircraftName = "UnknownAircraft"
if DCSInfo then
aircraftName = DCSInfo.Name or DCSInfo.Type or aircraftName
end
aircraftName = tostring(aircraftName):gsub("[^%w%-_]", "_")
aircraftName = aircraftName:gsub("_+", "_"):gsub("^_", ""):gsub("_$", "")
if aircraftName == "" then
aircraftName = "UnknownAircraft"
end
local index = 1
while true do
local suffix = index == 1 and "" or "_" .. index
local path = string.format("%s/%s_Argument_Log%s.log", logDirectory, aircraftName, suffix)
local existingFile = io.open(path, "r")
if existingFile then
existingFile:close()
index = index + 1
else
logFile = assert(io.open(path, "w"))
return
end
end
end
----------------------------------------------------------------------
-- Utility: value formatting and change detection
----------------------------------------------------------------------
local function packResults(...)
return select("#", ...), { ... }
end
local function formatNumber(v)
if v ~= v then return "nan" end
if v == math.huge then return "inf" end
if v == -math.huge then return "-inf" end
if v == math.floor(v) and math.abs(v) < 1e15 then
return string.format("%.0f", v)
end
return string.format("%.4f", v)
end
-- Keeps text on one log line. binary=true also escapes every byte that
-- is not printable ASCII.
local function escapeText(s, binary, limit)
s = tostring(s)
local extra = 0
if limit and #s > limit then
extra = #s - limit
s = string.sub(s, 1, limit)
end
s = s:gsub("\\", "\\\\"):gsub("\"", "\\\""):gsub("\n", "\\n"):gsub("\r", "\\r"):gsub("\t", "\\t")
local pattern = binary and "[^\32-\126]" or "%c"
s = s:gsub(pattern, function(c) return string.format("\\x%02X", string.byte(c)) end)
if extra > 0 then
s = s .. string.format("...(+%d bytes)", extra)
end
return s
end
local function formatValue(v)
local tv = type(v)
if tv == "number" then return formatNumber(v) end
if tv == "string" then return '"' .. escapeText(v, false, 200) .. '"' end
if tv == "boolean" or tv == "nil" then return tostring(v) end
return "<" .. tv .. ">"
end
-- Flattens any value into out["a.b.c"] = "text" pairs.
local function flatten(value, prefix, out, depth, seen)
local tv = type(value)
if tv == "table" then
if depth >= MAX_TABLE_DEPTH or seen[value] then
out[prefix] = "<table>"
return
end
seen[value] = true
local empty = true
for k, v in pairs(value) do
empty = false
flatten(v, prefix .. "." .. tostring(k), out, depth + 1, seen)
end
seen[value] = nil
if empty then
out[prefix] = "{}"
end
elseif tv ~= "nil" then
out[prefix] = formatValue(value)
end
end
-- Logs every key whose text differs from the previous scan. The first
-- time a storeKey is seen every key is logged (a snapshot).
local function diffAndLog(store, storeKey, newFlat, changedFormat, removedFormat)
local old = store[storeKey]
local changed = {}
for k, v in pairs(newFlat) do
if old == nil or old[k] ~= v then
changed[#changed + 1] = k
end
end
table.sort(changed)
for _, k in ipairs(changed) do
logLine(string.format(changedFormat, k, newFlat[k]))
end
if old then
local removed = {}
for k in pairs(old) do
if newFlat[k] == nil then
removed[#removed + 1] = k
end
end
table.sort(removed)
for _, k in ipairs(removed) do
logLine(string.format(removedFormat, k))
end
end
store[storeKey] = newFlat
end
local function modelTime()
if type(LoGetModelTime) == "function" then
local ok, t = pcall(LoGetModelTime)
if ok and type(t) == "number" then return t end
end
return 0
end
----------------------------------------------------------------------
-- Hooks: commands received
--
-- Hooks are installed the first time their category is enabled and are
-- removed in LuaExportStop. A hook always calls the original function
-- with the original arguments; logging is protected so a logger fault
-- can never break the script that was hooked.
----------------------------------------------------------------------
local hooks = {}
local hookGeneration = 0
local hookedIndex = setmetatable({}, { __mode = "k" })
local deviceIds = setmetatable({}, { __mode = "k" })
local commandHooksInstalled = false
local function installHook(tbl, key, makeWrapper)
local orig = rawget(tbl, key)
if type(orig) ~= "function" then
return false
end
local wrapper = makeWrapper(orig, hookGeneration)
rawset(tbl, key, wrapper)
hooks[#hooks + 1] = { tbl = tbl, key = key, orig = orig, wrapper = wrapper }
return true
end
local function removeHooks()
for i = #hooks, 1, -1 do
local h = hooks[i]
-- Only restore when nobody else wrapped the function after us.
if rawget(h.tbl, h.key) == h.wrapper then
rawset(h.tbl, h.key, h.orig)
end
hooks[i] = nil
end
hookGeneration = hookGeneration + 1 -- silences any wrapper left in a chain
hookedIndex = setmetatable({}, { __mode = "k" })
deviceIds = setmetatable({}, { __mode = "k" })
commandHooksInstalled = false
end
local function formatCallArgs(...)
local n = select("#", ...)
local parts = {}
for i = 1, n do
local v = select(i, ...)
if type(v) == "number" then
if v == math.floor(v) then
parts[i] = string.format("%.0f", v)
else
parts[i] = string.format("%.3f", v)
end
else
parts[i] = formatValue(v)
end
end
return table.concat(parts, ", ")
end
local function deviceLabel(dev)
local id = deviceIds[dev]
if id == nil and type(dev) == "table" then
local link = rawget(dev, "link")
if link ~= nil then
id = deviceIds[link]
end
end
if id == nil then
return "Dev ???"
end
return string.format("Dev %03d", id)
end
local function hookDeviceMethods(dev)
local mt = getmetatable(dev)
local idx = type(mt) == "table" and rawget(mt, "__index") or nil
if type(idx) ~= "table" or hookedIndex[idx] then
return
end
hookedIndex[idx] = true
for _, method in ipairs({ "performClickableAction", "SetCommand" }) do
installHook(idx, method, function(orig, generation)
return function(self, ...)
if loggingEnabled and opts.COMMANDS and generation == hookGeneration then
pcall(function(...)
logLine(string.format("CMD IN: t=%.3f %s %s(%s)",
modelTime(), deviceLabel(self), method, formatCallArgs(...)))
end, ...)
end
return orig(self, ...)
end
end)
end
end
local function registerDevice(dev, id)
if type(dev) ~= "table" and type(dev) ~= "userdata" then
return
end
deviceIds[dev] = id
if type(dev) == "table" then
local link = rawget(dev, "link")
if link ~= nil then
deviceIds[link] = id
end
end
if commandHooksInstalled then
hookDeviceMethods(dev)
end
end
local function ensureCommandHooks()
if commandHooksInstalled then
return
end
commandHooksInstalled = true
installHook(_G, "LoSetCommand", function(orig, generation)
return function(...)
if loggingEnabled and opts.COMMANDS and generation == hookGeneration then
pcall(function(...)
logLine(string.format("CMD IN: t=%.3f LoSetCommand(%s)", modelTime(), formatCallArgs(...)))
end, ...)
end
return orig(...)
end
end)
-- Wrapping GetDevice lets us learn which device id each object is.
installHook(_G, "GetDevice", function(orig, generation)
return function(id, ...)
local dev = orig(id, ...)
if dev ~= nil and generation == hookGeneration then
pcall(registerDevice, dev, id)
end
return dev
end
end)
-- Hook the devices that already exist.
for id = 0, MAX_DEVICE_ID do
local ok, dev = pcall(GetDevice, id)
if ok and dev ~= nil then
pcall(registerDevice, dev, id)
end
end
end
----------------------------------------------------------------------
-- Collectors
----------------------------------------------------------------------
local function scanCockpitArguments()
local dev = GetDevice(0)
if not dev then
return
end
dev:update_arguments()
local markerArg = 1352 -- This is used to print out a marker value
local val = dev:get_argument_value(markerArg)
-- Only log if:
-- 1) value changed
if prevArgs[markerArg] ~= val and not firstRun and LOG_ARGUMENT_CHANGES then
local msg = string.format(
"ARG Marker : Arg %03d = %.3f",
markerArg, val
)
logLine(msg)
end
prevArgs[markerArg] = val
local baseCount = 0
for arg = 1, MAX_COCKPIT_ARG do
local val = dev:get_argument_value(arg)
-- Only log if:
-- 1) value changed
if prevArgs[arg] ~= val and not firstRun and LOG_ARGUMENT_CHANGES then
local msg = string.format(
"ARG CHANGE: Arg %03d = %.3f",
arg, val
)
logLine(msg)
elseif firstRun and LOG_ARGUMENT_CHANGES and val ~= 0 then
-- Starting values: only the non-zero ones are written, so the
-- GUI knows every other argument started at zero and can show
-- the previous value for the first change of any argument.
logLine(string.format("ARG BASE: Arg %03d = %.3f", arg, val))
baseCount = baseCount + 1
end
prevArgs[arg] = val
end
if firstRun and LOG_ARGUMENT_CHANGES then
logLine(string.format("ARG BASE: %d non-zero argument values recorded", baseCount))
end
end
local function scanDrawArguments()
if type(LoGetAircraftDrawArgumentValue) ~= "function" then
return
end
-- The first scan after logging starts records the starting values.
-- Only the non-zero ones are written (DRAW BASE), so the GUI knows every
-- other draw argument started at zero.
local baseline = next(prevDrawArgs) == nil
local baseCount = 0
for arg = 0, MAX_DRAW_ARG do
local ok, val = pcall(LoGetAircraftDrawArgumentValue, arg)
if ok and type(val) == "number" then
local prev = prevDrawArgs[arg]
if prev ~= nil and prev ~= val then
logLine(string.format("DRAW CHANGE: Arg %03d = %.3f", arg, val))
elseif baseline and val ~= 0 then
logLine(string.format("DRAW BASE: Arg %03d = %.3f", arg, val))
baseCount = baseCount + 1
end
prevDrawArgs[arg] = val
end
end
if baseline then
logLine(string.format("DRAW BASE: %d non-zero draw argument values recorded", baseCount))
end
end
local function indicationSignature(li)
local keys = {}
for k in pairs(li) do keys[#keys + 1] = k end
table.sort(keys)
local parts = {}
for i, k in ipairs(keys) do
parts[i] = k .. "=" .. tostring(li[k])
end
return table.concat(parts, "\n")
end
local function scanIndications()
for ii = 1, MAX_INDICATION do
local ok, li = pcall(parse_indication, ii)
if not ok then li = nil end
local signature = li and indicationSignature(li) or nil
local previous = prevIndications[ii]
if li and signature ~= previous then
logLine(string.format("indications Dump %d\n%s\n", ii, Heliosdump(li, 3)))
elseif not li and previous then
logLine(string.format("indications Removed %d", ii))
end
prevIndications[ii] = signature
end
end
local function scanLoGetGroup(label, names)
local changedFormat = "DATA CHANGE: [" .. label .. "] %s = %s"
local removedFormat = "DATA REMOVED: [" .. label .. "] %s"
for _, name in ipairs(names) do
local fn = rawget(_G, name)
if type(fn) == "function" then
local n, res = packResults(pcall(fn))
local flat = {}
if res[1] then
if n == 2 then
flatten(res[2], name, flat, 0, {})
elseif n > 2 then
for i = 2, n do
flatten(res[i], name .. "." .. (i - 1), flat, 0, {})
end
end
end
diffAndLog(prevData, name, flat, changedFormat, removedFormat)
end
end
end
local devices = nil
local function discoverDevices()
devices = {}
for id = 1, MAX_DEVICE_ID do
local ok, dev = pcall(GetDevice, id)
if ok and dev ~= nil then
pcall(registerDevice, dev, id)
local methods = {}
local mt = getmetatable(dev)
local idx = type(mt) == "table" and rawget(mt, "__index") or nil
if type(idx) == "table" then
for name, fn in pairs(idx) do
if type(name) == "string" and type(fn) == "function" then
methods[#methods + 1] = name
end
end
table.sort(methods)
end
devices[#devices + 1] = { id = id, obj = dev, methods = methods, bad = {}, announced = false }
end
end
end
local function wantDeviceGetter(name)
if SAFE_DEVICE_GETTERS[name] then
return true
end
if opts.PROBE and not PROBE_EXCLUDE[name] then
return string.find(name, "^get_") ~= nil or string.find(name, "^is_") ~= nil
end
return false
end
local function scanDevices()
if devices == nil or #devices == 0 then
discoverDevices()
end
for _, d in ipairs(devices) do
if not d.announced then
d.announced = true
if #d.methods > 0 then
logLine(string.format("DEV INFO: Dev %03d methods: %s", d.id, table.concat(d.methods, ", ")))
end
end
local flat = {}
for _, name in ipairs(d.methods) do
if not d.bad[name] and wantDeviceGetter(name) then
local n, res = packResults(pcall(function() return d.obj[name](d.obj) end))
if not res[1] then
d.bad[name] = true -- needs arguments or failed: never call again
elseif n == 2 then
flatten(res[2], name, flat, 0, {})
elseif n > 2 then
for i = 2, n do
flatten(res[i], name .. "." .. (i - 1), flat, 0, {})
end
end
end
end
local prefix = string.format("Dev %03d", d.id)
diffAndLog(prevDeviceData, d.id, flat,
"DEV CHANGE: " .. prefix .. " %s = %s",
"DEV REMOVED: " .. prefix .. " %s")
end
end
local function resetScanState()
firstRun = true
prevDrawArgs = {}
prevIndications = {}
prevData = {}
prevDeviceData = {}
if devices then
for _, d in ipairs(devices) do d.announced = false end
end
end
local function runCollector(name, fn, ...)
local ok, err = pcall(fn, ...)
if not ok then
logLine(string.format("LOGGER ERROR: %s: %s", name, tostring(err)))
end
end
local function scan(t)
logLine(string.format("=== Scan === %.3f", t))
if firstRun then
logLine("= Suppressing Initial Values =")
logLine("= (non-zero arguments are recorded as ARG BASE; other data is listed once in full) =")
end
if opts.ARGS then runCollector("ARGS", scanCockpitArguments) end
if opts.DRAWARGS then runCollector("DRAWARGS", scanDrawArguments) end
if opts.FLIGHT then runCollector("FLIGHT", scanLoGetGroup, "FLIGHT", FLIGHT_FUNCTIONS) end
if opts.SYSTEMS then runCollector("SYSTEMS", scanLoGetGroup, "SYSTEMS", SYSTEMS_FUNCTIONS) end
if opts.SENSORS then runCollector("SENSORS", scanLoGetGroup, "SENSORS", SENSOR_FUNCTIONS) end
if opts.DEVICES or opts.PROBE then runCollector("DEVICES", scanDevices) end
-- Dump out the List Items
if opts.INDICATIONS then runCollector("INDICATIONS", scanIndications) end
firstRun = false
end
----------------------------------------------------------------------
-- Lifecycle
----------------------------------------------------------------------
function LuaExportStart()
resetScanState()
prevArgs = {}
devices = nil
nextTickTime = 0
nextScanTime = 0
local enabled, newOpts = readControl()
loggingEnabled = enabled == true
if newOpts then opts = newOpts end
log.write("ArgumentLogger_For_PythonGUI.EXPORT", log.INFO, "Export Started")
DCSInfo = LoGetSelfData()
if logFile then
logFile:flush()
logFile:close()
end
openNewLogFile()
logLine(string.format("=== Argument Logger Started at %s ===", os.date("%H:%M:%S")))
if DCSInfo ~= nil then
logLine(string.format("=== Aircraft %s ===", tostring(DCSInfo.Name)))
end
logLine(string.format("=== Options: %s ===", optionsSummary()))
flushLog()
if PrevExport.LuaExportStart then
PrevExport.LuaExportStart()
end
end
function LuaExportStop()
pcall(removeHooks)
if logFile then
logLine("=== Logger Stopped ===")
logFile:flush()
logFile:close()
logFile = nil
end
if PrevExport.LuaExportStop then
PrevExport.LuaExportStop()
end
-- A stop has been issued so we unhook the child routines because if
-- we restart, it could be with a new aircraft
LuaExportStart = ThisExport.LuaExportStart
LuaExportStop = ThisExport.LuaExportStop
LuaExportAfterNextFrame = ThisExport.LuaExportAfterNextFrame
LuaExportBeforeNextFrame = ThisExport.LuaExportBeforeNextFrame
LuaExportActivityNextEvent = ThisExport.LuaExportActivityNextEvent
end
----------------------------------------------------------------------
-- Main loop
----------------------------------------------------------------------
local function tickInterval()
-- The control file is checked at least once a second so Start/Stop
-- respond quickly even with a long scan interval.
return math.min(opts.INTERVAL, 1.0)
end
local function tick(t)
if t < nextTickTime and nextTickTime - t < MAX_INTERVAL * 2 then
return
end
nextTickTime = t + tickInterval() - 0.01
local enabled, newOpts = readControl()
if enabled ~= nil then
local before = optionsSummary()
opts = newOpts
if optionsSummary() ~= before then
logLine(string.format("=== Options: %s ===", optionsSummary()))
end
if enabled ~= loggingEnabled then
loggingEnabled = enabled
if loggingEnabled then
resetScanState()
nextScanTime = t
logLine(string.format("=== Logging Enabled at %s ===", os.date("%H:%M:%S")))
else
logLine(string.format("=== Logging Paused at %s ===", os.date("%H:%M:%S")))
end
end
end
if loggingEnabled then
if opts.COMMANDS then runCollector("COMMANDS", ensureCommandHooks) end
if t >= nextScanTime - 0.01 then
nextScanTime = t + opts.INTERVAL
scan(t)
end
end
flushLog()
end
function LuaExportActivityNextEvent(t)
local ok, err = pcall(tick, t)
if not ok then
pcall(logLine, "LOGGER ERROR: " .. tostring(err))
end
local lt = t + tickInterval()
local lot = lt
if PrevExport.LuaExportActivityNextEvent then
lt = PrevExport.LuaExportActivityNextEvent(t)
end
if type(lt) ~= "number" or lt > lot then
lt = lot -- take the lesser of the next event times
end
return lt
end
function LuaExportBeforeNextFrame()
if PrevExport.LuaExportBeforeNextFrame then
PrevExport.LuaExportBeforeNextFrame()
end
end
function Heliosdump(var, depth)
depth = depth or 0
if type(var) == "string" then
return 'string: "' .. var .. '"\n'
elseif type(var) == "nil" then
return 'nil\n'
elseif type(var) == "number" then
return 'number: "' .. var .. '"\n'
elseif type(var) == "boolean" then
return 'boolean: "' .. tostring(var) .. '"\n'
elseif type(var) == "function" then
if debug and debug.getinfo then
local fcnname = tostring(var)
local info = debug.getinfo(var, "S")
if info.what == "C" then
return string.format('%q', fcnname .. ', C function') .. '\n'
else
if (string.sub(info.source, 1, 2) == [[./]]) then
return string.format('%q', fcnname .. ', defined in (' .. info.linedefined .. '-' .. info.lastlinedefined .. ')' .. info.source) ..'\n'
else
return string.format('%q', fcnname .. ', defined in (' .. info.linedefined .. '-' .. info.lastlinedefined .. ')') ..'\n'
end
end
else
return 'a function\n'
end
elseif type(var) == "thread" then
return 'thread\n'
elseif type(var) == "userdata" then
return tostring(var)..'\n'
elseif type(var) == "table" then
depth = depth + 1
local out = "{\n"
for k,v in pairs(var) do
out = out .. (" "):rep(depth*4).. "["..tostring(k).."] = " .. Heliosdump(v, depth)
end
return out .. (" "):rep((depth-1)*4) .. "}\n"
else
return tostring(var) .. "\n"
end
end
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
function parse_indication(indicator_id) -- Thanks to [FSF]Ian code
local ret = {}
local li = list_indication(indicator_id)
if li == "" then return nil end
local m = li:gmatch("-----------------------------------------\n([^\n]+)\n([^\n]*)\n")
while true do
local name, value = m()
if not name then break end
ret[name] = value
end
return ret
end
ThisExport.LuaExportStart = LuaExportStart
ThisExport.LuaExportStop = LuaExportStop
ThisExport.LuaExportAfterNextFrame = LuaExportAfterNextFrame
ThisExport.LuaExportBeforeNextFrame = LuaExportBeforeNextFrame
ThisExport.LuaExportActivityNextEvent = LuaExportActivityNextEvent