Advertisement
Guest User

Untitled

a guest
Apr 9th, 2025
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 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,
  6. pingTime: 60,
  7. startupDelay: 600, // 10 minutes delay before starting ping
  8. jitterRange: 15, // ±15s random offset
  9. rebootCooldown: 30 * 60 * 1000 // 30 minutes between reboots
  10. };
  11.  
  12. let endpointIdx = 0;
  13. let failCounter = 0;
  14. let pingTimer = null;
  15. let lastRebootTime = 0;
  16.  
  17. function jitteredPingLoop() {
  18. let jitter = Math.floor(Math.random() * (2 * CONFIG.jitterRange + 1)) - CONFIG.jitterRange;
  19. let delay = (CONFIG.pingTime + jitter) * 1000;
  20. pingTimer = Timer.set(delay, false, pingEndpoints);
  21. }
  22.  
  23. function pingEndpoints() {
  24. Shelly.call(
  25. "http.get",
  26. { url: CONFIG.endpoints[endpointIdx], timeout: CONFIG.httpTimeout },
  27. function (response, error_code, error_message) {
  28. if (error_code === -114 || error_code === -104 || !response || response.code !== 200) {
  29. print("Router: Ping failed to", CONFIG.endpoints[endpointIdx]);
  30. failCounter++;
  31. endpointIdx = (endpointIdx + 1) % CONFIG.endpoints.length;
  32. } else {
  33. failCounter = 0;
  34. }
  35.  
  36. if (failCounter >= CONFIG.numberOfFails) {
  37. let now = Date.now();
  38. if ((now - lastRebootTime) > CONFIG.rebootCooldown) {
  39. print("Router: Too many failures, rebooting...");
  40. lastRebootTime = now;
  41. Timer.clear(pingTimer);
  42. Shelly.call("Switch.Set", { id: 0, on: false, toggle_after: CONFIG.toggleTime }, function () {});
  43. return;
  44. } else {
  45. print("Router: Skipping reboot (cooldown active)");
  46. }
  47. }
  48.  
  49. jitteredPingLoop();
  50. }
  51. );
  52. }
  53.  
  54. function startAfterDelay() {
  55. print("Router: Starting ping loop after initial delay...");
  56. jitteredPingLoop();
  57. }
  58.  
  59. print("Router: Waiting", CONFIG.startupDelay, "seconds before starting checks.");
  60. Timer.set(CONFIG.startupDelay * 1000, false, startAfterDelay);
  61.  
  62. Shelly.addStatusHandler(function (status) {
  63. if (status.name !== "switch" || status.id !== 0) return;
  64. if (typeof status.delta.source === "undefined" || status.delta.source !== "timer") return;
  65. if (status.delta.output !== true) return;
  66.  
  67. print("Router: Power restored. Waiting before resuming pings.");
  68. Timer.set(CONFIG.startupDelay * 1000, false, startAfterDelay);
  69. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement