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
| // Shelly Pro 2 State Manager
// Manages transitions between SAP and PAP states with an intermediate switching state
// State definitions
const STATES = {
SAP: "SAP", // Output1: ON, Output2: ON
PAP: "PAP", // Output1: OFF, Output2: OFF
SWITCHING: "SWITCHING" // Output1: OFF, Output2: ON (temporary intermediate state, everything OFF)
};
// Configuration
const CONFIG = {
switchingDurationMs: 2000, // Duration to stay in SWITCHING state (2 seconds)
mqttTopic: "shelly-pro2-load-home/state", // MQTT topic for state changes
useInputControl: true, // Use Shelly's physical input for state control
useMqtt: true, // Allow MQTT for state control
inputId: 0, // ID for the physical input to use
retainMqttMessages: true // Set to true to retain MQTT messages
};
// State variable
let currentState = null;
let switchingTimer = null;
let isInitialized = false;
// Initialize the system
function init() {
if (isInitialized) {
return;
}
log("INFO", "Initializing Shelly Pro 2 State Manager");
// Sete initial PAP state
switchingTimer = Timer.set(CONFIG.switchingDurationMs, false, function() {
log("INFO", "Initial state set to PAP state");
setStateInternal(STATES.PAP);
switchingTimer = null;
});
// Register event handlers for different control methods
if (CONFIG.useInputControl) {
setupInputHandler();
}
if (CONFIG.useMqtt) {
setupMqtt();
}
isInitialized = true;
log("INFO", "Initialization complete");
}
// Set up input handler for state control
function setupInputHandler() {
log("INFO", "Setting up input handler for input " + CONFIG.inputId);
// Listen for input events on specified input
Shelly.addEventHandler(function(event) {
// Check if this is an input event from our configured input
if (event.component === "input:" + CONFIG.inputId && event.info.state === true) {
log("INFO", "Input triggered, toggling state");
toggleStateInternal();
}
});
log("INFO", "Input handler setup complete");
}
// Set up MQTT for state control (if enabled)
function setupMqtt() {
if (!CONFIG.useMqtt) {
log("INFO", "MQTT disabled in configuration");
return;
}
log("INFO", "Setting up MQTT for state control");
try {
// Subscribe to the state topic
MQTT.subscribe(CONFIG.mqttTopic, function(topic, message) {
log("INFO", "MQTT message received: " + message + " on topic: " + topic);
try {
const data = JSON.parse(message);
if (data.state && (data.state === STATES.SAP || data.state === STATES.PAP)) {
log("INFO", "State change requested via MQTT: " + data.state);
setTargetStateInternal(data.state);
} else {
log("WARN", "Invalid MQTT payload: " + message);
}
} catch (e) {
// Simple string payload handling
if (message === STATES.SAP || message === STATES.PAP) {
log("INFO", "State change requested via MQTT: " + message);
setTargetStateInternal(message);
} else {
log("WARN", "Invalid MQTT payload format: " + message);
}
}
});
log("INFO", "MQTT setup complete");
} catch (e) {
log("ERROR", "MQTT setup failed: " + JSON.stringify(e));
}
}
// Toggle between SAP and PAP states
function toggleStateInternal() {
log("INFO", "Toggle state requested");
if (currentState === STATES.SAP) {
setTargetStateInternal(STATES.PAP);
} else if (currentState === STATES.PAP) {
setTargetStateInternal(STATES.SAP);
} else {
log("WARN", "Toggle ignored - system is in SWITCHING state");
}
}
// Set target state (SAP or PAP)
function setTargetStateInternal(targetState) {
if (currentState === STATES.SWITCHING) {
log("WARN", "State change ignored - system is already in SWITCHING state");
return;
}
if (targetState === currentState) {
log("INFO", "State is already " + targetState + " - no change needed");
return;
}
log("INFO", "Changing state from " + currentState + " to " + targetState);
// First, transition to SWITCHING state
setStateInternal(STATES.SWITCHING);
// Cancel any existing timer
if (switchingTimer !== null) {
Timer.clear(switchingTimer);
}
// Set timer to complete the transition
switchingTimer = Timer.set(CONFIG.switchingDurationMs, false, function() {
log("INFO", "Switching period complete, setting final state: " + targetState);
setStateInternal(targetState);
switchingTimer = null;
});
}
// Apply the specified state to outputs
function setStateInternal(state) {
log("INFO", "Setting system state to: " + state);
switch(state) {
case STATES.SAP:
setOutputs(true, true);
break;
case STATES.PAP:
setOutputs(false, false);
break;
case STATES.SWITCHING:
setOutputs(false, true);
break;
default:
log("ERROR", "Invalid state: " + state);
return;
}
currentState = state;
// Only try to publish MQTT if it's enabled
if (CONFIG.useMqtt) {
try {
publishStateToMqtt();
} catch (e) {
log("ERROR", "Failed to publish MQTT: " + JSON.stringify(e));
}
}
log("INFO", "State change complete: " + state);
}
// Set the physical outputs
function setOutputs(output1State, output2State) {
log("INFO", "Setting outputs - Output1: " + (output1State ? "ON" : "OFF") +
", Output2: " + (output2State ? "ON" : "OFF"));
try {
Shelly.call("Switch.Set", { id: 0, on: output1State }, function(result, error_code, error_message) {
if (error_code) {
log("ERROR", "Failed to set Output1: " + error_message);
} else {
log("DEBUG", "Output1 set successfully to " + (output1State ? "ON" : "OFF"));
}
});
Shelly.call("Switch.Set", { id: 1, on: output2State }, function(result, error_code, error_message) {
if (error_code) {
log("ERROR", "Failed to set Output2: " + error_message);
} else {
log("DEBUG", "Output2 set successfully to " + (output2State ? "ON" : "OFF"));
}
});
} catch (e) {
log("ERROR", "Exception setting outputs: " + JSON.stringify(e));
}
}
// Publish state to MQTT
function publishStateToMqtt() {
if (!CONFIG.useMqtt) return;
try {
// Get current output states safely
let output1State = false;
let output2State = false;
try {
const status0 = Shelly.getComponentStatus("switch:0");
if (status0) output1State = status0.output;
} catch (e) {
log("ERROR", "Failed to get switch:0 status: " + JSON.stringify(e));
}
try {
const status1 = Shelly.getComponentStatus("switch:1");
if (status1) output2State = status1.output;
} catch (e) {
log("ERROR", "Failed to get switch:1 status: " + JSON.stringify(e));
}
const payload = JSON.stringify({
state: currentState,
outputs: {
output1: output1State,
output2: output2State
}
});
log("DEBUG", "Publishing state to MQTT: " + payload);
MQTT.publish(CONFIG.mqttTopic + "/status", payload, CONFIG.retainMqttMessages);
} catch (e) {
log("ERROR", "Exception in publishStateToMqtt: " + JSON.stringify(e));
}
}
// Logging function with severity levels
function log(level, message) {
try {
const formattedMessage = "[" + level + "] " + message;
console.log(formattedMessage);
} catch (e) {
console.log("Error in logging: " + e.toString());
}
}
// Initialize the system
try {
init();
// Output something to confirm script loaded successfully
console.log("SAP/PAP state manager initialized successfully");
} catch (e) {
console.log("Error during initialization: " + JSON.stringify(e));
} |