Advertisement
Guest User

Untitled

a guest
Apr 9th, 2025
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. let CONFIG = {
  2. endpoints: ["http://1.1.1.1", "http://8.8.8.8"],
  3. numberOfFails: 3,
  4. httpTimeout: 10,
  5. toggleTime: 30, // Power off duration for modem
  6. pingTime: 60, // Base ping interval (in seconds)
  7. jitterRange: 15, // ±15s jitter to avoid sync
  8. rebootCooldown: 15 * 60 * 1000 // 15 min cooldown between reboots
  9. };
  10.  
  11. let endpointIdx = 0;
  12. let failCounter = 0;
  13. let pingTimer = null;
  14. let lastRebootTime = 0;
  15.  
  16. function jitteredPingLoop() {
  17. let jitter = Math.floor(Math.random() * (2 * CONFIG.jitterRange + 1)) - CONFIG.jitterRange;
  18. let delay = (CONFIG.pingTime + jitter) * 1000;
  19. pingTimer = Timer.set(delay, false, pingEndpoints);
  20. }
  21.  
  22. function pingEndpoints() {
  23. Shelly.call(
  24. "http.get",
  25. { url: CONFIG.endpoints[endpointIdx], timeout: CONFIG.httpTimeout },
  26. function (response, error_code, error_message) {
  27. if (error_code === -114 || error_code === -104 || !response || response.code !== 200) {
  28. print("Modem: Ping failed to", CONFIG.endpoints[endpointIdx]);
  29. failCounter++;
  30. endpointIdx = (endpointIdx + 1) % CONFIG.endpoints.length;
  31. } else {
  32. failCounter = 0;
  33. }
  34.  
  35. if (failCounter >= CONFIG.numberOfFails) {
  36. let now = Date.now();
  37. if ((now - lastRebootTime) > CONFIG.rebootCooldown) {
  38. print("Modem: Too many failures, rebooting...");
  39. lastRebootTime = now;
  40. Timer.clear(pingTimer);
  41. Shelly.call("Switch.Set", { id: 0, on: false, toggle_after: CONFIG.toggleTime }, function () {});
  42. return;
  43. } else {
  44. print("Modem: Skipping reboot (cooldown active)");
  45. }
  46.  
  47. jitteredPingLoop();
  48. }
  49. );
  50. }
  51.  
  52. print("Modem watchdog started");
  53. jitteredPingLoop();
  54.  
  55. Shelly.addStatusHandler(function (status) {
  56. if (status.name !== "switch" || status.id !== 0) return;
  57. if (typeof status.delta.source === "undefined" || status.delta.source !== "timer") return;
  58. if (status.delta.output !== true) return;
  59.  
  60. print("Modem: Power restored. Waiting 120s before resuming ping checks...");
  61. Timer.set(120 * 1000, false, jitteredPingLoop); // Delay restart to allow modem to boot
  62. });
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement