From 263457dfb2937a6b5e03d68aa1a85957b3df84e7 Mon Sep 17 00:00:00 2001 From: Zack Hoherchak Date: Wed, 23 Feb 2022 18:30:52 -0500 Subject: [PATCH] fixed event bugs --- .../property-inspector/inspector.html | 2 +- src/com.elgato.template.sdPlugin/app.html | 2 +- src/com.elgato.template.sdPlugin/app.js | 65 +- .../libs/js/action.js | 234 +++---- .../libs/js/constants.js | 35 +- .../libs/js/event-emitter.js | 31 + .../libs/js/event-handler.js | 45 -- .../libs/js/stream-deck.js | 612 +++++++++--------- 8 files changed, 525 insertions(+), 501 deletions(-) create mode 100644 src/com.elgato.template.sdPlugin/libs/js/event-emitter.js delete mode 100644 src/com.elgato.template.sdPlugin/libs/js/event-handler.js diff --git a/src/com.elgato.template.sdPlugin/actions/template/property-inspector/inspector.html b/src/com.elgato.template.sdPlugin/actions/template/property-inspector/inspector.html index 46d8fd6..336e966 100644 --- a/src/com.elgato.template.sdPlugin/actions/template/property-inspector/inspector.html +++ b/src/com.elgato.template.sdPlugin/actions/template/property-inspector/inspector.html @@ -48,7 +48,7 @@ - + diff --git a/src/com.elgato.template.sdPlugin/app.html b/src/com.elgato.template.sdPlugin/app.html index aa82cec..a8992cc 100644 --- a/src/com.elgato.template.sdPlugin/app.html +++ b/src/com.elgato.template.sdPlugin/app.html @@ -13,7 +13,7 @@ - + diff --git a/src/com.elgato.template.sdPlugin/app.js b/src/com.elgato.template.sdPlugin/app.js index fd7efc5..12f7604 100644 --- a/src/com.elgato.template.sdPlugin/app.js +++ b/src/com.elgato.template.sdPlugin/app.js @@ -4,14 +4,63 @@ /** * The first event fired when Stream Deck starts */ -StreamDeck.onConnected(({actionInfo, appInfo, connection, messageType, port, uuid}) => { - const myAction = new Action('com.elgato.template.action'); +StreamDeck.onConnected(({ actionInfo, appInfo, connection, messageType, port, uuid }) => { + // TODO: Remove this test logging code and replace with simple action + console.log({ object: 'stream-deck', event: 'onConnected' }); - myAction.onKeyUp(({action, context, device, event, payload}) => { - StreamDeck.openUrl('https://developer.elgato.com/documentation/stream-deck/sdk/overview/'); + new Action('com.elgato.template.action') + .onDidReceiveGlobalSettings(() => { + console.log({ object: 'action', event: 'onDidReceiveGlobalSettings' }); + }) + .onDidReceiveSettings(() => { + console.log({ object: 'action', event: 'onDidReceiveSettings' }); + }) + .onKeyDown(() => { + console.log({ object: 'action', event: 'onKeyDown' }); + }) + .onKeyUp(() => { + console.log({ object: 'action', event: 'onKeyUp' }); + }) + .onWillAppear(() => { + console.log({ object: 'action', event: 'onWillAppear' }); + }) + .onWillDisappear(() => { + console.log({ object: 'action', event: 'onWillDisappear' }); + }) + .onTitleParametersDidChange(() => { + console.log({ object: 'action', event: 'onTitleParametersDidChange' }); + }) + .onPropertyInspectorDidAppear(() => { + console.log({ object: 'action', event: 'onPropertyInspectorDidAppear' }); + }) + .onPropertyInspectorDidDisappear(() => { + console.log({ object: 'action', event: 'onPropertyInspectorDidDisappear' }); + }) + .onSendToPlugin(() => { + console.log({ object: 'action', event: 'onSendToPlugin' }); + }) + .onSendToPropertyInspector(() => { + console.log({ object: 'action', event: 'onSendToPropertyInspector' }); + }); - console.log('Your code goes here!'); - - StreamDeck.showOk(context); - }); + StreamDeck.onDeviceDidConnect(() => { + console.log({ object: 'stream-deck', event: 'onDeviceDidConnect' }); + }) + .onDeviceDidDisconnect(() => { + console.log({ object: 'stream-deck', event: 'onDeviceDidDisconnect' }); + }) + .onSendToPropertyInspector(() => { + console.log({ object: 'stream-deck', event: 'onSendToPropertyInspector' }); + }) + .onApplicationDidLaunch(() => { + // TODO: figure out why this event does not fire + console.log({ object: 'stream-deck', event: 'onApplicationDidLaunch' }); + }) + .onApplicationDidTerminate(() => { + // TODO: figure out why this event does not fire + console.log({ object: 'stream-deck', event: 'onApplicationDidTerminate' }); + }) + .onSystemDidWakeUp(() => { + console.log({ object: 'stream-deck', event: 'onSystemDidWakeUp' }); + }); }); diff --git a/src/com.elgato.template.sdPlugin/libs/js/action.js b/src/com.elgato.template.sdPlugin/libs/js/action.js index 289afa5..0101394 100644 --- a/src/com.elgato.template.sdPlugin/libs/js/action.js +++ b/src/com.elgato.template.sdPlugin/libs/js/action.js @@ -5,159 +5,111 @@ * A Stream Deck plugin action, where you can register callback functions for different events */ class ELGSDAction { - UUID; - #on = EventHandler.on; - #removeListener = EventHandler.remove; - #removeAllListeners = EventHandler.removeAll; + UUID; + #on = EventEmitter.on; - constructor(UUID) { - this.UUID = UUID; - } + constructor(UUID) { + this.UUID = UUID; + } - /** - * Registers a callback function for the didReceiveSettings event, which fires when calling getSettings - * @param {*} fn - */ - onDidReceiveSettings(fn) { - this.#on(`${this.UUID}.${DID_RECEIVE_SETTINGS}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the didReceiveSettings event, which fires when calling getSettings + * @param {*} fn + */ + onDidReceiveSettings(fn) { + this.#on(`${this.UUID}.${DID_RECEIVE_SETTINGS}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the didReceiveGlobalSettings event, which fires when calling getGlobalSettings - * @param {*} fn - */ - onDidReceiveGlobalSettings(fn) { - this.#on(DID_RECEIVE_GLOBAL_SETTINGS, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the didReceiveGlobalSettings event, which fires when calling getGlobalSettings + * @param {*} fn + */ + onDidReceiveGlobalSettings(fn) { + this.#on(DID_RECEIVE_GLOBAL_SETTINGS, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the keyDown event, which fires when pressing a key down - * @param {*} fn - */ - onKeyDown(fn) { - this.#on(`${this.UUID}.${KEY_DOWN}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the keyDown event, which fires when pressing a key down + * @param {*} fn + */ + onKeyDown(fn) { + this.#on(`${this.UUID}.${KEY_DOWN}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the keyUp event, which fires when releasing a key - * @param {*} fn - */ - onKeyUp(fn) { - this.#on(`${this.UUID}.${KEY_UP}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the keyUp event, which fires when releasing a key + * @param {*} fn + */ + onKeyUp(fn) { + this.#on(`${this.UUID}.${KEY_UP}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the willAppear event, which fires when an action appears on they key - * @param {*} fn - */ - onWillAppear(fn) { - this.#on(`${this.UUID}.${WILL_APPEAR}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the willAppear event, which fires when an action appears on the canvas + * @param {*} fn + */ + onWillAppear(fn) { + this.#on(`${this.UUID}.${WILL_APPEAR}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the titleParametersDidChange event, which fires when a user changes the key title - * @param {*} fn - */ - onTitleParametersDidChange(fn) { - this.#on(`${this.UUID}.${TITLE_PARAMETERS_DID_CHANGE}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the willAppear event, which fires when an action disappears on the canvas + * @param {*} fn + */ + onWillDisappear(fn) { + this.#on(`${this.UUID}.${WILL_DISAPPEAR}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the deviceDidConnect event, which fires when a device is plugged in - * @param {*} fn - */ - onDeviceDidConnect(fn) { - this.#on(`${this.UUID}.${DEVICE_DID_CONNECT}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the titleParametersDidChange event, which fires when a user changes the key title + * @param {*} fn + */ + onTitleParametersDidChange(fn) { + this.#on(`${this.UUID}.${TITLE_PARAMETERS_DID_CHANGE}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the deviceDidDisconnect event, which fires fires when a device is unplugged - * @param {*} fn - */ - onDeviceDidDisconnect(fn) { - this.#on(`${this.UUID}.${DEVICE_DID_DISCONNECT}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the propertyInspectorDidAppear event, which fires when the property inspector is displayed + * @param {*} fn + */ + onPropertyInspectorDidAppear(fn) { + this.#on(`${this.UUID}.${PROPERTY_INSPECTOR_DID_APPEAR}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the applicationDidLaunch event, which fires fires when the application starts - * @param {*} fn - */ - onApplicationDidLaunch(fn) { - this.#on(`${this.UUID}.${APPLICATION_DID_LAUNCH}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the propertyInspectorDidDisappear event, which fires when the property inspector is closed + * @param {*} fn + */ + onPropertyInspectorDidDisappear(fn) { + this.#on(`${this.UUID}.${PROPERTY_INSPECTOR_DID_DISAPPEAR}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the applicationDidTerminate event, which fires fires when the application exits - * @param {*} fn - */ - onApplicationDidTerminate(fn) { - this.#on(`${this.UUID}.${APPLICATION_DID_TERMINATE}`, (jsn) => fn(jsn)); - return this; - } + /** + * Registers a callback function for the sendToPlugin event, which fires when the property inspector uses the sendToPlugin api + * @param {*} fn + */ + onSendToPlugin(fn) { + this.#on(`${this.UUID}.${SEND_TO_PLUGIN}`, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for the systemDidWakeUp event, which fires fires when the computer wakes - * @param {*} fn - */ - onSystemDidWakeUp(fn) { - this.#on(`${this.UUID}.${SYSTEM_DID_WAKE_UP}`, (jsn) => fn(jsn)); - return this; - } - - /** - * Registers a callback function for the propertyInspectorDidAppear event, which fires fires when the property inspector is displayed - * @param {*} fn - */ - onPropertyInspectorDidAppear(fn) { - this.#on(`${this.UUID}.${PROPERTY_INSPECTOR_DID_APPEAR}`, (jsn) => fn(jsn)); - return this; - } - - /** - * Registers a callback function for the propertyInspectorDidDisappear event, which fires fires when the property inspector is closed - * @param {*} fn - */ - onPropertyInspectorDidDisappear(fn) { - this.#on(`${this.UUID}.${PROPERTY_INSPECTOR_DID_DISAPPEAR}`, (jsn) => fn(jsn)); - return this; - } - - /** - * Registers a callback function for the sendToPlugin event, which fires fires when the property inspector uses the sendToPlugin api - * @param {*} fn - */ - onSendToPlugin(fn) { - this.#on(`${this.UUID}.${SEND_TO_PLUGIN}`, (jsn) => fn(jsn)); - return this; - } - - /** - * Registers a callback function for the sendToPropertyInspector event, which fires fires when the plugin uses the sendToPropertyInspector api - * @param {*} fn - */ - onSendToPropertyInspector(fn) { - this.#on(`${this.UUID}.${SEND_TO_PROPERTY_INSPECTOR}`, (jsn) => fn(jsn)); - return this; - } - - /** - * Removes the event listener - * @param eventName - */ - removeListener(eventName) { - if (!eventName) return this.#removeAllListeners(this.UUID); - if (eventName === DID_RECEIVE_GLOBAL_SETTINGS) return this.#removeListener(eventName); - return this.#removeListener(`${this.UUID}.${eventName}`); - } + /** + * Registers a callback function for the sendToPropertyInspector event, which fires when the plugin uses the sendToPropertyInspector api + * @param {*} fn + */ + onSendToPropertyInspector(fn) { + this.#on(`${this.UUID}.${SEND_TO_PROPERTY_INSPECTOR}`, (jsn) => fn(jsn)); + return this; + } } var Action = ELGSDAction; diff --git a/src/com.elgato.template.sdPlugin/libs/js/constants.js b/src/com.elgato.template.sdPlugin/libs/js/constants.js index ac37f18..79d7399 100644 --- a/src/com.elgato.template.sdPlugin/libs/js/constants.js +++ b/src/com.elgato.template.sdPlugin/libs/js/constants.js @@ -1,21 +1,21 @@ const SocketErrors = { - 0: 'The connection has not yet been established', - 1: 'The connection is established and communication is possible', - 2: 'The connection is going through the closing handshake', - 3: 'The connection has been closed or could not be opened', - 1000: 'Normal Closure. The purpose for which the connection was established has been fulfilled.', - 1001: 'Going Away. An endpoint is "going away", such as a server going down or a browser having navigated away from a page.', - 1002: 'Protocol error. An endpoint is terminating the connection due to a protocol error', - 1003: "Unsupported Data. An endpoint received a type of data it doesn't support.", - 1004: '--Reserved--. The specific meaning might be defined in the future.', - 1005: 'No Status. No status code was actually present.', - 1006: 'Abnormal Closure. The connection was closed abnormally, e.g., without sending or receiving a Close control frame', - 1007: 'Invalid frame payload data. The connection was closed, because the received data was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629]).', - 1008: 'Policy Violation. The connection was closed, because current message data "violates its policy". This reason is given either if there is no other suitable reason, or if there is a need to hide specific details about the policy.', - 1009: 'Message Too Big. Connection closed because the message is too big for it to process.', - 1010: "Mandatory Extension. Connection is terminated the connection because the server didn't negotiate one or more extensions in the WebSocket handshake.", - 1011: 'Internl Server Error. Connection closed because it encountered an unexpected condition that prevented it from fulfilling the request.', - 1015: "TLS Handshake. The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).", + 0: 'The connection has not yet been established', + 1: 'The connection is established and communication is possible', + 2: 'The connection is going through the closing handshake', + 3: 'The connection has been closed or could not be opened', + 1000: 'Normal Closure. The purpose for which the connection was established has been fulfilled.', + 1001: 'Going Away. An endpoint is "going away", such as a server going down or a browser having navigated away from a page.', + 1002: 'Protocol error. An endpoint is terminating the connection due to a protocol error', + 1003: "Unsupported Data. An endpoint received a type of data it doesn't support.", + 1004: '--Reserved--. The specific meaning might be defined in the future.', + 1005: 'No Status. No status code was actually present.', + 1006: 'Abnormal Closure. The connection was closed abnormally, e.g., without sending or receiving a Close control frame', + 1007: 'Invalid frame payload data. The connection was closed, because the received data was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629]).', + 1008: 'Policy Violation. The connection was closed, because current message data "violates its policy". This reason is given either if there is no other suitable reason, or if there is a need to hide specific details about the policy.', + 1009: 'Message Too Big. Connection closed because the message is too big for it to process.', + 1010: "Mandatory Extension. Connection is terminated the connection because the server didn't negotiate one or more extensions in the WebSocket handshake.", + 1011: 'Internl Server Error. Connection closed because it encountered an unexpected condition that prevented it from fulfilling the request.', + 1015: "TLS Handshake. The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).", }; /** @@ -26,6 +26,7 @@ const DID_RECEIVE_GLOBAL_SETTINGS = 'didReceiveGlobalSettings'; const KEY_DOWN = 'keyDown'; const KEY_UP = 'keyUp'; const WILL_APPEAR = 'willAppear'; +const WILL_DISAPPEAR = 'willDisappear'; const TITLE_PARAMETERS_DID_CHANGE = 'titleParametersDidChange'; const DEVICE_DID_CONNECT = 'deviceDidConnect'; const DEVICE_DID_DISCONNECT = 'deviceDidDisconnect'; diff --git a/src/com.elgato.template.sdPlugin/libs/js/event-emitter.js b/src/com.elgato.template.sdPlugin/libs/js/event-emitter.js new file mode 100644 index 0000000..5f7a217 --- /dev/null +++ b/src/com.elgato.template.sdPlugin/libs/js/event-emitter.js @@ -0,0 +1,31 @@ +class ELGSDEventEmitter { + eventList = new Map(); + + on(name, fn) { + if (!EventEmitter.eventList.has(name)) { + EventEmitter.eventList.set(name, EventEmitter.pubSub()); + } + + return EventEmitter.eventList.get(name).sub(fn); + } + + emit(name, data) { + return EventEmitter.eventList.has(name) && EventEmitter.eventList.get(name).pub(data); + } + + pubSub() { + const subscribers = new Set(); + + const sub = (fn) => { + subscribers.add(fn); + return () => { + subscribers.delete(fn); + }; + }; + + const pub = (data) => subscribers.forEach((fn) => fn(data)); + return Object.freeze({pub, sub}); + } +} + +var EventEmitter = new ELGSDEventEmitter(); diff --git a/src/com.elgato.template.sdPlugin/libs/js/event-handler.js b/src/com.elgato.template.sdPlugin/libs/js/event-handler.js deleted file mode 100644 index bea3d24..0000000 --- a/src/com.elgato.template.sdPlugin/libs/js/event-handler.js +++ /dev/null @@ -1,45 +0,0 @@ -class ELGSDEventHandler { - eventList = new Map(); - - on(name, fn) { - if (!EventHandler.eventList.has(name)) { - EventHandler.eventList.set(name, EventHandler.pubSub()); - } - - return EventHandler.eventList.get(name).sub(fn); - } - - remove(name) { - this.eventList.delete(name); - } - - removeAll(name) { - Array.from(this.eventList.keys()) - .filter((key) => key.startsWith(name)) - .forEach((key) => this.eventList.delete(key)); - } - - has(name) { - return EventHandler.eventList.has(name); - } - - emit(name, data) { - return EventHandler.eventList.has(name) && EventHandler.eventList.get(name).pub(data); - } - - pubSub() { - const subscribers = new Set(); - - const sub = (fn) => { - subscribers.add(fn); - return () => { - subscribers.delete(fn); - }; - }; - - const pub = (data) => subscribers.forEach((fn) => fn(data)); - return Object.freeze({ pub, sub }); - } -} - -var EventHandler = new ELGSDEventHandler(); diff --git a/src/com.elgato.template.sdPlugin/libs/js/stream-deck.js b/src/com.elgato.template.sdPlugin/libs/js/stream-deck.js index 97e4e7b..31bd13b 100644 --- a/src/com.elgato.template.sdPlugin/libs/js/stream-deck.js +++ b/src/com.elgato.template.sdPlugin/libs/js/stream-deck.js @@ -7,327 +7,363 @@ * communication with SD-Software and the Property Inspector */ class ELGSDStreamDeck { - #port; - #uuid; - #messageType; - #actionInfo; - #websocket; - #language; - #localization; - #appInfo; - #on = EventHandler.on; - #emit = EventHandler.emit; - #removeListener = EventHandler.remove; - #removeAllListeners = EventHandler.removeAll; + #port; + #uuid; + #messageType; + #actionInfo; + #websocket; + #language; + #localization; + #appInfo; + #on = EventEmitter.on; + #emit = EventEmitter.emit; - constructor() { - if (ELGSDStreamDeck.__instance) { - return ELGSDStreamDeck.__instance; - } + constructor() { + if (ELGSDStreamDeck.__instance) { + return ELGSDStreamDeck.__instance; + } - ELGSDStreamDeck.__instance = this; - } + ELGSDStreamDeck.__instance = this; + } - /** - * Connect to Stream Deck - * @param port - * @param uuid - * @param messageType - * @param appInfoString - * @param actionString - * @private - */ - connect([port, uuid, messageType, appInfoString, actionString]) { - this.#port = port; - this.#uuid = uuid; - this.#messageType = messageType; - this.#actionInfo = actionString ? JSON.parse(actionString) : null; - this.#appInfo = JSON.parse(appInfoString); - this.#language = this.#appInfo?.application?.language ?? null; + /** + * Connect to Stream Deck + * @param port + * @param uuid + * @param messageType + * @param appInfoString + * @param actionString + * @private + */ + connect([port, uuid, messageType, appInfoString, actionString]) { + this.#port = port; + this.#uuid = uuid; + this.#messageType = messageType; + this.#actionInfo = actionString ? JSON.parse(actionString) : null; + this.#appInfo = JSON.parse(appInfoString); + this.#language = this.#appInfo?.application?.language ?? null; - if (this.#websocket) { - this.#websocket.close(); - this.#websocket = null; - } + if (this.#websocket) { + this.#websocket.close(); + this.#websocket = null; + } - this.#websocket = new WebSocket('ws://127.0.0.1:' + this.#port); + this.#websocket = new WebSocket('ws://127.0.0.1:' + this.#port); - this.#websocket.onopen = () => { - const json = { - event: this.#messageType, - uuid: this.#uuid, - }; + this.#websocket.onopen = () => { + const json = { + event: this.#messageType, + uuid: this.#uuid, + }; - this.#websocket.send(JSON.stringify(json)); + this.#websocket.send(JSON.stringify(json)); - this.#emit(CONNECTED, { - connection: this.#websocket, - port: this.#port, - uuid: this.#uuid, - actionInfo: this.#actionInfo, - appInfo: this.#appInfo, - messageType: this.#messageType, - }); - }; + this.#emit(CONNECTED, { + connection: this.#websocket, + port: this.#port, + uuid: this.#uuid, + actionInfo: this.#actionInfo, + appInfo: this.#appInfo, + messageType: this.#messageType, + }); + }; - this.#websocket.onerror = (evt) => { - const error = `WEBOCKET ERROR: ${evt}, ${evt.data}, ${SocketErrors[evt?.code]}`; - console.warn(error); - this.log(error); - }; + this.#websocket.onerror = (evt) => { + const error = `WEBOCKET ERROR: ${evt}, ${evt.data}, ${SocketErrors[evt?.code]}`; + console.warn(error); + this.log(error); + }; - this.#websocket.onclose = (evt) => { - console.warn('WEBOCKET CLOSED:', SocketErrors[evt?.code]); - }; + this.#websocket.onclose = (evt) => { + console.warn('WEBOCKET CLOSED:', SocketErrors[evt?.code]); + }; - this.#websocket.onmessage = (evt) => { - const data = evt?.data ? JSON.parse(evt.data) : {}; - const {action, event} = data; - const message = action ? `${action}.${event}` : event; + this.#websocket.onmessage = (evt) => { + const data = evt?.data ? JSON.parse(evt.data) : {}; + const {action, event} = data; + const message = action ? `${action}.${event}` : event; - if (message && message !== '') this.#emit(message, data); - }; - } + if (message && message !== '') this.#emit(message, data); + }; + } - /** - * Write to log file - * @param message - */ - log(message) { - try { - if (this.#websocket) { - const json = { - event: LOG_MESSAGE, - payload: { - message: message, - }, - }; - this.#websocket.send(JSON.stringify(json)); - } - } catch (e) { - console.log('Websocket not defined'); - } - } + /** + * Write to log file + * @param message + */ + log(message) { + try { + if (this.#websocket) { + const json = { + event: LOG_MESSAGE, + payload: { + message: message, + }, + }; + this.#websocket.send(JSON.stringify(json)); + } + } catch (e) { + console.log('Websocket not defined'); + } + } - /** - * Fetches the specified language json file - * @param pathPrefix - * @returns {Promise} - */ - async loadLocalization(pathPrefix) { - const manifest = await this.readJson(`${pathPrefix}${this.#language}.json`); - this.#localization = manifest['Localization'] ?? null; + /** + * Fetches the specified language json file + * @param pathPrefix + * @returns {Promise} + */ + async loadLocalization(pathPrefix) { + const manifest = await this.readJson(`${pathPrefix}${this.#language}.json`); + this.#localization = manifest['Localization'] ?? null; - if (this.#messageType === REGISTER_PROPERTY_INSPECTOR && this.#localization) { - const elements = document.querySelectorAll(DATA_LOCALIZE); + if (this.#messageType === REGISTER_PROPERTY_INSPECTOR && this.#localization) { + const elements = document.querySelectorAll(DATA_LOCALIZE); - elements.forEach((element) => { - element.textContent = - this.#localization[element.textContent] ?? element.textContent; - }); - } - } + elements.forEach((element) => { + element.textContent = + this.#localization[element.textContent] ?? element.textContent; + }); + } + } - /** - * - * @param {*} path - * @returns - */ - async readJson(path) { - return new Promise((resolve, reject) => { - const req = new XMLHttpRequest(); - req.onerror = reject; - req.overrideMimeType('application/json'); - req.open('GET', path, true); - req.onreadystatechange = (response) => { - if (req.readyState === 4) { - const jsonString = response?.target?.response; - if (jsonString) { - resolve(JSON.parse(response?.target?.response)); - } else { - reject(); - } - } - }; + /** + * + * @param {*} path + * @returns + */ + async readJson(path) { + return new Promise((resolve, reject) => { + const req = new XMLHttpRequest(); + req.onerror = reject; + req.overrideMimeType('application/json'); + req.open('GET', path, true); + req.onreadystatechange = (response) => { + if (req.readyState === 4) { + const jsonString = response?.target?.response; + if (jsonString) { + resolve(JSON.parse(response?.target?.response)); + } else { + reject(); + } + } + }; - req.send(); - }); - } + req.send(); + }); + } - /** - * Send JSON payload to StreamDeck - * @param context - * @param fn - * @param payload - */ - send(context, fn, payload) { - const pl = Object.assign({}, {event: fn, context: context}, payload); - this.#websocket && this.#websocket.send(JSON.stringify(pl)); - } + /** + * Send JSON payload to StreamDeck + * @param context + * @param fn + * @param payload + */ + send(context, fn, payload) { + const pl = Object.assign({}, {event: fn, context: context}, payload); + this.#websocket && this.#websocket.send(JSON.stringify(pl)); + } - /** - * Request the actions's persistent data. StreamDeck does not return the data, but trigger the actions's didReceiveSettings event - * @param context - */ - getSettings(context) { - this.send(context ?? this.#uuid, GET_SETTINGS, {}); - } + /** + * Request the actions's persistent data. StreamDeck does not return the data, but trigger the actions's didReceiveSettings event + * @param context + */ + getSettings(context) { + this.send(context ?? this.#uuid, GET_SETTINGS, {}); + } - /** - * Save the actions's persistent data. - * @param payload - * @param context - */ - setSettings(payload, context) { - this.send(context ?? this.#uuid, SET_SETTINGS, { - action: StreamDeck?.actionInfo?.action, - payload: payload || {}, - targetContext: StreamDeck?.actionInfo?.context, - }); - } + /** + * Save the actions's persistent data. + * @param payload + * @param context + */ + setSettings(payload, context) { + this.send(context ?? this.#uuid, SET_SETTINGS, { + action: StreamDeck?.actionInfo?.action, + payload: payload || {}, + targetContext: StreamDeck?.actionInfo?.context, + }); + } - /** - * Request the plugin's persistent data. StreamDeck does not return the data, but trigger the plugin/property inspectors didReceiveGlobalSettings event - */ - getGlobalSettings() { - this.send(this.#uuid, GET_GLOBAL_SETTINGS, {}); - } + /** + * Request the plugin's persistent data. StreamDeck does not return the data, but trigger the plugin/property inspectors didReceiveGlobalSettings event + */ + getGlobalSettings() { + this.send(this.#uuid, GET_GLOBAL_SETTINGS, {}); + } - /** - * Save the plugin's persistent data - * @param payload - */ - setGlobalSettings(payload) { - this.send(this.#uuid, SET_GLOBAL_SETTINGS, { - payload: payload, - }); - } + /** + * Save the plugin's persistent data + * @param payload + */ + setGlobalSettings(payload) { + this.send(this.#uuid, SET_GLOBAL_SETTINGS, { + payload: payload, + }); + } - /** - * Opens a URL in the default web browser - * @param urlToOpen - */ - openUrl(urlToOpen) { - this.send(this.#uuid, OPEN_URL, { - payload: { - url: urlToOpen, - }, - }); - } + /** + * Opens a URL in the default web browser + * @param urlToOpen + */ + openUrl(urlToOpen) { + this.send(this.#uuid, OPEN_URL, { + payload: { + url: urlToOpen, + }, + }); + } - /** - * Send payload from the property inspector to the plugin - * @param payload - * @param context - */ - sendToPlugin(payload, context) { - this.send( - context ?? this.#uuid, - SEND_TO_PLUGIN, - { - action: StreamDeck?.actionInfo?.action, - payload: payload || {}, - targetContext: StreamDeck?.actionInfo?.context, - }, - false - ); - } + /** + * Send payload from the property inspector to the plugin + * @param payload + * @param context + */ + sendToPlugin(payload, context) { + this.send( + context ?? this.#uuid, + SEND_TO_PLUGIN, + { + action: StreamDeck?.actionInfo?.action, + payload: payload || {}, + targetContext: StreamDeck?.actionInfo?.context, + }, + false + ); + } - /** - * Display alert triangle on actions key - * @param context - */ - showAlert(context) { - this.send(context, SHOW_ALERT, {}); - } + /** + * Display alert triangle on actions key + * @param context + */ + showAlert(context) { + this.send(context, SHOW_ALERT, {}); + } - /** - * Display ok check mark on actions key - * @param context - */ - showOk(context) { - this.send(context, SHOW_OK, {}); - } + /** + * Display ok check mark on actions key + * @param context + */ + showOk(context) { + this.send(context, SHOW_OK, {}); + } - /** - * Set the state of the actions - * @param context - * @param payload - */ - setState(context, payload) { - this.send(context, SET_STATE, { - payload: { - state: 1 - Number(payload === 0), - }, - }); - } + /** + * Set the state of the actions + * @param context + * @param payload + */ + setState(context, payload) { + this.send(context, SET_STATE, { + payload: { + state: 1 - Number(payload === 0), + }, + }); + } - /** - * Set the title of the actions's key - * @param context - * @param title - * @param target - */ - setTitle(context, title, target) { - this.send(context, SET_TITLE, { - payload: { - title: '' + title || '', - target: target || HARDWARE_AND_SOFTWARE, - }, - }); - } + /** + * Set the title of the actions's key + * @param context + * @param title + * @param target + */ + setTitle(context, title, target) { + this.send(context, SET_TITLE, { + payload: { + title: '' + title || '', + target: target || HARDWARE_AND_SOFTWARE, + }, + }); + } - /** - * Send payload to property inspector - * @param context - * @param payload - */ - sendToPropertyInspector(context, payload) { - this.send(context, SEND_TO_PROPERTY_INSPECTOR, { - action: this.#actionInfo.action, - payload: payload, - }); - } + /** + * Send payload to property inspector + * @param context + * @param payload + */ + sendToPropertyInspector(context, payload) { + this.send(context, SEND_TO_PROPERTY_INSPECTOR, { + action: this.#actionInfo.action, + payload: payload, + }); + } - /** - * Set the actions key image - * @param context - * @param img - * @param target - */ - setImage(context, img, target) { - this.send(context, SET_IMAGE, { - payload: { - image: img || '', - target: target || HARDWARE_AND_SOFTWARE, - }, - }); - } + /** + * Set the actions key image + * @param context + * @param img + * @param target + */ + setImage(context, img, target) { + this.send(context, SET_IMAGE, { + payload: { + image: img || '', + target: target || HARDWARE_AND_SOFTWARE, + }, + }); + } - /** - * Registers a callback function for when Stream Deck is connected - * @param {*} fn - */ - onConnected(fn) { - this.#on(CONNECTED, (jsn) => fn(jsn)); - } + /** + * Registers a callback function for when Stream Deck is connected + * @param {*} fn + */ + onConnected(fn) { + this.#on(CONNECTED, (jsn) => fn(jsn)); + return this; + } - /** - * Registers a callback function for when Stream Deck sends data to the property inspector - * @param fn - */ - onSendToPropertyInspector(fn) { - this.#on(SEND_TO_PROPERTY_INSPECTOR, (jsn) => fn(jsn)); - } + /** + * Registers a callback function for when Stream Deck sends data to the property inspector + * @param fn + */ + onSendToPropertyInspector(fn) { + this.#on(SEND_TO_PROPERTY_INSPECTOR, (jsn) => fn(jsn)); + return this; + } - /** - * Removes the event listener - * @param eventName - */ - removeListener(eventName) { - if (!eventName) return this.#removeAllListeners(); - return this.#removeListener(eventName); - } + /** + * Registers a callback function for the deviceDidConnect event, which fires when a device is plugged in + * @param {*} fn + */ + onDeviceDidConnect(fn) { + this.#on(DEVICE_DID_CONNECT, (jsn) => fn(jsn)); + return this; + } + + /** + * Registers a callback function for the deviceDidDisconnect event, which fires when a device is unplugged + * @param {*} fn + */ + onDeviceDidDisconnect(fn) { + this.#on(DEVICE_DID_DISCONNECT, (jsn) => fn(jsn)); + return this; + } + + /** + * Registers a callback function for the applicationDidLaunch event, which fires when the application starts + * @param {*} fn + */ + onApplicationDidLaunch(fn) { + this.#on(APPLICATION_DID_LAUNCH, (jsn) => fn(jsn)); + return this; + } + + /** + * Registers a callback function for the applicationDidTerminate event, which fires when the application exits + * @param {*} fn + */ + onApplicationDidTerminate(fn) { + this.#on(APPLICATION_DID_TERMINATE, (jsn) => fn(jsn)); + return this; + } + + /** + * Registers a callback function for the systemDidWakeUp event, which fires when the computer wakes + * @param {*} fn + */ + onSystemDidWakeUp(fn) { + this.#on(SYSTEM_DID_WAKE_UP, (jsn) => fn(jsn)); + return this; + } } var StreamDeck = new ELGSDStreamDeck(); @@ -343,5 +379,5 @@ var StreamDeck = new ELGSDStreamDeck(); * @param {string} actionInfo - Context is an internal identifier used to communicate to the host application. */ function connectElgatoStreamDeckSocket() { - StreamDeck.connect(arguments); + StreamDeck.connect(arguments); }