-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.js
411 lines (371 loc) · 16.2 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
/**
*
* ioBroker OPC UA Adapter
*
* (c) 2016-2024 bluefox <[email protected]>
*
* MIT License
*
*/
'use strict';
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const adapterName = require('./package.json').name.split('.').pop();
const fs = require('fs');
let server = null;
let client = null;
let states = {};
let Client;
const objects = {};
let certificateFile = `${__dirname}/certificates/certificate.pem`;
let privateKeyFile = `${__dirname}/certificates/privatekey.pem`;
const DEBUG = false;
const messageboxRegex = new RegExp('\\.messagebox$');
let adapter;
function startAdapter(options) {
options = options || {};
options = Object.assign({}, options, {name: adapterName});
adapter = new utils.Adapter(options);
adapter.on('message', obj => processMessage(adapter, obj));
adapter.on('ready', () => {
getCertificates(adapter.config.authType)
.then(data => {
if (data.error) {
adapter.log.error(`Cannot enable secure OPC UA server/client, because no certificates found: ${adapter.config.certPublic}, ${adapter.config.certPrivate}`);
} else {
adapter.config.certificates = data.certificates;
adapter.config.leConfig = data.leConfig;
if (data.certificates) {
if (!fs.existsSync(certificateFile) || fs.readFileSync(certificateFile).toString('utf8') !== adapter.config.certificates.cert) {
fs.writeFileSync(certificateFile, adapter.config.certificates.cert);
}
if (!fs.existsSync(privateKeyFile) || fs.readFileSync(privateKeyFile).toString('utf8') !== adapter.config.certificates.key) {
fs.writeFileSync(privateKeyFile, adapter.config.certificates.key);
}
} else {
certificateFile = `${__dirname}/certificates/default_client_selfsigned_cert_2048.pem`;
privateKeyFile = `${__dirname}/certificates/default_private_key.pem`;
}
main(adapter);
}
});
});
adapter.on('unload', cb => {
client && client.destroy(cb);
server && server.destroy(cb);
!client && !server && cb && cb();
});
// is called if a subscribed state changes
adapter.on('stateChange', (id, state) => {
if (id) {
let type;
if (adapter.config.type === 'server') {
type = states[id].type;
// State deleted
if (!state) {
states[id] = {};
if (type) {
states[id].type = type;
}
// If SERVER
server && server.onStateChange(id);
// if CLIENT
client && client.onStateChange(id);
return;
}
}
// you can use the ack flag to detect if state is desired or acknowledged
if ((adapter.config.sendAckToo || !state.ack) && !messageboxRegex.test(id)) {
const oldVal = states[id] ? states[id].val : null;
const oldAck = states[id] ? states[id].ack : null;
if (adapter.config.type === 'server') {
states[id] = state;
if (type) {
states[id].type = type;
}
}
// If value really changed
if (!adapter.config.onchange || oldVal !== state.val || oldAck !== state.ack) {
// If SERVER
server && server.onStateChange(id, state);
// if CLIENT
client && client.onStateChange(id, state);
}
}
}
});
adapter.on('objectChange', (id, obj) => {
client && client.onObjectChange(id, obj);
server && server.onObjectChange && server.onObjectChange(id, obj);
});
return adapter;
}
function getCertificates(type, publicCert, privateCert) {
return new Promise(resolve => {
if (type === 'cert') {
if (publicCert && privateCert) {
adapter.getCertificates(publicCert, privateCert, (err, certificates, leConfig) =>
resolve({certificates, leConfig}));
} else {
adapter.getCertificates((error, certificates, leConfig) =>
resolve({certificates, leConfig, error}));
}
} else {
resolve({});
}
});
}
function processMessage(adapter, obj) {
if (!obj || !obj.command) {
return;
}
switch (obj.command) {
case 'test': {
// Try to connect to opcua server
if (obj.callback && obj.message) {
Client = Client || require('./lib/client');
// store Test certificates
// {
// clientEndpointUrl,
// certPrivate,
// certPublic,
// }
getCertificates(obj.message.authType, obj.message.certPublic, obj.message.certPrivate)
.then(data => {
if (data.error) {
adapter.sendTo(obj.from, obj.command, {error: 'Certificates not found'}, obj.callback);
} else {
let certificateTest = `${__dirname}/certificates/certificateTest.pem`;
let privateKeyTest = `${__dirname}/certificates/privateKeyTest.pem`;
if (obj.message.authType === 'cert') {
if (!fs.existsSync(certificateTest) || fs.readFileSync(certificateTest).toString('utf8') !== data.certificates.cert) {
fs.writeFileSync(certificateTest, data.certificates.cert);
}
if (!fs.existsSync(privateKeyTest) || fs.readFileSync(privateKeyTest).toString('utf8') !== data.certificates.key) {
fs.writeFileSync(privateKeyTest, data.certificates.key);
}
} else {
certificateTest = `${__dirname}/certificates/default_client_selfsigned_cert_2048.pem`;
privateKeyTest = `${__dirname}/certificates/default_private_key.pem`;
}
const options = {
clientEndpointUrl: obj.message.clientEndpointUrl,
certPublic: obj.message.authType === 'cert' ? certificateTest : undefined,
certPrivate: obj.message.authType === 'cert' ? privateKeyTest : undefined,
clientReconnectInterval: obj.message.clientReconnectInterval
};
let _client = new Client(adapter, options, (err, result) => {
_client = null;
timeout && clearTimeout(timeout);
adapter.sendTo(obj.from, obj.command, {error: err, result}, obj.callback);
});
// Set timeout for connection
let timeout = setTimeout(() => {
timeout = null;
if (_client) {
_client.destroy();
adapter.sendTo(obj.from, obj.command, {error: 'timeout'}, obj.callback);
}
}, 2000);
}
});
}
break;
}
case 'uuid': {
adapter.getForeignObject('system.meta.uuid', (err, uuidObj) =>
obj.callback && adapter.sendTo(obj.from, obj.command, {uuid: uuidObj && uuidObj.native && uuidObj.native.uuid}, obj.callback));
break;
}
case 'browse': {
if (obj.callback) {
if (client) {
client.browse(obj.message)
.then(list => {
DEBUG && console.log(JSON.stringify(list, null, 2));
// make list compatible with a file system
list = list.map(item => {
const newItem = {
type: 'item',
name: item.displayName.text,
native: item,
id: item.nodeId
};
if (item.nodeClass === 'Object' || item.nodeClass === 1) {
newItem.type = 'folder';
}
return newItem;
});
adapter.sendTo(obj.from, obj.command, {list, path: obj.message.path || ''}, obj.callback);
})
.catch(error =>
adapter.sendTo(obj.from, obj.command, {error: error.toString()}, obj.callback))
} else {
adapter.sendTo(obj.from, obj.command, {error: 'no connection'}, obj.callback);
}
}
break;
}
case 'read': {
if (obj.callback) {
if (client) {
client.read(obj.message)
.then(value => {
DEBUG && console.log(JSON.stringify(value, null, 2));
adapter.sendTo(obj.from, obj.command, value, obj.callback);
})
.catch(error => adapter.sendTo(obj.from, obj.command, {error}, obj.callback))
} else {
adapter.sendTo(obj.from, obj.command, {error: 'no connection'}, obj.callback);
}
}
break;
}
case 'getSubscribes': {
if (obj.callback) {
if (client) {
client.getSubscribes()
.then(list => {
DEBUG && console.log(JSON.stringify(list, null, 2));
adapter.sendTo(obj.from, obj.command, list, obj.callback);
})
.catch(error => adapter.sendTo(obj.from, obj.command, {error}, obj.callback))
} else {
adapter.sendTo(obj.from, obj.command, {error: 'no connection'}, obj.callback);
}
}
break;
}
case 'add': {
if (obj.message && obj.message.nodeId) {
if (client) {
client.addState(obj.message)
.then(() => client.getSubscribes())
.then(list => {
DEBUG && console.log(JSON.stringify(list, null, 2));
obj.callback && adapter.sendTo(obj.from, obj.command, list, obj.callback);
})
.catch(error => obj.callback && adapter.sendTo(obj.from, obj.command, {error}, obj.callback))
} else {
obj.callback && adapter.sendTo(obj.from, obj.command, {error: 'no connection'}, obj.callback);
}
}
break;
}
case 'del': {
if (obj.message && obj.message.nodeId) {
if (client) {
client.delState(obj.message.nodeId)
.then(() => client.getSubscribes())
.then(list => {
DEBUG && console.log(JSON.stringify(list, null, 2));
obj.callback && adapter.sendTo(obj.from, obj.command, list, obj.callback);
})
.catch(error => obj.callback && adapter.sendTo(obj.from, obj.command, {error}, obj.callback));
} else {
obj.callback && adapter.sendTo(obj.from, obj.command, {error: 'no connection'}, obj.callback);
}
}
break;
}
}
}
function startClient(adapter) {
Client = Client || require('./lib/client');
const options = {
clientEndpointUrl: adapter.config.clientEndpointUrl,
certPublic: certificateFile,
certPrivate: privateKeyFile,
clientReconnectInterval: adapter.config.clientReconnectInterval
};
client = new Client(adapter, options);
client.on('connect', () => adapter.setState('info.connection', true, true));
client.on('disconnect', () => adapter.setState('info.connection', false, true));
}
function startOpc(adapter) {
if (adapter.config.type === 'client') {
// create a connected object and state
adapter.getObject('info.connection', (err, obj) => {
if (!obj || !obj.common || obj.common.type !== 'boolean') {
obj = {
_id: 'info.connection',
type: 'state',
common: {
role: 'indicator.connected',
name: 'If connected to OPC UA broker',
type: 'boolean',
read: true,
write: false,
def: false
},
native: {}
};
adapter.setObject('info.connection', obj, () =>
adapter.setState('info.connection', false, true, () => startClient(adapter)));
} else {
adapter.getState('info.connection', (err, state) => (!state || !state.val) && adapter.setState('info.connection', false, true));
startClient(adapter);
}
});
} else {
const Server = require('./lib/server');
server = new Server(adapter, states, objects);
}
}
function readStatesForPattern(tasks, callback) {
if (!tasks || !tasks.length) {
callback && callback();
} else {
const pattern = tasks.pop();
adapter.getForeignStates(pattern, function (err, res) {
if (!err && res) {
states = states || {};
let count = 0;
for (const id in res) {
if (res.hasOwnProperty(id) && !messageboxRegex.test(id) && !id.match(/^system\./)) {
count++;
states[id] = res[id];
}
}
adapter.getForeignObjects(pattern, (err, objs) => {
Object.keys(objs).forEach(id => {
if (!messageboxRegex.test(id) &&
!id.match(/^system\./) &&
objs[id] &&
objs[id].common &&
objs[id].type === 'state'
) {
objects[id] = objs[id];
}
});
adapter.log.info(`Published ${count} states`);
setImmediate(readStatesForPattern, tasks, callback);
});
} else {
adapter.log.error(`Cannot read states: ${err}`);
setTimeout(() => process.exit(45), 5000);
}
});
}
}
function main(adapter) {
// Subscribe on own variables to publish it
if (adapter.config.type === 'server') {
const patterns = (adapter.config.patterns || '')
.split(',')
.map(p => p.trim())
.filter(p => p);
patterns.forEach(p => adapter.subscribeForeignStates(p));
readStatesForPattern(patterns, () => startOpc(adapter));
} else {
// client
adapter.subscribeStatesAsync(`${adapter.namespace}.vars.*`)
.then(() => startOpc(adapter));
}
}
// If started as allInOne mode => return function to create instance
if (module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}