-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathscript.py
327 lines (304 loc) · 10.8 KB
/
script.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# -*- coding: utf-8 -*-
################ ITIS Paleocapa 2018 ################
# Main developers: Cristian Livella, Matteo Soldini #
# Project: Esperia Time Art #
#####################################################
import threading, time, telepot, telepot.loop, sys, os, requests, random
### CONFIGURAZIONE ###
# Token bot Telegram
botToken = "0123456789:BOT_TOKEN"
# Chat id consentiti
allowedChatId = []
# Colori
colors = [
"white",
"red",
"red2",
"green",
"green2",
"blue",
"blue2",
"blue3",
"orange",
"orange2",
"purple",
"purple2",
"ciano",
"ciano2",
"yellow",
"fuchsia"
]
# IP Arduino
ips = [
"10.205.0.11",
"10.205.0.12",
"10.205.0.13",
"10.205.0.14",
"10.205.0.15",
"10.205.0.16",
"10.205.0.17",
"10.205.0.18",
]
# Numero di giochi disponibili
nGiochi = 4
verbose = 2
#########################################
### NON MODIFICARE SOTTO QUESTA LINEA ###
#########################################
arduinoOnline = [0] * len(ips)
timeDelay = 500
stato = 0
class ThreadManager(threading.Thread):
def __init__(self, function):
self.running = False
self.function = function
super(ThreadManager, self).__init__()
def start(self):
self.running = True
super(ThreadManager, self).start()
def run(self):
while self.running:
try:
self.function()
except:
pass
def stop(self):
self.running = False
def checkArduinoOnline():
global arduinoOnline
if (verbose>=2):
print('INIZIO CHECK ARDUINO ONLINE..')
for x in range(len(ips)):
try:
requests.get('http://'+ips[x], timeout=0.5)
arduinoOnline[x] = 1
if (verbose>=2):
print('Arduino a '+ips[x]+': ONLINE')
except:
arduinoOnline[x] = 0
if (verbose>=2):
print('Arduino a '+ips[x]+': OFFLINE')
time.sleep(10)
def countArduinoOnline():
count = 0
for x in range(len(ips)):
if (arduinoOnline[x]==1):
count += 1
return count
def getStato():
if (stato==0):
return 'off'
else:
return 'gioco '+str(stato)
def startGameThread():
global gameThread
if (verbose>=1):
print('AVVIO GAME THREAD...')
try:
gameThread = ThreadManager(function = lightGame)
gameThread.start()
if (verbose>=2):
print('Game thread avviato')
except:
if (verbose>=2):
print('Impossibile avviare il game thread (potrebbe essere già attivo)')
def stopGameThread():
global gameThread
if (verbose>=1):
print('STOP GAME THREAD...')
try:
gameThread.stop()
if (verbose>=2):
print('Game thread stoppato')
except:
if (verbose>=2):
print('Impossibile stoppare il game thread (potrebbe essere già stoppato')
def lightsOff():
errorCount = 0
if (verbose>=1):
print('INVIO COMANDO SPEGNIMENTO ALLE LAMPADE...')
for ip in ips:
try:
requests.get('http://'+ip+'?ledoff', timeout=0.2)
if (verbose>=2):
print("Comando di spegnimento inviato correttamente a "+ip)
except:
if (verbose>=2):
print("ERRORE nell\'invio del comando di spegnimento a "+ip)
errorCount += 1
return errorCount
def handle(msg):
global stato
global timeDelay
global bot
try:
if (verbose>=2):
print('Ricevuto messaggio Telegram da '+str(msg['from']['id'])+': '+msg['text'])
chatId = msg['from']['id']
message = msg['text'].lower()
if (not chatId in allowedChatId):
bot.sendMessage(chatId, '*Ciao!*\nNon sei autorizzato ad utilizzare questo bot.\n\nQuesto è il tuo *chatId*: '+str(chatId)+'.', parse_mode='markdown')
return
if (message=='/start' or message=='start' or message=='/info' or message=='info' or message=='/help' or message=='help'):
text = '*- TIME ART BOT -*\n\nArduino list:\n'
for x in range(len(ips)):
text += ips[x]+': '
if arduinoOnline[x]==1:
text += 'online'
else:
text += 'offline'
text += '\n'
text += '\nTime delay: '+str(timeDelay)+' ms\n\n*Comandi:*\n/off -> spegne tutte le lampade\n/game \[ID] -> avvia il gioco di luce [ID] da 1 a 4\n/setTime \[TEMPO] -> imposta il delay tra ogni azione del gioco (millisecondi)'
bot.sendMessage(chatId, text, parse_mode='markdown')
elif (message=='/off' or message=='off'):
stopGameThread()
stato = 0
errorCode = lightsOff()
if (errorCode==0):
bot.sendMessage(chatId, 'Comando di spegnimento inviato correttamente a tutte le lampade.')
else:
bot.sendMessage(chatId, 'Problema con l\'invio del comando di spegnimento a '+str(errorCode)+' lampade.')
elif (message[0:5]=='/game' or message[0:4]=='game'):
try:
lightGame = int(message.replace('/', '').replace('game', ''))
except:
bot.sendMessage(chatId, 'Id gioco non valido.', parse_mode='markdown')
return
if (not lightGame in range(1, nGiochi+1)):
bot.sendMessage(chatId, 'Id gioco non valido.', parse_mode='markdown')
return
try:
gameThread.stop()
except:
pass
for ip in ips:
try:
requests.get('http://'+ip+'?ledoff', timeout=0.2)
except:
pass
try:
stato = lightGame
startGameThread()
bot.sendMessage(chatId, 'Gioco di luce '+str(lightGame)+' avviato!')
except:
bot.sendMessage(chatId, 'Errore con l\'avvio del thread.')
stato = 0
elif (message[0:8]=='/settime' or message[0:7]=="settime"):
try:
time = int(message.replace('/', '').replace('settime', ''))
except:
bot.sendMessage(chatId, 'Tempo non valido.', parse_mode='markdown')
return
if (not time in range (0, 100000)):
bot.sendMessage(chatId, 'Tempo non valido.', parse_mode='markdown')
return
timeDelay = time
bot.sendMessage(chatId, 'Delay impostato a '+str(timeDelay)+' ms.', parse_mode='markdown')
else:
bot.sendMessage(chatId, 'Comando non riconosciuto.\n\nScrivi /help per la lista dei comandi.', parse_mode='markdown')
except:
pass
def lightGame():
thisStato = stato
if (stato==0):
stopGameThread()
ligthsOff()
return
if (stato==1):
if (verbose>=1):
print('Partenza ciclo gioco 1')
for color in colors:
for ip in range(0,len(ips)-1):
if (stato!=thisStato):
break
try:
if (verbose>=2):
print('Invio '+color+' a '+ips[ip])
requests.get('http://'+ips[ip]+'?'+color, timeout=0.1)
if (verbose>=2):
print('Delay '+str(timeDelay*0.001))
time.sleep(timeDelay*0.001)
if (verbose>=2):
print('Invio comando di spegnimento a '+ips[ip])
requests.get('http://'+ips[ip]+'?ledoff')
except requests.exceptions.RequestException:
print('Errore a '+ips[ip])
for ip in range(len(ips)-1,0,-1):
if (stato!=thisStato):
break
try:
if (verbose>=2):
print('Invio '+color+' a '+ips[ip])
requests.get('http://'+ips[ip]+'?'+color, timeout=0.1)
if (verbose>=2):
print('Delay '+str(timeDelay*0.001))
time.sleep(timeDelay*0.001)
if (verbose>=2):
print('Invio comando di spegnimento a '+ips[ip])
requests.get('http://'+ips[ip]+'?ledoff')
except requests.exceptions.RequestException:
print('Errore a '+ips[ip])
if (stato==2):
if (verbose>=1):
print('Partenza ciclo gioco 2')
for color in colors:
for ip in ips:
if (stato!=thisStato):
break
try:
if (verbose>=2):
print('Invio '+color+' a '+ip)
requests.get('http://'+ip+'?'+color, timeout=0.1)
except requests.exceptions.RequestException:
print('Errore a '+ip)
if (verbose>=2):
print('Delay '+str(timeDelay*0.001))
time.sleep(timeDelay*0.001)
if (stato==3):
if (verbose>=1):
print('Partenza ciclo gioco 3')
for color in colors:
for i in range(0,len(ips)-1):
if (stato!=thisStato):
break
try:
print('Sending '+random.choice(colors)+' at '+ips[i])
requests.get('http://'+ips[i]+'?'+color, timeout=0.1)
print('Sending '+random.choice(colors)+' at '+ips[len(ips)-i-1])
requests.get('http://'+ips[len(ips)-i-1]+'?'+color, timeout=0.1)
time.sleep(timeDelay*0.001)
requests.get('http://'+ips[i]+'?off', timeout=0.1)
requests.get('http://'+ips[len(ips)-i-1]+'?off', timeout=0.1)
print('Sending off')
except requests.exceptions.RequestException:
print('Error sending command')
for i in range(len(ips)-1,0,-1):
if (stato!=thisStato):
break
try:
print('Sending '+random.choice(colors)+' at '+ips[i])
requests.get('http://'+ips[i]+'?'+color, timeout=0.1)
print('Sending '+random.choice(colors)+' at '+ips[len(ips)-i-1])
requests.get('http://'+ips[len(ips)-i-1]+'?'+color, timeout=0.1)
time.sleep(timeDelay*0.001)
requests.get('http://'+ips[i]+'?off', timeout=0.1)
requests.get('http://'+ips[len(ips)-i-1]+'?off', timeout=0.1)
print('Sending off')
except requests.exceptions.RequestException:
print('Error sending command')
if (stato==4):
if (verbose>=1):
print('Partenza ciclo gioco 4')
try:
requests.get('http://'+random.choice(ips)+'?'+random.choice(colors), timeout=0.1)
time.sleep(timeDelay*0.001)
except requests.exceptions.RequestException:
print('Error sending command')
print("TIME ART DAEMON - V. 1.0.0")
# AVVIO BOT TELEGRAM #
bot = telepot.Bot(botToken)
telepot.loop.MessageLoop(bot, handle).run_as_thread()
print("Telegram bot: ok")
# THREAD PER CONTROLLO CONTINUO STATO ARDUINO #
checkThread = ThreadManager(function = checkArduinoOnline)
checkThread.start()