Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let CONFIG = {
- endpoints: ["http://1.1.1.1", "http://8.8.8.8"],
- numberOfFails: 3,
- httpTimeout: 10,
- toggleTime: 30,
- pingTime: 60,
- startupDelay: 600, // 10 minutes delay before starting ping
- jitterRange: 15, // ±15s random offset
- rebootCooldown: 30 * 60 * 1000 // 30 minutes between reboots
- };
- let endpointIdx = 0;
- let failCounter = 0;
- let pingTimer = null;
- let lastRebootTime = 0;
- function jitteredPingLoop() {
- let jitter = Math.floor(Math.random() * (2 * CONFIG.jitterRange + 1)) - CONFIG.jitterRange;
- let delay = (CONFIG.pingTime + jitter) * 1000;
- pingTimer = Timer.set(delay, false, pingEndpoints);
- }
- function pingEndpoints() {
- Shelly.call(
- "http.get",
- { url: CONFIG.endpoints[endpointIdx], timeout: CONFIG.httpTimeout },
- function (response, error_code, error_message) {
- if (error_code === -114 || error_code === -104 || !response || response.code !== 200) {
- print("Router: Ping failed to", CONFIG.endpoints[endpointIdx]);
- failCounter++;
- endpointIdx = (endpointIdx + 1) % CONFIG.endpoints.length;
- } else {
- failCounter = 0;
- }
- if (failCounter >= CONFIG.numberOfFails) {
- let now = Date.now();
- if ((now - lastRebootTime) > CONFIG.rebootCooldown) {
- print("Router: Too many failures, rebooting...");
- lastRebootTime = now;
- Timer.clear(pingTimer);
- Shelly.call("Switch.Set", { id: 0, on: false, toggle_after: CONFIG.toggleTime }, function () {});
- return;
- } else {
- print("Router: Skipping reboot (cooldown active)");
- }
- }
- jitteredPingLoop();
- }
- );
- }
- function startAfterDelay() {
- print("Router: Starting ping loop after initial delay...");
- jitteredPingLoop();
- }
- print("Router: Waiting", CONFIG.startupDelay, "seconds before starting checks.");
- Timer.set(CONFIG.startupDelay * 1000, false, startAfterDelay);
- Shelly.addStatusHandler(function (status) {
- if (status.name !== "switch" || status.id !== 0) return;
- if (typeof status.delta.source === "undefined" || status.delta.source !== "timer") return;
- if (status.delta.output !== true) return;
- print("Router: Power restored. Waiting before resuming pings.");
- Timer.set(CONFIG.startupDelay * 1000, false, startAfterDelay);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement