Skip to content

Instantly share code, notes, and snippets.

@gaetancollaud
Created January 1, 2024 09:39
Show Gist options
  • Save gaetancollaud/23236d16b765d5e0448e9e009355b2d7 to your computer and use it in GitHub Desktop.
Save gaetancollaud/23236d16b765d5e0448e9e009355b2d7 to your computer and use it in GitHub Desktop.
Shelly 4PM expose outputs in MQTT in a simple way
let CONFIG = {
topic_prefix: "",
output_count: 4
};
let value;
//Read mqtt topic prefix
Shelly.call("MQTT.GetConfig", null, function (config) {
CONFIG.topic_prefix = config.topic_prefix;
startSubscribing();
});
function getStateTopic(component){
return CONFIG.topic_prefix + "/output/"+component+"/state";
}
function getCommandTopic(component){
return CONFIG.topic_prefix + "/output/"+component+"/command";
}
Shelly.addEventHandler(
function (event) {
if(event.info.output !== undefined){
value = event.info.output ? "on" : "off"
print("output changed on "+event.component+" : "+value);
if(MQTT.isConnected()){
MQTT.publish(getStateTopic(event.component), value);
}else{
print("MQTT not connected, unable to publish")
}
}
}, {}
);
function outputCommandCallback(topic, message, switchId){
print("Command received on topic "+topic+": "+JSON.stringify(message));
if(message==="on" || message==="off"){
let params = {id: switchId, on: message === "on"};
Shelly.call("Switch.Set", params);
}else{
print("Unknown command: "+message)
}
}
function startSubscribing(){
if(MQTT.isConnected()){
for(let switchId=0; switchId<CONFIG.output_count; switchId++){
let component = "switch:"+JSON.stringify(switchId);
print("Subscribing on topic "+getCommandTopic(component));
MQTT.subscribe(getCommandTopic(component), outputCommandCallback, switchId);
}
}else{
print("MQTT not connected, unable to subscribe")
}
}
print("script started");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment