diff --git a/cli_meter.py b/cli_meter.py index f1ee85f..15018ca 100755 --- a/cli_meter.py +++ b/cli_meter.py @@ -39,7 +39,7 @@ a_pin = 18 # Charges the capacitor. b_pin = 23 # Discharges the capacitor. device_id = platform.node() # For servers logs. - +session = requests.Session() # Persist connection for REST calls. def get_api_url(): # Yes, I know I could do this better. Stop moaning. @@ -56,7 +56,6 @@ def discharge(): GPIO.output(b_pin, False) time.sleep(0.01) # 0.01 -- initial/default value. - def charge_time(): GPIO.setup(b_pin, GPIO.IN) GPIO.setup(a_pin, GPIO.OUT) @@ -67,12 +66,10 @@ def charge_time(): t2 = time.time() return (t2 - t1) * 1000000 - def analog_read(): discharge() return charge_time() - def read_resistance(): n = 20 total = 0 @@ -82,23 +79,20 @@ def read_resistance(): resistance = reading * 6.05 - 939 return resistance - def light_from_r(R): return math.log(1000000.0/R) * 10.0 - def get_timestamp(): return datetime.now().strftime(("%Y-%m-%d %H:%M:%S")) - def push_reading(lvalue): time = get_timestamp() headers = {"content-type": "application/json"} payload = {"reading": int(lvalue), "time": time, "token": "QWERTYuiopasdfghjklzxcvbnm_1234567890"} - # print(payload) # For testing. - res = requests.post(api_url, data=json.dumps(payload), headers=headers) - + print(payload) # For testing. + # res = requests.post(api_url, data=json.dumps(payload), headers=headers) + res = session.post(api_url, data=json.dumps(payload), headers=headers) def update_reading(): light = light_from_r(read_resistance()) @@ -113,11 +107,22 @@ def main(): # pdb.set_trace() # For testing. update_reading() except KeyboardInterrupt: - print("Keyboard Interrupt: quitting program.") - except: - print("Error updating light reading...") + print("[INFO] KEYBOARD INTERRUPT: quitting program.") + except requests.exceptions.ConnectionError: + pause = 60 + time.sleep(60) + print(f"[WARNING] MAX. REQUESTS EXCEEDED: Pausing requests for {pause} seconds...") + pass + except requests.exceptions.Timeout: + t_stamp = datetime.datetime.now() + print(f"[WARNING] TIMEOUT EXCEPTION: Request timed-out at {t_stamp}.") + time.sleep(60) + pass + except Exception as e: + print(f"[ERROR] GENERAL EXCEPTION: {e}") finally: - print("Cleaning up GPIO before closing...") + print("[INFO] Terminating relay.py...") + print("[INFO] Cleaning up GPIO before closing...") GPIO.cleanup() diff --git a/startup.sh b/startup.sh index 0d5d912..9af3fcb 100755 --- a/startup.sh +++ b/startup.sh @@ -20,7 +20,7 @@ # times". -sleep 60 +# sleep 60 logDate=$(date '+%Y-%m-%dT%TZ') logFile="/home/rtrp/logs/startup-logs.txt"