-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathapp.py
executable file
·186 lines (146 loc) · 5.57 KB
/
app.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env python
""" Home surveillance application """
import sys
import re
import time
from functools import wraps
from picamera import PiCamera
from telegram import Update, Bot
from telegram.ext import (
Updater,
CommandHandler,
CallbackContext,
)
from config import TOKEN_ID, REGISTRATION_FOLDER, CHAT_ID, VIDEO_TIME
from lib.pir import motion_detected
from lib.camera import Camera
from lib.home_surveillance import HomeSurveillance
#################
# Instantiation #
#################
# Create an instance of the telegram bot
bot = Bot(token=TOKEN_ID)
# Create an instance of HomeSurveillance
surveillance = HomeSurveillance()
# Create an instance of the camera
camera = Camera(PiCamera(), REGISTRATION_FOLDER)
###########
# Utility #
###########
def restricted(func):
"""Restrict usage of func to allowed users only and replies if necessary"""
@wraps(func)
def wrapped(update, context, *args, **kwargs):
chat_id = update.effective_chat.id
if int(chat_id) != int(CHAT_ID):
update.message.reply_text('Unauthorized access.')
return None # quit function
return func(update, context, *args, **kwargs)
return wrapped
###############
# Bot command #
###############
@restricted
def start(update: Update, context: CallbackContext) -> None:
"""Command /start: start surveillance."""
surveillance.start()
context.bot.send_message(chat_id=CHAT_ID, text="Surveillance is start")
@restricted
def stop(update: Update, context: CallbackContext) -> None:
"""Command /stop: stop surveillance."""
surveillance.stop()
context.bot.send_message(chat_id=CHAT_ID, text="Surveillance is stop")
@restricted
def status(update: Update, context: CallbackContext) -> None:
"""Command /status: show surveillance status."""
context.bot.send_message(
chat_id=CHAT_ID,
text="Surveillance is active" if surveillance.is_start else "Surveillance is deactivated"
)
@restricted
def man(update: Update, context: CallbackContext) -> None:
"""Command /help: show help."""
usage = "command help:\n"
usage += "\t/start : start the home monitoring system \n"
usage += "\t/stop : stop the home monitoring system\n"
usage += "\t/status : show the status of the monitoring system \n"
usage += "\t/photo : take a picture\n"
usage += "\t/video time=<duration> : records a video, by default duration is " \
+ str(VIDEO_TIME) \
+ "s \n"
usage += "\t/clean : remove all files in video folder\n"
usage += "\t/help : show help\n"
context.bot.send_message(chat_id=CHAT_ID, text=usage)
@restricted
def photo(update: Update, context: CallbackContext) -> None:
""" Command /photo: take a photo"""
with open(camera.take_photo(), 'rb') as img:
context.bot.send_photo(chat_id=CHAT_ID, photo=img)
@restricted
def video(update: Update, context: CallbackContext) -> None:
"""
Command /video: record a video
Takes an argument named time, corresponds to the duration of the video
example: /video time=30 for take a video of 30s
"""
duration = VIDEO_TIME
# Parse args to get duration value
if context.args:
key, value = context.args[0].split('=')
if key == 'time':
if re.match(r'\d+', value):
duration = value
else:
context.bot.send_message(
chat_id=CHAT_ID,
text=F"Duration of the video not correct: {value}"
)
else:
context.bot.send_message(chat_id=CHAT_ID, text=F"Argument {key} not recognized")
# Start video recording
try:
with open(camera.start_recording(duration), 'rb') as video_file:
context.bot.send_video(chat_id=CHAT_ID, video=video_file)
except OSError as err:
context.bot.send_message(chat_id=CHAT_ID, text=str(err))
@restricted
def clean(update: Update, context: CallbackContext) -> None:
""" command /clean: remove file in REGISTRATION_FOLDER """
try:
context.bot.send_message(chat_id=CHAT_ID, text=camera.purge_records())
except OSError as err:
context.bot.send_message(chat_id=CHAT_ID, text=str(err))
def main() -> None:
"""Run the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater(TOKEN_ID)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("stop", stop))
dispatcher.add_handler(CommandHandler("status", status))
dispatcher.add_handler(CommandHandler("help", man))
dispatcher.add_handler(CommandHandler("photo", photo))
dispatcher.add_handler(CommandHandler("video", video, pass_args=True))
dispatcher.add_handler(CommandHandler("clean", clean))
# Start the Bot
updater.start_polling()
# Infinite loop, if a motion is detected and surveillance is start
# a video recording is taken and sent through the telegram bot.
while True:
if surveillance.is_start and motion_detected():
try:
with open(camera.start_recording(VIDEO_TIME), 'rb') as video_file:
bot.send_video(chat_id=CHAT_ID, video=video_file, caption="Motion detected")
except OSError as err:
bot.send_message(chat_id=CHAT_ID, text=str(err))
if surveillance.is_interrupted:
break
time.sleep(1)
print("Stop the bot")
updater.stop()
print('Exit')
sys.exit(0)
if __name__ == '__main__':
main()