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
+ "\n STATE: %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 + "\n STATE: %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 + "\n STATE: %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 + "\n STATE: %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 + "\n STATE: %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 + "\n STATE: %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 + "\n STATE: %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 )
0 commit comments