loupedeck-commander 1.0.2 → 1.2.1

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.
@@ -1,9 +1,8 @@
1
- import pkg from 'loupedeck'
1
+ import { HAPTIC } from 'loupedeck'
2
2
  import { BaseLoupeDeckHandler } from '../common/BaseLoupeDeckHandler.mjs'
3
- const { HAPTIC } = pkg
4
3
 
5
4
  /**
6
- * Our Special-Handler just used the Default - and adds Vibration after triggers through Button-Releases
5
+ * Our Special-Handler just used the Default - and adds Vibration after triggers through Button-Releases
7
6
  */
8
7
  export class ExampleDeviceHandler extends BaseLoupeDeckHandler {
9
8
  /**
@@ -2,12 +2,20 @@ import { ExampleDeviceHandler } from './ExampleDeviceHandler.mjs'
2
2
 
3
3
  const handler = new ExampleDeviceHandler('config.json')
4
4
 
5
- const stopHandler = () => {
6
- console.log('Receiving SIGINT => Stopping processes.')
7
- handler.stop()
5
+
6
+ /**
7
+ * Stop the handlers when a signal like SIGINT or SIGTERM arrive
8
+ * @param {*} signal
9
+ */
10
+ const stopHandler = async(signal) => {
11
+ console.log(`Receiving ${signal} => Stopping processes.`)
12
+ await handler.stop()
8
13
  }
9
14
 
10
- // Initiating a process
11
- process.on('SIGINT', stopHandler)
15
+ // Initiating the signal handlers:
16
+ // see https://www.tutorialspoint.com/unix/unix-signals-traps.htm
17
+ process.on('SIGINT', async (signal) => { stopHandler(signal) })
18
+ process.on('SIGTERM', async (signal) => { stopHandler(signal) })
12
19
 
20
+ // Initiating a process
13
21
  await handler.start()
@@ -0,0 +1,68 @@
1
+ import format from 'string-template'
2
+
3
+ export class BaseIf {
4
+ formattedCommand
5
+ cmd
6
+ options
7
+ call (cmd, options = {}) {
8
+ var res = this.Check(options)
9
+ if (res < 0){
10
+ LogError("Missing essential options in dictionary => Quitting\n",res,options)
11
+ return false
12
+ }
13
+
14
+ this.cmd = cmd
15
+ this.options = options
16
+ this.formattedCommand = this.formatString(cmd, options)
17
+ return this.formattedCommand
18
+ }
19
+
20
+ async stop (){
21
+
22
+ }
23
+
24
+ formatString (cmd, options = {}) {
25
+ let f =""
26
+ try{
27
+ f = format(cmd, options)
28
+ }catch(e){}
29
+ return f
30
+ }
31
+
32
+ Check(options) {
33
+ if (!"id" in options)
34
+ return -1
35
+ if (!"key" in options)
36
+ return -2
37
+ if (!"state" in options)
38
+ return -3
39
+ if (!"min" in options)
40
+ return -4
41
+ if (!"max" in options)
42
+ return -5
43
+ if (!"color" in options)
44
+ return -6
45
+ if (!"image" in options)
46
+ return -7
47
+ return 0
48
+ }
49
+
50
+ LogError(...args){
51
+ let str = new String(args)
52
+ process.stderr.write(str.toString())
53
+ }
54
+
55
+ LogDebug(...args){
56
+ if (this.options && this.options.verbose){
57
+ let str = new String(args)
58
+ process.stdout.write(str.toString())
59
+ }
60
+ }
61
+
62
+ LogInfo(...args){
63
+ let str = new String(args)
64
+ process.stdout.write(str.toString())
65
+ }
66
+ }
67
+
68
+
@@ -0,0 +1,81 @@
1
+ import * as http from 'node:http'
2
+ import url from 'node:url'
3
+ import { BaseIf } from './baseif.mjs'
4
+
5
+ /**
6
+ * Our Special-Handler just used the Default - and adds Vibration after triggers through Button-Releases
7
+ */
8
+ export class HTTPif extends BaseIf {
9
+ async call (url1, options = {}) {
10
+ url1 = super.call(url1, options)
11
+ let myURL
12
+ try {
13
+ myURL = new url.URL(url1)
14
+ await this.get(myURL, options)
15
+ } catch (e) {
16
+ this.LogError(`HTTPif: error with URL: ${e.message}\n`)
17
+ return false
18
+ }
19
+ return true
20
+ }
21
+
22
+ async stop(){
23
+ this.LogInfo("HTTPif: Stopping\n")
24
+
25
+ }
26
+
27
+ Check(options) {
28
+ var res= super.Check(options)
29
+ if (res <0)
30
+ return res
31
+ if (!options.hostname)
32
+ return -21
33
+ return 0
34
+ }
35
+
36
+ /**
37
+ * Handle a HTTP Get request with Basic Authentification
38
+ * @param {*} myURL Uri
39
+ */
40
+ async get (myURL) {
41
+ const auth = 'Basic ' + Buffer.from(myURL.username + ':' + myURL.password).toString('base64')
42
+ const getOptions = {
43
+ hostname: myURL.hostname,
44
+ port: myURL.port,
45
+ path: myURL.pathname,
46
+ agent: false, // Create a new agent just for this one request
47
+ headers: {
48
+ Authorization: auth
49
+ }
50
+ }
51
+
52
+ this.LogInfo(`HTTPIf: call URL ${myURL} ${getOptions}\n`)
53
+
54
+
55
+ const prom = new Promise((resolve, reject) => {
56
+ const req = http.get(getOptions, (response) => {
57
+ const chunksOfData = []
58
+
59
+ response.on('data', (fragments) => {
60
+ chunksOfData.push(fragments)
61
+ })
62
+
63
+ response.on('end', () => {
64
+ const responseBody = Buffer.concat(chunksOfData)
65
+ resolve(responseBody.toString())
66
+ })
67
+
68
+ response.on('error', (error) => {
69
+ resolve("")
70
+ })
71
+ })
72
+
73
+ req.on('error', (e) => {
74
+ this.LogError(`HTTPif: ignore other errors like ERRNOTCONNECTED: ${e.message}\n`)
75
+ return false
76
+ });
77
+ }).catch(function (error) { // (*)
78
+ return false
79
+ })
80
+ }
81
+ }
@@ -0,0 +1,283 @@
1
+ import {
2
+ OPCUAClient,
3
+ MessageSecurityMode,
4
+ SecurityPolicy,
5
+ BrowseDirection,
6
+ AttributeIds,
7
+ NodeClassMask,
8
+ makeBrowsePath,
9
+ resolveNodeId,
10
+ TimestampsToReturn,
11
+ coerceInt32,
12
+ coerceByteString,
13
+ DataType
14
+ } from "node-opcua";
15
+ import { EventEmitter } from 'node:events'
16
+ import { BaseIf } from './baseif.mjs'
17
+
18
+ const subscriptionParameters = {
19
+ maxNotificationsPerPublish: 1000,
20
+ publishingEnabled: true,
21
+ requestedLifetimeCount: 100,
22
+ requestedMaxKeepAliveCount: 10,
23
+ requestedPublishingInterval: 1000
24
+ };
25
+
26
+
27
+ /**
28
+ * Our Special-Handler just used the Default - and adds Vibration after triggers through Button-Releases
29
+ */
30
+ export class OPCUAIf extends BaseIf {
31
+
32
+ #client
33
+ #session
34
+ #sub
35
+ #connected
36
+ #endpointurl
37
+ monitoreditems
38
+ buttons
39
+ #callback
40
+ myEmitter
41
+ constructor() {
42
+ super()
43
+ this.myEmitter = new EventEmitter();
44
+
45
+ this.LogInfo(`OPCUAIf Constructed`);
46
+ }
47
+
48
+ async stop(){
49
+ if (!this.#client)
50
+ return
51
+
52
+ this.LogInfo(`OPCUAIf Stopping`)
53
+ await this.#client.closeSession(this.#session,true)
54
+ await this.#client.disconnect()
55
+ this.#connected = false
56
+ this.#client = null
57
+ this.LogInfo(`OPCUAIf Stopped\n`)
58
+ }
59
+
60
+ async init( options = {},config = {},callbackFunction){
61
+ var res = this.Check(options)
62
+ if (res<0){
63
+ this.LogError(`OPCUAIf: Missing essential options in dictionary => Quitting $res $options\n`)
64
+ }
65
+ try{
66
+ this.#endpointurl = options.endpointurl
67
+ this.#callback = callbackFunction
68
+ this.monitoreditems = {}
69
+ this.buttons = {}
70
+ this.LogInfo(`OPCUAIf init ${this.#endpointurl}\n`);
71
+
72
+ await this.Connect(this.#endpointurl);
73
+
74
+ let field=config.touch.center
75
+ const keys = Object.keys(field)
76
+ for (let i = 0; i < keys.length; i++) {
77
+ const key = keys[i]
78
+ const elem = config.touch.center[key]
79
+ if (elem.nodeid){
80
+ let format = this.formatString(elem.nodeid,options)
81
+ let monitoredItemId = await this.Subscribe(format)
82
+ this.buttons[monitoredItemId] = i
83
+ }
84
+
85
+ }
86
+ } catch (error) {
87
+ this.LogError(`OPCUAIf: Error $error\n`)
88
+ }
89
+ }
90
+
91
+ async call (opcuaNode, options = {}) {
92
+ var res = this.Check(options)
93
+ if (res<0){
94
+ this.LogError(`OPCUAIf call: Missing essential options in dictionary => Quitting $res\n`)
95
+ return false
96
+ }
97
+
98
+ var nodeId = super.formatString(opcuaNode, options)
99
+ var value = super.formatString(options.value, options)
100
+
101
+ this.LogInfo(`OPCUAIf: write ${nodeId} => ${value}\n`)
102
+ await this.Write(nodeId,value)
103
+
104
+ var NewState = "waiting"
105
+ return NewState
106
+ }
107
+
108
+ Check(options) {
109
+ var res= super.Check(options)
110
+ if (res <0)
111
+ return res
112
+ if (!options.endpointurl)
113
+ return -11
114
+ if (!options.nodeid)
115
+ return -12
116
+ if (!options.value)
117
+ return -13
118
+ return 0
119
+ }
120
+
121
+ async Disconnect() {
122
+ if (this.#client){
123
+ this.LogInfo(`OPCUAIf: Disconnect\n`);
124
+ await this.#client.Disconnect()
125
+ this.LogInfo(`OPCUAIf: Disconnected\n`);
126
+ }
127
+ }
128
+ async Connect(url) {
129
+ let self = this
130
+ this.#client = OPCUAClient.create({
131
+ applicationName: "NodeOPCUA-Client",
132
+
133
+ endpointMustExist: false,
134
+ // keepSessionAlive: true,
135
+ requestedSessionTimeout: 60 * 1000,
136
+ securityMode: MessageSecurityMode.None,
137
+ securityPolicy: SecurityPolicy.None,
138
+ connectionStrategy: {
139
+ maxRetry: -1,
140
+ maxDelay: 5000,
141
+ initialDelay: 2500
142
+ },
143
+
144
+ defaultSecureTokenLifetime: 20000,
145
+ tokenRenewalInterval: 1000
146
+ });
147
+
148
+ this.#client.on("backoff", (retry, delay) => {
149
+ if((retry%10) == 0)
150
+ this.LogInfo(`OPCUAIf Try Reconnection ${retry} next attempt in ${delay}ms ${self.#endpointurl}\n`);
151
+ });
152
+
153
+ this.#client.on("connection_lost", () => {
154
+ this.LogInfo(`OPCUAIf: Connection lost\n`);
155
+ });
156
+
157
+ this.#client.on("connection_reestablished", () => {
158
+ this.LogInfo(`OPCUAIf: Connection re-established\n`);
159
+ });
160
+
161
+ this.#client.on("connection_failed", () => {
162
+ this.LogInfo(`OPCUAIf: Connection failed\n`);
163
+ });
164
+ this.#client.on("start_reconnection", () => {
165
+ this.LogInfo(`OPCUAIf: Starting reconnection\n`);
166
+ });
167
+
168
+ this.#client.on("after_reconnection", (err) => {
169
+ this.LogInfo(`OPCUAIf: After Reconnection event => ${err}\n`);
170
+ });
171
+ this.#client.on("security_token_renewed", () => {
172
+ this.LogInfo(`OPCUAIf: security_token_renewed\n`);
173
+ })
174
+ this.#client.on("lifetime_75", (token) => {})
175
+
176
+ this.LogInfo(`OPCUAIf: connecting client to ${url}\n`);//, this.#session.toString());
177
+ await this.#client.connect(url);
178
+
179
+ this.#session = await this.#client.createSession();
180
+
181
+ this.#session.on("session_closed", (statusCode) => {
182
+ this.LogInfo(`OPCUAIf: Session has been closed\n`);
183
+ })
184
+ this.#session.on("session_restored", () => {
185
+ this.LogInfo(`OPCUAIf: Session has been restored\n`);
186
+ });
187
+ this.#session.on("keepalive", (lastKnownServerState) => {
188
+ this.LogInfo(`OPCUAIf: KeepAlive lastKnownServerState ${lastKnownServerState}\n`);
189
+ });
190
+ this.#session.on("keepalive_failure", () => {
191
+ this.LogInfo(`OPCUAIf: KeepAlive failure\n`);
192
+ });
193
+
194
+ this.#sub = await this.#session.createSubscription2({
195
+ maxNotificationsPerPublish: 9000,
196
+ publishingEnabled: true,
197
+ requestedLifetimeCount: 10,
198
+ requestedMaxKeepAliveCount: 10,
199
+ requestedPublishingInterval: 1000
200
+ });
201
+
202
+ this.LogInfo(`OPCUAIf: session created\n`);//, this.#session.toString());
203
+ this.LogInfo(`OPCUAIf: client\n`);
204
+ this.LogInfo(`OPCUAIf: subscription\n`);
205
+ this.#connected = true
206
+ this.#endpointurl = url
207
+ }
208
+
209
+ async Subscribe(nodeID) {
210
+ // install monitored item
211
+ const itemToMonitor = {
212
+ nodeId: resolveNodeId(nodeID),
213
+ attributeId: AttributeIds.Value
214
+ };
215
+ const monitoringParameters = {
216
+ samplingInterval: 100,
217
+ discardOldest: true,
218
+ queueSize: 10
219
+ };
220
+
221
+ if (!this.#sub){
222
+ this.LogError(`OPCUAIf: not register monitored items $itemToMonitor\n`);
223
+ return
224
+ }
225
+ const monitoredItem = await this.#sub.monitor(itemToMonitor, monitoringParameters, TimestampsToReturn.Both);
226
+ this.monitoreditems[monitoredItem.monitoredItemId] = nodeID
227
+ var self=this
228
+ monitoredItem.on("changed", function (dataValue) {
229
+ var nodeId = self.monitoreditems[this.monitoredItemId]
230
+ var buttonID = self.buttons[this.monitoredItemId]
231
+ this.LogDebug("OPCUAIf: monitored item changed: ", this.monitoredItemId,nodeId, dataValue.value.value,"\n");
232
+ self.myEmitter.emit('monitored item changed',buttonID,nodeId, dataValue.value.value)
233
+ });
234
+
235
+ return monitoredItem.monitoredItemId;
236
+ }
237
+
238
+ async Read(nodeID) {
239
+ const nodeToRead = {
240
+ nodeId: nodeID,
241
+ attributeId: AttributeIds.Value
242
+ };
243
+ if (!this.#connected){
244
+ this.LogError(`OPCUAIf: not connected, cannot read ${nodeID}\n`);
245
+ return
246
+ }
247
+ const dataValue2 = await this.#session.read(nodeToRead, 0);
248
+ this.LogError("OPCUAIf: read nodeID ",nodeID, dataValue2.toString(),"\n");
249
+ return dataValue2
250
+ }
251
+
252
+ async Write(nodeID,value,datatype=DataType.String) {
253
+ let self = this
254
+ if (!this.#connected){
255
+ self.LogError("OPCUAIf: not connected, cannot write",nodeID, value,"\n");
256
+ return
257
+ }
258
+ var nodesToWrite = [{
259
+ nodeId: nodeID,
260
+ attributeId: AttributeIds.Value,
261
+ indexRange: null,
262
+ value: {
263
+ value: {
264
+ dataType: datatype,
265
+ value: value
266
+ }
267
+ }
268
+ }];
269
+ await this.#session.write(nodesToWrite, function(err,statusCodes) {
270
+ if (!err) {
271
+ if (statusCodes && statusCodes[0].value != 0){
272
+ self.LogInfo(`OPCUAIf: status $statusCodes\n`);
273
+ }else{
274
+ self.LogInfo(`OPCUAIf: wrote $nodeID => $value\n`);
275
+ }
276
+ }else{
277
+ self.LogError("OPCUAIf: write NOT ok",nodeID, value,"\n");
278
+ self.LogError(err)
279
+ }
280
+ });
281
+ }
282
+ }
283
+
@@ -0,0 +1,47 @@
1
+ import { exec } from 'child_process'
2
+ //import { exec } from 'node:child_process'
3
+ import { BaseIf } from './baseif.mjs'
4
+
5
+ /**
6
+ * Our Special-Handler just used the Default - and adds Vibration after triggers through Button-Releases
7
+ */
8
+ export class SHELLif extends BaseIf {
9
+ async call (cmd, options = {}) {
10
+ cmd = super.call(cmd, options)
11
+ return await this.sh(cmd)
12
+ }
13
+
14
+ async stop(){
15
+ this.LogInfo("SHELLif: Stopping")
16
+ }
17
+
18
+ Check(options) {
19
+ var res= super.Check(options)
20
+ if (res <0)
21
+ return res
22
+ }
23
+
24
+ /**
25
+ * Run a Shell command in ASYNC mode
26
+ * @param {*} cmd
27
+ * @returns
28
+ */
29
+ async sh (cmd) {
30
+ let self = this;
31
+ this.LogDebug(`ShellIf: runCmd: ${cmd}\n`)
32
+
33
+ return new Promise(function (resolve, reject) {
34
+ exec(cmd, (err, stdout, stderr) => {
35
+ if (stdout.length>0)
36
+ self.LogInfo(`SHELLif Out: ${stdout}`)
37
+ if (stderr.length>0)
38
+ self.LogError(`SHELLif Err: ${stderr}`)
39
+ if (err) {
40
+ reject(err)
41
+ } else {
42
+ resolve({ stdout, stderr })
43
+ }
44
+ })
45
+ })
46
+ }
47
+ }
package/package.json CHANGED
@@ -1,24 +1,19 @@
1
1
  {
2
2
  "name": "loupedeck-commander",
3
- "version": "1.0.2",
4
- "description": "A system to ease working with LoupeDeck devices using CMD-line interfaces",
3
+ "version": "1.2.1",
4
+ "description": "A system to ease working with LoupeDeck devices using CMD-line, OPC/UA or HTTP-client interfaces",
5
5
  "main": "index.mjs",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
7
+ "test": "node test.mjs",
8
+ "start": "node index.mjs"
8
9
  },
9
10
  "dependencies": {
10
11
  "canvas": "^2.11.2",
11
- "loupedeck": "^4.3.0",
12
+ "loupedeck": "^6.0.1",
12
13
  "mkdirp": "^3.0.1",
14
+ "node-opcua": "^2.138.1",
13
15
  "string-template": "^1.0.0"
14
16
  },
15
- "devDependencies": {
16
- "eslint": "^8.53.0",
17
- "eslint-config-standard": "^17.1.0",
18
- "eslint-plugin-import": "^2.29.0",
19
- "eslint-plugin-n": "^16.3.1",
20
- "eslint-plugin-promise": "^6.1.1"
21
- },
22
17
  "author": "Thomas Schneider",
23
18
  "license": "MIT",
24
19
  "repository": {
@@ -27,5 +22,8 @@
27
22
  },
28
23
  "bugs": {
29
24
  "url": "https://gitlab.com/keckxde/loupedeck-commander/-/issues"
25
+ },
26
+ "devDependencies": {
27
+ "eslint": "^9.8.0"
30
28
  }
31
- }
29
+ }