fixed event bugs

This commit is contained in:
Zack Hoherchak 2022-02-23 18:30:52 -05:00
commit 263457dfb2
8 changed files with 571 additions and 547 deletions

View file

@ -48,7 +48,7 @@
<div class="sdpi-info-label hidden" style="top: -1000" value=""></div> <div class="sdpi-info-label hidden" style="top: -1000" value=""></div>
<script src="../../../libs/js/utils.js"></script> <script src="../../../libs/js/utils.js"></script>
<script src="../../../libs/js/constants.js"></script> <script src="../../../libs/js/constants.js"></script>
<script src="../../../libs/js/event-handler.js"></script> <script src="../../../libs/js/event-emitter.js"></script>
<script src="../../../libs/js/stream-deck.js"></script> <script src="../../../libs/js/stream-deck.js"></script>
<script src="../../../libs/js/dynamic-styles.js"></script> <script src="../../../libs/js/dynamic-styles.js"></script>
<script src="inspector.js"></script> <script src="inspector.js"></script>

View file

@ -13,7 +13,7 @@
<body> <body>
<script src="libs/js/constants.js"></script> <script src="libs/js/constants.js"></script>
<script src="libs/js/event-handler.js"></script> <script src="libs/js/event-emitter.js"></script>
<script src="libs/js/stream-deck.js"></script> <script src="libs/js/stream-deck.js"></script>
<script src="libs/js/action.js"></script> <script src="libs/js/action.js"></script>
<script src="app.js"></script> <script src="app.js"></script>

View file

@ -4,14 +4,63 @@
/** /**
* The first event fired when Stream Deck starts * The first event fired when Stream Deck starts
*/ */
StreamDeck.onConnected(({actionInfo, appInfo, connection, messageType, port, uuid}) => { StreamDeck.onConnected(({ actionInfo, appInfo, connection, messageType, port, uuid }) => {
const myAction = new Action('com.elgato.template.action'); // 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}) => { new Action('com.elgato.template.action')
StreamDeck.openUrl('https://developer.elgato.com/documentation/stream-deck/sdk/overview/'); .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.onDeviceDidConnect(() => {
console.log({ object: 'stream-deck', event: 'onDeviceDidConnect' });
StreamDeck.showOk(context); })
}); .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' });
});
}); });

View file

@ -5,159 +5,111 @@
* A Stream Deck plugin action, where you can register callback functions for different events * A Stream Deck plugin action, where you can register callback functions for different events
*/ */
class ELGSDAction { class ELGSDAction {
UUID; UUID;
#on = EventHandler.on; #on = EventEmitter.on;
#removeListener = EventHandler.remove;
#removeAllListeners = EventHandler.removeAll;
constructor(UUID) { constructor(UUID) {
this.UUID = UUID; this.UUID = UUID;
} }
/** /**
* Registers a callback function for the didReceiveSettings event, which fires when calling getSettings * Registers a callback function for the didReceiveSettings event, which fires when calling getSettings
* @param {*} fn * @param {*} fn
*/ */
onDidReceiveSettings(fn) { onDidReceiveSettings(fn) {
this.#on(`${this.UUID}.${DID_RECEIVE_SETTINGS}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${DID_RECEIVE_SETTINGS}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the didReceiveGlobalSettings event, which fires when calling getGlobalSettings * Registers a callback function for the didReceiveGlobalSettings event, which fires when calling getGlobalSettings
* @param {*} fn * @param {*} fn
*/ */
onDidReceiveGlobalSettings(fn) { onDidReceiveGlobalSettings(fn) {
this.#on(DID_RECEIVE_GLOBAL_SETTINGS, (jsn) => fn(jsn)); this.#on(DID_RECEIVE_GLOBAL_SETTINGS, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the keyDown event, which fires when pressing a key down * Registers a callback function for the keyDown event, which fires when pressing a key down
* @param {*} fn * @param {*} fn
*/ */
onKeyDown(fn) { onKeyDown(fn) {
this.#on(`${this.UUID}.${KEY_DOWN}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${KEY_DOWN}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the keyUp event, which fires when releasing a key * Registers a callback function for the keyUp event, which fires when releasing a key
* @param {*} fn * @param {*} fn
*/ */
onKeyUp(fn) { onKeyUp(fn) {
this.#on(`${this.UUID}.${KEY_UP}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${KEY_UP}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the willAppear event, which fires when an action appears on they key * Registers a callback function for the willAppear event, which fires when an action appears on the canvas
* @param {*} fn * @param {*} fn
*/ */
onWillAppear(fn) { onWillAppear(fn) {
this.#on(`${this.UUID}.${WILL_APPEAR}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${WILL_APPEAR}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the titleParametersDidChange event, which fires when a user changes the key title * Registers a callback function for the willAppear event, which fires when an action disappears on the canvas
* @param {*} fn * @param {*} fn
*/ */
onTitleParametersDidChange(fn) { onWillDisappear(fn) {
this.#on(`${this.UUID}.${TITLE_PARAMETERS_DID_CHANGE}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${WILL_DISAPPEAR}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the deviceDidConnect event, which fires when a device is plugged in * Registers a callback function for the titleParametersDidChange event, which fires when a user changes the key title
* @param {*} fn * @param {*} fn
*/ */
onDeviceDidConnect(fn) { onTitleParametersDidChange(fn) {
this.#on(`${this.UUID}.${DEVICE_DID_CONNECT}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${TITLE_PARAMETERS_DID_CHANGE}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the deviceDidDisconnect event, which fires fires when a device is unplugged * Registers a callback function for the propertyInspectorDidAppear event, which fires when the property inspector is displayed
* @param {*} fn * @param {*} fn
*/ */
onDeviceDidDisconnect(fn) { onPropertyInspectorDidAppear(fn) {
this.#on(`${this.UUID}.${DEVICE_DID_DISCONNECT}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${PROPERTY_INSPECTOR_DID_APPEAR}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the applicationDidLaunch event, which fires fires when the application starts * Registers a callback function for the propertyInspectorDidDisappear event, which fires when the property inspector is closed
* @param {*} fn * @param {*} fn
*/ */
onApplicationDidLaunch(fn) { onPropertyInspectorDidDisappear(fn) {
this.#on(`${this.UUID}.${APPLICATION_DID_LAUNCH}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${PROPERTY_INSPECTOR_DID_DISAPPEAR}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the applicationDidTerminate event, which fires fires when the application exits * Registers a callback function for the sendToPlugin event, which fires when the property inspector uses the sendToPlugin api
* @param {*} fn * @param {*} fn
*/ */
onApplicationDidTerminate(fn) { onSendToPlugin(fn) {
this.#on(`${this.UUID}.${APPLICATION_DID_TERMINATE}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${SEND_TO_PLUGIN}`, (jsn) => fn(jsn));
return this; return this;
} }
/** /**
* Registers a callback function for the systemDidWakeUp event, which fires fires when the computer wakes * Registers a callback function for the sendToPropertyInspector event, which fires when the plugin uses the sendToPropertyInspector api
* @param {*} fn * @param {*} fn
*/ */
onSystemDidWakeUp(fn) { onSendToPropertyInspector(fn) {
this.#on(`${this.UUID}.${SYSTEM_DID_WAKE_UP}`, (jsn) => fn(jsn)); this.#on(`${this.UUID}.${SEND_TO_PROPERTY_INSPECTOR}`, (jsn) => fn(jsn));
return this; 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}`);
}
} }
var Action = ELGSDAction; var Action = ELGSDAction;

View file

@ -1,21 +1,21 @@
const SocketErrors = { const SocketErrors = {
0: 'The connection has not yet been established', 0: 'The connection has not yet been established',
1: 'The connection is established and communication is possible', 1: 'The connection is established and communication is possible',
2: 'The connection is going through the closing handshake', 2: 'The connection is going through the closing handshake',
3: 'The connection has been closed or could not be opened', 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.', 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.', 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', 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.", 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.', 1004: '--Reserved--. The specific meaning might be defined in the future.',
1005: 'No Status. No status code was actually present.', 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', 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]).', 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.', 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.', 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.", 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.', 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).", 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_DOWN = 'keyDown';
const KEY_UP = 'keyUp'; const KEY_UP = 'keyUp';
const WILL_APPEAR = 'willAppear'; const WILL_APPEAR = 'willAppear';
const WILL_DISAPPEAR = 'willDisappear';
const TITLE_PARAMETERS_DID_CHANGE = 'titleParametersDidChange'; const TITLE_PARAMETERS_DID_CHANGE = 'titleParametersDidChange';
const DEVICE_DID_CONNECT = 'deviceDidConnect'; const DEVICE_DID_CONNECT = 'deviceDidConnect';
const DEVICE_DID_DISCONNECT = 'deviceDidDisconnect'; const DEVICE_DID_DISCONNECT = 'deviceDidDisconnect';

View file

@ -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();

View file

@ -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();

View file

@ -7,327 +7,363 @@
* communication with SD-Software and the Property Inspector * communication with SD-Software and the Property Inspector
*/ */
class ELGSDStreamDeck { class ELGSDStreamDeck {
#port; #port;
#uuid; #uuid;
#messageType; #messageType;
#actionInfo; #actionInfo;
#websocket; #websocket;
#language; #language;
#localization; #localization;
#appInfo; #appInfo;
#on = EventHandler.on; #on = EventEmitter.on;
#emit = EventHandler.emit; #emit = EventEmitter.emit;
#removeListener = EventHandler.remove;
#removeAllListeners = EventHandler.removeAll;
constructor() { constructor() {
if (ELGSDStreamDeck.__instance) { if (ELGSDStreamDeck.__instance) {
return ELGSDStreamDeck.__instance; return ELGSDStreamDeck.__instance;
} }
ELGSDStreamDeck.__instance = this; ELGSDStreamDeck.__instance = this;
} }
/** /**
* Connect to Stream Deck * Connect to Stream Deck
* @param port * @param port
* @param uuid * @param uuid
* @param messageType * @param messageType
* @param appInfoString * @param appInfoString
* @param actionString * @param actionString
* @private * @private
*/ */
connect([port, uuid, messageType, appInfoString, actionString]) { connect([port, uuid, messageType, appInfoString, actionString]) {
this.#port = port; this.#port = port;
this.#uuid = uuid; this.#uuid = uuid;
this.#messageType = messageType; this.#messageType = messageType;
this.#actionInfo = actionString ? JSON.parse(actionString) : null; this.#actionInfo = actionString ? JSON.parse(actionString) : null;
this.#appInfo = JSON.parse(appInfoString); this.#appInfo = JSON.parse(appInfoString);
this.#language = this.#appInfo?.application?.language ?? null; this.#language = this.#appInfo?.application?.language ?? null;
if (this.#websocket) { if (this.#websocket) {
this.#websocket.close(); this.#websocket.close();
this.#websocket = null; 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 = () => { this.#websocket.onopen = () => {
const json = { const json = {
event: this.#messageType, event: this.#messageType,
uuid: this.#uuid, uuid: this.#uuid,
}; };
this.#websocket.send(JSON.stringify(json)); this.#websocket.send(JSON.stringify(json));
this.#emit(CONNECTED, { this.#emit(CONNECTED, {
connection: this.#websocket, connection: this.#websocket,
port: this.#port, port: this.#port,
uuid: this.#uuid, uuid: this.#uuid,
actionInfo: this.#actionInfo, actionInfo: this.#actionInfo,
appInfo: this.#appInfo, appInfo: this.#appInfo,
messageType: this.#messageType, messageType: this.#messageType,
}); });
}; };
this.#websocket.onerror = (evt) => { this.#websocket.onerror = (evt) => {
const error = `WEBOCKET ERROR: ${evt}, ${evt.data}, ${SocketErrors[evt?.code]}`; const error = `WEBOCKET ERROR: ${evt}, ${evt.data}, ${SocketErrors[evt?.code]}`;
console.warn(error); console.warn(error);
this.log(error); this.log(error);
}; };
this.#websocket.onclose = (evt) => { this.#websocket.onclose = (evt) => {
console.warn('WEBOCKET CLOSED:', SocketErrors[evt?.code]); console.warn('WEBOCKET CLOSED:', SocketErrors[evt?.code]);
}; };
this.#websocket.onmessage = (evt) => { this.#websocket.onmessage = (evt) => {
const data = evt?.data ? JSON.parse(evt.data) : {}; const data = evt?.data ? JSON.parse(evt.data) : {};
const {action, event} = data; const {action, event} = data;
const message = action ? `${action}.${event}` : event; const message = action ? `${action}.${event}` : event;
if (message && message !== '') this.#emit(message, data); if (message && message !== '') this.#emit(message, data);
}; };
} }
/** /**
* Write to log file * Write to log file
* @param message * @param message
*/ */
log(message) { log(message) {
try { try {
if (this.#websocket) { if (this.#websocket) {
const json = { const json = {
event: LOG_MESSAGE, event: LOG_MESSAGE,
payload: { payload: {
message: message, message: message,
}, },
}; };
this.#websocket.send(JSON.stringify(json)); this.#websocket.send(JSON.stringify(json));
} }
} catch (e) { } catch (e) {
console.log('Websocket not defined'); console.log('Websocket not defined');
} }
} }
/** /**
* Fetches the specified language json file * Fetches the specified language json file
* @param pathPrefix * @param pathPrefix
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async loadLocalization(pathPrefix) { async loadLocalization(pathPrefix) {
const manifest = await this.readJson(`${pathPrefix}${this.#language}.json`); const manifest = await this.readJson(`${pathPrefix}${this.#language}.json`);
this.#localization = manifest['Localization'] ?? null; this.#localization = manifest['Localization'] ?? null;
if (this.#messageType === REGISTER_PROPERTY_INSPECTOR && this.#localization) { if (this.#messageType === REGISTER_PROPERTY_INSPECTOR && this.#localization) {
const elements = document.querySelectorAll(DATA_LOCALIZE); const elements = document.querySelectorAll(DATA_LOCALIZE);
elements.forEach((element) => { elements.forEach((element) => {
element.textContent = element.textContent =
this.#localization[element.textContent] ?? element.textContent; this.#localization[element.textContent] ?? element.textContent;
}); });
} }
} }
/** /**
* *
* @param {*} path * @param {*} path
* @returns * @returns
*/ */
async readJson(path) { async readJson(path) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const req = new XMLHttpRequest(); const req = new XMLHttpRequest();
req.onerror = reject; req.onerror = reject;
req.overrideMimeType('application/json'); req.overrideMimeType('application/json');
req.open('GET', path, true); req.open('GET', path, true);
req.onreadystatechange = (response) => { req.onreadystatechange = (response) => {
if (req.readyState === 4) { if (req.readyState === 4) {
const jsonString = response?.target?.response; const jsonString = response?.target?.response;
if (jsonString) { if (jsonString) {
resolve(JSON.parse(response?.target?.response)); resolve(JSON.parse(response?.target?.response));
} else { } else {
reject(); reject();
} }
} }
}; };
req.send(); req.send();
}); });
} }
/** /**
* Send JSON payload to StreamDeck * Send JSON payload to StreamDeck
* @param context * @param context
* @param fn * @param fn
* @param payload * @param payload
*/ */
send(context, fn, payload) { send(context, fn, payload) {
const pl = Object.assign({}, {event: fn, context: context}, payload); const pl = Object.assign({}, {event: fn, context: context}, payload);
this.#websocket && this.#websocket.send(JSON.stringify(pl)); 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 * Request the actions's persistent data. StreamDeck does not return the data, but trigger the actions's didReceiveSettings event
* @param context * @param context
*/ */
getSettings(context) { getSettings(context) {
this.send(context ?? this.#uuid, GET_SETTINGS, {}); this.send(context ?? this.#uuid, GET_SETTINGS, {});
} }
/** /**
* Save the actions's persistent data. * Save the actions's persistent data.
* @param payload * @param payload
* @param context * @param context
*/ */
setSettings(payload, context) { setSettings(payload, context) {
this.send(context ?? this.#uuid, SET_SETTINGS, { this.send(context ?? this.#uuid, SET_SETTINGS, {
action: StreamDeck?.actionInfo?.action, action: StreamDeck?.actionInfo?.action,
payload: payload || {}, payload: payload || {},
targetContext: StreamDeck?.actionInfo?.context, targetContext: StreamDeck?.actionInfo?.context,
}); });
} }
/** /**
* Request the plugin's persistent data. StreamDeck does not return the data, but trigger the plugin/property inspectors didReceiveGlobalSettings event * Request the plugin's persistent data. StreamDeck does not return the data, but trigger the plugin/property inspectors didReceiveGlobalSettings event
*/ */
getGlobalSettings() { getGlobalSettings() {
this.send(this.#uuid, GET_GLOBAL_SETTINGS, {}); this.send(this.#uuid, GET_GLOBAL_SETTINGS, {});
} }
/** /**
* Save the plugin's persistent data * Save the plugin's persistent data
* @param payload * @param payload
*/ */
setGlobalSettings(payload) { setGlobalSettings(payload) {
this.send(this.#uuid, SET_GLOBAL_SETTINGS, { this.send(this.#uuid, SET_GLOBAL_SETTINGS, {
payload: payload, payload: payload,
}); });
} }
/** /**
* Opens a URL in the default web browser * Opens a URL in the default web browser
* @param urlToOpen * @param urlToOpen
*/ */
openUrl(urlToOpen) { openUrl(urlToOpen) {
this.send(this.#uuid, OPEN_URL, { this.send(this.#uuid, OPEN_URL, {
payload: { payload: {
url: urlToOpen, url: urlToOpen,
}, },
}); });
} }
/** /**
* Send payload from the property inspector to the plugin * Send payload from the property inspector to the plugin
* @param payload * @param payload
* @param context * @param context
*/ */
sendToPlugin(payload, context) { sendToPlugin(payload, context) {
this.send( this.send(
context ?? this.#uuid, context ?? this.#uuid,
SEND_TO_PLUGIN, SEND_TO_PLUGIN,
{ {
action: StreamDeck?.actionInfo?.action, action: StreamDeck?.actionInfo?.action,
payload: payload || {}, payload: payload || {},
targetContext: StreamDeck?.actionInfo?.context, targetContext: StreamDeck?.actionInfo?.context,
}, },
false false
); );
} }
/** /**
* Display alert triangle on actions key * Display alert triangle on actions key
* @param context * @param context
*/ */
showAlert(context) { showAlert(context) {
this.send(context, SHOW_ALERT, {}); this.send(context, SHOW_ALERT, {});
} }
/** /**
* Display ok check mark on actions key * Display ok check mark on actions key
* @param context * @param context
*/ */
showOk(context) { showOk(context) {
this.send(context, SHOW_OK, {}); this.send(context, SHOW_OK, {});
} }
/** /**
* Set the state of the actions * Set the state of the actions
* @param context * @param context
* @param payload * @param payload
*/ */
setState(context, payload) { setState(context, payload) {
this.send(context, SET_STATE, { this.send(context, SET_STATE, {
payload: { payload: {
state: 1 - Number(payload === 0), state: 1 - Number(payload === 0),
}, },
}); });
} }
/** /**
* Set the title of the actions's key * Set the title of the actions's key
* @param context * @param context
* @param title * @param title
* @param target * @param target
*/ */
setTitle(context, title, target) { setTitle(context, title, target) {
this.send(context, SET_TITLE, { this.send(context, SET_TITLE, {
payload: { payload: {
title: '' + title || '', title: '' + title || '',
target: target || HARDWARE_AND_SOFTWARE, target: target || HARDWARE_AND_SOFTWARE,
}, },
}); });
} }
/** /**
* Send payload to property inspector * Send payload to property inspector
* @param context * @param context
* @param payload * @param payload
*/ */
sendToPropertyInspector(context, payload) { sendToPropertyInspector(context, payload) {
this.send(context, SEND_TO_PROPERTY_INSPECTOR, { this.send(context, SEND_TO_PROPERTY_INSPECTOR, {
action: this.#actionInfo.action, action: this.#actionInfo.action,
payload: payload, payload: payload,
}); });
} }
/** /**
* Set the actions key image * Set the actions key image
* @param context * @param context
* @param img * @param img
* @param target * @param target
*/ */
setImage(context, img, target) { setImage(context, img, target) {
this.send(context, SET_IMAGE, { this.send(context, SET_IMAGE, {
payload: { payload: {
image: img || '', image: img || '',
target: target || HARDWARE_AND_SOFTWARE, target: target || HARDWARE_AND_SOFTWARE,
}, },
}); });
} }
/** /**
* Registers a callback function for when Stream Deck is connected * Registers a callback function for when Stream Deck is connected
* @param {*} fn * @param {*} fn
*/ */
onConnected(fn) { onConnected(fn) {
this.#on(CONNECTED, (jsn) => fn(jsn)); this.#on(CONNECTED, (jsn) => fn(jsn));
} return this;
}
/** /**
* Registers a callback function for when Stream Deck sends data to the property inspector * Registers a callback function for when Stream Deck sends data to the property inspector
* @param fn * @param fn
*/ */
onSendToPropertyInspector(fn) { onSendToPropertyInspector(fn) {
this.#on(SEND_TO_PROPERTY_INSPECTOR, (jsn) => fn(jsn)); this.#on(SEND_TO_PROPERTY_INSPECTOR, (jsn) => fn(jsn));
} return this;
}
/** /**
* Removes the event listener * Registers a callback function for the deviceDidConnect event, which fires when a device is plugged in
* @param eventName * @param {*} fn
*/ */
removeListener(eventName) { onDeviceDidConnect(fn) {
if (!eventName) return this.#removeAllListeners(); this.#on(DEVICE_DID_CONNECT, (jsn) => fn(jsn));
return this.#removeListener(eventName); 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(); 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. * @param {string} actionInfo - Context is an internal identifier used to communicate to the host application.
*/ */
function connectElgatoStreamDeckSocket() { function connectElgatoStreamDeckSocket() {
StreamDeck.connect(arguments); StreamDeck.connect(arguments);
} }