-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAZM_Lib.js
1776 lines (1620 loc) · 73 KB
/
AZM_Lib.js
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
/********************************************************
Copyright (c) 2024 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately in
writing, software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied.
*********************************************************
* Author(s): Robert(Bobby) McGonigle Jr
* Technical Marketing Engineering, Technical Leader
* Cisco Systems
*
* Consulting Engineer(s) Gerardo Chaves William Mills
* Leader, Systems Engineering Technical Solutions Specialist
* Cisco Systems Cisco Systems
*
* Description:
* - Audio Zone Manager (AZM)
* - Suite of custom Commands, Statuses and Events that have been
* tailored to enable Audio Based Automation
* - This Library is intended to be imported into a Project
*
* - Dependencies
* - The Device xAPI
* - Audio Configuration Object
*
* - Documentation
* - https://github.com/ctg-tme/audio-zone-manager-library-macro
*/
import xapi from 'xapi';
/*****[Configurable Options]***********************************************************/
/**
* Set the Mode for AZM Automatic Updates
*
* Periodically reaches out to github to check for updates to the AZM_Lib.
*
* @value off(default): disables automatic update checks to AZM Library
* @value monitor: If available, will log update details to the console and provides a UI element in the Control Panel notifying the user.
*
* @link [Audio Zone Manager Releases](https://github.com/ctg-tme/audio-zone-manager-library-macro/releases)
*
* @acceptedValues [Off, Monitor]
*
* @see config_AutomaticUpdates_Schedule_Day
* @see config_AutomaticUpdates_Schedule_Time
*/
const config_AutomaticUpdates_Mode = 'Off';
/**
* Set the Day to check for AZM Updates
*
* @acceptedValues ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
* @see config_AutomaticUpdates_Schedule_Time
*/
const config_AutomaticUpdates_Schedule_Day = ['Sunday', 'Saturday'];
/**
* Set the Time to check for AZM Updates
*
* @acceptedValues 24hr Format String. Ex: 00:00
* @see config_AutomaticUpdates_Schedule_Day
*/
const config_AutomaticUpdates_Schedule_Time = '03:00';
/*****[Troubleshooting Tools]***********************************************************/
/**
* AZM Debug flags should remain `false` by default as they produce ALOT of information and could slow a browser session if left `true` for too long
*
* Only set `true` only when you need to troubleshoot
*
* When complete, please set all flags to `false` to improve browser performance
*
* @see createDebugMethod
* @see console.AZM
*/
const AZM_DebugFlags = {
SetupDebug: false, // Enables Debugging for the AZM Setup Process
ZonesDebug: false, // Enables Debugging for changes in Zones
MonitorDebug: false, // Enables Debugging for Starting and Stopping the AZM Monitor
Analog_BucketDebug: false, // Enables Debugging for processing Analog Audio data
Ethernet_BucketDebug: false, // Enables Debugging for processing Ethernet/AES67 Audio data
USB_BucketDebug: false, // Enables Debugging for processing USB Audio data
ExternalVuMeter_BucketDebug: false, // Enables Debugging for processing ExternalVuMeter Audio Data
ExternalGate_BucketDebug: false, // Enables Debugging for processing ExternalGate Audio Data
MessageSendEvent_Debug: false, // Enables Debugging for raw event data coming into the Message Send Event
AudioInputConnectorEvent_Debug: false // Enables Debugging for raw event data coming into the Audio Input Connector Event
};
/*****[Const, Let, Var Objects]***********************************************************/
/**
* The Installed Version of AZM
*
* Do NOT alter this value unless you choose to fork the library, as it could impact the operation fo the Macro
*/
const version = '1.0.0';
/**
* AZM Path Object. Contains Command, Status and Event Nodes that are exported by AZM_Lib
*
* @exports
*/
const AZM = {
Command: {
Zone: {
/** Initializes the Audio Zone mappings assigned in the Audio Configuration Object
*
* Required on script boot, but can be modified
* @param {object} AudioZoneInfo
* A multi-node configuration for both settings and zone information
*
* @link [AZM Configuration Guide](https://github.com/ctg-tme/audio-zone-manager-library-macro/tree/main?tab=readme-ov-file#azm-audio-configuration-)
*
* @xapi [xConfiguration HttpClient Mode](https://roomos.cisco.com/xapi/Configuration.HttpClient.Mode/)
* @xapi [xConfiguration Audio Microphones VoiceActivityDetector Mode](https://roomos.cisco.com/xapi/Configuration.Audio.Microphones.VoiceActivityDetector.Mode/)
*/
Setup: {},
Monitor: {
/** Starts the VU Meter on all Audio Input Connectors defined in your Audio Configuration
*
* @param {string} cause
* For logging purposes, provide a reason why this function was declared
*
* @xapi [xCommand Audio VuMeter Start](https://roomos.cisco.com/xapi/Command.Audio.VuMeter.Start/)
*/
Start: {},
/** Stops the VU Meter on all Audio Input Connectors defined in your Audio Configuration
*
* @param {string} cause
* For logging purposes, provide a reason why this function was declared
*
* @xapi [xCommand Audio VuMeter Stop](https://roomos.cisco.com/xapi/Command.Audio.VuMeter.Stop/)
*/
Stop: {}
},
/** Provides a list of all available Zone Information
*/
List: {}
}
},
Status: {
Audio: {
/**
* Pull information about a target zone by including the Zone ID in its path
*
* Zone IDs are assigned a value +1 to their index position
*
* @see ```AZM.Command.Zone.List()``` to print a list of Zones and their IDs
*
* @example AZM.Status.Audio.Zone[N].State.get()
* @example AZM.Status.Audio.Zone[N].get()
*/
Zone: {}
}
},
Event: {
/**
* Serves as a universal subscriptions to audio events
*
* It not only subscribes to the data requests, but it then processes and calls back a refined dataset to leverage in you projects
*
* This subscription is the core to the AZM library
*
* @xapi [xEvent Audio Input Connectors <Microphone, USB, Ethernet>](https://roomos.cisco.com/xapi/Event.Audio.Input.Connectors/)
* @xapi [xEvent Message Send](https://roomos.cisco.com/xapi/Event.Message.Send/)
* @xapi [xStatus Audio Microphones VoiceActivityDetector Activity](https://roomos.cisco.com/xapi/Status.Audio.Microphones.VoiceActivityDetector.Activity/)
*/
TrackZones: {}
}
};
/**
* Panel ID for the AXM Notifications Panel
*
* Panel is used for AZM Update Checks
*/
const azmnotifyPanelId = 'azm_notify';
/**
* Object to store Audio Connector Data, later instantiated by their respective _Bucket Classes
*/
const AudioBucket = { Ethernet: {}, Analog: {}, USB: {}, ExternalVuMeter: {}, ExternalGate: {} }
/**
* Data repository for EthernetSubId information
*
* @see Normalize_Ethernet_Audio_Data()
*/
let Ethernet_SubId_Backfill = {}
/**
* Object used to store AZM Configuration
*
* @see AZM.Command.Zone.Setup(AudioConfiguration)
*/
let AudioConfiguration;
/**
* This object tracks if the AZM.Command.Zone.Setup has been successfully run
*
* This ensures those developing with AZM_Lib has passed a configuration
* into their project prior to executing other tasks
*
* @see AZM.Command.Zone.Setup(AudioConfiguration)
*/
let ZoneSetupStatus = false;
/**
* Used to assign VoiceActivity Detection based on the provided configuration
*
* @see AZM.Command.Zone.Setup(AudioConfiguration)
* @link [xStatus Audio Microphones VoiceActivityDetector Activity](https://roomos.cisco.com/xapi/Status.Audio.Microphones.VoiceActivityDetector.Activity/)
*/
let allowVoiceActivityDetection = true;
/**
* Used to assign the Sample Mode based on the provided configuration
*
* @see AZM.Command.Zone.Setup(AudioConfiguration)
*/
let audioSamplingMode = 'Snapshot';
/**
* Helps educate integrators which connector types are allowed in this Library on Error
*
* Has no impact other than logging
*/
const allowedAudioTypes = `Analog, USB, Ethernet, AES67, ExternalVuMeter, ExternalGate`;
/**Aids in the mapping of Ethernet Connector Inputs
*
* Allows for discrete zoning on a single ethernet base microphone per its SubIds
* @see Instantiate_Audio_Zones_And_Buckets()
*/
const zoneConnectorMap = {
Ethernet: []
};
/*****[Prototype Objects]***********************************************************/
/**
* Checks if the array includes a specified value using the loose equality operator (`==`).
*
* This method works similarly to `Array.prototype.includes()`, but it uses loose equality (`==`)
* instead of strict equality (`===`) to determine if the value is present.
*
* @param {*} value The value to search for in the array.
* @returns {boolean} `true` if the value is found in the array, otherwise `false`.
*/
Array.prototype.includish = function (value) {
for (let i = 0; i < this.length; i++) { if (this[i] == value) { return true; }; };
return false;
};
/**
* Safely clones an object in code in order to prevent changes to the original object
*/
Object.prototype.clone = Array.prototype.clone = function () {
if (Object.prototype.toString.call(this) === '[object Array]') {
const clone = [];
for (let i = 0; i < this.length; i++) {
clone[i] = this[i].clone();
}
return clone;
} else if (typeof (this) == "object") {
const clone = {};
for (let prop in this)
if (this.hasOwnProperty(prop)) {
clone[prop] = this[prop].clone();
}
return clone;
}
else {
return this;
}
}
/*****[Class Objects]***********************************************************/
/**
* Custom Error class for AZM Lib errors.
*
* Functions like Error but clearly marks this an an error associated to AZMLib
*/
class AZM_Error extends Error {
constructor(message) {
super(`[AZM Error]: ${message}`);
}
}
/**
* This tracks the Zone State based on it's Connector States
*
* This Class is instantiated in AZM.Status.Audio.Zone[N]
* - This path allows a developer to poll the current state of a specific Zone
*
* @param {number} zoneId
* Numeric ID for the Zone, used in AZM.Status Node
* @param {number} zoneLabel
* The Label assigned to the Zone
* @param {number} zoneType
* The type of Microphones assigned to the zone
* @param {number} assets
* The Assets associated to the zone
*/
class Zone_Tracker {
constructor(zoneId, zoneLabel, zoneType, assets) {
this._ZoneId = zoneId;
this._Label = zoneLabel;
this._Connectors = [];
this._State = 'Unset';
this._ZoneType = zoneType;
this._Assets = assets;
console.AZM.ZonesDebug(`New [${this._ZoneType}] Zone instantiated || ZoneId: [${this._ZoneId}]`)
}
addConnector(connectorId, state, zoneId) {
if (zoneId == this._ZoneId) {
this._Connectors.push({ ConnectorId: connectorId, State: state })
console.AZM.ZonesDebug(`ConnectorId [${connectorId}] added || ZoneId: [${this._ZoneId}]`)
}
}
setConnectorState(connectorId, newState, zoneId) {
checkZoneSetup(`Unable to set connector state on ZoneId: [${this._ZoneId}]`)
if (zoneId == this._ZoneId) {
const index = this._Connectors.findIndex(item => item.ConnectorId === connectorId);
if (index != -1) {
this._Connectors[index].State = newState;
console.AZM.ZonesDebug(`ConnectorId [${connectorId}] State updated to [${newState}] || ZoneId: [${this._ZoneId}]`)
}
}
return new Promise(resolve => resolve(`Ok`));
}
get State() {
checkZoneSetup(`Unable to request Zone information from ZoneId: [${this._ZoneId}]`)
let hasHigh = false;
let hasLow = false;
let hasUnset = false;
for (const item of this._Connectors) {
if (item.State == 'High') {
hasHigh = true;
} else if (item.State == 'Low') {
hasLow = true;
} else if (item.State == 'Unset') {
hasUnset = true;
}
}
const stateObject = {
get: () => {
if (hasHigh) {
return 'High';
} else if (hasLow && !hasUnset) {
return 'Low';
} else if (!hasLow && hasUnset) {
return 'Unset';
} else {
return 'Low';
}
},
};
this._State = stateObject
return stateObject;
}
get() {
checkZoneSetup(`Unable to request Zone information from ZoneId: [${this._ZoneId}]`)
this._State = this.State.get()
return { Id: this._ZoneId, Label: this._Label, Type: this._ZoneType, Connectors: this._Connectors, State: this._State }
}
}
/**
* AudioBuckets are used to collect and process incoming audio data
*
* The Base_AudioBucket is a template class for all other buckets to extend from
*
* @param connectorId
* The audio connector IDs associated to this Audio Bucket
* @param zoneId
* The Zone Id this Audio Bucket belongs too
* @param zoneLabel
* The Zone Label this Audio Bucket belongs too
* @param assets
* The Assets that are associated to this Audio Bucket
*
* @method ```run``` Processes incoming audio data, updates AZM Status Branch, calls back Zone Event States
*
* @see Analog_Bucket
* @see USB_Bucket
* @see Ethernet_Bucket
*/
class Base_AudioBucket {
constructor(connectorId, zoneId, zoneLabel, assets) {
this.ConnectorId = connectorId;
this.ZoneId = zoneId;
this.Label = zoneLabel;
this.Assets = assets;
this.bin = { VuMeter: [], PPMeter: [], NoiseLevel: [], LoudspeakerActivity: [] };
this.State = 'Unset';
this.audioConnectorType = 'Unset';
}
run(data, callback) {
this.bin.VuMeter.push(data.VuMeter)
this.bin.PPMeter.push(data.PPMeter)
this.bin.NoiseLevel.push(data.NoiseLevel)
this.bin.LoudspeakerActivity.push(data.LoudspeakerActivity)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`[${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] payload pushed into bins || ZoneId: [${this.ZoneId}] || Bucketlength: [${this.bin.VuMeter.length}] || Payload: ${data}`)
if (this.bin.VuMeter.length == AudioConfiguration.Settings.Sample.Size) {
let process_vu_meter = '';
switch (audioSamplingMode) {
case 'Snapshot':
process_vu_meter = Process_BIN_Data(this.bin.VuMeter)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] met Snapshot Sample Size [${AudioConfiguration.Settings.Sample.Size}], processing bin || ZoneId: [${this.ZoneId}]`)
this.bin = { VuMeter: [], PPMeter: [], NoiseLevel: [], LoudspeakerActivity: [] }
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] cleared || ZoneId: [${this.ZoneId}]`)
break;
case 'Rolling':
process_vu_meter = Process_BIN_Data(this.bin.VuMeter)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] met Rolling Sample Size [${AudioConfiguration.Settings.Sample.Size}], processing bin || ZoneId: [${this.ZoneId}]`)
this.bin.VuMeter.shift()
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin Shifted for [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}], waiting for next value || ZoneId: [${this.ZoneId}]`)
break;
}
if (process_vu_meter.Average >= this.thresholds.High) {
if (allowVoiceActivityDetection) {
if (AZM.Status.VoiceActivity) {
this.State = 'High'
} else {
this.State = 'Low'
}
} else {
this.State = 'High'
}
} else if (process_vu_meter.Average <= this.thresholds.Low) {
this.State = 'Low'
}
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] State set [${this.State}] || ZoneId: [${this.ZoneId}]`)
AZM.Status.Audio.Zone[this.ZoneId].setConnectorState(this.ConnectorId, this.State, this.ZoneId).then(() => {
const payload = {
Zone: {
Label: this.Label,
State: AZM.Status.Audio.Zone[this.ZoneId].State.get(),
Id: this.ZoneId
}, Connector: {
Type: this.audioConnectorType,
State: this.State,
Id: this.ConnectorId
}, Assets: this.Assets,
DataSet: { VuMeter: process_vu_meter }
}
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] Callback Fired || ZoneId: [${this.ZoneId}]`)
callback(payload);
})
}
}
}
/**
* Collects and Processes Audio data coming from Analog Input sources
*
* Extends from Base_AudioBucket
*
* @see Base_AudioBucket
* @see AZM.Command.Zone.Setup()
*/
class Analog_Bucket extends Base_AudioBucket {
constructor(connectorId, zoneId, zoneLabel, assets) {
super(connectorId, zoneId, zoneLabel, assets);
this.audioConnectorType = 'Analog';
this.thresholds = setBucketAudioThresholds(this.ZoneId, AudioConfiguration, this.audioConnectorType)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`New [${this.audioConnectorType}] Bucket instantiated for the [${this.Label}] Zone || Bucket: [Connector: ${this.ConnectorId} || ZoneId: [${this.ZoneId}]`)
}
}
/**
* Collects and Processes Audio data coming from USB Input sources
*
* Extends from Base_AudioBucket
*
* @see Base_AudioBucket
* @see AZM.Command.Zone.Setup()
*/
class USB_Bucket extends Base_AudioBucket {
constructor(connectorId, zoneId, zoneLabel, assets) {
super(connectorId, zoneId, zoneLabel, assets)
this.audioConnectorType = 'USB'
this.thresholds = setBucketAudioThresholds(this.ZoneId, AudioConfiguration, this.audioConnectorType)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`New [${this.audioConnectorType}] Bucket instantiated for the [${this.Label}] Zone || Bucket: [Connector: ${this.ConnectorId} || ZoneId: [${this.ZoneId}]`)
}
}
/**
* Collects and Processes Audio data coming from Ethernet Input sources (Cisco or AES67)
*
* Extends from Base_AudioBucket
*
* @see Base_AudioBucket
* @see AZM.Command.Zone.Setup()
*
* @method ```run``` Processes incoming audio data, updates AZM Status Branch, calls back Zone Event States. Modified run method, accounts for SubIds of Ethernet based microphones
* @method ```setSubIdProperties``` instantiates bins for each SubId for independent tracking and Processing of each Ethernet SubID
*/
class Ethernet_Bucket extends Base_AudioBucket {
constructor(connectorId, connectorSubId, zoneId, zoneLabel, assets) {
super(connectorId, zoneId, zoneLabel, assets)
this.audioConnectorType = 'Ethernet'
this.thresholds = setBucketAudioThresholds(this.ZoneId, AudioConfiguration, this.audioConnectorType)
this.ConnectorSubIds = connectorSubId;
this.SubStates = {};
this.bin = this.setSubIdProperties();
console.AZM[`${this.audioConnectorType}_BucketDebug`](`New [${this.audioConnectorType}] Bucket instantiated for the [${this.Label}] Zone || Bucket: [Connector: ${this.ConnectorId} || ZoneId: [${this.ZoneId}]`)
}
setSubIdProperties() {
const initialBins = {};
let binCount = 0
this.ConnectorSubIds.forEach(element => {
binCount++
//Based on configured SubIds, instantiate bins to collect audio data
initialBins[element] = { VuMeter: [], PPMeter: [], NoiseLevel: [], LoudspeakerActivity: [] };
//Also instantiate substates, for Connector State evaluation
this.SubStates[element] = 'Unset';
});
console.AZM[`${this.audioConnectorType}_BucketDebug`](`[${binCount}] [Ethernet] Bucket bins created || Bucket: [Connector: ${this.ConnectorId}, SubId: ${this.ConnectorSubIds}] || ZoneId: [${this.ZoneId}]`)
return initialBins;
}
run(data, callback) {
data.SubId.forEach(subElement => {
if (this.ConnectorSubIds.includish(subElement.id)) {
this.bin[subElement.id].VuMeter.push(subElement.VuMeter);
this.bin[subElement.id].PPMeter.push(subElement.PPMeter);
this.bin[subElement.id].NoiseLevel.push(subElement.NoiseLevel);
this.bin[subElement.id].LoudspeakerActivity.push(subElement.LoudspeakerActivity);
console.AZM[`${this.audioConnectorType}_BucketDebug`](`[${this.audioConnectorType}] SubId [${subElement.id}] payload pushed into bins || ZoneId: [${this.ZoneId}] || Bucketlength: [${this.bin[subElement.id].VuMeter.length}] || Payload: ${subElement}`)
if (this.bin[subElement.id].VuMeter.length == AudioConfiguration.Settings.Sample.Size) {
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] SubId [${subElement.id}] met Sample Size [${AudioConfiguration.Settings.Sample.Size}], processing bin || ZoneId: [${this.ZoneId}]`)
let process_vu_meter = '';
switch (audioSamplingMode) {
case 'Snapshot':
process_vu_meter = Process_BIN_Data(this.bin[subElement.id].VuMeter)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] SubId [${subElement.id}] Snapshot processed. Result [${JSON.stringify(process_vu_meter)}] || ZoneId: [${this.ZoneId}]`)
this.bin[subElement.id] = { VuMeter: [], PPMeter: [], NoiseLevel: [], LoudspeakerActivity: [] };
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] SubId [${subElement.id}] cleared || ZoneId: [${this.ZoneId}]`)
break;
case 'Rolling':
process_vu_meter = Process_BIN_Data(this.bin[subElement.id].VuMeter)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] SubId [${subElement.id}] Rolling processed. Result [${JSON.stringify(process_vu_meter)}] || ZoneId: [${this.ZoneId}]`)
this.bin[subElement.id].VuMeter.shift()
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin Shifted for [${this.audioConnectorType}] SubId [${subElement.id}], waiting for next value || ZoneId: [${this.ZoneId}]`)
break;
}
//Compare Average VU against Threshold and set SubId state
if (process_vu_meter.Average >= this.thresholds.High) {
if (allowVoiceActivityDetection) {
if (AZM.Status.VoiceActivity) {
this.SubStates[subElement.id] = 'High'
} else {
this.SubStates[subElement.id] = 'Low'
}
} else {
this.SubStates[subElement.id] = 'High'
}
} else if (process_vu_meter.Average <= this.thresholds.Low) {
this.SubStates[subElement.id] = 'Low'
} else {
//May implement a Middle state in the future?
//Perhaps an ExitHigh or ExitLow callback?
//this.SubStates[subElement.id] = 'Middle'
}
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] SubId [${subElement.id}] State set [${this.SubStates[subElement.id]}] || ZoneId: [${this.ZoneId}]`)
//Check all SubId States, and set Connector State
let hasHigh = false;
let hasLow = false;
let hasUnset = false;
for (const item of this.ConnectorSubIds) {
if (this.SubStates[item] == 'High') {
hasHigh = true;
} else if (this.SubStates[item] == 'Low') {
hasLow = true;
} else if (this.SubStates[item] == 'Unset') {
hasUnset = true;
}
}
if (hasHigh) {
this.State = 'High';
} else if (hasLow && !hasUnset) {
this.State = 'Low';
} else if (!hasLow && hasUnset) {
this.State = 'Unset';
} else {
this.State = 'Low';
}
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] State set [${this.State}] || ZoneId: [${this.ZoneId}]`)
AZM.Status.Audio.Zone[this.ZoneId].setConnectorState(this.ConnectorId, this.State, this.ZoneId).then(() => {
const payload = {
Zone: {
Label: this.Label,
State: AZM.Status.Audio.Zone[this.ZoneId].State.get(),
Id: this.ZoneId
}, Connector: {
Type: this.audioConnectorType,
State: this.State,
Id: this.ConnectorId, SubId: subElement.id
}, Assets: this.Assets,
DataSet: { VuMeter: process_vu_meter }
}
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] Callback Fired || ZoneId: [${this.ZoneId}]`)
callback(payload)
})
}
}
});
}
}
/**
* Collects and Processes Audio data submitted by an integration external to the codec
*
* ExternalVuMeter expects a payload containing VuMeter Data
*
* Extends from Base_AudioBucket
*
* @see Base_AudioBucket
* @see AZM.Command.Zone.Setup()
*/
class ExternalVuMeter_Bucket extends Base_AudioBucket {
constructor(connectorId, zoneId, zoneLabel, assets, controllerId) {
super(connectorId, zoneId, zoneLabel, assets)
this.ControllerId = controllerId
this.bin = { VuMeter: [] };
this.audioConnectorType = 'ExternalVuMeter'
this.thresholds = setBucketAudioThresholds(this.ZoneId, AudioConfiguration, this.audioConnectorType)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`New [${this.audioConnectorType}] Bucket instantiated for the [${this.Label}] Zone || Bucket: [Connector: ${this.ConnectorId} || ZoneId: [${this.ZoneId}]`)
}
run(data, callback) {
this.bin.VuMeter.push(data)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`[${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] payload pushed into bins || ZoneId: [${this.ZoneId}] || Bucketlength: [${this.bin.VuMeter.length}] || Payload: ${data}`)
if (this.bin.VuMeter.length == AudioConfiguration.Settings.Sample.Size) {
let process_vu_meter = '';
switch (audioSamplingMode) {
case 'Snapshot':
process_vu_meter = Process_BIN_Data(this.bin.VuMeter)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] met Snapshot Sample Size [${AudioConfiguration.Settings.Sample.Size}], processing bin || ZoneId: [${this.ZoneId}]`)
this.bin = { VuMeter: [], PPMeter: [], NoiseLevel: [], LoudspeakerActivity: [] }
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] cleared || ZoneId: [${this.ZoneId}]`)
break;
case 'Rolling':
process_vu_meter = Process_BIN_Data(this.bin.VuMeter)
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] met Rolling Sample Size [${AudioConfiguration.Settings.Sample.Size}], processing bin || ZoneId: [${this.ZoneId}]`)
this.bin.VuMeter.shift()
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin Shifted for [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}], waiting for next value || ZoneId: [${this.ZoneId}]`)
break;
}
if (process_vu_meter.Average >= this.thresholds.High) {
if (allowVoiceActivityDetection) {
if (AZM.Status.VoiceActivity) {
this.State = 'High'
} else {
this.State = 'Low'
}
} else {
this.State = 'High'
}
} else if (process_vu_meter.Average <= this.thresholds.Low) {
this.State = 'Low'
}
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] State set [${this.State}] || ZoneId: [${this.ZoneId}]`)
AZM.Status.Audio.Zone[this.ZoneId].setConnectorState(this.ConnectorId, this.State, this.ZoneId).then(() => {
const payload = {
Zone: {
Label: this.Label,
State: AZM.Status.Audio.Zone[this.ZoneId].State.get(),
Id: this.ZoneId
}, Connector: {
Type: this.audioConnectorType,
State: this.State,
Id: this.ConnectorId
}, Assets: this.Assets,
DataSet: { VuMeter: process_vu_meter }
}
console.AZM[`${this.audioConnectorType}_BucketDebug`](`VuMeter Bin [${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] Callback Fired || ZoneId: [${this.ZoneId}]`)
callback(payload);
})
}
}
}
/**
* Collects and Processes Audio data submitted by an integration external to the codec
*
* ExternalGate expects a payload containing Audio Gate States
*
* Extends from Base_AudioBucket
*
* @see Base_AudioBucket
* @see AZM.Command.Zone.Setup()
*
* @method ```run``` Processes incoming audio data, updates AZM Status Branch, calls back Zone Event States. Modified run method, expects a ```open``` or ```close``` message instead of VuMeter data
*/
class ExternalGate_Bucket extends Base_AudioBucket {
constructor(connectorId, zoneId, zoneLabel, assets, controllerId) {
super(connectorId, zoneId, zoneLabel, assets)
this.ControllerId = controllerId;
this.audioConnectorType = 'ExternalGate'
console.AZM[`${this.audioConnectorType}_BucketDebug`](`New [${this.audioConnectorType}] Bucket instantiated for the [${this.Label}] Zone || Bucket: [Connector: ${this.ConnectorId} || ZoneId: [${this.ZoneId}]`)
}
run(data, callback) {
console.AZM[`${this.audioConnectorType}_BucketDebug`](`New Payload passed into [${this.audioConnectorType}], Payload`, data)
switch (data.toLowerCase()) {
case 'open': case 'opened':
if (allowVoiceActivityDetection) {
if (AZM.Status.VoiceActivity) {
this.State = 'High';
} else {
this.State = 'Low';
};
} else {
this.State = 'High';
};
break;
case 'close': case 'closed':
this.State = 'Low';
break;
default:
console.AZM.error(`[${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] offered unknown Gate State [${data}]. Unable to process, setting ZoneId: [${this.ZoneId}] state Low`)
this.State = 'Low';
break;
}
console.AZM[`${this.audioConnectorType}_BucketDebug`](`[${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] State set [${this.State}] || ZoneId: [${this.ZoneId}]`);
AZM.Status.Audio.Zone[this.ZoneId].setConnectorState(this.ConnectorId, this.State, this.ZoneId).then(() => {
const payload = {
Zone: {
Label: this.Label,
State: AZM.Status.Audio.Zone[this.ZoneId].State.get(),
Id: this.ZoneId
}, Connector: {
Type: this.audioConnectorType,
State: this.State,
Id: this.ConnectorId
}, Assets: this.Assets,
DataSet: { Gate: data }
}
callback(payload);
console.AZM[`${this.audioConnectorType}_BucketDebug`](`[${this.audioConnectorType}] ConnectorId [${this.ConnectorId}] Callback Fired || ZoneId: [${this.ZoneId}]`)
})
}
}
/*****[Non Exported Function Objects]***********************************************************/
/**
* Instantiates AZM branch of the JS Console
*/
console.AZM = {};
/**
* Alternate console methods for AZM_Lib
*
* Provides context for AZM when imported into another projects. Helps isolate where to troubleshoot your project.
*/
console.AZM.log = function (...args) { console.log('[AZM.log]:', ...args); };
console.AZM.info = function (...args) { console.info('[AZM.info]:', ...args); };
console.AZM.warn = function (...args) { console.warn('[AZM.warn]:', ...args); };
console.AZM.error = function (...args) { console.error('[AZM.error]:', ...args); };
/**
* Checks the OS of the device to see validate minimum requirements
*
* on the device or not
* @parameter { String } minimumOs - Numeric RoomOS Number separated by dots
*
* @example ```check4_Minimum_Version_Required(11.1.1.0);```
*
* @xapi [xStatus SystemUnit Software Version](https://roomos.cisco.com/xapi/Status.SystemUnit.Software.Version/)
*
* @returns boolean
*/
async function check4_Minimum_Version_Required(minimumOs) {
const reg = /^\D*(?<MAJOR>\d*)\.(?<MINOR>\d*)\.(?<EXTRAVERSION>\d*)\.(?<BUILDID>\d*).*$/i;
const minOs = minimumOs;
const os = await xapi.Status.SystemUnit.Software.Version.get();
const x = (reg.exec(os)).groups;
const y = (reg.exec(minOs)).groups;
if (parseInt(x.MAJOR) > parseInt(y.MAJOR)) return true;
if (parseInt(x.MAJOR) < parseInt(y.MAJOR)) return false;
if (parseInt(x.MINOR) > parseInt(y.MINOR)) return true;
if (parseInt(x.MINOR) < parseInt(y.MINOR)) return false;
if (parseInt(x.EXTRAVERSION) > parseInt(y.EXTRAVERSION)) return true;
if (parseInt(x.EXTRAVERSION) < parseInt(y.EXTRAVERSION)) return false;
if (parseInt(x.BUILDID) > parseInt(y.BUILDID)) return true;
if (parseInt(x.BUILDID) < parseInt(y.BUILDID)) return false;
return false;
}
function filterEthernetZoneMap(data, connectorId) {
const result = [];
for (const key in data) {
if (data[key].ConnectorId == connectorId) {
result.push(data[key]);
}
}
return result;
}
/**
* Creates new Debug Function that respects AZM_DebugFlags
*
* This is used to tailor logs, to make sure only relevant context is active in a standard deployment
*
* @see AZM_DebugFlags
*/
function createDebugMethod(methodName, debugFlag) {
return function (...args) {
if (AZM_DebugFlags[debugFlag]) {
console.debug(`[AZM.${methodName}]:`, ...args);
}
};
}
/**
* Loops through AZM_DebugFlags to instantiate new console.AZM[X] debug nodes
*
* @see AZM_DebugFlags
*/
function buildDebugFlagLogLevels() {
let list = Object.getOwnPropertyNames(AZM_DebugFlags);
list.forEach(element => { console.AZM[element] = createDebugMethod(element, element); });
}
/**
* Enables a time based subscription
*
* @param timeOfDay: Hour and Minute for event to fire. 24hr format. Ex: 00:00
* @param day: Day of Week to for event to fire. Ex: "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
* @param callBack: produces a callback. This triggers the event necessary to execute other code
*/
function Schedule(timeOfDay = '00:00', day, callBack) {
const dayToNumber = { "monday": 1, "tuesday": 2, "wednesday": 3, "thursday": 4, "friday": 5, "saturday": 6, "sunday": 7 };
const [configuredHour, configuredMinute] = timeOfDay.replace('.', ':').split(':');
const now = new Date();
const thisDay = now.getDay();
const parseNow = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
let difference = parseInt(configuredHour) * 3600 + parseInt(configuredMinute) * 60 - parseNow;
if (difference <= 0) {
difference += 24 * 3600
};
return setTimeout(function () {
if (thisDay == dayToNumber[day.toLowerCase()]) {
const message = { Message: `[${timeOfDay}] Scheduled event fired` }
callBack(message)
}
setTimeout(function () {
Schedule(timeOfDay, day, callBack)
}, 1000)
}, difference * 1000);
}
/**
* Contains All functions associated to automatic update process, excluding UI elements
*/
const automaticUpdates = {
/**
* Compares current AZM version running against incoming version from update process
*
* Versions contain a major, minor and build versions separated by dots.
*
* @param {string} currentVersion
* The current version of the AZM Library Running
*
* @param {string} incomingVersion
* The version of the AZM library reported by the manifest on Github
*
* @example automaticUpdates.CompareAZMVersion('1.0.0', '1.0.1');
*/
CompareAZMVersion: function (currentVersion, incomingVersion) {
const parseVersion = (version) => version.split('.').map(Number);
const [currentMajor, currentMinor, currentBuild] = parseVersion(currentVersion);
const [incomingMajor, incomingMinor, incomingBuild] = parseVersion(incomingVersion);
if (incomingMajor > currentMajor) {
return "Higher";
} else if (incomingMajor < currentMajor) {
return "Lower";
} else if (incomingMinor > currentMinor) {
return "Higher";
} else if (incomingMinor < currentMinor) {
return "Lower";
} else if (incomingBuild > currentBuild) {
return "Higher";
} else if (incomingBuild < currentBuild) {
return "Lower";
} else {
return "Match";
}
},
/**
* Parses headers from a request to github to discover the location URL
*
* @param {object} headers
* The headers from a 302 redirect response code from Github
*/
GetReleaseLocationUrl: function (headers) {
const locationHeader = headers.find(header => header.Key === 'location');
return locationHeader ? locationHeader.Value : null;
},
/** Initiates the update process utilizing the github releases API
*
* @see automaticUpdates.GetReleaseLocationUrl()
* @see automaticUpdates.CompareAZMVersion()
*
* @xapi [xCommand HttpClient Get](https://roomos.cisco.com/xapi/Command.HttpClient.Get/)
*/
StartUpdateProcess: async function () {
if (config_AutomaticUpdates_Mode.toLowerCase() == 'off') {
await removeAZMNotifications()
return;
} else {
await buildAZMNotifications();
await updateAZMUpdateStatusUIExtension(`Checking for AZM File Updates...`, '- - -');
}
let newAZMMacro = undefined;
let manifest = {};
let releaseFileUrl = {
AZM_Lib: '',
manifest: ''
}
// First get latest release information from github
// Parse the information to grab the download URLs for both the AZM Lib and Manifest
try {
const requestRelease = await xapi.Command.HttpClient.Get({
Url: `https://api.github.com/repos/ctg-tme/audio-zone-manager-library-macro/releases/latest`
})
const releaseManifest = JSON.parse(requestRelease.Body);
releaseManifest.assets.forEach(item => {
// Check the name of the asset and assign the URL accordingly
switch (item.name) {
case 'AZM_Lib.js':
releaseFileUrl.AZM_Lib = item.browser_download_url;
break;
case 'manifest.json':
releaseFileUrl.manifest = item.browser_download_url;
break;
default:
break;
}
});
} catch (e) {
await updateAZMUpdateStatusUIExtension(`Uh-Oh! Unable to reach Github. Installed Version: v${version}. Check the Macro Console for more information`, '- - -');