-
Notifications
You must be signed in to change notification settings - Fork 6
/
libvisca.lua
1640 lines (1454 loc) · 56.9 KB
/
libvisca.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
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local bit = require("bit")
local socket = require("ljsocket")
local obs = obslua
--- Visca module
local Visca = {}
-- Constants
Visca.default_port = 52381
Visca.default_camera_nr = 1
Visca.debug = false
Visca.log_fnc = nil
Visca.EnumMeta = {}
Visca.EnumMeta.__index = Visca.EnumMeta
function Visca.EnumMeta:has_value(value)
for _, v in pairs(self) do
if v == value then
return true
end
end
return false
end
--- @class ViscaModes Enumeration of supported Visca protocol modes
Visca.modes = setmetatable({
generic = 0,
ptzoptics = 1
}, Visca.EnumMeta)
-- Payload type
-- Stores the value (Byte 0 and Byte 1) of the following table on the payload division
Visca.payload_types = setmetatable({
visca_command = 0x0100, -- VISCA command, Stores the VISCA command.
visca_inquiry = 0x0110, -- VISCA inquiry, Stores the VISCA inquiry.
visca_reply = 0x0111, -- VISCA reply, Stores the reply for the VISCA command and VISCA inquiry,
-- or VISCA device setting command.
visca_setting = 0x0120, -- VISCA device setting command, Stores the VISCA device setting command.
control_command = 0x0200, -- Control command, Stores the control command.
control_reply = 0x0201 -- Control reply, Stores the reply for the control command.
}, Visca.EnumMeta)
Visca.payload_type_names = {
[Visca.payload_types.visca_command] = "VISCA Command",
[Visca.payload_types.visca_inquiry] = "VISCA Inquiry",
[Visca.payload_types.visca_reply] = "VISCA Reply",
[Visca.payload_types.visca_setting] = "VISCA Device Setting Command",
[Visca.payload_types.control_command] = "Control Command",
[Visca.payload_types.control_reply] = "Control Reply"
}
Visca.packet_consts = setmetatable({
req_addr_base = 0x80,
command = 0x01,
inquiry = 0x09,
reply_ack = 0x40,
reply_completion = 0x50,
reply_error = 0x60,
reply = 0x90,
terminator = 0xFF
}, Visca.EnumMeta)
Visca.error_type_names = {
[0x01] = "Message length error",
[0x02] = "Syntax error",
[0x03] = "Command buffer full",
[0x04] = "Command canceled",
[0x05] = "No socket", -- To be cancelled
[0x41] = "Command not executable",
}
Visca.categories = setmetatable({
interface = 0x00,
camera = 0x04,
color = 0x04,
exposure = 0x04,
focus = 0x04,
exposure_ext = 0x05,
pan_tilter = 0x06,
camera_ext = 0x07
}, Visca.EnumMeta)
Visca.category_names = {
[Visca.categories.interface] = "Interface",
[Visca.categories.camera] = "Camera/Color/Exposure/Focus/Zoom",
[Visca.categories.color] = "Camera/Color/Exposure/Focus/Zoom",
[Visca.categories.exposure] = "Camera/Color/Exposure/Focus/Zoom",
[Visca.categories.focus] = "Camera/Color/Exposure/Focus/Zoom",
[Visca.categories.exposure_ext] = "Exposure",
[Visca.categories.pan_tilter] = "Pan/Tilt",
[Visca.categories.camera_ext] = "Exposure/Camera",
}
Visca.commands = setmetatable({
power = 0x00,
pantilt_drive = 0x01,
pantilt_absolute = 0x02,
pantilt_home = 0x04,
pantilt_reset = 0x05,
zoom = 0x07,
focus = 0x08,
color_gain = 0x09,
exposure_gain = 0x0C,
preset = 0x3F,
zoom_direct = 0x47,
focus_direct = 0x48,
color_gain_direct = 0x49,
exposure_shutter_direct = 0x4A,
exposure_iris_direct = 0x4B,
exposure_gain_direct = 0x4B,
brightness_direct = 0xA1,
}, Visca.EnumMeta)
Visca.command_names = {
[Visca.commands.power] = "Power",
[Visca.commands.pantilt_drive] = "Pan/Tilt (Direction)",
[Visca.commands.pantilt_absolute] = "Pan/Tilt (Absolute)",
[Visca.commands.pantilt_home] = "Pan/Tilt (Home)",
[Visca.commands.pantilt_reset] = "Pan/Tilt (Reset)",
[Visca.commands.zoom] = "Zoom",
[Visca.commands.focus] = "Focus",
[Visca.commands.color_gain] = "Color Gain/Saturation",
[Visca.commands.exposure_gain] = "Gain",
[Visca.commands.preset] = "Preset",
[Visca.commands.zoom_direct] = "Zoom (Direct)",
[Visca.commands.focus_direct] = "Focus (Direct)",
[Visca.commands.color_gain_direct] = "Color Gain/Saturation (Direct)",
[Visca.commands.exposure_iris_direct] = "Iris Absolute",
[Visca.commands.exposure_shutter_direct] = "Shutter Absolute",
[Visca.commands.exposure_gain_direct] = "Gain Absolute",
[Visca.commands.brightness_direct] = "Brightness (Direct)",
}
Visca.command_arguments = setmetatable({
color_gain_reset = 0x00,
color_gain_up = 0x02,
color_gain_down = 0x03,
preset_recall = 0x02,
power_on = 0x02,
power_standby = 0x03,
focus_stop = 0x00,
focus_far_std = 0x02,
focus_near_std = 0x03,
focus_far_var = 0x20,
focus_near_var = 0x30,
}, Visca.EnumMeta)
Visca.inquiry_commands = setmetatable({
software_version = 0x02,
pantilt_position = 0x12,
zoom_position = 0x47,
color_gain = 0x49,
brightness_position = 0xA1,
}, Visca.EnumMeta)
Visca.inquiry_command_names = {
[Visca.inquiry_commands.software_version] = "Software Version",
[Visca.inquiry_commands.pantilt_position] = "Pan/Tilt (Position)",
[Visca.inquiry_commands.zoom_position] = "Zoom (Position)",
[Visca.inquiry_commands.color_gain] = "Color Gain - Saturation (Level)",
[Visca.inquiry_commands.brightness_position] = "Brightness (Position)",
}
local function ca_key(command, argument)
return bit.lshift(command or 0, 8) + (argument or 0)
end
Visca.command_argument_names = {
[ca_key(Visca.commands.color_gain, Visca.command_arguments.color_gain_reset)] = "Reset",
[ca_key(Visca.commands.color_gain, Visca.command_arguments.color_gain_up)] = "Up (increment)",
[ca_key(Visca.commands.color_gain, Visca.command_arguments.color_gain_down)] = "Down (decrement)",
[ca_key(Visca.commands.preset, Visca.command_arguments.preset_recall)] = "Absolute Position (Preset)",
[ca_key(Visca.commands.power, Visca.command_arguments.power_on)] = "On",
[ca_key(Visca.commands.power, Visca.command_arguments.power_standby)] = "Standby",
[ca_key(Visca.commands.focus, Visca.command_arguments.focus_stop)] = "Stop",
[ca_key(Visca.commands.focus, Visca.command_arguments.focus_far_std)] = "Far (standard speed)",
[ca_key(Visca.commands.focus, Visca.command_arguments.focus_near_std)] = "Near (standard speed)",
[ca_key(Visca.commands.focus, Visca.command_arguments.focus_far_var)] = "Far (variable speed)",
[ca_key(Visca.commands.focus, Visca.command_arguments.focus_near_var)] = "Near (variable speed)",
}
Visca.Focus_modes = setmetatable({
auto = 0x3802,
manual = 0x3803,
toggle = 0x3810,
one_push_trigger = 0x1801,
infinity = 0x1802,
}, Visca.EnumMeta)
Visca.PanTilt_directions = setmetatable({
upleft = 0x0101,
upright = 0x0201,
up = 0x0301,
downleft = 0x0102,
downright = 0x0202,
down = 0x0302,
left = 0x0103,
right = 0x0203,
stop = 0x0303,
}, Visca.EnumMeta)
Visca.Zoom_subcommand = setmetatable({
stop = 0x00,
tele_standard = 0x02,
wide_standard = 0x03,
tele_variable = 0x20,
wide_variable = 0x30,
}, Visca.EnumMeta)
Visca.limits = {
BRIGHTNESS_MIN = 0x00,
BRIGHTNESS_MAX = 0xFF,
COLOR_GAIN_MIN_LEVEL = 0x00,
COLOR_GAIN_MAX_LEVEL = 0x0E,
PAN_MIN_SPEED = 0x01,
PAN_MAX_SPEED = 0x18,
FOCUS_MIN_SPEED = 0x00,
FOCUS_MAX_SPEED = 0x07,
PAN_MIN_VALUE = 0x00000,
PAN_MAX_VALUE = 0xFFFFF,
TILT_MIN_VALUE = 0x0000,
TILT_MAX_VALUE = 0xFFFF,
TILT_MIN_SPEED = 0x01,
TILT_MAX_SPEED = 0x18,
ZOOM_MIN_SPEED = 0x00,
ZOOM_MAX_SPEED = 0x07,
ZOOM_MIN_VALUE = 0x0000,
ZOOM_MAX_VALUE = 0x4000,
}
Visca.CameraVendor = {
[0x0001] = "Sony/NewTek",
[0x0003] = "Everet",
[0x0010] = "HuddleCamHD",
[0x0020] = "Sony", -- According libvisca
[0x0220] = "GlowStream",
}
Visca.CameraModelMeta = {}
Visca.CameraModelMeta.__index = function(_, _) return {} end
Visca.CameraModel = {
[0x0001] = {
[0x0501] = "BRC-H700",
[0x0502] = "BRU-H700",
[0x0505] = "BRC-Z700",
[0x0507] = "BRC-Z330",
[0x050B] = "BRC-H900",
[0x0513] = "PTZ1 NDI",
[0x051C] = "BRC-X400",
[0x051D] = "BRC-X401",
[0x0617] = "SRG-X400",
[0x0618] = "SRG-X120",
[0x061A] = "SRG-201M2",
[0x061B] = "SRG-HD1M2",
},
[0x0003] = {
[0x0002] = "EVZ405N",
[0x013B] = "EVP212N",
},
[0x0010] = {
[0x0502] = "HC12X-HuddleView",
},
[0x0220] = {
[0x0511] = "GS300-20x-NDI",
},
}
setmetatable(Visca.CameraModel, Visca.CameraModelMeta)
--- @class ViscaCompatibility Configuration table with camera compatibility options
Visca.compatibility = {
fixed_sequence_number = nil, -- Set to a non-nil numeric value to keep the message sequence counter at a fixed value
preset_nr_offset = nil, -- Set to non-nil to to compensate for the preset numbering in the camera.
-- When the first preset is 1, leave it nil (or set to 0).
-- When the first preset is 0, set the offset to 1.
-- The preset recalled at the camera is 'preset - <preset_nr_offset>'
pantilt_pan_bytes = 4 -- The number of bytes used for the pan argument in absolute pan/tilt commands
}
local function log(fmt, ...)
if Visca.log_fnc then
local status, msg = pcall(Visca.log_fnc, fmt, unpack(arg or { ... }))
if not status then
print(string.format("Logging '%s' failed: %s", fmt, msg))
end
elseif Visca.debug then
print(string.format(fmt, unpack(arg or { ... })))
end
end
--- Sets the function to be called for logging as alternative to using print
---
--- @param func fun(fmt: string, ...)
function Visca.set_log_function(func)
Visca.log_fnc = func
Visca.debug = true
end
--- @class PayloadCommand object
--- @field category integer The Visca command category
--- @field command integer The Visca command
--- @field arguments table The command data bytes
Visca.PayloadCommand = {}
Visca.PayloadCommand.__index = Visca.PayloadCommand
function Visca.PayloadCommand.new()
local self = {
command_inquiry = 0x00,
category = 0x00,
command = 0x00,
arguments = {}
}
setmetatable(self, Visca.PayloadCommand)
return self
end
function Visca.PayloadCommand:from_payload(payload)
self.command_inquiry = payload[2]
self.category = payload[3] or 0
self.command = payload[4] or 0
for i = 5, #payload do
if not ((i == #payload) and (payload[i] == Visca.packet_consts.terminator)) then
table.insert(self.arguments, payload[i])
end
end
return self
end
function Visca.PayloadCommand:is_command()
return self.command_inquiry == Visca.packet_consts.command
end
function Visca.PayloadCommand:is_inquiry()
return self.command_inquiry == Visca.packet_consts.inquiry
end
function Visca.PayloadCommand:is_reply()
return self.command_inquiry == Visca.packet_consts.reply
end
function Visca.PayloadCommand:as_string()
local args = '- (no arguments)'
if #self.arguments > 0 then
local descr = Visca.command_argument_names[ca_key(self.command, self.arguments[1])]
local str_a = {}
for i = descr and 2 or 1, #self.arguments do
table.insert(str_a, string.format('%02X', self.arguments[i]))
end
args = (descr or 'arguments') .. ' ' .. table.concat(str_a, ' ')
end
if self:is_command() then
return string.format('Command on %s: %s, %s',
Visca.category_names[self.category],
Visca.command_names[self.command] or string.format("Unknown (0x%0x)", self.command),
args)
elseif self:is_inquiry() then
return string.format('Inquiry on %s: %s, %s',
Visca.category_names[self.category],
Visca.command_names[self.command] or string.format("Unknown (0x%0x)", self.command),
args)
else
return 'Unknown'
end
end
--- @class PayloadReply object
--- @field error_type integer The reply error type - if any
--- @field arguments table The command reply data bytes
--- @field argument_cnt integer The nummer of reply data bytes
Visca.PayloadReply = {}
Visca.PayloadReply.__index = Visca.PayloadReply
function Visca.PayloadReply.new()
local self = {
reply_type = 0x00,
socket_number = 0,
error_type = 0x00,
arguments = {},
argument_cnt = 0
}
setmetatable(self, Visca.PayloadReply)
return self
end
function Visca.PayloadReply:from_payload(payload)
self.reply_type = bit.band(payload[2], 0xF0)
self.socket_number = bit.band(payload[2], 0x0F)
if self:is_error() then
self.error_type = payload[3] or 0
else
for i = 3, #payload do
if not ((i == #payload) and (payload[i] == Visca.packet_consts.terminator)) then
table.insert(self.arguments, payload[i])
self.argument_cnt = self.argument_cnt + 1
end
end
end
return self
end
function Visca.PayloadReply:is_ack()
return self.reply_type == Visca.packet_consts.reply_ack
end
function Visca.PayloadReply:is_completion()
return self.reply_type == Visca.packet_consts.reply_completion
end
function Visca.PayloadReply:is_error()
return self.reply_type == Visca.packet_consts.reply_error
end
function Visca.PayloadReply:get_inquiry_data_for(inquiry_payload)
local _,_,category,inquiry_command = unpack(inquiry_payload)
local data = {}
local unsupported_nr_of_arguments = false
if category == Visca.categories.interface then
if inquiry_command == Visca.inquiry_commands.software_version then
if self.argument_cnt == 7 then
-- The SOFTWARE VERSION (CAM_VersionInq) response is: y0 50 pp pp qq qq rr rr 0s FF
-- pppp: Vendor ID
-- qqqq: Model Code
-- rrrr: ROM version
-- s: (max) Socket Number
data = {
vendor_id = bit.lshift(self.arguments[1] or 0, 8) + (self.arguments[2] or 0),
model_code = bit.lshift(self.arguments[3] or 0, 8) + (self.arguments[4] or 0),
rom_version = bit.lshift(self.arguments[5] or 0, 8) + (self.arguments[6] or 0),
max_nr_sockets = bit.band(self.arguments[7] or 0, 0x0F),
}
else
unsupported_nr_of_arguments = true
end
end
elseif category == Visca.categories.camera then
if inquiry_command == Visca.inquiry_commands.color_gain then
if self.argument_cnt == 4 then
data = {
color_level = bit.band(self.arguments[4] or 0, 0x0F)
}
else
unsupported_nr_of_arguments = true
end
elseif inquiry_command == Visca.inquiry_commands.brightness_position then
if self.argument_cnt == 4 then
data = {
brightness = bit.lshift(bit.band(self.arguments[3] or 0, 0x0F), 4) +
bit.band(self.arguments[4] or 0, 0x0F),
}
else
unsupported_nr_of_arguments = true
end
elseif inquiry_command == Visca.inquiry_commands.zoom_position then
if self.argument_cnt == 4 then
data = {
zoom = bit.lshift(bit.band(self.arguments[1] or 0, 0x0F), 12) +
bit.lshift(bit.band(self.arguments[2] or 0, 0x0F), 8) +
bit.lshift(bit.band(self.arguments[3] or 0, 0x0F), 4) +
bit.band(self.arguments[4] or 0, 0x0F),
}
else
unsupported_nr_of_arguments = true
end
end
elseif category == Visca.categories.pan_tilter then
if inquiry_command == Visca.inquiry_commands.pantilt_position then
if self.argument_cnt == 8 then
data = {
pantilt_pan_bytes = 4,
pan = bit.lshift(bit.band(self.arguments[1] or 0, 0x0F), 12) +
bit.lshift(bit.band(self.arguments[2] or 0, 0x0F), 8) +
bit.lshift(bit.band(self.arguments[3] or 0, 0x0F), 4) +
bit.band(self.arguments[4] or 0, 0x0F),
tilt = bit.lshift(bit.band(self.arguments[5] or 0, 0x0F), 12) +
bit.lshift(bit.band(self.arguments[6] or 0, 0x0F), 8) +
bit.lshift(bit.band(self.arguments[7] or 0, 0x0F), 4) +
bit.band(self.arguments[8] or 0, 0x0F)
}
elseif self.argument_cnt == 9 then
data = {
pantilt_pan_bytes = 5,
pan = bit.lshift(bit.band(self.arguments[1] or 0, 0x0F), 16) +
bit.lshift(bit.band(self.arguments[2] or 0, 0x0F), 12) +
bit.lshift(bit.band(self.arguments[3] or 0, 0x0F), 8) +
bit.lshift(bit.band(self.arguments[4] or 0, 0x0F), 4) +
bit.band(self.arguments[5] or 0, 0x0F),
tilt = bit.lshift(bit.band(self.arguments[6] or 0, 0x0F), 12) +
bit.lshift(bit.band(self.arguments[7] or 0, 0x0F), 8) +
bit.lshift(bit.band(self.arguments[8] or 0, 0x0F), 4) +
bit.band(self.arguments[9] or 0, 0x0F)
}
else
unsupported_nr_of_arguments = true
end
end
end
if next(data) == nil then
if Visca.debug then
if unsupported_nr_of_arguments then
log("Unsupported number of arguments received for inquiry %d (%d)", inquiry_command, self.argument_cnt)
else
log("Unsupported inquiry type received (%d) for command category %d", inquiry_command, category)
end
end
end
return data
end
function Visca.PayloadReply:as_string()
if self:is_ack() then
return 'Acknowledge'
elseif self:is_completion() then
if #self.arguments > 0 then
local str_a = {}
for b = 1, #self.arguments do
table.insert(str_a, string.format('%02X', self.arguments[b]))
end
return 'Completion, inquiry: ' .. table.concat(str_a, ' ')
else
return 'Completion, command'
end
elseif self:is_error() then
return string.format('Error on socket %d: %s (%02x)',
self.socket_number,
Visca.error_type_names[self.error_type] or 'Unknown',
self.error_type)
else
return 'Unknown'
end
end
--- @class Message Visca Message object
--- @field payload_size number The lenght in bytes of the payload in the message
--- @field seq_nr number Sequential incrementing number of the message
--- @field payload table The raw data in the massage
--- @field message table Structure containing the decoded response object, either a PayloadCommand or PayloadReply
Visca.Message = {}
Visca.Message.__index = Visca.Message
--- Visca Message Constructor
---
--- A Visca message is binary data with a message header (8 bytes) and payload (1 to 16 bytes).
--- mode=generic uses this header, mode=PTZoptics skips this header
---
--- Byte: 0 1 2 3 4 5 6 7 8 9 A B C D E F
--- Payload type (byte 0-1): |
--- Payload length (byte 2-3): |
--- Sequence number (byte 4-7): |
--- Payload (byte 8 - max 23): |
---
--- The wire format is big-endian (LSB first)
---
--- @return Message
function Visca.Message.new()
local msg = {
payload_type = 0x0000,
payload_size = 0x0000,
seq_nr = 0x00000000,
payload = {},
message = {},
}
setmetatable(msg, Visca.Message)
return msg
end
function Visca.Message:from_data(data)
local message_length = #(data or '')
if message_length > 1 then
if (string.byte(data, 1) == 0x01 or
string.byte(data, 1) == 0x02) and message_length >= 9 and message_length <= 24 then
self.payload_type = string.byte(data, 1) * 256 + string.byte(data, 2)
self.payload_size = string.byte(data, 3) * 256 + string.byte(data, 4)
self.seq_nr = string.byte(data, 5) * 2^24 +
string.byte(data, 6) * 2^16 +
string.byte(data, 7) * 2^8 +
string.byte(data, 8)
for b = 1, self.payload_size do
if 8+b <= message_length then
table.insert(self.payload, string.byte(data, 8 + b))
else
if self.payload_size > #self.payload then
self.payload_size = #self.payload
end
log("Ignoring byte %d, payload index beyond message length %d", 8+b, message_length)
end
end
elseif message_length >= 1 and message_length <= 16 then
self.payload_size = message_length
for b = 1, message_length do
table.insert(self.payload, string.byte(data, b))
end
end
if (bit.band(self.payload[1] or 0, 0xF0) == 0x80) then
-- command or inquiry
self.message.command = Visca.PayloadCommand.new():from_payload(self.payload)
elseif (bit.band(self.payload[1] or 0, 0xF0) == 0x90) then
-- reply
self.message.reply = Visca.PayloadReply.new():from_payload(self.payload)
end
end
return self
end
--- Generate a data bytestring of this message
---
--- @param mode ViscaModes|integer
--- @return string
function Visca.Message:to_data(mode)
mode = mode or Visca.modes.generic
local payload_size = (self.payload_size > 0) and self.payload_size or #self.payload
local data = {}
if mode == Visca.modes.generic then
data = {
bit.band(bit.rshift(self.payload_type, 8), 0xFF),
bit.band(self.payload_type, 0xFF),
bit.band(bit.rshift(payload_size, 8), 0xFF),
bit.band(payload_size, 0xFF),
bit.band(bit.rshift(self.seq_nr, 24), 0xFF),
bit.band(bit.rshift(self.seq_nr, 16), 0xFF),
bit.band(bit.rshift(self.seq_nr, 8), 0xFF),
bit.band(self.seq_nr, 0xFF),
}
end
for b = 1, payload_size do
table.insert(data, self.payload[b])
end
local str_a = {}
for _,v in ipairs(data) do
table.insert(str_a, string.char(v))
end
return table.concat(str_a)
end
--- Generate a human readable representation in hex of this message
---
--- @param mode ViscaModes|integer
function Visca.Message:as_string(mode)
mode = mode or Visca.modes.generic
local bin_str = self:to_data(mode)
local bin_len = #(bin_str or "")
local str_a = {}
for b = 1, bin_len do
table.insert(str_a, string.format('%02X', string.byte(bin_str, b)))
end
return table.concat(str_a, ' ')
end
function Visca.Message:dump(name, prefix, mode)
local str_a = {}
if name then
table.insert(str_a, '\n' .. name .. ':')
end
prefix = prefix or '- '
table.insert(str_a, string.format('%sMessage: %s',
prefix or '',
self:as_string(mode)))
table.insert(str_a, string.format("%sPayload type: %s (0x%02X%02X)",
prefix or '',
Visca.payload_type_names[self.payload_type] or 'Unknown',
math.floor(self.payload_type/256), self.payload_type % 256))
table.insert(str_a, string.format('%sPayload length: %d',
prefix or '',
(self.payload_size > 0) and self.payload_size or #self.payload))
table.insert(str_a, string.format('%sSequence number: %d',
prefix or '',
self.seq_nr))
if self.message.command then
table.insert(str_a, string.format('%sPayload: Command',
prefix or ''))
table.insert(str_a, string.format('%s %s',
prefix or '',
self.message.command:as_string()))
elseif self.message.reply then
table.insert(str_a, string.format('%sPayload: Reply',
prefix or ''))
table.insert(str_a, string.format('%s %s',
prefix or '',
self.message.reply:as_string()))
else
table.insert(str_a, string.format('%sPayload: %s',
prefix or '',
tostring(self.payload)))
for k,v in pairs(self.payload) do
table.insert(str_a, string.format('%sPayload: - byte %02X: 0x%02X',
prefix or '',
k,
v))
end
end
log(table.concat(str_a, '\n'))
return self
end
--- @class ReplyServer Server for cameras sending out-of-socket replies
Visca.ReplyServer = {
clients = {},
whitelist = {},
servers = {},
replies = {},
}
function Visca.ReplyServer.add_listener_for(address, port)
local cnt = (Visca.ReplyServer.clients[port] or 0)
--- @type string|table|nil
local err
if cnt == 0 then
local sock_address, num
sock_address, err, num = socket.find_first_address("*", port,
{family="inet", socket_type="dgram", protocol="udp"})
if sock_address then
local server
server, err, num = socket.create("inet", "dgram", "udp")
if server then
local success
success, err, num = server:set_blocking(false)
if success then
success, err, num = server:bind(sock_address, port)
if success then
Visca.ReplyServer.servers[port] = server
cnt = cnt + 1
if Visca.debug then
log("Started new reply server at %s:%s",
sock_address:get_ip(), sock_address:get_port())
end
else
log("Failed to bind server to %s:%s: %s (%d)",
sock_address:get_ip(), sock_address:get_port(), err or "Unknown", num or 0)
end
else
log("Failed to set nonblocking server at %s:%s: %s (%d)",
sock_address:get_ip(), sock_address:get_port(), err or "Unknown", num or 0)
end
else
log("Failed to start new reply server at %s:%s: %s (%d)",
sock_address:get_ip(), sock_address:get_port(), err or "Unknown", num or 0)
end
else
log("Failed to determine server address for port %d: %s (%d)",
port, err or "Unknown", num or 0)
end
end
if Visca.ReplyServer.whitelist[address] == nil then
Visca.ReplyServer.whitelist[address] = 1
end
Visca.ReplyServer.clients[port] = cnt
end
function Visca.ReplyServer.remove_listener_for(port)
local cnt = (Visca.ReplyServer.clients[port] or 0) - 1
if cnt <= 0 then
local server = Visca.ReplyServer.servers[port]
if server ~= nil then
server:close()
Visca.ReplyServer.servers[port] = nil
end
Visca.ReplyServer.clients[port] = nil
else
Visca.ReplyServer.clients[port] = cnt
end
end
function Visca.ReplyServer.shutdown()
for _,server in pairs(Visca.ReplyServer.servers) do
server:close()
end
Visca.ReplyServer.servers = {}
Visca.ReplyServer.whitelist = {}
Visca.ReplyServer.clients = {}
Visca.ReplyServer.replies = {}
end
function Visca.ReplyServer.receive()
for _,server in pairs(Visca.ReplyServer.servers) do
local data, reply_source = server:receive_from()
if data ~= nil then
local address = reply_source:get_ip()
if Visca.ReplyServer.whitelist[address] ~= nil then
table.insert(Visca.ReplyServer.replies, {address, data})
end
end
end
end
function Visca.ReplyServer.get_data_for(address)
for k,v in pairs(Visca.ReplyServer.replies) do
if v ~= nil then
local reply_source, data = unpack(v)
if reply_source == address then
Visca.ReplyServer.replies[k] = nil
return data
end
end
end
end
--- @class Transmission The Transmission object tracks responses received on a send message.
--- It stores the response by type (ack, error or completion) and tracks timeout.
--- @field send Message The message send
--- @field send_timestamp number|nil The timestamp in nanseconds at which the message was send, or nil
Visca.Transmission = {}
Visca.Transmission.__index = Visca.Transmission
--- Visca Transaction Constructor
---
--- @param message Message The original sent message
--- @return Transmission
function Visca.Transmission.new(message)
local transmission = {
send = message,
send_timestamp = nil,
ack = nil, -- received ack message
ack_timestamp = nil, -- received ack timestamp
error = nil, -- received ack message
error_timestamp = nil, -- received ack timestamp
completion = nil, -- received completion message
completion_timestamp = nil, -- received completion timestamp
}
setmetatable(transmission, Visca.Transmission)
return transmission
end
function Visca.Transmission:add_reply(reply)
if reply:is_ack() then
self.ack = reply
self.ack_timestamp = obs.os_gettime_ns()
elseif reply:is_completion() then
self.completion = reply
self.completion_timestamp = obs.os_gettime_ns()
elseif reply:is_error() then
self.error = reply
self.error_timestamp = obs.os_gettime_ns()
end
end
function Visca.Transmission:timed_out()
-- One reply cycle should take maximum 4V. 1V is 42msec (worst case) for Sony.
-- Including one 1V for sending, the timeout needed should only be 210000000ns.
-- This typically not met by Visca over IP, so an increased timeout is used.
local visca_timeout = 1000000000
if not self.send_timestamp then
return false
elseif self.send_timestamp and (self.ack_timestamp or self.error_timestamp or self.completion_timestamp) then
return false
else
return (obs.os_gettime_ns() - (self.send_timestamp or 0)) > visca_timeout
end
end
function Visca.Transmission:is_inquiry()
return self.send and (self.send.payload_type == Visca.payload_types.visca_inquiry)
end
function Visca.Transmission:inquiry_data()
if self:is_inquiry() and self.completion then
return self.completion:get_inquiry_data_for(self.send.payload)
else
return nil
end
end
--- @class Connection Connection to a Visca camera
--- @field private sock_address unknown The socket address structure of the destination
--- @field public sock_err string The last error obtained from the socket or address detection
--- @field private address string The IP address or DNS of the camera
--- @field private transmission_queue Transmission[] List of Transmission objects
--- @field private callbacks table List of callbacks: [type][id] = function
--- @field private compatibility table List of compatibility settings (key/value)
Visca.Connection = {}
Visca.Connection.__index = Visca.Connection
--- Visca Connection constructor
---
--- @param address string The IP address or DNS of the camera
--- @param port integer|nil The Visca control port of the camera
--- @return Connection
function Visca.Connection.new(address, port)
port = port or Visca.default_port
if (port < 1) or (port > 65535) then
port = Visca.default_port
end
local sock_addr, sock_err = socket.find_first_address(address, port)
local connection = {
sock = nil,
last_seq_nr = 0xFFFFFFFF,
address = address,
sock_address = sock_addr,
sock_err = sock_err,
mode = Visca.modes.generic,
transmission_queue = {}, -- List of Transmission objects
callbacks = {}, -- List of callbacks: [type][id] = function
compatibility = {} -- List of compatibility settings (key/value)
}
setmetatable(connection, Visca.Connection)
if sock_addr then
local sock = assert(socket.create("inet", "dgram", "udp"))
local success, _ = sock:set_blocking(false)
if success then
connection.sock = sock
Visca.ReplyServer.add_listener_for(address, port)
end
end
return connection
end
--- @param mode ViscaModes|integer
function Visca.Connection:set_mode(mode)
if Visca.modes:has_value(mode or Visca.modes.generic) then
self.mode = mode
return true
else
return false
end
end
--- @param compatibility ViscaCompatibility
function Visca.Connection:set_compatibility(compatibility)
for k,v in pairs(compatibility or {}) do
self.compatibility[k] = v
end
end
function Visca.Connection:__register_callback(callback_type, id, callback)
if type(self.callbacks[callback_type]) ~= 'table' then
self.callbacks[callback_type] = {}
end
self.callbacks[callback_type][id] = callback
end
function Visca.Connection:__unregister_callback(callback_type, id)
if self.callbacks[callback_type] ~= nil then
self.callbacks[callback_type][id] = nil
end
end
function Visca.Connection:__exec_callback(callback_type, t, ...)
if self.callbacks[callback_type] ~= nil then
for id,callback in pairs(self.callbacks[callback_type]) do
if type(callback) == 'function' then
local status,result_or_error = pcall(callback, t, unpack(arg or {}))
if not status then
log("Callback %s for %s failed: %s", id, callback_type, result_or_error)
end
end
end
end
end
function Visca.Connection:register_on_ack_callback(id, callback)
self:__register_callback('ack', id, callback)
end
function Visca.Connection:register_on_completion_callback(id, callback)
self:__register_callback('completion', id, callback)
end
function Visca.Connection:register_on_error_callback(id, callback)
self:__register_callback('error', id, callback)
end
function Visca.Connection:register_on_timeout_callback(id, callback)
self:__register_callback('timeout', id, callback)
end
function Visca.Connection:unregister_on_ack_callback(id)
self:__unregister_callback('ack', id)
end
function Visca.Connection:unregister_on_completion_callback(id)
self:__unregister_callback('completion', id)
end
function Visca.Connection:unregister_on_error_callback(id)