Skip to content

Commit 29732aa

Browse files
committed
Refactor part 1
1 parent 073e159 commit 29732aa

8 files changed

+734
-713
lines changed

autocopter.py

+500-121
Large diffs are not rendered by default.

dronekit_functions.py

-540
This file was deleted.

log_and_messages.py

-14
This file was deleted.

other_functions.py

-21
This file was deleted.

requrements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
dronekit==2.9.1

telegrambot.py

+206
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf8 -*-
3+
4+
import time
5+
import traceback
6+
import telepot
7+
from telepot.loop import MessageLoop
8+
9+
import sys
10+
reload(sys)
11+
sys.setdefaultencoding('utf8')
12+
13+
class TelegramBot(object):
14+
"""
15+
Здесь находится метод для создания отладочных сообщений,
16+
а также здесь крутиться в отдельном потоке метод обработки
17+
пользовательских сообщений
18+
"""
19+
20+
def __init__(self, _token, _chat_id, _debug, _autocopter):
21+
self.bot = telepot.Bot(_token)
22+
self.chat_id = _chat_id
23+
self.debug = _debug
24+
self.autocopter = _autocopter
25+
telepot.api.set_proxy('http://200.172.103.227:20183')
26+
27+
def debug_message(self, msg):
28+
if self.debug:
29+
try:
30+
print msg
31+
self.bot.sendMessage(self.chat_id, msg)
32+
except Exception as ex:
33+
print "Произошла ошибка при отправке сообщения:\n" + ex.message + "\n" + traceback.format_exc()
34+
35+
def start_handler(self):
36+
MessageLoop(self.bot, self.handle).run_as_thread()
37+
38+
def handle(self, msg):
39+
"""
40+
хендлер выполняется в отдельном потоке,
41+
вызывается событием на подобие блокирующей очереди
42+
"""
43+
content_type, chat_type, chat_id = telepot.glance(msg)
44+
if self.debug:
45+
print(content_type, chat_type, chat_id)
46+
if chat_id == self.chat_id:
47+
if content_type == 'text':
48+
self.debug_message(self.new_command(msg['text']))
49+
elif content_type == 'location':
50+
self.debug_message(self.new_command('create_mission', msg['location']))
51+
elif content_type == 'sticker':
52+
self.new_command('get_location')
53+
else:
54+
self.debug_message("Ошибка 2! Неверный тип: только text и location")
55+
else:
56+
self.debug_message("Ошибка 1! Access error!")
57+
58+
def new_command(self, command, params = None):
59+
if self.autocopter.current_state == States.INIT:
60+
return "Ошибка 3! Некорректная команда %s" % command + " для состояния %s" % self.autocopter.current_state
61+
62+
elif self.autocopter.current_state == States.IDLE:
63+
if command == '/status':
64+
# вывод информации о коптере, ip, заряд батареи
65+
return "copter ip: %s" % get_ip() + \
66+
"\nSTATE: %s" % self.autocopter.current_state + \
67+
"\n%s" % self.autocopter.get_status
68+
elif command == 'create_mission':
69+
self.autocopter.new_state(States.TAKEOFF)
70+
return self.autocopter.create_mission(params['latitude'], params['longitude'])
71+
elif command == '/takeoff':
72+
self.autocopter.new_state(States.TAKEOFF)
73+
#return "Взлет из состояния: %s" % self.autocopter.current_state
74+
elif command == 'get_location':
75+
lat, lon = self.autocopter.get_location()
76+
self.bot.sendLocation(self.chat_id, lat, lon)
77+
else:
78+
return 'Ошибка 3! Некорректная команда ' + command + " для состояния %s" % self.autocopter.current_state
79+
80+
elif self.autocopter.current_state == States.TAKEOFF:
81+
if command == '/status':
82+
# вывод информации о коптере, ip, заряд батареи
83+
return "copter ip: " + get_ip() + "\n" + self.autocopter.get_status + "\nSTATE: %s" % self.autocopter.current_state
84+
elif command == 'create_mission':
85+
return self.autocopter.create_mission(params['latitude'], params['longitude'])
86+
elif command == '/land':
87+
self.autocopter.new_state(States.LAND)
88+
return "Посадка из состояния: %s" % self.autocopter.current_state
89+
elif command == '/hover':
90+
self.autocopter.new_state(States.HOVER)
91+
return "Зависнуть из состояния: %s" % self.autocopter.current_state
92+
elif command == 'get_location':
93+
lat, lon = self.autocopter.get_location()
94+
self.bot.sendLocation(self.chat_id, lat, lon)
95+
else:
96+
return "Ошибка 3! Некорректная команда " + command + " для состояния %s" % self.autocopter.current_state
97+
98+
elif self.autocopter.current_state == States.HOVER:
99+
if command == '/status':
100+
# вывод информации о коптере, ip, заряд батареи
101+
return "copter ip: " + get_ip() + "\n" + self.autocopter.get_status + "\nSTATE: %s" % self.autocopter.current_state
102+
elif command == 'create_mission':
103+
return self.autocopter.create_mission(params['latitude'], params['longitude'])
104+
elif command == '/land':
105+
self.autocopter.new_state(States.LAND)
106+
return "Посадка из состояния: %s" % self.autocopter.current_state
107+
elif command == '/rtl':
108+
self.autocopter.new_state('RTL')
109+
return "Возврат на точку взлета из состояния: %s" % self.autocopter.current_state
110+
elif command == '/auto':
111+
self.autocopter.new_state(States.AUTO)
112+
return "Автопилот из состояния: %s" % self.autocopter.current_state
113+
elif command == '/goto':
114+
self.autocopter.new_state(States.GOTO)
115+
return "Полет по координатам из состояния: %s" % self.autocopter.current_state
116+
elif command == 'get_location':
117+
lat, lon = self.autocopter.get_location()
118+
self.bot.sendLocation(self.chat_id, lat, lon)
119+
else:
120+
return "Ошибка 3! Некорректная команда " + command + " для состояния %s" % self.autocopter.current_state
121+
122+
elif self.autocopter.current_state == States.GOTO:
123+
if command == '/status':
124+
# вывод информации о коптере, ip, заряд батареи
125+
return "copter ip: " + get_ip() + "\n" + self.autocopter.get_status + "\nSTATE: %s" % self.autocopter.current_state
126+
elif command == '/land':
127+
self.autocopter.new_state(States.LAND)
128+
return "Посадка из состояния: %s" % self.autocopter.current_state
129+
elif command == '/rtl':
130+
self.autocopter.new_state('RTL')
131+
return "Возврат на точку взлета из состояния: %s" % self.autocopter.current_state
132+
elif command == '/hover':
133+
self.autocopter.new_state(States.HOVER)
134+
return "Зависнуть из состояния: %s" % self.autocopter.current_state
135+
elif command == 'get_location':
136+
lat, lon = self.autocopter.get_location()
137+
self.bot.sendLocation(self.chat_id, lat, lon)
138+
else:
139+
return 'Ошибка 3! Некорректная команда ' + command + " для состояния %s" % self.autocopter.current_state
140+
141+
elif self.autocopter.current_state == States.LAND:
142+
if command == '/status':
143+
# вывод информации о коптере, ip, заряд батареи
144+
return "copter ip: " + get_ip() + "\n" + self.autocopter.get_status + "\nSTATE: %s" % self.autocopter.current_state
145+
elif command == 'create_mission':
146+
return self.autocopter.create_mission(params['latitude'], params['longitude'])
147+
elif command == '/hover':
148+
self.autocopter.new_state(States.HOVER)
149+
return "Зависнуть из состояния: %s" % self.autocopter.current_state
150+
elif command == 'get_location':
151+
lat, lon = self.autocopter.get_location()
152+
self.bot.sendLocation(self.chat_id, lat, lon)
153+
else:
154+
return 'Ошибка 3! Некорректная команда ' + command + " для состояния %s" % self.autocopter.current_state
155+
156+
elif self.autocopter.current_state == States.AUTO:
157+
if command == '/status':
158+
# вывод информации о коптере, ip, заряд батареи
159+
return "copter ip: " + get_ip() + "\n" + self.autocopter.get_status + "\nSTATE: %s" % self.autocopter.current_state + '\nРасстояние до следующего WP: ' + self.distance_to_current_waypoint + "м"
160+
elif command == '/land':
161+
self.autocopter.new_state(States.LAND)
162+
return "Посадка из состояния: %s" % self.autocopter.current_state
163+
elif command == '/rtl':
164+
self.autocopter.new_state('RTL')
165+
return "Возврат на точку взлета из состояния: %s" % self.autocopter.current_state
166+
elif command == '/hover':
167+
self.autocopter.new_state(States.HOVER)
168+
return "Зависнуть из состояния: %s" % self.autocopter.current_state
169+
elif command == 'get_location':
170+
lat, lon = self.autocopter.get_location()
171+
self.bot.sendLocation(self.chat_id, lat, lon)
172+
else:
173+
return 'Ошибка 3! Некорректная команда ' + command + " для состояния %s" % self.autocopter.current_state
174+
175+
elif self.autocopter.current_state == States.RTL:
176+
if command == '/status':
177+
# вывод информации о коптере, ip, заряд батареи
178+
return "copter ip: " + get_ip() + "\n" + self.autocopter.get_status + "\nSTATE: %s" % self.autocopter.current_state
179+
elif command == '/land':
180+
self.autocopter.new_state(States.LAND)
181+
return "Посадка из состояния: %s" % self.autocopter.current_state
182+
elif command == '/hover':
183+
self.autocopter.new_state(States.HOVER)
184+
return "Зависнуть из состояния: %s" % self.autocopter.current_state
185+
elif command == 'get_location':
186+
lat, lon = self.autocopter.get_location()
187+
self.bot.sendLocation(self.chat_id, lat, lon)
188+
else:
189+
return "Ошибка 3! Некорректная команда " + command + " для состояния " + self.autocopter.current_state
190+
191+
else:
192+
return "Ошибка 4! Нет обработчика для состояния: " + self.autocopter.current_state
193+
194+
if __name__ == "__main__":
195+
from autocopter import States
196+
class Autocopter(object):
197+
def __init__(self):
198+
self.current_state = States.IDLE
199+
def get_location(self):
200+
return 53, 50
201+
autocopter = Autocopter()
202+
bot = TelegramBot("326953186:AAHGxltq7oYvgfJXh0_76O96pGIpeKr8x-Q", 62922848, True, autocopter)
203+
bot.start_handler()
204+
bot.debug_message("Listening...")
205+
while 1:
206+
time.sleep(10)

tests/dronekit_test.py

+10-7
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
#!/usr/bin/python
22
# -*- coding: utf8 -*-
33

4-
from dronekit import connect, VehicleMode
4+
from dronekit import connect
55

6-
def get_status(vehicle):
7-
buf = "\nGPS: %s" % vehicle.gps_0 + \
8-
"\nBattery: %s" % vehicle.battery + \
9-
"\nLast Heartbeat: %s" % vehicle.last_heartbeat + \
6+
def get_status(_vehicle):
7+
"""
8+
Get some vehicle atribute values
9+
"""
10+
buf = "\nGPS: %s" % _vehicle.gps_0 + \
11+
"\nBattery: %s" % _vehicle.battery + \
12+
"\nLast Heartbeat: %s" % _vehicle.last_heartbeat + \
1013
"\nIs Armable?: %s" % vehicle._is_armable + \
11-
"\nSystem status: %s" % vehicle.system_status.state + \
12-
"\nMode: %s" % vehicle.mode.name
14+
"\nSystem status: %s" % _vehicle.system_status.state + \
15+
"\nMode: %s" % _vehicle.mode.name
1316
return buf
1417

1518
vehicle = connect('tcp:127.0.0.1:14600', wait_ready=True)

tests/telepot_test.py

+17-10
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,31 @@
11
#!/usr/bin/python
22
# -*- coding: utf8 -*-
33

4-
# USE: python ./tepelot_test.py 'BOT_TOKEN' ['CHAT_ID']
4+
# http://telepot.readthedocs.io/en/latest/
55

6-
import sys, telepot
7-
import http.client
6+
import sys
7+
import time
8+
import telepot
9+
from telepot.loop import MessageLoop
810

911
def handle(msg):
1012
content_type, chat_type, chat_id = telepot.glance(msg)
1113
print(content_type, chat_type, chat_id)
14+
print params
1215

1316
if content_type == 'text':
1417
bot.sendMessage(chat_id, msg['text'])
15-
msg['text'] == '/start':
16-
else:
17-
bot.sendMessage(chat_id, 'Bad command!')
1818

19-
bot = telepot.Bot(sys.argv[1])
20-
bot.message_loop(handle)
19+
TOKEN = sys.argv[1] # get token from command-line
20+
21+
bot = telepot.Bot(TOKEN)
22+
23+
#telepot.api.set_proxy('http://........')
24+
#telepot.api.set_proxy('http://........', ('username', 'password'))
25+
26+
MessageLoop(bot, handle).run_as_thread()
2127
print ('Listening ...')
2228

23-
if (len(sys.argv) == 3):
24-
bot.sendMessage(sys.argv[2], "Hello world!")
29+
# Keep the program running.
30+
while 1:
31+
time.sleep(10)

0 commit comments

Comments
 (0)