|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import time, os, sys |
| 4 | +import json |
| 5 | + |
| 6 | +import BlynkLib |
| 7 | +import BlynkEdgent |
| 8 | +import RPi.GPIO as GPIO |
| 9 | + |
| 10 | +# -- Configuration -------------------- |
| 11 | +BLYNK_TEMPLATE_ID = "" |
| 12 | +BLYNK_DEVICE_NAME = "" |
| 13 | + |
| 14 | +BLYNK_FIRMWARE_VERSION = "0.1.0" |
| 15 | + |
| 16 | +BUTTON_GPIO = 16 |
| 17 | +# ------------------------------------- |
| 18 | + |
| 19 | +try: |
| 20 | + with open("config.json") as jsonFile: |
| 21 | + config = json.load(jsonFile) |
| 22 | + needToSave = False |
| 23 | +except: |
| 24 | + config = BlynkEdgent.provision(BLYNK_DEVICE_NAME, BLYNK_TEMPLATE_ID, BLYNK_FIRMWARE_VERSION, prefix="Beemate") |
| 25 | + needToSave = True |
| 26 | + |
| 27 | +def reset_config(): |
| 28 | + if os.path.exists("config.json"): |
| 29 | + print("Resetting configuration") |
| 30 | + os.remove("config.json") |
| 31 | + # Restart |
| 32 | + os.execv(sys.executable, ['python3'] + sys.argv) |
| 33 | + sys.exit(0) |
| 34 | + |
| 35 | +# Initialize Blynk |
| 36 | +blynk = BlynkLib.Blynk(config['auth'], |
| 37 | + server = config['server'], |
| 38 | + port = config['port_ssl'], |
| 39 | + tmpl_id = BLYNK_TEMPLATE_ID, |
| 40 | + fw_ver = BLYNK_FIRMWARE_VERSION) |
| 41 | + |
| 42 | +@blynk.on("connected") |
| 43 | +def blynk_connected(ping): |
| 44 | + print('Blynk ready. Ping:', ping, 'ms') |
| 45 | + if needToSave: |
| 46 | + with open('config.json', 'w') as jsonFile: |
| 47 | + json.dump(config, jsonFile) |
| 48 | + print("Configuration is saved") |
| 49 | + |
| 50 | +@blynk.on("disconnected") |
| 51 | +def blynk_disconnected(): |
| 52 | + print('Blynk disconnected') |
| 53 | + |
| 54 | +@blynk.on("V*") |
| 55 | +def blynk_handle_vpins(pin, value): |
| 56 | + print("V{} value: {}".format(pin, value)) |
| 57 | + |
| 58 | +def button_callback(channel): |
| 59 | + if GPIO.input(channel) == 1: |
| 60 | + return |
| 61 | + |
| 62 | + print("Hold button for 10 seconds to reset configuration") |
| 63 | + start_time = time.time() |
| 64 | + # Wait for the button up |
| 65 | + while (GPIO.input(channel) == 0 and |
| 66 | + time.time() - start_time <= 10): |
| 67 | + time.sleep(0.1) |
| 68 | + if time.time() - start_time > 10: |
| 69 | + reset_config() |
| 70 | + |
| 71 | +# Main |
| 72 | + |
| 73 | +GPIO.setmode(GPIO.BCM) |
| 74 | +GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP) |
| 75 | + |
| 76 | +GPIO.add_event_detect(BUTTON_GPIO, GPIO.BOTH, |
| 77 | + callback=button_callback, bouncetime=50) |
| 78 | + |
| 79 | +def blynk_connect_with_retries(): |
| 80 | + while True: |
| 81 | + try: |
| 82 | + blynk.connect() |
| 83 | + return |
| 84 | + except Exception as e: |
| 85 | + print(e) |
| 86 | + time.sleep(1) |
| 87 | + |
| 88 | +blynk_connect_with_retries() |
| 89 | + |
| 90 | +while True: |
| 91 | + blynk.run() |
0 commit comments