-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
299 lines (256 loc) · 8.42 KB
/
main.ts
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
289
290
291
292
293
294
295
296
297
298
299
/**
* Created with @iobroker/create-adapter v2.1.1
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
import * as utils from "@iobroker/adapter-core";
const ps4waker = require("ps4-waker");
interface PlaystationDevice {
name: string;
ip: string;
}
class SonyPlaystation extends utils.Adapter {
private pollAPITimer: NodeJS.Timeout | undefined;
private readonly pollAPIInterval: number;
public constructor(options: Partial<utils.AdapterOptions> = {}) {
super({
...options,
name: "sony-playstation",
});
// this.pollAPIInterval = 60_000 * 10;
this.pollAPIInterval = 60000;
this.on("ready", this.onReady.bind(this));
this.on("unload", this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
private async onReady(): Promise<void> {
// Initialize your adapter here
// The adapters config (in the instance object everything under the attribute "native") is accessible via
// this.config:
this.log.info("Search Timeout: " + this.config.searchTimeOut);
// examples for the checkPassword/checkGroup functions
let result = await this.checkPasswordAsync("admin", "iobroker");
this.log.info("check user admin pw iobroker: " + result);
result = await this.checkGroupAsync("admin", "admin");
this.log.info("check group user admin group admin: " + result);
this.log.debug("synchronizing configuration with state");
await this.syncConfig();
this.pollAPI();
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
*/
private onUnload(callback: () => void): void {
try {
this.log.info("Shutting down Sony Playstation adapter");
callback();
} catch (e) {
callback();
}
}
private async syncConfig(): Promise<void> {
this.log.debug("sync State");
const devices = await this.getDevicesAsync();
const configDevices: PlaystationDevice[] = this.config.devices;
this.log.debug("retrieved devices: " + JSON.stringify(devices));
this.log.debug("configured devices: " + JSON.stringify(configDevices));
if (devices && devices.length) {
const missingDevices = [];
const toRemoveDevices = [];
for (let d = 0; d < devices.length; d++) {
this.log.debug("Device to check: " + JSON.stringify(devices[d]));
const states = await this.getStatesOfAsync(devices[d]._id);
this.log.debug("States: " + JSON.stringify(states));
for (let s = 0; s < states.length; s++) {
this.log.debug("State: " + JSON.stringify(states[s]));
if (states[s].common.role === "address") {
this.log.debug("Verifying if the found device with the same address also exists in config");
const state = await this.getStateAsync(states[s]._id);
if (!state) {
this.log.warn("No State found for given State Obj: " + JSON.stringify(states[s]));
continue;
}
let foundExisting = false;
for (let c = 0; c < this.config.devices.length; c++) {
this.log.debug(
"Config IP: " + this.config.devices[c].ip + " Device-State IP: " + state.val,
);
if (this.config.devices[c].ip === state.val) {
this.log.debug("Found Device with IP: " + this.config.devices[c].ip);
foundExisting = true;
continue;
}
this.log.debug("Found missing Device with IP address: " + this.config.devices[c].ip);
missingDevices.push(this.config.devices[c]);
}
if (!foundExisting) {
this.log.debug("No config found for Device: " + JSON.stringify(devices[d]));
toRemoveDevices.push(devices[d]);
}
}
}
this.log.debug("Devices to be removed: " + toRemoveDevices.length);
this.log.debug("Devices to be added: " + missingDevices.length);
toRemoveDevices.forEach((device) => {
this.log.debug("remove Device, as it doesn't exist in Config: " + JSON.stringify(device));
this.deleteDeviceAsync(device._id);
});
missingDevices.forEach((device) => {
this.log.debug(
"adding Device as found in config, but missing in devices: " + JSON.stringify(device),
);
this.createDeviceChannel(device.name, device.ip);
});
}
} else {
this.log.debug("only new config found, adding those");
for (let r = 0; r < this.config.devices.length; r++) {
if (!this.config.devices[r].ip) {
this.log.debug(
"Following device is missing an IP-Address: " + JSON.stringify(this.config.devices[r]),
);
continue;
}
this.log.debug("adding channel");
//const obj = await this.createDeviceChannel(this.config.devices[r].name, this.config.devices[r].ip);
//const _obj = await this.getObjectAsync(obj.id);
}
}
}
private async createDeviceChannel(name: any, ip: any): Promise<object> {
this.log.debug("Create Device Channel with Name: " + name + " and IP: " + ip);
const id = ip.replace(/[.\s]+/g, "_");
const obj = await this.createDevice(id);
this.log.debug("Created Channel Obj: " + JSON.stringify(obj));
await this.createState(
id,
"",
"state",
{
type: "string",
read: true,
write: true,
role: "state",
name: "Power Status Active",
},
true,
);
const nameState = await this.createState(
id,
"",
"name",
{
type: "string",
read: true,
write: true,
role: "name",
name: "Name of Playstation",
},
true,
);
this.log.debug("created Name-State: " + JSON.stringify(nameState));
const addressState = await this.createState(
id,
"",
"address",
{
type: "string",
read: true,
write: true,
role: "address",
name: "IP address of Playstation",
},
true,
);
this.log.debug("created Address-State: " + JSON.stringify(addressState));
await this.setState(id + ".name", name, true);
await this.setState(id + ".address", ip, true);
return obj;
}
private browse(callback: (res: any[]) => void): void {
this.log.info("Browse function called");
const deviceOptions = new Map();
//deviceOptions.set("debug","true");
deviceOptions.set("timeout", this.config.searchTimeOut);
this.log.debug("Calling detector with options: " + deviceOptions);
//discovery is a promise ...
ps4waker.Detector.findAny(deviceOptions, (err: any, device: any) => {
if (err === undefined) {
this.log.error(err.message);
callback(err);
} else {
this.log.debug("discovered: " + JSON.stringify(device, null, 2));
this.log.debug("Name: " + device["host-name"]);
this.log.debug("address: " + device["address"]);
const result = [];
if (device) {
const x = {
ip: device["address"] === undefined ? "" : device["address"],
name: device["host-name"],
};
this.log.debug("adding to result: " + x);
result.push(x);
}
this.log.info("calling callback");
callback && callback(result);
}
});
}
/**
* Poll states from API and syncs them to ioBroker states
*/
private async pollAPI(): Promise<void> {
this.log.info("Poll PS4 state");
this.config.devices.forEach((device) => {
try {
const deviceOptions = {
debug: true,
timeout: parseInt(this.config.searchTimeOut) * 1000,
address: device.ip,
};
this.log.debug("Device Options: " + JSON.stringify(deviceOptions));
const ps4Device = new ps4waker.Device(deviceOptions);
this.log.debug("retrieving device status for device with IP: " + device.ip);
ps4Device
.getDeviceStatus()
.then(
(element: any) => {
this.log.debug(`PS4-Device: ${JSON.stringify(element)}`);
const id = device.ip.replace(/[.\s]+/g, "_");
this.setState(id + ".state", element["status"], true);
},
(error: Error) => {
this.log.warn(`Could not poll API: ${this.errorToText(error)}`);
},
)
.then(() => ps4Device.close());
} catch (e) {
this.log.warn(`Could not poll API: ${this.errorToText(e)}`);
}
});
this.pollAPITimer = setTimeout(() => {
this.pollAPI();
}, this.pollAPIInterval);
}
/**
* Checks if a real error was thrown and returns message then, else it stringifies
*
* @param error any kind of thrown error
*/
private errorToText(error: unknown): string {
if (error instanceof Error) {
return error.message;
} else {
return JSON.stringify(error);
}
}
}
if (require.main !== module) {
// Export the constructor in compact mode
module.exports = (options: Partial<utils.AdapterOptions> | undefined) => new SonyPlaystation(options);
} else {
// otherwise start the instance directly
(() => new SonyPlaystation())();
}