@etm-professional-control/winccoa-mcp-server 1.3.2 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +8 -1
- package/LEGAL_INFO.md +47 -0
- package/LICENSE.md +21 -0
- package/OSS.md +178 -0
- package/README.md +62 -7
- package/build/config/demo-project-instructions.md +28 -0
- package/build/config/server.config.d.ts +16 -1
- package/build/config/server.config.d.ts.map +1 -1
- package/build/config/server.config.js +60 -10
- package/build/config/server.config.js.map +1 -1
- package/build/fields/default.md +50 -0
- package/build/fields/oil.md +46 -0
- package/build/fields/transport.md +70 -0
- package/build/helpers/drivers/MqttConnection.d.ts +113 -0
- package/build/helpers/drivers/MqttConnection.d.ts.map +1 -0
- package/build/helpers/drivers/MqttConnection.js +644 -0
- package/build/helpers/drivers/MqttConnection.js.map +1 -0
- package/build/helpers/pmon/PmonClient.d.ts.map +1 -1
- package/build/helpers/pmon/PmonClient.js +53 -27
- package/build/helpers/pmon/PmonClient.js.map +1 -1
- package/build/index_http.d.ts +14 -1
- package/build/index_http.d.ts.map +1 -1
- package/build/index_http.js +122 -45
- package/build/index_http.js.map +1 -1
- package/build/server.d.ts +38 -4
- package/build/server.d.ts.map +1 -1
- package/build/server.js +192 -142
- package/build/server.js.map +1 -1
- package/build/systemprompt.md +50 -0
- package/build/tool_loader.d.ts.map +1 -1
- package/build/tool_loader.js +18 -4
- package/build/tool_loader.js.map +1 -1
- package/build/tools/common/common_query.d.ts.map +1 -1
- package/build/tools/common/common_query.js +49 -32
- package/build/tools/common/common_query.js.map +1 -1
- package/build/tools/dashboards/widget.d.ts.map +1 -1
- package/build/tools/dashboards/widget.js +12 -2
- package/build/tools/dashboards/widget.js.map +1 -1
- package/build/tools/datapoints/dp_basic.d.ts.map +1 -1
- package/build/tools/datapoints/dp_basic.js +48 -0
- package/build/tools/datapoints/dp_basic.js.map +1 -1
- package/build/tools/datapoints/dp_types.d.ts.map +1 -1
- package/build/tools/datapoints/dp_types.js +16 -1
- package/build/tools/datapoints/dp_types.js.map +1 -1
- package/build/tools/mqtt/mqtt_connection.d.ts +14 -0
- package/build/tools/mqtt/mqtt_connection.d.ts.map +1 -0
- package/build/tools/mqtt/mqtt_connection.js +380 -0
- package/build/tools/mqtt/mqtt_connection.js.map +1 -0
- package/build/types/drivers/connection.d.ts +36 -53
- package/build/types/drivers/connection.d.ts.map +1 -1
- package/build/types/drivers/connection.js +38 -31
- package/build/types/drivers/connection.js.map +1 -1
- package/build/types/drivers/mqtt.d.ts +253 -0
- package/build/types/drivers/mqtt.d.ts.map +1 -0
- package/build/types/drivers/mqtt.js +142 -0
- package/build/types/drivers/mqtt.js.map +1 -0
- package/build/types/drivers/opcua.d.ts +62 -0
- package/build/types/drivers/opcua.d.ts.map +1 -0
- package/build/types/drivers/opcua.js +41 -0
- package/build/types/drivers/opcua.js.map +1 -0
- package/build/types/drivers/{browse.d.ts → opcua_browse.d.ts} +1 -1
- package/build/types/drivers/opcua_browse.d.ts.map +1 -0
- package/build/types/drivers/{browse.js → opcua_browse.js} +1 -1
- package/build/types/drivers/opcua_browse.js.map +1 -0
- package/build/types/index.d.ts +3 -1
- package/build/types/index.d.ts.map +1 -1
- package/build/types/index.js +6 -2
- package/build/types/index.js.map +1 -1
- package/build/utils/logger.d.ts +29 -0
- package/build/utils/logger.d.ts.map +1 -0
- package/build/utils/logger.js +56 -0
- package/build/utils/logger.js.map +1 -0
- package/package.json +83 -71
- package/sbom.json +5541 -0
- package/build/types/drivers/browse.d.ts.map +0 -1
- package/build/types/drivers/browse.js.map +0 -1
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MQTT Connection Manager
|
|
3
|
+
*
|
|
4
|
+
* Provides functionality to create, configure, and manage MQTT connections in WinCC OA.
|
|
5
|
+
* Based on WinCC OA _MqttConnection internal datapoint structure.
|
|
6
|
+
*/
|
|
7
|
+
import { BaseConnection } from './BaseConnection.js';
|
|
8
|
+
import { PmonClient } from '../pmon/PmonClient.js';
|
|
9
|
+
import { ManagerState } from '../../types/pmon/protocol.js';
|
|
10
|
+
import { MqttConnectionType, MqttConnectionState, MqttProtocolVersion, MqttSslVersion, MqttAddressDirection, MqttTransformation, MQTT_DEFAULTS } from '../../types/index.js';
|
|
11
|
+
import { DpConfigType, DpAddressDirection } from '../../types/index.js';
|
|
12
|
+
// Re-export for convenience
|
|
13
|
+
export { MqttConnectionType, MqttConnectionState, MqttProtocolVersion, MqttSslVersion, MqttQoS, MqttAddressDirection, MqttTransformation, MQTT_DEFAULTS } from '../../types/index.js';
|
|
14
|
+
/**
|
|
15
|
+
* MQTT Connection Manager Class
|
|
16
|
+
*
|
|
17
|
+
* Extends BaseConnection with MQTT-specific functionality.
|
|
18
|
+
*/
|
|
19
|
+
export class MqttConnection extends BaseConnection {
|
|
20
|
+
/**
|
|
21
|
+
* Generate a unique connection name for MQTT
|
|
22
|
+
* @returns Connection name in format _MqttConnection<n>
|
|
23
|
+
*/
|
|
24
|
+
async generateConnectionName() {
|
|
25
|
+
return super.generateConnectionName('_MqttConnection');
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Get available MQTT driver numbers from Pmon
|
|
29
|
+
* Similar to CTRL paMqttCheckDrvNums()
|
|
30
|
+
* @returns Array of MQTT driver numbers, sorted ascending
|
|
31
|
+
*/
|
|
32
|
+
async getMqttDriverNumbers() {
|
|
33
|
+
try {
|
|
34
|
+
const pmonClient = new PmonClient();
|
|
35
|
+
const managerList = await pmonClient.getManagerList();
|
|
36
|
+
const mqttDriverNums = [];
|
|
37
|
+
for (const mgr of managerList) {
|
|
38
|
+
// Check if this is an MQTT driver (name contains 'mqtt', case insensitive)
|
|
39
|
+
const mgrName = mgr.manager?.toLowerCase() ?? '';
|
|
40
|
+
if (mgrName.includes('mqtt') && !mgrName.includes('pub')) {
|
|
41
|
+
// Extract -num from command line options
|
|
42
|
+
const cmdLine = mgr.commandlineOptions ?? '';
|
|
43
|
+
const numMatch = cmdLine.match(/-num\s+(\d+)/);
|
|
44
|
+
const drvNum = numMatch && numMatch[1] ? parseInt(numMatch[1], 10) : 1;
|
|
45
|
+
mqttDriverNums.push(drvNum);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
// Sort ascending and return
|
|
49
|
+
return mqttDriverNums.sort((a, b) => a - b);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
console.warn('Could not get MQTT driver numbers from Pmon:', error);
|
|
53
|
+
return [];
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Get all used driver numbers (MQTT, simulation, other drivers)
|
|
58
|
+
* @returns Array of used driver numbers
|
|
59
|
+
*/
|
|
60
|
+
async getUsedDriverNumbers() {
|
|
61
|
+
try {
|
|
62
|
+
const pmonClient = new PmonClient();
|
|
63
|
+
const managerList = await pmonClient.getManagerList();
|
|
64
|
+
const usedNums = [];
|
|
65
|
+
for (const mgr of managerList) {
|
|
66
|
+
const mgrName = mgr.manager?.toLowerCase() ?? '';
|
|
67
|
+
// Check for any driver type (sim, mqtt, other drivers)
|
|
68
|
+
if (mgrName.includes('sim') || mgrName.includes('drv') || mgrName.includes('mqtt')) {
|
|
69
|
+
const cmdLine = mgr.commandlineOptions ?? '';
|
|
70
|
+
const numMatch = cmdLine.match(/-num\s+(\d+)/);
|
|
71
|
+
// If no -num specified, driver uses 1 by default
|
|
72
|
+
const drvNum = numMatch && numMatch[1] ? parseInt(numMatch[1], 10) : 1;
|
|
73
|
+
if (!usedNums.includes(drvNum)) {
|
|
74
|
+
usedNums.push(drvNum);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return usedNums.sort((a, b) => a - b);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
console.warn('Could not get used driver numbers from Pmon:', error);
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Get the lowest available MQTT driver number (avoiding sim driver conflicts)
|
|
87
|
+
* @returns Lowest available driver number for MQTT
|
|
88
|
+
*/
|
|
89
|
+
async getDefaultMqttDriverNumber() {
|
|
90
|
+
const mqttNums = await this.getMqttDriverNumbers();
|
|
91
|
+
// If MQTT drivers exist, use the lowest one
|
|
92
|
+
if (mqttNums.length > 0) {
|
|
93
|
+
return mqttNums[0];
|
|
94
|
+
}
|
|
95
|
+
// No MQTT driver yet - find a free number avoiding sim driver
|
|
96
|
+
const usedNums = await this.getUsedDriverNumbers();
|
|
97
|
+
// Start at 1, find first unused number
|
|
98
|
+
let candidate = 1;
|
|
99
|
+
while (usedNums.includes(candidate) && candidate < 100) {
|
|
100
|
+
candidate++;
|
|
101
|
+
}
|
|
102
|
+
return candidate;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Ensure MQTT driver with specified number is running
|
|
106
|
+
* Creates and starts the driver if it doesn't exist
|
|
107
|
+
* @param managerNumber - The driver number to ensure
|
|
108
|
+
* @returns Object with success status and optional warnings
|
|
109
|
+
*/
|
|
110
|
+
async ensureMqttDriverRunning(managerNumber) {
|
|
111
|
+
const warnings = [];
|
|
112
|
+
const pmonClient = new PmonClient();
|
|
113
|
+
try {
|
|
114
|
+
console.log(`🔍 Checking MQTT driver with -num ${managerNumber}...`);
|
|
115
|
+
// Get current manager list
|
|
116
|
+
const managerList = await pmonClient.getManagerList();
|
|
117
|
+
const managerStatus = await pmonClient.getManagerStatus();
|
|
118
|
+
// Collect all used driver numbers (including sim drivers)
|
|
119
|
+
const usedDriverNumbers = [];
|
|
120
|
+
for (const mgr of managerList) {
|
|
121
|
+
const mgrName = mgr.manager?.toLowerCase() ?? '';
|
|
122
|
+
// Check for any driver type (sim, mqtt, etc.)
|
|
123
|
+
if (mgrName.includes('sim') || mgrName.includes('drv') || mgrName.includes('mqtt')) {
|
|
124
|
+
const cmdLine = mgr.commandlineOptions ?? '';
|
|
125
|
+
const numMatch = cmdLine.match(/-num\s+(\d+)/);
|
|
126
|
+
// If no -num specified, driver uses 1 by default
|
|
127
|
+
const drvNum = numMatch && numMatch[1] ? parseInt(numMatch[1], 10) : 1;
|
|
128
|
+
usedDriverNumbers.push(drvNum);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// Check if simulation driver is using this number
|
|
132
|
+
for (const mgr of managerList) {
|
|
133
|
+
const mgrName = mgr.manager?.toLowerCase() ?? '';
|
|
134
|
+
if (mgrName.includes('sim')) {
|
|
135
|
+
const cmdLine = mgr.commandlineOptions ?? '';
|
|
136
|
+
const numMatch = cmdLine.match(/-num\s+(\d+)/);
|
|
137
|
+
const simNum = numMatch && numMatch[1] ? parseInt(numMatch[1], 10) : 1;
|
|
138
|
+
if (simNum === managerNumber) {
|
|
139
|
+
// Find next available number
|
|
140
|
+
let suggestedNum = 2;
|
|
141
|
+
while (usedDriverNumbers.includes(suggestedNum) && suggestedNum < 100) {
|
|
142
|
+
suggestedNum++;
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
success: false,
|
|
146
|
+
error: `Driver number ${managerNumber} is used by simulation driver. ` +
|
|
147
|
+
`Use managerNumber: ${suggestedNum} instead.`
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// Find if MQTT driver with this number exists
|
|
153
|
+
let driverFound = false;
|
|
154
|
+
let driverIndex = null;
|
|
155
|
+
let driverRunning = false;
|
|
156
|
+
for (const mgr of managerList) {
|
|
157
|
+
const mgrName = mgr.manager?.toLowerCase() ?? '';
|
|
158
|
+
if (mgrName.includes('mqtt') && !mgrName.includes('pub')) {
|
|
159
|
+
const cmdLine = mgr.commandlineOptions ?? '';
|
|
160
|
+
const numMatch = cmdLine.match(/-num\s+(\d+)/);
|
|
161
|
+
const drvNum = numMatch && numMatch[1] ? parseInt(numMatch[1], 10) : 1;
|
|
162
|
+
if (drvNum === managerNumber) {
|
|
163
|
+
driverFound = true;
|
|
164
|
+
driverIndex = mgr.index;
|
|
165
|
+
// Check if running
|
|
166
|
+
const statusEntry = managerStatus.managers.find(m => m.index === mgr.index);
|
|
167
|
+
driverRunning = statusEntry?.state === ManagerState.Running;
|
|
168
|
+
console.log(`✓ Found MQTT driver at index ${driverIndex}, running: ${driverRunning}`);
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// If driver not found, create it
|
|
174
|
+
if (!driverFound) {
|
|
175
|
+
console.log(`⚠️ No MQTT driver with -num ${managerNumber} found, creating...`);
|
|
176
|
+
// Find next available index
|
|
177
|
+
const maxIndex = managerList.reduce((max, m) => Math.max(max, m.index), 0);
|
|
178
|
+
const nextIndex = maxIndex + 1;
|
|
179
|
+
// Try different MQTT driver names (varies by WinCC OA version)
|
|
180
|
+
const mqttDriverNames = ['WCCOAmqtt', 'WCCOAmqttdrv'];
|
|
181
|
+
let addSuccess = false;
|
|
182
|
+
for (const driverName of mqttDriverNames) {
|
|
183
|
+
console.log(`🔧 Trying to add MQTT driver '${driverName}' at index ${nextIndex}...`);
|
|
184
|
+
const addResult = await pmonClient.addManager(nextIndex, driverName, 'always', 30, 3, 5, `-num ${managerNumber}`);
|
|
185
|
+
if (addResult.success) {
|
|
186
|
+
console.log(`✅ Successfully added MQTT driver '${driverName}'`);
|
|
187
|
+
driverIndex = nextIndex;
|
|
188
|
+
addSuccess = true;
|
|
189
|
+
warnings.push(`MQTT driver '${driverName}' was automatically created at index ${nextIndex}.`);
|
|
190
|
+
break;
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
console.log(`Could not add '${driverName}': ${addResult.error}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (!addSuccess) {
|
|
197
|
+
return {
|
|
198
|
+
success: false,
|
|
199
|
+
error: `Could not create MQTT driver with -num ${managerNumber}. ` +
|
|
200
|
+
`Please add the driver manually in WinCC OA Console.`
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
// Start driver if not running
|
|
205
|
+
if (!driverRunning && driverIndex !== null) {
|
|
206
|
+
console.log(`🔧 Starting MQTT driver at index ${driverIndex}...`);
|
|
207
|
+
const startResult = await pmonClient.startManager(driverIndex);
|
|
208
|
+
if (startResult.success) {
|
|
209
|
+
console.log(`✅ Successfully started MQTT driver`);
|
|
210
|
+
warnings.push(`MQTT driver at index ${driverIndex} was automatically started.`);
|
|
211
|
+
// Wait a moment for driver to initialize
|
|
212
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
warnings.push(`Could not start MQTT driver: ${startResult.error}. Please start manually.`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return { success: true, warnings: warnings.length > 0 ? warnings : undefined };
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
222
|
+
console.error('Error ensuring MQTT driver:', error);
|
|
223
|
+
return { success: false, error: errorMessage };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Build the JSON address string for Config.Address
|
|
228
|
+
* This is the format stored in _MqttConnection.Config.Address
|
|
229
|
+
* Required keys: Username, ConnectionType, ConnectionString, Certificate, Password, Identity, PSK
|
|
230
|
+
*/
|
|
231
|
+
buildAddressJson(config) {
|
|
232
|
+
// These keys must always be present (even if empty)
|
|
233
|
+
const addressJson = {
|
|
234
|
+
ConnectionType: config.connectionType,
|
|
235
|
+
ConnectionString: config.connectionString,
|
|
236
|
+
Username: config.username ?? '',
|
|
237
|
+
Password: config.password ?? '', // Must be pre-encrypted (WinCC OA blob), driver decrypts
|
|
238
|
+
Certificate: config.certificate ?? '',
|
|
239
|
+
Identity: config.pskIdentity ?? '',
|
|
240
|
+
PSK: config.psk ?? '' // Must be pre-encrypted (WinCC OA blob), driver decrypts
|
|
241
|
+
};
|
|
242
|
+
// Add optional fields only if they have values
|
|
243
|
+
if (config.clientId) {
|
|
244
|
+
addressJson.ClientId = config.clientId;
|
|
245
|
+
}
|
|
246
|
+
if (config.clientCertificate) {
|
|
247
|
+
addressJson.ClientCert = config.clientCertificate;
|
|
248
|
+
}
|
|
249
|
+
if (config.clientKey) {
|
|
250
|
+
addressJson.ClientKey = config.clientKey;
|
|
251
|
+
}
|
|
252
|
+
if (config.clientCertPassword) {
|
|
253
|
+
addressJson.ClientPass = config.clientCertPassword;
|
|
254
|
+
}
|
|
255
|
+
if (config.sslVersion !== undefined && config.sslVersion !== MqttSslVersion.Default) {
|
|
256
|
+
addressJson.SslVersion = config.sslVersion;
|
|
257
|
+
}
|
|
258
|
+
if (config.protocolVersion !== undefined && config.protocolVersion !== MqttProtocolVersion.Default) {
|
|
259
|
+
addressJson.ProtVersion = config.protocolVersion;
|
|
260
|
+
}
|
|
261
|
+
return addressJson;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Add a new MQTT connection
|
|
265
|
+
*
|
|
266
|
+
* @param config - MQTT connection configuration
|
|
267
|
+
* @returns Object with success status, connection name, and any errors
|
|
268
|
+
*/
|
|
269
|
+
async addConnection(config) {
|
|
270
|
+
try {
|
|
271
|
+
// Validate configuration
|
|
272
|
+
if (!config.connectionString || config.connectionString.trim() === '') {
|
|
273
|
+
return { success: false, error: 'Connection string (host:port) is required' };
|
|
274
|
+
}
|
|
275
|
+
// Determine manager number: use provided or auto-detect lowest MQTT driver
|
|
276
|
+
let managerNumber;
|
|
277
|
+
if (config.managerNumber !== undefined) {
|
|
278
|
+
if (!this.validateManagerNumber(config.managerNumber)) {
|
|
279
|
+
return { success: false, error: 'Manager number must be between 1 and 99' };
|
|
280
|
+
}
|
|
281
|
+
managerNumber = config.managerNumber;
|
|
282
|
+
console.log(`Using specified manager number: ${managerNumber}`);
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
managerNumber = await this.getDefaultMqttDriverNumber();
|
|
286
|
+
console.log(`Auto-detected MQTT driver number: ${managerNumber}`);
|
|
287
|
+
}
|
|
288
|
+
// Ensure MQTT driver is running (create if necessary)
|
|
289
|
+
const driverResult = await this.ensureMqttDriverRunning(managerNumber);
|
|
290
|
+
if (!driverResult.success) {
|
|
291
|
+
return { success: false, error: driverResult.error };
|
|
292
|
+
}
|
|
293
|
+
if (driverResult.warnings) {
|
|
294
|
+
driverResult.warnings.forEach(w => console.log(`⚠️ ${w}`));
|
|
295
|
+
}
|
|
296
|
+
// Validate connection string format (host:port)
|
|
297
|
+
const connParts = config.connectionString.split(':');
|
|
298
|
+
if (connParts.length !== 2 || !connParts[1]) {
|
|
299
|
+
return { success: false, error: 'Connection string must be in format "host:port"' };
|
|
300
|
+
}
|
|
301
|
+
const port = parseInt(connParts[1], 10);
|
|
302
|
+
if (isNaN(port) || !this.validatePort(port)) {
|
|
303
|
+
return { success: false, error: 'Port must be between 1 and 65535' };
|
|
304
|
+
}
|
|
305
|
+
// Generate unique connection name
|
|
306
|
+
const connectionName = await this.generateConnectionName();
|
|
307
|
+
// Create the connection datapoint
|
|
308
|
+
const dpCreated = await this.ensureConnectionDpExists(connectionName, '_MqttConnection');
|
|
309
|
+
if (!dpCreated) {
|
|
310
|
+
return { success: false, error: `Failed to create connection datapoint ${connectionName}` };
|
|
311
|
+
}
|
|
312
|
+
// Build the address JSON for Config.Address
|
|
313
|
+
const addressJson = this.buildAddressJson(config);
|
|
314
|
+
const addressString = JSON.stringify(addressJson);
|
|
315
|
+
// Build empty ReduAddress JSON (same structure, empty values)
|
|
316
|
+
const reduAddressJson = {
|
|
317
|
+
ConnectionType: config.connectionType,
|
|
318
|
+
ConnectionString: '',
|
|
319
|
+
Username: '',
|
|
320
|
+
Password: '',
|
|
321
|
+
Certificate: '',
|
|
322
|
+
Identity: '',
|
|
323
|
+
PSK: ''
|
|
324
|
+
};
|
|
325
|
+
const reduAddressString = JSON.stringify(reduAddressJson);
|
|
326
|
+
// Apply default values
|
|
327
|
+
const keepAlive = config.keepAliveInterval ?? MQTT_DEFAULTS.keepAliveInterval;
|
|
328
|
+
const reconnect = config.reconnectInterval ?? MQTT_DEFAULTS.reconnectInterval;
|
|
329
|
+
const useUtc = config.useUtc ?? MQTT_DEFAULTS.useUtc;
|
|
330
|
+
const timezone = config.timezoneOffset ?? MQTT_DEFAULTS.timezoneOffset;
|
|
331
|
+
const setInvalidBit = config.setInvalidBit ?? MQTT_DEFAULTS.setInvalidBit;
|
|
332
|
+
const enableStatistics = config.enableStatistics ?? MQTT_DEFAULTS.enableStatistics;
|
|
333
|
+
const persistentSession = config.persistentSession ?? MQTT_DEFAULTS.persistentSession;
|
|
334
|
+
const enableConnection = config.enableConnection ?? MQTT_DEFAULTS.enableConnection;
|
|
335
|
+
// PHASE 1: Create DP with initial values (like CTRL createNewDp)
|
|
336
|
+
// All values set in one dpSet, matching CTRL code structure
|
|
337
|
+
const dpes = [
|
|
338
|
+
`${connectionName}.Config.Address`,
|
|
339
|
+
`${connectionName}.Config.EstablishmentMode`,
|
|
340
|
+
`${connectionName}.Config.SetInvalidBit`,
|
|
341
|
+
`${connectionName}.Config.UseUTC`,
|
|
342
|
+
`${connectionName}.Config.DrvNumber`,
|
|
343
|
+
`${connectionName}.Config.CheckConn`,
|
|
344
|
+
`${connectionName}.Config.EnableStatistics`,
|
|
345
|
+
`${connectionName}.Config.Timezone`,
|
|
346
|
+
`${connectionName}.Config.LifebeatTimeout`,
|
|
347
|
+
`${connectionName}.Config.ReconnectTimeout`,
|
|
348
|
+
`${connectionName}.Config.ReduAddress`,
|
|
349
|
+
`${connectionName}.Config.LastWill.Topic`,
|
|
350
|
+
`${connectionName}.Config.LastWill.Message`,
|
|
351
|
+
`${connectionName}.Config.LastWill.QoS`,
|
|
352
|
+
`${connectionName}.Config.LastWill.Retain`,
|
|
353
|
+
`${connectionName}.Config.PersistentSession`,
|
|
354
|
+
`${connectionName}.Command.Enable`,
|
|
355
|
+
`${connectionName}.Command.IGQ`,
|
|
356
|
+
`${connectionName}.Config.Sparkplug.HostId`,
|
|
357
|
+
`${connectionName}.Config.AutoIGQ`
|
|
358
|
+
];
|
|
359
|
+
const values = [
|
|
360
|
+
addressString,
|
|
361
|
+
0, // EstablishmentMode: 0 initially (like CTRL)
|
|
362
|
+
setInvalidBit,
|
|
363
|
+
useUtc,
|
|
364
|
+
managerNumber,
|
|
365
|
+
false, // CheckConn: false initially (NOT _address config!)
|
|
366
|
+
enableStatistics,
|
|
367
|
+
timezone,
|
|
368
|
+
keepAlive,
|
|
369
|
+
reconnect,
|
|
370
|
+
reduAddressString,
|
|
371
|
+
config.lastWillTopic ?? '',
|
|
372
|
+
config.lastWillMessage ?? '',
|
|
373
|
+
config.lastWillQoS ?? MQTT_DEFAULTS.lastWillQoS,
|
|
374
|
+
config.lastWillRetain ?? MQTT_DEFAULTS.lastWillRetain,
|
|
375
|
+
persistentSession,
|
|
376
|
+
false, // Command.Enable: 0 initially (like CTRL)
|
|
377
|
+
false, // Command.IGQ: 0
|
|
378
|
+
'', // Sparkplug.HostId: empty
|
|
379
|
+
0 // AutoIGQ: 0
|
|
380
|
+
];
|
|
381
|
+
console.log(`\n╔════════════════════════════════════════════════════════════════╗`);
|
|
382
|
+
console.log(`║ Creating MQTT Connection: ${connectionName.padEnd(36)} ║`);
|
|
383
|
+
console.log(`╠════════════════════════════════════════════════════════════════╣`);
|
|
384
|
+
console.log(`║ Configuration: ║`);
|
|
385
|
+
console.log(` - Connection Type: ${MqttConnectionType[config.connectionType]}`);
|
|
386
|
+
console.log(` - Connection String: ${config.connectionString}`);
|
|
387
|
+
console.log(` - Manager Number: ${managerNumber}`);
|
|
388
|
+
console.log(` - Username: ${config.username ?? '(none)'}`);
|
|
389
|
+
console.log(` - Keep Alive: ${keepAlive}s`);
|
|
390
|
+
console.log(` - Reconnect: ${reconnect}s`);
|
|
391
|
+
console.log(` - Use UTC: ${useUtc}`);
|
|
392
|
+
console.log(` - Enable Statistics: ${enableStatistics}`);
|
|
393
|
+
console.log(` - Persistent Session: ${persistentSession}`);
|
|
394
|
+
console.log(` - Enable Connection: ${enableConnection}`);
|
|
395
|
+
console.log(`╚════════════════════════════════════════════════════════════════╝\n`);
|
|
396
|
+
// Apply initial configuration (Phase 1)
|
|
397
|
+
await this.winccoa.dpSetWait(dpes, values);
|
|
398
|
+
console.log(`✓ Initial configuration applied`);
|
|
399
|
+
// Set JSON Profiles (empty array if not provided)
|
|
400
|
+
const jsonProfiles = config.jsonProfiles ?? [];
|
|
401
|
+
await this.winccoa.dpSetWait([`${connectionName}.Config.JsonProfiles`], [jsonProfiles]);
|
|
402
|
+
console.log(`✓ JSON Profiles set (${jsonProfiles.length} profiles)`);
|
|
403
|
+
// PHASE 2: If enableConnection, set CheckConn _address and activate
|
|
404
|
+
if (enableConnection) {
|
|
405
|
+
// Set EstablishmentMode to 1 (auto active)
|
|
406
|
+
await this.winccoa.dpSetWait([`${connectionName}.Config.EstablishmentMode`], [1]);
|
|
407
|
+
// Configure CheckConn address using base class method (sets _distrib + _address)
|
|
408
|
+
const checkConnSuccess = await this.setAddressAndDistribConfig(`${connectionName}.Config.CheckConn`, {
|
|
409
|
+
_type: DpConfigType.DPCONFIG_PERIPH_ADDR_MAIN,
|
|
410
|
+
_drv_ident: 'MQTT',
|
|
411
|
+
_connection: connectionName,
|
|
412
|
+
_reference: '__check__',
|
|
413
|
+
_direction: DpAddressDirection.DPATTR_ADDR_MODE_UNDEFINED,
|
|
414
|
+
_datatype: 0,
|
|
415
|
+
_subindex: 0,
|
|
416
|
+
_internal: true,
|
|
417
|
+
_active: true
|
|
418
|
+
}, {
|
|
419
|
+
_type: DpConfigType.DPCONFIG_DISTRIBUTION_INFO,
|
|
420
|
+
_driver: managerNumber
|
|
421
|
+
});
|
|
422
|
+
if (!checkConnSuccess) {
|
|
423
|
+
console.warn(`⚠️ Warning: Could not configure CheckConn address`);
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
console.log(`✓ CheckConn _distrib + _address configured`);
|
|
427
|
+
}
|
|
428
|
+
// Enable the connection
|
|
429
|
+
await this.winccoa.dpSetWait([`${connectionName}.Command.Enable`], [true]);
|
|
430
|
+
console.log(`✓ Connection enabled`);
|
|
431
|
+
}
|
|
432
|
+
console.log(`✓ Successfully created MQTT connection: ${connectionName}`);
|
|
433
|
+
return { success: true, connectionName };
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
437
|
+
console.error(`✗ Error creating MQTT connection:`, error);
|
|
438
|
+
return { success: false, error: errorMessage };
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Delete an MQTT connection
|
|
443
|
+
*
|
|
444
|
+
* @param connectionName - Name of the connection to delete (with or without leading _)
|
|
445
|
+
* @returns Object with success status and any errors
|
|
446
|
+
*/
|
|
447
|
+
async deleteConnection(connectionName) {
|
|
448
|
+
try {
|
|
449
|
+
// Normalize connection name (ensure it starts with _)
|
|
450
|
+
const dpName = connectionName.startsWith('_') ? connectionName : `_${connectionName}`;
|
|
451
|
+
// Check if connection exists
|
|
452
|
+
if (!this.checkDpExists(dpName)) {
|
|
453
|
+
return { success: false, error: `Connection ${dpName} does not exist` };
|
|
454
|
+
}
|
|
455
|
+
// Disable the connection first
|
|
456
|
+
try {
|
|
457
|
+
await this.winccoa.dpSetWait([`${dpName}.Command.Enable`], [false]);
|
|
458
|
+
// Small delay to allow driver to disconnect
|
|
459
|
+
await new Promise(resolve => setTimeout(resolve, 500));
|
|
460
|
+
}
|
|
461
|
+
catch (e) {
|
|
462
|
+
console.warn(`Warning: Could not disable connection before deletion`);
|
|
463
|
+
}
|
|
464
|
+
// Delete the datapoint
|
|
465
|
+
const deleted = await this.winccoa.dpDelete(dpName);
|
|
466
|
+
if (!deleted) {
|
|
467
|
+
return { success: false, error: `Failed to delete connection ${dpName}` };
|
|
468
|
+
}
|
|
469
|
+
console.log(`✓ Successfully deleted MQTT connection: ${dpName}`);
|
|
470
|
+
return { success: true };
|
|
471
|
+
}
|
|
472
|
+
catch (error) {
|
|
473
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
474
|
+
console.error(`✗ Error deleting MQTT connection:`, error);
|
|
475
|
+
return { success: false, error: errorMessage };
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Get the connection state of an MQTT connection
|
|
480
|
+
*
|
|
481
|
+
* @param connectionName - Name of the connection
|
|
482
|
+
* @returns Connection state or error
|
|
483
|
+
*/
|
|
484
|
+
async getConnectionState(connectionName) {
|
|
485
|
+
try {
|
|
486
|
+
const dpName = connectionName.startsWith('_') ? connectionName : `_${connectionName}`;
|
|
487
|
+
if (!this.checkDpExists(dpName)) {
|
|
488
|
+
return { success: false, error: `Connection ${dpName} does not exist` };
|
|
489
|
+
}
|
|
490
|
+
const state = await this.winccoa.dpGet(`${dpName}.State.ConnState`);
|
|
491
|
+
const stateTexts = {
|
|
492
|
+
0: 'Inactive',
|
|
493
|
+
1: 'Disconnected',
|
|
494
|
+
2: 'Connecting',
|
|
495
|
+
3: 'Connected',
|
|
496
|
+
4: 'Disconnecting',
|
|
497
|
+
5: 'Failure',
|
|
498
|
+
6: 'Listening'
|
|
499
|
+
};
|
|
500
|
+
return {
|
|
501
|
+
success: true,
|
|
502
|
+
state: state,
|
|
503
|
+
stateText: stateTexts[state] ?? 'Unknown'
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
catch (error) {
|
|
507
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
508
|
+
return { success: false, error: errorMessage };
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* List all MQTT connections
|
|
513
|
+
*
|
|
514
|
+
* @returns Array of connection names and their states
|
|
515
|
+
*/
|
|
516
|
+
async listConnections() {
|
|
517
|
+
try {
|
|
518
|
+
// Get all datapoints of type _MqttConnection
|
|
519
|
+
const dpNames = await this.winccoa.dpNames('*', '_MqttConnection');
|
|
520
|
+
if (!dpNames || dpNames.length === 0) {
|
|
521
|
+
return { success: true, connections: [] };
|
|
522
|
+
}
|
|
523
|
+
const connections = [];
|
|
524
|
+
for (const dpName of dpNames) {
|
|
525
|
+
// In WinCC OA redundant systems, connection datapoints are duplicated
|
|
526
|
+
// with a "_2" suffix for the redundant partner. We skip these to avoid
|
|
527
|
+
// listing the same logical connection twice.
|
|
528
|
+
if (dpName.endsWith('_2'))
|
|
529
|
+
continue;
|
|
530
|
+
try {
|
|
531
|
+
const stateResult = await this.getConnectionState(dpName);
|
|
532
|
+
let connectionString;
|
|
533
|
+
try {
|
|
534
|
+
const addressJson = await this.winccoa.dpGet(`${dpName}.Config.Address`);
|
|
535
|
+
if (addressJson) {
|
|
536
|
+
const address = JSON.parse(addressJson);
|
|
537
|
+
connectionString = address.ConnectionString;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
catch (e) {
|
|
541
|
+
// Log warning for debugging - parse errors may indicate corrupt config
|
|
542
|
+
console.warn(`Warning: Could not parse address config for ${dpName}:`, e);
|
|
543
|
+
}
|
|
544
|
+
connections.push({
|
|
545
|
+
name: dpName,
|
|
546
|
+
state: stateResult.state ?? MqttConnectionState.Inactive,
|
|
547
|
+
stateText: stateResult.stateText ?? 'Unknown',
|
|
548
|
+
connectionString
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
catch (e) {
|
|
552
|
+
// Skip connections that can't be read
|
|
553
|
+
console.warn(`Warning: Could not read connection ${dpName}`);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
return { success: true, connections };
|
|
557
|
+
}
|
|
558
|
+
catch (error) {
|
|
559
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
560
|
+
return { success: false, error: errorMessage };
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Configure address settings for a datapoint (peripheral address)
|
|
565
|
+
* Implementation of abstract method from BaseConnection
|
|
566
|
+
*
|
|
567
|
+
* @param params - MQTT address parameters
|
|
568
|
+
* @returns true on success
|
|
569
|
+
* @throws Error with detailed message on failure
|
|
570
|
+
*/
|
|
571
|
+
async addAddressConfig(params) {
|
|
572
|
+
// Validate DPE exists
|
|
573
|
+
const dpeParts = params.dpeName.split('.');
|
|
574
|
+
const dpName = dpeParts[0];
|
|
575
|
+
if (!dpName || !this.checkDpExists(dpName)) {
|
|
576
|
+
throw new Error(`Datapoint ${dpName} does not exist. Please create it first.`);
|
|
577
|
+
}
|
|
578
|
+
// Normalize connection name (ensure it starts with _)
|
|
579
|
+
const connectionName = params.connectionName.startsWith('_')
|
|
580
|
+
? params.connectionName
|
|
581
|
+
: `_${params.connectionName}`;
|
|
582
|
+
// Sanitize topic: remove trailing slashes
|
|
583
|
+
const topic = params.topic.replace(/\/+$/, '');
|
|
584
|
+
// Verify connection exists
|
|
585
|
+
if (!this.checkDpExists(connectionName)) {
|
|
586
|
+
throw new Error(`MQTT connection ${connectionName} does not exist. ` +
|
|
587
|
+
`Use mqtt-add-connection to create a connection first.`);
|
|
588
|
+
}
|
|
589
|
+
// Get driver number from connection if not provided
|
|
590
|
+
let driverNumber = params.driverNumber;
|
|
591
|
+
if (!driverNumber) {
|
|
592
|
+
try {
|
|
593
|
+
driverNumber = await this.winccoa.dpGet(`${connectionName}.Config.DrvNumber`);
|
|
594
|
+
}
|
|
595
|
+
catch {
|
|
596
|
+
throw new Error(`Could not get driver number from connection ${connectionName}`);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
// Map direction: MqttAddressDirection values match DpAddressDirection
|
|
600
|
+
// Publish=1 (OUTPUT), Subscribe=2 (INPUT_SPONT), Both=6 (IO_SPONT)
|
|
601
|
+
const direction = params.direction;
|
|
602
|
+
// Transformation type (default: PlainString = 1000)
|
|
603
|
+
console.log(" DEBUG - params.transformation received:", params.transformation, "type:", typeof params.transformation);
|
|
604
|
+
const datatype = params.transformation ?? MqttTransformation.PlainString;
|
|
605
|
+
console.log(" DEBUG - datatype after default:", datatype);
|
|
606
|
+
console.log(`\n╔════════════════════════════════════════════════════════════════╗`);
|
|
607
|
+
console.log(`║ Configuring MQTT Address for: ${params.dpeName.padEnd(31)} ║`);
|
|
608
|
+
console.log(`╠════════════════════════════════════════════════════════════════╣`);
|
|
609
|
+
console.log(` - Topic: ${topic}`);
|
|
610
|
+
console.log(` - Connection: ${connectionName}`);
|
|
611
|
+
console.log(` - Direction: ${MqttAddressDirection[direction]} (${direction})`);
|
|
612
|
+
console.log(` - Transformation: ${MqttTransformation[datatype]} (${datatype})`);
|
|
613
|
+
console.log(` - Driver Number: ${driverNumber}`);
|
|
614
|
+
if (params.qos !== undefined)
|
|
615
|
+
console.log(` - QoS: ${params.qos}`);
|
|
616
|
+
if (params.retain !== undefined)
|
|
617
|
+
console.log(` - Retain: ${params.retain}`);
|
|
618
|
+
if (params.oldNewComparison !== undefined)
|
|
619
|
+
console.log(` - Old/New Comparison: ${params.oldNewComparison}`);
|
|
620
|
+
console.log(`╚════════════════════════════════════════════════════════════════╝\n`);
|
|
621
|
+
// Use setAddressAndDistribConfig from BaseConnection
|
|
622
|
+
const success = await this.setAddressAndDistribConfig(params.dpeName, {
|
|
623
|
+
_type: DpConfigType.DPCONFIG_PERIPH_ADDR_MAIN,
|
|
624
|
+
_drv_ident: 'MQTT',
|
|
625
|
+
_connection: connectionName,
|
|
626
|
+
_reference: topic,
|
|
627
|
+
_direction: direction,
|
|
628
|
+
_datatype: datatype,
|
|
629
|
+
_subindex: 0,
|
|
630
|
+
_internal: false,
|
|
631
|
+
_lowlevel: params.oldNewComparison ?? true,
|
|
632
|
+
_active: true
|
|
633
|
+
}, {
|
|
634
|
+
_type: DpConfigType.DPCONFIG_DISTRIBUTION_INFO,
|
|
635
|
+
_driver: driverNumber
|
|
636
|
+
});
|
|
637
|
+
if (!success) {
|
|
638
|
+
throw new Error('Failed to set address configuration');
|
|
639
|
+
}
|
|
640
|
+
console.log(`✓ MQTT address configured for ${params.dpeName}`);
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
//# sourceMappingURL=MqttConnection.js.map
|