homebridge-prusa-link
Version:
An homebridge plugin for Prusa Link
91 lines • 3.35 kB
JavaScript
import httpClient from 'urllib';
import { Paths, PrinterStates, SensorModes } from './values.js';
export class PrusaLinkAccessory {
log;
config;
api;
statusUrl;
sensorMode;
sensorService;
informationService;
batteryService;
constructor(log, config, api) {
this.log = log;
this.config = config;
this.api = api;
this.statusUrl = Paths.Http + this.config.ip + Paths.StatusPath;
switch (this.config.sensorMode) {
case SensorModes.OCCUPANCY:
this.sensorMode = SensorModes.OCCUPANCY;
this.sensorService = new this.api.hap.Service.OccupancySensor();
break;
case SensorModes.MOTION:
default:
this.sensorMode = SensorModes.MOTION;
this.sensorService = new this.api.hap.Service.MotionSensor();
break;
}
this.batteryService = new this.api.hap.Service.Battery();
this.informationService = new this.api.hap.Service.AccessoryInformation();
this.informationService
.setCharacteristic(api.hap.Characteristic.Manufacturer, this.config.manufacturer)
.setCharacteristic(api.hap.Characteristic.SerialNumber, this.config.serialnumber)
.setCharacteristic(api.hap.Characteristic.Model, this.config.model);
// Refresh state every 10 seconds
setInterval(() => {
this.refreshState();
}, 10000);
}
async refreshState() {
let state = PrinterStates.OFFLINE;
let completion = 1;
try {
const options = {
digestAuth: `${this.config.user}:${this.config.password}`,
};
const response = await httpClient.request(this.statusUrl, options);
const body = JSON.parse(response.data);
state = body.printer.state;
completion = body.job?.progress ?? 100;
}
catch (e) {
// do nothing -> standard values will be set
}
this.log.debug(`${this.config.name} is ${state}`);
switch (this.sensorMode) {
case SensorModes.OCCUPANCY:
this.updateOccupancySensor(state);
break;
case SensorModes.MOTION:
this.updateMotionSensor(state);
break;
}
this.updateBatteryLevel(completion);
}
updateMotionSensor(state) {
let motion = false;
if (state === PrinterStates.FINISHED) {
motion = true;
}
this.sensorService.updateCharacteristic(this.api.hap.Characteristic.MotionDetected, motion);
}
updateOccupancySensor(state) {
let occupied = false;
if (state === PrinterStates.PRINTING) {
occupied = true;
}
this.sensorService.updateCharacteristic(this.api.hap.Characteristic.OccupancyDetected, occupied);
}
updateBatteryLevel(completion) {
this.batteryService.updateCharacteristic(this.api.hap.Characteristic.BatteryLevel, completion);
this.log.debug(`${this.config.name} Progress: ${completion}`);
}
getServices() {
return [
this.sensorService,
this.batteryService,
this.informationService,
];
}
}
//# sourceMappingURL=prusaLinkAccessory.js.map