Many thanks to koush, who was patient and kind enough to help me learn a few basics, and spot the final errors in this script. Not really any error handling in here, but it seems to work. Note that, if you need identical switches for multiple cameras, easiest way is to define all of them in this script, giving each one unique "nativeID" and "name" values.
// Create multiple switches, each with its own MQTT action.
// These examples implement pan/tilt for https://github.com/EliasKotlyar/Xiaomi-Dafang-Hacks
// Other controls are easily added by creating another device block with unique nativeID,
// and a corresponding case statement with the desired MQTT parameters.
// To use, create an MQTT device of type DeviceProvider.
class TypescriptSwitch extends ScryptedDeviceBase implements OnOff {
constructor(nativeId: string, public topic: string, public value: string) {
super(nativeId);
this.on = this.on || false;
}
async turnOff() {
this.on = false;
}
async turnOn() {
mqtt.publish(this.topic, this.value);
this.on = true;
setTimeout(() => this.turnOff(), 1000);
}
}
class DafangMqtt extends ScryptedDeviceBase implements DeviceProvider {
constructor(nativeId?: string) {
super(nativeId);
this.prepareDevices();
}
async prepareDevices() {
await deviceManager.onDevicesChanged({
providerNativeId: this.nativeId,
devices: [
{
nativeId: 'panRight',
name: 'Pan Right',
type: ScryptedDeviceType.Switch,
interfaces: [
ScryptedInterface.OnOff,
]
},
{
nativeId: 'panLeft',
name: 'Pan Left',
type: ScryptedDeviceType.Switch,
interfaces: [
ScryptedInterface.OnOff,
]
},
{
nativeId: 'tiltUp',
name: 'Tilt Up',
type: ScryptedDeviceType.Switch,
interfaces: [
ScryptedInterface.OnOff,
]
},
{
nativeId: 'tiltDown',
name: 'Tilt Down',
type: ScryptedDeviceType.Switch,
interfaces: [
ScryptedInterface.OnOff,
]
},
]
});
}
getDevice(nativeId: string) {
let topic : string = '';
let value : string = '';
switch (nativeId) {
case 'panRight':
topic = 'motors/horizontal/set';
value = 'right';
break;
case 'panLeft':
topic = 'motors/horizontal/set';
value = 'left';
break;
case 'tiltUp':
topic = 'motors/vertical/set';
value = 'up';
break;
case 'tiltDown':
topic = 'motors/vertical/set';
value = 'down';
break;
}
return new TypescriptSwitch(nativeId, topic, value);
}
}
export default DafangMqtt;
Many thanks to koush, who was patient and kind enough to help me learn a few basics, and spot the final errors in this script. Not really any error handling in here, but it seems to work. Note that, if you need identical switches for multiple cameras, easiest way is to define all of them in this script, giving each one unique "nativeID" and "name" values.