-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.js
2389 lines (2101 loc) · 83 KB
/
main.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
/**
*
* snmp adapter,
* copyright CTJaeger 2017, MIT
* copyright McM1957 2022-2023, MIT
*
*/
/*
* Remark related to REAL / FLOAT values returned:
*
* see http://www.net-snmp.org/docs/mibs/NET-SNMP-TC.txt
*
* --
* -- Define the Float Textual Convention
* -- This definition was written by David Perkins.
* --
*
* Float ::= TEXTUAL-CONVENTION
* STATUS current
* DESCRIPTION
* "A single precision floating-point number. The semantics
* and encoding are identical for type 'single' defined in
* IEEE Standard for Binary Floating-Point,
* ANSI/IEEE Std 754-1985.
* The value is restricted to the BER serialization of
* the following ASN.1 type:
* FLOATTYPE ::= [120] IMPLICIT FloatType
* (note: the value 120 is the sum of '30'h and '48'h)
* The BER serialization of the length for values of
* this type must use the definite length, short
* encoding form.
*
* For example, the BER serialization of value 123
* of type FLOATTYPE is '9f780442f60000'h. (The tag
* is '9f78'h; the length is '04'h; and the value is
* '42f60000'h.) The BER serialization of value
* '9f780442f60000'h of data type Opaque is
* '44079f780442f60000'h. (The tag is '44'h; the length
* is '07'h; and the value is '9f780442f60000'h.)"
* SYNTAX Opaque (SIZE (7))
*
*/
/*
* Some general REMINDERS for further development
*
* - Ensure that every timer value is less than 0x7fffffff - otherwise the time will fire immidiatly
*
*/
/*
* description if major internal objects
*
* CTXs object (array) of CTX objectes
*
* CTX object for one signle device
* containing
* name string name of the device
* ipAddr string ip address (without port number)
* ipPort number ip port number
* devId string devId of device, dereived from ip address or from name
* isIPv6 bool true if IPv6 to be used
* timeout number snmp connect timeout (ms)
* retryIntvl number snmp retry intervall (ms)
* pollIntvl number snmp poll intervall (ms)
* snmpVers number snmp version
* community string snmp comunity (v1, v2c)
* chunks array array of oid data consiting of
* {
* OIDs array of objects
* oid config object (contains i.e. flags)
* oids array of strings
* oids to be read
* ids array of strings
* ids for oids to be read
* }
* pollTimer object timer object for poll timer
* retryTimer object timer object for retry timer
* session object snmp session object
*/
/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
'use strict';
const F_TEXT = 0;
const F_NUMERIC = 1;
const F_BOOLEAN = 2;
const F_JSON = 3;
const F_AUTO = 99;
// snmp protocols
const SNMP_V1 = 1;
const SNMP_V2c = 2;
const SNMP_V3 = 3;
// authentication protocols
const MD5 = 1;
const SHA = 2;
const SHA224 = 3;
const SHA256 = 4;
const SHA384 = 5;
const SHA512 = 6;
const DES = 1;
const AES = 2;
const AES256B = 3;
const AES256R = 4;
/*
* based on template created with @iobroker/create-adapter v2.1.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
const { EXIT_CODES } = require('@iobroker/js-controller-common');
const adapterName = require('./package.json').name.split('.').pop();
const InstallUtils = require('./lib/installUtils');
// Load modules required by adapter
const snmp = require('net-snmp');
const net = require('net');
// init installation marker
let doInstall = false;
let didInstall = false;
// #################### global variables ####################
let adapter; // adapter instance - @type {ioBroker.Adapter}
const CTXs = []; // see description at header of file
const STATEs = []; // states cache, index by full id
let g_isConnected = false; // local copy of info.connection state
let g_shutdownInProgress = false; // maximum number of OIDs per request
let g_connUpdateTimer = null;
let g_chunkSize = 3; // maximum number of OIDs per request
/**
* Start the adapter instance
* @param {Partial<utils.AdapterOptions>} [options]
*/
function startAdapter(options) {
// Create the adapter and define its methods
adapter = utils.adapter(Object.assign({}, options, {
name: 'snmp',
// ready callback is called when databases are connected and adapter received configuration.
ready: onReady, // Main method defined below for readability
// unload callback is called when adapter shuts down - callback has to be called under any circumstances!
unload: onUnload,
// If you need to react to object changes, uncomment the following method.
// You also need to subscribe to the objects with `adapter.subscribeObjects`, similar to `adapter.subscribeStates`.
// objectChange: (id, obj) => {
// if (obj) {
// // The object was changed
// adapter.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
// } else {
// // The object was deleted
// adapter.log.info(`object ${id} deleted`);
// }
// },
// stateChange is called if a subscribed state changes
stateChange: onStateChange,
// If you need to accept messages in your adapter, uncomment the following block.
// /**
// * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
// * Using this method requires "common.messagebox" property to be set to true in io-package.json
// */
// message: (obj) => {
// if (typeof obj === 'object' && obj.message) {
// if (obj.command === 'send') {
// // e.g. send email or pushover or whatever
// adapter.log.info('send command');
// // Send response in callback if required
// if (obj.callback) adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
// }
// }
// },
}));
return adapter;
}
/* *** end of initialization section *** */
// #################### general utility functions ####################
/**
* Convert name to id
*
* This utility routine replaces all forbidden chars and the characters '-' and any whitespace
* with an underscore ('_').
*
* @param {string} pName name of an object
* @return {string} name of the object with all forbidden chars replaced
*
*/
function name2id(pName) {
return (pName || '').replace(adapter.FORBIDDEN_CHARS, '_').replace(/[-\s]/g, '_');
}
/**
* convert ip to ipStr
*
* This utility routine replaces any dots within an ip address with an underscore ('_').
*
* @param {string} ip ip string with standard foematting
* @return {string} ipStr with all dots removed and useable as identifier
*
*/
function ip2ipStr(ip) {
return (ip || '').replace(/\./g, '_');
}
/**
* convert oid format to state format
*
* @param {number} pOidFormat OID format code
* @return {string} state type
*
*/
function oidFormat2StateType(pOidFormat){
switch (pOidFormat){
case F_TEXT /* 0 */: {
return 'string';
}
case F_NUMERIC /* 1 */: {
return 'number';
}
case F_BOOLEAN /* 2 */: {
return 'boolean';
}
case F_JSON /* 3 */: {
return 'string';
}
case F_AUTO /* 99 */: {
return 'mixed';
}
default:{
adapter.log.warn('oidFormat2StateType - unknown code ' + pOidFormat );
return 'mixed';
}
}
}
// #################### object initialization functions ####################
/**
* cleanupStates - cleanup unused states
*
* @param {string} pPattern pattern to match state id
*
* @return objects
*
*/
async function delStates( pPattern ) {
adapter.log.debug ( 'delStates ('+pPattern+')');
const objs = await adapter.getForeignObjectsAsync( `${adapterName}.${adapter.instance}.${pPattern}` );
if (objs){
if ( Object.values(objs).length ) {
adapter.log.info(`removing states ${pPattern}...`);
}
for (const obj of Object.values(objs)) {
adapter.log.debug(`removing object ${obj._id}...`);
await adapter.delForeignObjectAsync( obj._id, {recursive: true} );
}
}
}
/**
* cleanupStates - cleanup unused states
*
* @return nothing
*
*/
async function cleanupStates() {
adapter.log.debug('cleanupStates ');
// delete -rap states if no lonager enabled
if ( ! adapter.config.optRawStates )
{
await delStates ( '*-raw' );
}
// delete -type states if no lonager enabled
if ( ! adapter.config.optTypeStates )
{
await delStates ( '*-type' );
}
}
// #################### object initialization functions ####################
/**
* initObject - create or reconfigure single object
*
* creates object if it does not exist
* overrides object data otherwise
* waits for action to complete using await
*
* @param {object} pObj objectstructure
* @return
*
*/
async function initObject(pObj) {
adapter.log.debug('initobject ' + pObj._id);
const fullId = `${adapterName}.${adapter.instance}.${pObj._id}`;
if (typeof(STATEs[fullId]) === 'undefined') {
try {
adapter.log.debug('creating obj "' + pObj._id + '" with type ' + pObj.type);
await adapter.setObjectNotExistsAsync(pObj._id, pObj);
await adapter.extendObjectAsync(pObj._id, pObj);
} catch (e) {
adapter.log.error('error initializing obj "' + pObj._id + '" ' + e.message);
}
STATEs[fullId] = {
type: pObj.type,
commonType: null,
};
}
if (pObj.type === 'state') {
if ( (typeof (STATEs[fullId].commonType) === 'undefined' ) ||
(STATEs[fullId].commonType === null ) ) {
const obj = await adapter.getObjectAsync(pObj._id);
STATEs[fullId] = {
commonType: obj.common.type
};
}
if ( STATEs[fullId].commonType !== pObj.common.type ) {
try {
if ( STATEs[fullId].commonType === 'mixed') {
adapter.log.debug('reinitializing obj "' + pObj._id + '" state-type change '+STATEs[fullId].commonType+' -> '+pObj.common.type);
} else {
adapter.log.info('reinitializing obj "' + pObj._id + '" state-type change '+STATEs[fullId].commonType+' -> '+pObj.common.type);
}
await adapter.extendObjectAsync(pObj._id, {common: { type: pObj.common.type }});
STATEs[fullId].commonType = pObj.common.type;
} catch (e) {
adapter.log.error('error reinitializing obj "' + pObj._id + '" ' + e.message);
}
}
}
}
/**
* initDeviceObjects - initializes all objects related to a device
*
* @param {string} pId id of device
* @param {string} pIp ip of device
* @return
*
*/
async function initDeviceObjects(pId, pIp) {
adapter.log.debug('initdeviceObjects (' + pId + '/' + pIp + ')');
try {
await adapter.delForeignObjectAsync(`${adapterName}.${adapter.instance}.${pId}.online`, {recursive: false});
} catch (e) { /* */ }
try {
// create <ip> device object
await initObject({
_id: pId,
type: 'device',
common: {
name: pIp,
statusStates: {
onlineId: `${adapterName}.${adapter.instance}.${pId}.info.online`,
errorId: `${adapterName}.${adapter.instance}.${pId}.info.error`
}
},
native: {
}
}
);
// create <ip>.online and .alarm state objects
await initObject({
_id: pId + '.info',
type: 'folder',
common: {
name:'',
desc: 'folder containing device status states'
},
native: {
}
}
);
await initObject({
_id: pId + '.info.online',
type: 'state',
common: {
name: pId + '.info.online',
desc: 'true if device is reachable',
write: false,
read: true,
type: 'boolean',
role: 'indicator.reachable'
},
native: {
}
}
);
await initObject({
_id: pId + '.info.error',
type: 'state',
common: {
name: pId + '.info.error',
desc: 'true if error occured',
write: false,
read: true,
type: 'boolean',
role: 'indicator.reachable'
},
native: {
}
}
);
await initObject({
_id: pId + '.info.error_text',
type: 'state',
common: {
name: pId + '.info.error_text',
desc: 'text describing last error',
write: false,
read: true,
type: 'string',
role: 'text'
},
native: {
}
}
);
} catch (e) {
adapter.log.error('error creating objects for ip "' + pIp + '" (' + pId + '), ' + e.message);
}
}
/**
* initOidObjects - initializes objects for one OID
*
* @param {string} pId if of object
* @return
*
* ASSERTION: root device object is already created
*
*/
async function initOidObjects(pId, pOid, pOID) {
adapter.log.debug('initOidObjects (' + pId + ')');
try {
// create OID folder objects
const idArr = pId.split('.');
let partlyId = idArr[0];
for (let ii = 1; ii < idArr.length - 1; ii++) {
const el = idArr[ii];
partlyId += '.' + el;
await initObject({
_id: partlyId,
type: 'folder',
common: {
name: ''
},
native: {
}
});
}
// create OID state objects
// id ........ normal data returned (string, json, number, boolean)
// id.type ... iod type code
// id.raw .... json stringified origianl data received (optional)
await initObject({
_id: pId,
type: 'state',
common: {
name: pId,
write: !!pOID.oidWriteable,
read: true,
type: oidFormat2StateType(pOID.oidFormat),
role: 'value'
},
native: {
}
});
if (pOID.oidWriteable) {
const fullId = `${adapterName}.${adapter.instance}.${pId}`;
adapter.log.debug ( `subscribing state ${fullId}` );
await adapter.subscribeStatesAsync( fullId );
}
if (adapter.config.optTypeStates) {
await initObject({
_id: pId+'-type',
type: 'state',
common: {
name: pId+'-type',
write: false,
read: true,
type: 'string',
role: 'type.encoding'
},
native: {
}
});
}
// create OID state.raw objects
if (adapter.config.optRawStates) {
await initObject({
_id: pId+'-raw',
type: 'state',
common: {
name: pId+'-raw',
write: false,
read: true,
type: 'string',
role: 'json'
},
native: {
}
});
}
} catch (e) {
adapter.log.error('error processing oid id "' + pId + '" (oid "' + pOid + ') - ' + e.message);
}
}
/**
* initAllObjects - initialize all objects
*
* @param
* @return
*
*/
async function initAllObjects() {
adapter.log.debug('initAllObjects - initializing objects');
for (let ii = 0; ii < CTXs.length; ii++) {
await initDeviceObjects(CTXs[ii].id, CTXs[ii].ipAddr);
for (let cc = 0; cc < CTXs[ii].chunks.length; cc++) {
for (let jj = 0; jj < CTXs[ii].chunks[cc].ids.length; jj++) {
await initOidObjects(CTXs[ii].chunks[cc].ids[jj], CTXs[ii].chunks[cc].oids[jj], CTXs[ii].chunks[cc].OIDs[jj]);
}
}
}
}
// #################### varbind convert functions ####################
/**
* oidObjType2Text - translate oid object type into textual string
*
* @param {number} pOidObjType oid object type
* @return {string} textual representation of object type
*
*/
function oidObjType2Text( pOidObjType ) {
adapter.log.debug('oidObjType2Text - stringify oid object type');
const OBJECT_TYPE ={
[snmp.ObjectType.Boolean] : 'Boolean',
[snmp.ObjectType.Integer] : 'Integer',
[snmp.ObjectType.OctetString] : 'OctetString',
[snmp.ObjectType.Null] : 'Null',
[snmp.ObjectType.OID] : 'OID',
[snmp.ObjectType.IpAddress] : 'IpAddress',
[snmp.ObjectType.Counter] : 'Counter',
[snmp.ObjectType.Gauge] : 'Gauge',
[snmp.ObjectType.TimeTicks] : 'TimeTicks',
[snmp.ObjectType.Opaque] : 'Opaque',
[snmp.ObjectType.Integer32] : 'Integer32',
[snmp.ObjectType.Counter32] : 'Counter32',
[snmp.ObjectType.Gauge32] : 'Gauge32',
[snmp.ObjectType.Unsigned32] : 'Unsigned32',
[snmp.ObjectType.Counter64] : 'Counter64',
[snmp.ObjectType.NoSuchObject] : 'NoSuchObject',
[snmp.ObjectType.NoSuchInstance]: 'NoSuchInstance',
[snmp.ObjectType.EndOfMibView] : 'EndOfMibView',
};
return OBJECT_TYPE[pOidObjType] || `Unknown (${pOidObjType})`;
}
/**
* varbindDecode - convert varbind data to native data
*
* @param {object} pVarbind varbind to decode
* @param {number} pFormat format constant
* @param {string} pDevId id of device
* @param {string} pStateId id of state
* @return {object} state object containing val, typestr and qual values
*
*/
function varbindDecode( pVarbind, pFormat, pDevId, pStateId ) {
adapter.log.debug('varbindDeode - decode varbind');
// taken from https://github.com/markabrahams/node-net-snmp#oid-strings--varbinds
// varbind data is encoded based on snmp.ObjectType object.
//
// The JavaScript true and false keywords are used for the values of varbinds with type Boolean.
//
// All integer based types are specified as expected (this includes Integer, Counter, Gauge, TimeTicks, Integer32,
// Counter32, Gauge32, and Unsigned32), e.g. -128 or 100.
//
// Since JavaScript does not offer full 64 bit integer support objects with type Counter64 cannot be supported in the same way
// as other integer types, instead Node.js Buffer objects are used. Users are responsible for producing (i.e. for set() requests)
// and consuming (i.e. the varbinds passed to callback functions) Buffer objects. That is, this module does not work with
// 64 bit integers, it simply treats them as opaque Buffer objects.
//
// Dotted decimal strings are used for the values of varbinds with type OID, e.g. 1.3.6.1.2.1.1.5.0.
//
// Dotted quad formatted strings are used for the values of varbinds with type IpAddress, e.g. 192.168.1.1.
//
// Node.js Buffer objects are used for the values of varbinds with type Opaque and OctetString. For varbinds with type
// OctetString this module will accept JavaScript strings, but will always give back Buffer objects.
//
// The NoSuchObject, NoSuchInstance and EndOfMibView types are used to indicate an error condition. Currently there is
// no reason for users of this module to to build varbinds using these types.
//
const retval = {
val: null,
typeStr: oidObjType2Text(pVarbind.type),
qual: 0x00, // assume OK
format: pFormat
};
//
switch (pVarbind.type) {
// The JavaScript true and false keywords are used for the values of varbinds with type Boolean.
case snmp.ObjectType.Boolean: {
switch (pFormat) {
case F_TEXT /* 0 */:
default:
retval.val = pVarbind.value.toString();
break;
case F_NUMERIC /* 1 */:
retval.val = pVarbind.value?1:0;
break;
case F_BOOLEAN /* 2 */:
case F_AUTO /* 99 */:
retval.val = pVarbind.value;
retval.format = F_BOOLEAN;
break;
case F_JSON /* 3 */:
retval.val = JSON.stringify({type: 'boolean', data: pVarbind.value});
break;
}
break;
}
// All integer based types are specified as expected
case snmp.ObjectType.Integer:
case snmp.ObjectType.Counter:
case snmp.ObjectType.Gauge:
case snmp.ObjectType.TimeTicks:
case snmp.ObjectType.Integer32:
case snmp.ObjectType.Counter32:
case snmp.ObjectType.Gauge32:
case snmp.ObjectType.Unsigned32: {
switch (pFormat) {
case F_TEXT /* 0 */:
default:
retval.val = pVarbind.value.toString();
break;
case F_NUMERIC /* 1 */:
case F_AUTO /* 99 */:
//retval.val = parseInt(pVarbind.value.toString(), 10);
retval.val = pVarbind.value;
if (isNaN(retval.val)) retval.qual=0x01; // general error
retval.format = F_NUMERIC;
break;
case F_BOOLEAN /* 2 */: {
const valint = pVarbind.value;
retval.val = valint !== 0;
if (isNaN (valint)) retval.qual=0x01; // general error
break;
}
case F_JSON /* 3 */:
retval.val = JSON.stringify({type: 'number', data: pVarbind.value});
break;
}
break;
}
// Since JavaScript does not offer full 64 bit integer support objects with type Counter64 cannot be supported in the same way
// as other integer types, instead Node.js Buffer objects are used. Users are responsible for producing (i.e. for set() requests)
// and consuming (i.e. the varbinds passed to callback functions) Buffer objects.
case snmp.ObjectType.Counter64:{
// convert buffer to string using bigin
let value = BigInt(0); //bigint constant
for (let ii= 0; ii<pVarbind.value.length; ii++){
value=value*BigInt(256) + BigInt(pVarbind.value[ii]);
}
switch (pFormat) {
case F_TEXT /* 0 */:
default:
retval.val = value.toString();
break;
case F_NUMERIC /* 1 */:
case F_AUTO /* 99 */:
retval.val = Number(value);
if (isNaN(retval.val)) retval.qual=0x01; // general error
retval.format = F_NUMERIC;
break;
case F_BOOLEAN /* 2 */: {
const valint = Number(value);
retval.val = valint !== 0;
if (isNaN (valint)) retval.qual=0x01; // general error
break;
}
case F_JSON /* 3 */:
retval.val = JSON.stringify({type: 'number', data: pVarbind.value});
break;
}
break;
}
// Node.js Buffer objects are used for the values of varbinds with type Opaque and OctetString. For varbinds with type
// OctetString this module will accept JavaScript strings, but will always give back Buffer objects.
case snmp.ObjectType.OctetString: {
switch (pFormat) {
case F_TEXT /* 0 */:
case F_AUTO /* 99 */:
default:
retval.val = pVarbind.value.toString();
retval.format = F_TEXT;
break;
case F_NUMERIC /* 1 */: {
const valint = parseInt(pVarbind.value.toString(), 10);
retval.val = valint;
if (isNaN (valint)) retval.qual=0x01; // general error
break;
}
case F_BOOLEAN /* 2 */: {
const valint = parseInt(pVarbind.value.toString(), 10);
retval.val = valint !== 0;
if (isNaN (valint)) retval.qual=0x01; // general error
break;
}
case F_JSON /* 3 */:
retval.val = JSON.stringify(pVarbind.value); /* type: Buffer */
break;
}
break;
}
// no dcumentation for type null available
case snmp.ObjectType.Null: {
retval.val = null;
retval.qual = 0x1; // general error
retval.format = F_TEXT;
adapter.log.warn(`[${pDevId}] ${pStateId} cannot convert data of type null` + JSON.stringify(pVarbind));
break;
}
// Dotted decimal strings are used for the values of varbinds with type OID, e.g. 1.3.6.1.2.1.1.5.0.
case snmp.ObjectType.OID: {
switch (pFormat) {
case F_TEXT /* 0 */:
case F_AUTO /* 99 */:
default:
retval.val = pVarbind.value.toString();
retval.format = F_TEXT;
break;
case F_NUMERIC /* 1 */:
retval.val = null;
retval.qual = 0x1; // general error
adapter.log.warn(`[${pDevId}] ${pStateId} cannot convert data of type oid to numeric ` + JSON.stringify(pVarbind));
break;
case F_BOOLEAN /* 2 */:
retval.val = null;
retval.qual = 0x1; // general error
adapter.log.warn(`[${pDevId}] ${pStateId} cannot convert data of type oid to boolean ` + JSON.stringify(pVarbind));
break;
case F_JSON /* 3 */:
retval.val = JSON.stringify(pVarbind.value); /* Buffer */
break;
}
break;
}
// Dotted quad formatted strings are used for the values of varbinds with type IpAddress, e.g. 192.168.1.1.
case snmp.ObjectType.IpAddress:{
switch (pFormat) {
case F_TEXT /* 0 */:
case F_AUTO /* 99 */:
default:
retval.val = pVarbind.value.toString();
retval.format = F_TEXT;
break;
case F_NUMERIC /* 1 */:
retval.val = null;
retval.qual = 0x1; // general error
adapter.log.warn(`[${pDevId}] ${pStateId} cannot convert data of type ipaddress to numeric ` + JSON.stringify(pVarbind));
break;
case F_BOOLEAN /* 2 */:
retval.val = null;
retval.qual = 0x1; // general error
adapter.log.warn(`[${pDevId}] ${pStateId} cannot convert data of type ipaddress to boolean ` + JSON.stringify(pVarbind));
break;
case F_JSON /* 3 */:
retval.val = JSON.stringify(pVarbind.value); /* Buffer */
break;
}
break;
}
// Node.js Buffer objects are used for the values of varbinds with type Opaque and OctetString.
// NOTE: currently only a heuristic implementation for floating point number is implemented for formats other than json.
case snmp.ObjectType.Opaque:{
if ( pVarbind.value.length === 7 &&
pVarbind.value[0] === 159 &&
pVarbind.value[1] === 120 &&
pVarbind.value[2] === 4 ) {
const value = pVarbind.value.readFloatBE(3);
switch (pFormat) {
case F_TEXT /* 0 */:
default:
retval.val = value.toString();
break;
case F_NUMERIC /* 1 */:
case F_AUTO /* 99 */:
retval.val = value;
retval.format = F_NUMERIC;
break;
case F_BOOLEAN /* 2 */:
retval.val = value !== 0;
break;
case F_JSON /* 3 */:
retval.val = JSON.stringify(pVarbind.value); /* Buffer */
break;
}
} else {
retval.val = null;
retval.qual = 0x1; // general error
retval.format = F_TEXT;
adapter.log.warn(`[${pDevId}] ${pStateId} cannot convert opaque data` + JSON.stringify(pVarbind));
}
break;
}
case snmp.ObjectType.NoSuchObject:
case snmp.ObjectType.NoSuchInstance:
case snmp.ObjectType.EndOfMibView:
default:
retval.val = null;
retval.qual = 0x1; // general error
retval.format = F_TEXT;
adapter.log.warn(`[${pDevId}] ${pStateId} cannot convert data` + JSON.stringify(pVarbind));
break;
}
return retval;
}
/**
*/
function json2buffer(pJson){
adapter.log.debug(`json2buffer - ${pJson}`);
let json = {};
try {
json=JSON.parse(pJson);
} catch (e) {
adapter.log.warn(`cannot parse json data ${e.error} - ${pJson}`);
return null;
}
if (json.type !== 'Buffer') {
adapter.log.warn(`cannot convert json data, type must be Buffer - ${pJson}`);
return null;
}
if (!json.data){
adapter.log.warn(`cannot convert json data, data element missing - ${pJson}`);
return null;
}
return Buffer.from(json.data);
}
function json2boolean(pJson){
adapter.log.debug(`json2buffer - ${pJson}`);
let json = {};
try {
json=JSON.parse(pJson);
} catch (e) {
adapter.log.warn(`cannot parse json data ${e.error} - ${pJson}`);
return null;
}
if (json.type !== 'boolean') {
adapter.log.warn(`cannot convert json data, type must be boolean - ${pJson}`);
return null;
}
if (!json.data){
adapter.log.warn(`cannot convert json data, data element missing - ${pJson}`);
return null;
}
return Number(json.data) != 0;
}
function json2number(pJson){
adapter.log.debug(`json2buffer - ${pJson}`);
let json = {};
try {
json=JSON.parse(pJson);
} catch (e) {
adapter.log.warn(`cannot parse json data ${e.error} - ${pJson}`);
return null;
}
if (json.type !== 'number') {
adapter.log.warn(`cannot convert json data, type must be number - ${pJson}`);
return null;
}
if (!json.data){
adapter.log.warn(`cannot convert json data, data element missing - ${pJson}`);
return null;
}
return Number(json.data);
}
/**
* varbindEncode - convert native data to varbind data
*
* @param {object} pState state object
* @param {any} pData data to store in varbind
* @param {string} pDevId id of device
* @param {string} pStateId id of state
* @return {object} varbind object containing data
*
*/
function varbindEncode( pState, pData, pDevId, pStateId ) {
adapter.log.debug('varbindEncode - encode varbind');
const retval = {
oid: pState.varbind.oid,
type: pState.varbind.type,
value: null
};
let dataType;
dataType = typeof(pData);
switch (dataType) {
case 'boolean':
case 'number':
break; /* ok, we can handle it */
case 'string':
if (pState.format === F_JSON) dataType='json'; /* json must be handled special */
break; /* ok, we can handle it */
default:
retval.value = null;
adapter.log.warn(`[${pDevId}] ${pStateId} cannot encode data of type ${dataType} - ` + pData);
return retval;
}
switch (pState.varbind.type) {
// The JavaScript true and false keywords are used for the values of varbinds with type Boolean.
case snmp.ObjectType.Boolean: {
switch (dataType) {
case 'string':
retval.value = pData.toString() == 'true';
break;
case 'number':
retval.value = pData != 0;
break;
case 'boolean':
retval.value = pData;
break;