-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
86 lines (69 loc) · 2.61 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import sys
import dotenv
import time
import RPi.GPIO as GPIO
import discord
from logging.handlers import RotatingFileHandler
import logging
dotenv.load_dotenv()
DISCORD_TOKEN = os.environ['DISCORD_TOKEN']
client = discord.Client()
OUTPUT_PIN = 40
SCRIPT_DIR = os.path.realpath(os.path.dirname(__file__))
def init_logging(log_file_path=None, max_file_size_bytes=5000000, backups=10, file_level=logging.DEBUG, stdout_level=logging.INFO, disable_noisy_loggers=True):
handlers = []
handler = logging.StreamHandler()
handler.setLevel(stdout_level)
handlers.append(handler)
if log_file_path:
handler = RotatingFileHandler(log_file_path, maxBytes=max_file_size_bytes, backupCount=backups, encoding='utf-8')
handler.setLevel(file_level)
handlers.append(handler)
if disable_noisy_loggers:
logging.getLogger('werkzeug').setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("backoff").setLevel(logging.WARNING)
logging.getLogger("chardet").setLevel(logging.WARNING)
logging.getLogger("chardet.charsetprober").setLevel(logging.WARNING)
logging.getLogger("chardet.universaldetector").setLevel(logging.WARNING)
logging.getLogger("discord").setLevel(logging.WARNING)
logging.basicConfig(handlers=handlers,
level=min(file_level, stdout_level),
format='%(asctime)s %(levelname)s - %(message)s')
@client.event
async def on_message(message):
if message.author == client.user:
return
logging.info(f'Incoming command to open garage from {message.author}: {message.content}')
response = '👍'
try:
open_garage()
except Exception as e:
response = f'⚠ {e}'
await message.channel.send(response)
def open_garage():
GPIO.output(OUTPUT_PIN, GPIO.LOW)
time.sleep(0.8)
GPIO.output(OUTPUT_PIN, GPIO.HIGH)
def main():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(OUTPUT_PIN, GPIO.OUT)
GPIO.output(OUTPUT_PIN, GPIO.HIGH)
client.run(DISCORD_TOKEN)
if __name__ == '__main__':
try:
log_dir_path = os.path.join(SCRIPT_DIR, 'logs')
os.makedirs(log_dir_path, exist_ok=True)
log_file_name = 'service.log'
log_file_path = os.path.join(log_dir_path, log_file_name)
init_logging(log_file_path=log_file_path)
logging.info('Starting garage door opener...')
main()
except KeyboardInterrupt:
pass
except Exception as e:
logging.exception(f'Error: {e}')
finally:
GPIO.cleanup()
logging.info('Garage door opener stopped.')