Compare commits

...

2 Commits

2 changed files with 38 additions and 109 deletions

View File

@@ -3,81 +3,6 @@ _CONFIG = {"discord_webhook_url": None, "discord_alert_webhook_url": None}
# Cooldown after low-memory failures (epoch seconds)
_NEXT_ALLOWED_SEND_TS = 0
def debug_force_send(message):
"""
Force one send attempt and print gc.mem_free() at key points.
Bypasses cooldown and pre-checks so you can measure peak allocations.
Use from REPL after WiFi connects:
import scripts.discord_webhook as d
d.set_config(config)
d.debug_force_send("memory test")
WARNING: this can trigger ENOMEM and crash if device free RAM is too low.
"""
global _NEXT_ALLOWED_SEND_TS
resp = None
try:
import gc # type: ignore
import time # type: ignore
url = _get_webhook_url(False)
if not url:
print("DBG_FORCE: no webhook URL configured")
return False
print("DBG_FORCE: mem before gc:", getattr(gc, "mem_free", lambda: 0)() // 1024, "KB")
gc.collect(); gc.collect()
print("DBG_FORCE: mem after gc:", getattr(gc, "mem_free", lambda: 0)() // 1024, "KB")
# Try importing urequests and show mem impact
try:
print("DBG_FORCE: importing urequests...")
import urequests as requests # type: ignore
gc.collect()
print("DBG_FORCE: mem after import:", getattr(gc, "mem_free", lambda: 0)() // 1024, "KB")
except Exception as e:
print("DBG_FORCE: urequests import failed:", e)
return False
# Build tiny payload
body_bytes = ('{"content":"%s","username":"%s"}' % (str(message)[:140], "DBG")).encode("utf-8")
print("DBG_FORCE: mem before post:", getattr(gc, "mem_free", lambda: 0)() // 1024, "KB")
try:
resp = requests.post(str(url).strip().strip('\'"'), data=body_bytes, headers={"Content-Type": "application/json"})
print("DBG_FORCE: mem after post:", getattr(gc, "mem_free", lambda: 0)() // 1024, "KB", "status:", getattr(resp, "status", None))
status = getattr(resp, "status", getattr(resp, "status_code", None))
return bool(status and 200 <= status < 300)
except Exception as e:
print("DBG_FORCE: exception during post:", e)
return False
finally:
try:
if resp:
resp.close()
except:
pass
try:
if 'requests' in globals():
del requests
except:
pass
try:
import sys, gc
for m in ('urequests', 'ussl', 'ssl'):
if m in sys.modules:
try:
del sys.modules[m]
except:
pass
gc.collect(); gc.collect()
try:
print("DBG_FORCE: mem final:", getattr(gc, "mem_free", lambda: 0)() // 1024, "KB")
except:
pass
except:
pass
def set_config(cfg: dict):
"""Initialize module with minimal values from loaded config (call from main)."""
global _CONFIG
@@ -206,7 +131,7 @@ def send_discord_message(message, username="Auto Garden Bot", is_alert=False, de
except:
pass
try:
import gc
import gc # type: ignore
gc.collect(); gc.collect()
except:
pass

70
main.py
View File

@@ -144,6 +144,11 @@ def load_config():
return default_config
# global variables for Discord webhook status
discord_sent = False
discord_send_attempts = 0
pending_discord_message = None
# Load configuration from file
config = load_config()
import scripts.discord_webhook as discord_webhook
@@ -200,16 +205,22 @@ if wifi and wifi.isconnected():
print(f"Web Interface: http://{ifconfig[0]}")
print("="*50 + "\n")
# Send startup notification to Discord (schedule for later to avoid ENOMEM)
try:
gc.collect() # free heap before HTTPS attempt
# don't attempt HTTP/TLS immediately — schedule for retry from main loop
# Try sending Discord webhook NOW, before creating other objects
gc.collect()
mem_ok = gc.mem_free() > 140000
if mem_ok:
ok = discord_webhook.send_discord_message("Pico W online at http://{}".format(ifconfig[0]), debug=False)
if ok:
print("Discord startup notification sent")
discord_sent = True
else:
print("Discord startup notification failed")
pending_discord_message = "Pico W online at http://{}".format(ifconfig[0])
discord_send_attempts = 1
else:
print("Not enough memory for Discord startup notification")
pending_discord_message = "Pico W online at http://{}".format(ifconfig[0])
discord_send_attempts = 0
discord_sent = False
print("Startup discord message queued (will send when memory available)")
except Exception as e:
print("Discord notification scheduling error: {}".format(e))
discord_send_attempts = 1
# Start web server early so page can load even if time sync is slow
web_server = TempWebServer(port=80)
@@ -401,33 +412,26 @@ last_ntp_sync = time.time() # Track when we last synced
while True:
try:
# Try to send pending discord startup message when memory permits
try:
if not globals().get('discord_sent', True) and globals().get('pending_discord_message'):
import gc as _gc # type: ignore
# run GC before measuring free memory
_gc.collect()
_gc.collect()
# require larger headroom (observed successful test ~174 KB free)
mem_ok = getattr(_gc, 'mem_free', lambda: 0)() > 140000
if mem_ok:
try:
# production send: don't enable verbose debug prints here
ok = discord_webhook.send_discord_message(pending_discord_message, debug=False)
if ok:
print("Discord startup notification sent")
discord_sent = True
else:
discord_send_attempts += 1
if discord_send_attempts >= 3:
print("Discord startup notification failed after retries")
discord_sent = True
except Exception:
# swallow errors here; discord module already handles backoff
if not discord_sent and pending_discord_message and discord_send_attempts < 3:
import gc as _gc # type: ignore
_gc.collect()
_gc.collect()
mem_ok = getattr(_gc, 'mem_free', lambda: 0)() > 140000
if mem_ok:
try:
ok = discord_webhook.send_discord_message(pending_discord_message, debug=False)
if ok:
print("Discord startup notification sent")
discord_sent = True
else:
discord_send_attempts += 1
if discord_send_attempts >= 3:
print("Discord startup notification failed after retries")
discord_sent = True
except Exception:
pass
except Exception:
discord_send_attempts += 1
if discord_send_attempts >= 3:
discord_sent = True
# Run all monitors (each checks if it's time to run via should_run())
run_monitors(monitors)