-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBMDevice.js
288 lines (233 loc) · 9.62 KB
/
BMDevice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/* Blackmagic Camera Control JS Class
Written based on the Camera Control
API Documentation from Blackmagic's
Developer info website.
(c) Dylan Speiser 2024
github.com/DylanSpeiser
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published.
This program is distributed in the hope that it will be useful but without
any warranty; without even the implied warranty of merchantability or fitness
for a particular purpose as specified by the License, which you should consult
for more details at LICENSE.txt in this repository.
*/
// Generic Blackmagic Device class, use with HyperDecks.
class BMDevice {
// Pretty name and network hostname (strings)
name;
hostname;
APIAddress;
// Are we using HTTPS?
useHTTPS;
// WebSocket items
ws;
availableProperties;
// Active Flag
// Won't call updateUI if this is false
active = false;
// JSON Object to store all data
propertyData = {};
// Reference to UI Updating callback function
// For BYOUI purposes (Bring-Your-Own-UI). If you're using this class for your own UI,
// set this function to point to your UI updater.
updateUI() {};
// ============= CONSTRUCTOR ================
constructor(hostname, secure=false) {
// Set Security
this.useHTTPS = secure;
// Set name properties
this.hostname = hostname;
this.APIAddress = (this.useHTTPS ? "https://" : "http://")+hostname+"/control/api/v1";
this.name = this.hostname.replace(".local","").replaceAll("-"," ");
// Initialize WebSocket
this.ws = new WebSocket((this.useHTTPS ? "wss://" : "ws://")+hostname+"/control/api/v1/event/websocket");
// Get a self object for accessing within callback fns
var self = this;
// Set the onmessage behavior
this.ws.onmessage = (event) => {
// Parse the event's data as JSON
let eventData = JSON.parse(event.data);
// Extract data we really care about
let messageData = eventData.data;
// If it's a listProperties message, update the available properties array
if (messageData.action == "listProperties") {
self.availableProperties = messageData.properties;
}
// If we get a response from the camera with property information, save it.
if (eventData.type == "response") {
Object.assign(this.propertyData, messageData.values);
}
// If it's a propertyValueChanged event, update the camera object accordingly and show it on the web page.
if (messageData.action == "propertyValueChanged") {
this.propertyData[messageData.property] = messageData.value;
}
if (this.active) {
// Update the UI
this.updateUI();
}
// Output info to console.
// console.log("WebSocket message received: ", eventData);
}
// Wait for the WebSocket to open
this.ws.onopen = (event) => {
// Once the WebSocket is open,
// Ask it for all the properties
self.ws.send(JSON.stringify({type: "request", data: {action: "listProperties"}}));
sleep(100).then(() => {
// Subscribe to all available events
this.availableProperties.forEach((str) => {
self.ws.send(JSON.stringify({type: "request", data: {action: "subscribe", properties: [str]}}));
});
});
}
}
// Returns a JSON Object of data we got from the device
GETdata(endpoint) {
// Just call sendRequest
return sendRequest("GET", this.APIAddress+endpoint);
}
// Send JSON Object data to the device
PUTdata(endpoint, data) {
// Just call sendRequest
return sendRequest("PUT", this.APIAddress+endpoint, data);
}
// ================= SETTERS =================
// Basically just wrappers for PUT requests to specific endpoints
// If the optional parameter is set to false, it will stop recording
record(state = true) {
this.PUTdata("/transports/0/record",{recording: state});
}
toggleRecord() {
let recordState = this.propertyData['/transports/0/record'].recording;
this.PUTdata("/transports/0/record",{recording: !recordState});
}
play() {
this.PUTdata("/transports/0/play");
}
stop() {
this.PUTdata("/transports/0/stop");
}
// Boolean parameter, true = forward, false = backwards
seek(direction) {
let clips = this.GETdata("/timelines/0")?.clips;
let playbackData = this.GETdata("/transports/0/playback");
let runningSum = 0;
let currentClipFound = false;
let currentClipIndex = 0;
let clipStartingTimecodes = [];
let i = 0;
clips.forEach((clip) => {
if ((runningSum+clip.frameCount > playbackData.position) && !currentClipFound) {
currentClipIndex = i;
currentClipFound = true;
}
clipStartingTimecodes[i] = runningSum;
runningSum += clip.frameCount;
i++;
});
let newClipIndex = Math.min(Math.max(0,(direction ? currentClipIndex+1 : currentClipIndex-1)), clips.length-1);
playbackData.position = clipStartingTimecodes[newClipIndex];
this.PUTdata("/transports/0/playback", playbackData);
}
// Sets Timeline / Clip Looping
// Argument can be either "None", "Loop", or "Loop Clip"
setLoopMode(modeString) {
let newStateObj = this.propertyData['/transports/0/playback'];
if (modeString === "None") {
newStateObj.loop = false;
newStateObj.singleClip = false;
} else if (modeString === "Loop") {
newStateObj.loop = true;
newStateObj.singleClip = false;
} else if (modeString === "Loop Clip") {
newStateObj.loop = true;
newStateObj.singleClip = true;
}
this.PUTdata("/transports/0/playback", newStateObj);
}
}
// Child Class Specifically for Cameras
class BMCamera extends BMDevice {
// Child class constructor
// Just passing the hostname and security to the superclass's constructor
constructor(hostname, secure=false) {
super(hostname, secure);
}
// Sets the white balance and tint based on the following preset:
// 0: Sunlight, 1: Tungsten, 2: Fluorescent, 3: Shade, 4: Cloudy
// Any other value will not affect the WB setting
setWhiteBalancePreset(presetIndex) {
let newWhiteBalance;
let newWhiteBalanceTint;
switch (presetIndex) {
case 0:
// Sunlight
newWhiteBalance = 5600;
newWhiteBalanceTint = 10;
break;
case 1:
// Tungsten
newWhiteBalance = 3200;
newWhiteBalanceTint = 0;
break;
case 2:
// Fluorescent
newWhiteBalance = 4000;
newWhiteBalanceTint = 15;
break;
case 3:
// Shade
newWhiteBalance = 4500;
newWhiteBalanceTint = 15;
break;
case 4:
// Cloudy
newWhiteBalance = 6500;
newWhiteBalanceTint = 10;
break;
default:
// If any other value is set, don't change anything
newWhiteBalance = this.GETdata("/video/whiteBalance").whiteBalance;
newWhiteBalanceTint = this.GETdata("/video/whiteBalanceTint").whiteBalanceTint;
}
this.PUTdata("/video/whiteBalance",{whiteBalance: newWhiteBalance});
this.PUTdata("/video/whiteBalanceTint",{whiteBalanceTint: newWhiteBalanceTint});
}
doAutoFocus() {
this.PUTdata("/lens/focus/doAutoFocus");
}
doAutoWhitebalance() {
this.PUTdata("/video/whiteBalance/doAuto");
}
}
/* Helper Functions */
// Send request with other method type
function sendRequest(method, url, data) {
// Instantiate the XMLHttpRequest object
let xhr = new XMLHttpRequest();
// Create an object to store and return the response
let responseObject = {};
// Define the onload function
xhr.onload = function() {
if (this.status < 300) { // If the operation is successful
if (this.responseText)
responseObject = JSON.parse(this.responseText); // Give the data to the responseObject
responseObject.status = this.status; // Also pass along the status code for error handling
} else { // If there has been an error
responseObject = this; // Give the XMLHttpRequest data to the responseObject
console.error("Error ", this.status, ": ", this.statusText); // Log the error in the console
}
};
// Open the connection
// The "false" here specifies that we want to wait for the response to come back before returning from xhr.send()
xhr.open(method, url, false);
// Send the request with data
xhr.send(JSON.stringify(data));
// Return response data
return responseObject;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/* (c) Dylan Speiser 2024
github.com/DylanSpeiser */