Doodle3D-API/src/doodle3dmanager.js

85 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2017-11-30 17:23:13 +01:00
import EventDispatcher from 'eventdispatcher.js';
import { sleep, parseFetch } from './utils.js';
2015-10-15 10:56:01 +02:00
export default class Doodle3DManager extends EventDispatcher {
2016-04-21 15:52:23 +02:00
constructor() {
super();
this.api = 'http://connect.doodle3d.com/api/';
this.boxes = [];
this.nonServerBoxes = [{
wifiboxid: 'Wired Printer',
localip: '192.168.5.1'
}/*, {
wifiboxid: 'Node JS Server',
localip: '127.0.0.1:3000'
}*/];
this.checkNonServerBoxes = true;
2016-04-21 15:52:23 +02:00
this.autoUpdate = false;
}
setAutoUpdate(autoUpdate = true, updateInterval = 1000) {
this.updateInterval = updateInterval;
2016-08-19 16:07:55 +02:00
if (this.autoUpdate === autoUpdate) return this;
2016-04-21 15:52:23 +02:00
this.autoUpdate = autoUpdate;
if (autoUpdate) this._update();
return this;
}
async _update() {
while (this.autoUpdate) {
await this._checkNew();
await sleep(this.updateInterval);
}
}
async _checkNew() {
let boxes = [];
2016-04-21 15:52:23 +02:00
try {
2017-11-30 17:23:13 +01:00
boxes = await fetch(`${this.api}list.php`, { method: 'GET' }).then(parseFetch);
2016-04-21 15:52:23 +02:00
} catch(error) {
console.warn('fail connecting to Doodle3D server');
}
if (this.checkNonServerBoxes) boxes = boxes.concat(this.nonServerBoxes);
2018-01-25 17:27:59 +01:00
const knownIPsClient = this.boxes.map(box => box.localip);
2016-04-21 15:52:23 +02:00
const knownIPsServer = boxes.map(box => box.localip);
const newBoxes = boxes.filter(box => knownIPsClient.indexOf(box.localip) === -1);
2018-01-25 17:27:59 +01:00
const removedBoxes = this.boxes.filter(box => knownIPsServer.indexOf(box.localip) === -1);
2016-04-21 15:52:23 +02:00
let changed = false;
for (const boxData of newBoxes) {
2018-01-25 17:27:59 +01:00
this._addBox(boxData);
2016-04-21 15:52:23 +02:00
changed = true;
}
for (const box of removedBoxes) {
this._removeBox(box);
changed = true;
}
if (changed) {
this.dispatchEvent({ type: 'boxeschanged', boxes: this.boxes });
}
}
_addBox(box) {
this.boxes.push(box);
this.dispatchEvent({ type: 'boxappeared', box });
}
_removeBox(box) {
const index = this.boxes.indexOf(box);
if (index !== -1) {
this.boxes.splice(index, 1);
this.dispatchEvent({ type: 'boxdisappeared', box });
}
}
}