Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

540 linhas
13 KiB

  1. import subprocess
  2. import sys, inspect, os
  3. import wiringpi
  4. import time
  5. from datetime import datetime
  6. from time import sleep
  7. import lirc
  8. import random
  9. import mpd
  10. from pyudmx import pyudmx
  11. import talkey
  12. # HTTP Server
  13. from twisted.web import server, resource
  14. from twisted.internet import reactor
  15. class Simple(resource.Resource):
  16. isLeaf = True
  17. def render_GET(self, request):
  18. statustext = ""
  19. if inUse:
  20. statustext = "true"
  21. else:
  22. statustext = "false"
  23. html = '[{"inuse":"%s"}]' % statustext
  24. return html.encode('utf-8')
  25. # GPIO
  26. pin_kugel = 2 # Input: dico ball + DMX on/off
  27. pin_sun = 4 # Input: light bulb on/off
  28. pin_pir = 0 # Output: PIR sensor
  29. pin_door = 11 # Output: door open/closed sensor
  30. # for system stuff
  31. dmxScenes = {
  32. "fadecolors":[255,255,255,255,255,192],
  33. "plain-red":[255,255,0,0,0,0],
  34. "strobe":[190,255,255,255,0,0],
  35. "nini":[120,0,255,255,0,224],
  36. "black":[0,0,0,0,0,0]
  37. }
  38. bye_sayings = [
  39. "Goodbye!",
  40. "Bye!",
  41. "Bye bye!",
  42. "See you!",
  43. #"Ciao!",
  44. "Have a nice day!",
  45. "Thank's for using!",
  46. #"I'm off!",
  47. "Take it easy!",
  48. "I look forward to our next meeting!",
  49. "Take care!",
  50. "See you later!",
  51. "This was nice. See you!",
  52. "Peace!"
  53. ]
  54. dmxUserScenes = [
  55. [255,255,255,255,255,192],
  56. [255,0,180,180,0,0],
  57. [255,255,0,0,0,0],
  58. [255,0,255,0,0,0],
  59. [255,0,0,255,0,0],
  60. [190,255,255,255,0,0],
  61. [120,0,255,255,0,224]
  62. ]
  63. # no strobe etc.
  64. dmxStartupScenes = [
  65. [255,255,255,255,255,192],
  66. [255,0,180,180,0,0],
  67. [255,255,0,0,0,0],
  68. [255,0,255,0,0,0],
  69. [255,0,0,255,0,0],
  70. [120,0,255,255,0,224]
  71. ]
  72. # Set a dmx scene by name
  73. def setDmxScene(scene):
  74. # a universe of zeros
  75. cv = [0 for v in range(0, 512)]
  76. errorcode = [240,255,0,0,0,0]
  77. for index, val in enumerate(dmxScenes.get(scene,errorcode)):
  78. cv[index] = val
  79. dev.send_multi_value(1, cv)
  80. # Set random startup dmx scene
  81. def setStartupDmxScene():
  82. # a universe of zeros
  83. cv = [0 for v in range(0, 512)]
  84. errorcode = [240,255,0,0,0,0]
  85. # get a random scene index
  86. scene = random.choice(list(enumerate(dmxStartupScenes)))[0]
  87. print(scene)
  88. for index, val in enumerate(dmxStartupScenes[scene]):
  89. cv[index] = val
  90. dev.send_multi_value(1, cv)
  91. # Switch betweeb user dmx scenes
  92. def setUserDmxScene():
  93. # loop through scenes
  94. global dmxScene
  95. if dmxScene < len(dmxUserScenes)-1:
  96. dmxScene += 1
  97. else:
  98. dmxScene = 0
  99. # setup the universe
  100. cv = [0 for v in range(0, 512)]
  101. for index, val in enumerate(dmxUserScenes[dmxScene]):
  102. cv[index] = val
  103. dev.send_multi_value(1, cv)
  104. def setKugel(state):
  105. if state == 'on':
  106. wiringpi.digitalWrite(pin_kugel, 0)
  107. if state == 'off':
  108. wiringpi.digitalWrite(pin_kugel, 1)
  109. def setSun(state):
  110. if state == 'off':
  111. wiringpi.digitalWrite(pin_sun, 0)
  112. if state == 'on':
  113. wiringpi.digitalWrite(pin_sun, 1)
  114. def startMusic(playlist, single=False, shuffle=True, repeat=True):
  115. try:
  116. client.clear() # clear playlist
  117. except Exception:
  118. client.connect("localhost", 6600)
  119. client.clear() # clear playlist
  120. client.add(playlist) # add file/directory to playlist
  121. if shuffle:
  122. client.shuffle() # shuffle playlist
  123. if repeat:
  124. client.repeat(1) # set playback mode repeat
  125. else:
  126. client.repeat(0) # set playback mode repeat
  127. if single:
  128. client.repeat(0) # set playback mode repeat
  129. client.single(1) # set playback mode single
  130. else:
  131. client.single(0) # set playback mode single
  132. client.setvol(80)# set volume
  133. client.play() # play
  134. def playMusic():
  135. try:
  136. client.play()
  137. except Exception:
  138. client.connect("localhost", 6600)
  139. client.play()
  140. def pauseMusic():
  141. try:
  142. client.pause()
  143. except Exception:
  144. client.connect("localhost", 6600)
  145. client.pause()
  146. def stopMusic():
  147. try:
  148. client.stop()
  149. except Exception:
  150. client.connect("localhost", 6600)
  151. client.stop()
  152. def nextSong():
  153. try:
  154. client.next()
  155. except Exception:
  156. client.connect("localhost", 6600)
  157. client.next()
  158. def previousSong():
  159. try:
  160. client.previous()
  161. except Exception:
  162. client.connect("localhost", 6600)
  163. client.previous()
  164. def muteMusic():
  165. global uservolume
  166. if getMpdVolume() != 0: # if not muted
  167. setMpdVolume(0)
  168. else:
  169. setMpdVolume(uservolume)
  170. def changeVolume(change=5):
  171. global uservolume
  172. global volume
  173. newvol = uservolume + change
  174. if newvol > 100:
  175. newvol = 100
  176. if newvol < 0:
  177. newvol = 0
  178. try:
  179. client.setvol(newvol)
  180. except Exception:
  181. client.connect("localhost", 6600)
  182. client.setvol(newvol)
  183. uservolume = newvol
  184. volume = newvol
  185. def setMode(string):
  186. global mode
  187. global inUse
  188. mode = string
  189. if mode == "off":
  190. inUse = False
  191. def setDiscoMode(startup=False):
  192. setKugel('on')
  193. if startup:
  194. setStartupDmxScene()
  195. else:
  196. setUserDmxScene()
  197. sleep(0.3)
  198. setSun('off')
  199. setMode('disco')
  200. def getMpdVolume():
  201. try:
  202. vol = int(client.status()['volume'])
  203. except Exception:
  204. client.connect("localhost", 6600)
  205. vol = int(client.status()['volume'])
  206. if vol != 0: #only if not muted
  207. global uservolume
  208. uservolume = vol
  209. return vol
  210. def setMpdVolume(vol):
  211. try:
  212. client.setvol(vol)
  213. except Exception:
  214. client.connect("localhost", 6600)
  215. client.setvol(vol)
  216. if vol != 0: #only if not muted
  217. global uservolume
  218. uservolume = vol
  219. return True
  220. def seek(secs):
  221. try:
  222. client.seekcur(secs)
  223. except Exception:
  224. client.connect("localhost", 6600)
  225. client.seekcur(secs)
  226. return True
  227. def getTrackInfo():
  228. try:
  229. currentsong = client.currentsong()
  230. except Exception:
  231. client.connect("localhost", 6600)
  232. currentsong = client.currentsong()
  233. print(currentsong)
  234. volume = getMpdVolume()
  235. setMpdVolume(10)
  236. try:
  237. tts.say(currentsong['artist'] + ', ' + currentsong['title'])
  238. except Exception:
  239. tts.say('Willkommen am Discoklo!', 'de')
  240. setMpdVolume(volume)
  241. def tour():
  242. tts.say("Hello, I'm Discobert!", "en")
  243. sleep(0.3)
  244. tts.say("Press 1 for nice electronic music", "en")
  245. sleep(0.3)
  246. tts.say("Press 2 for hard electronic music", "en")
  247. sleep(0.3)
  248. tts.say("Press 3 for HGichT", "en")
  249. sleep(0.3)
  250. tts.say("Press 4 for a good laugh", "en")
  251. sleep(0.3)
  252. tts.say("Press 5 for more music", "en")
  253. sleep(0.3)
  254. def setWorkingMode():
  255. setSun('on')
  256. sleep(0.3)
  257. setKugel('off')
  258. setDmxScene('black')
  259. setMode('work')
  260. def startTimeoutCountdown():
  261. global lastUsed
  262. global inUse
  263. tts.say('Timeout in')
  264. countdown = [5,4,3,2,1] #10,9,8,7,6,
  265. for sec in countdown:
  266. tts.say(str(sec))
  267. sleep(0.5)
  268. remotesignal = lirc.nextcode()
  269. if wiringpi.digitalRead(pin_pir) == 1 or remotesignal:
  270. lastUsed = time.time()
  271. tts.say('Timeout cancelled!')
  272. inUse = True
  273. toilet = lirc.nextcode()
  274. break
  275. if not inUse:
  276. tts.say('Shutting down now.', 'en')
  277. closeService()
  278. def inactiveShutdown():
  279. closeService()
  280. def closeService(sleepsecs=0):
  281. setSun('off')
  282. sleep(0.3)
  283. setKugel('off')
  284. setDmxScene('black')
  285. for x in range(0, 20):
  286. changeVolume(-5)
  287. sleep(0.1)
  288. stopMusic()
  289. inUseBefore = False # Pfusch pfusch!
  290. setMode('off')
  291. sleep(sleepsecs)
  292. # function when user arrives
  293. def initService():
  294. startMusic('0', True) # start intro music
  295. setDiscoMode(True)
  296. global volume
  297. global defaultvolume
  298. global uservolume
  299. try:
  300. client.setvol(defaultvolume)
  301. except Exception:
  302. client.connect("localhost", 6600)
  303. client.setvol(defaultvolume)
  304. volume = defaultvolume
  305. uservolume = defaultvolume
  306. global starttime
  307. starttime = time.time()
  308. def say(text, lang="en"):
  309. originalvol = getMpdVolume()
  310. setMpdVolume(10)
  311. tts.say(text, lang)
  312. setMpdVolume(originalvol)
  313. def setOnOff():
  314. global mode
  315. stopMusic()
  316. if mode is not 'work':
  317. setWorkingMode()
  318. else:
  319. initService()
  320. def doorShutdown():
  321. #tts.say(random.choice(bye_sayings), "en")
  322. # sleep to give user some time to close the door
  323. # (pir sensor also stays up for 2 sec)
  324. closeService(5)
  325. def bootstrap():
  326. wiringpi.wiringPiSetup()
  327. wiringpi.pinMode(pin_kugel, 1) # set Relay Disokugel mode to OUTPUT
  328. wiringpi.pinMode(pin_door, 0) # set Circuit Door mode to INPUT
  329. wiringpi.pinMode(pin_sun, 1) # set Relay Sun mode to OUTPUT # TODO: Set pin!
  330. wiringpi.pinMode(pin_pir, 0) # set PIR Sensor mode to INPUT
  331. def timestamp(stamp=time.time()):
  332. return datetime.fromtimestamp(stamp).strftime('%Y-%m-%d %H:%M:%S')
  333. dmxScene = 0
  334. bootstrap()
  335. dev = pyudmx.uDMXDevice()
  336. dev.open()
  337. client = mpd.MPDClient()
  338. client.connect("localhost", 6600)
  339. tts = talkey.Talkey(
  340. preferred_languages=['en'],
  341. engine_preference=['pico'],
  342. )
  343. site = server.Site(Simple())
  344. reactor.listenTCP(8080, site)
  345. reactor.startRunning(False)
  346. starttime = time.time() # helper for doorshutdown
  347. lastUsed = time.time() # helper for timeout
  348. inUse = False # is toilet in use?
  349. inUseBefore = False # helper to check statechanges
  350. mode = "off" # can be: disco, work, off
  351. timeout = 5 * 60 - 5 # timeout since last user interaction
  352. defaultvolume = 90 # Volume when user enters the toilet
  353. volume = 90 # Global for actual volume
  354. uservolume = 90 # Global for user volume (ignores mute state)
  355. setSun('off')
  356. print(timestamp(), "Ready!")
  357. lirc.init("disco", "~/discobert/lircrc", blocking=False)
  358. # Main event loop ...
  359. while True:
  360. sleep(0.25)
  361. pirstate = wiringpi.digitalRead(pin_pir)
  362. doorstate = wiringpi.digitalRead(pin_door)
  363. #print('pirstate: ', pirstate)
  364. #print('doorstate: ', doorstate)
  365. # 0 => door closed
  366. # 1 => door open
  367. if doorstate == 1:
  368. # don't do a doorShutdown when user comes in
  369. # or when door stays open after user left
  370. if (time.time() > (starttime + 15) and inUse == True):
  371. doorShutdown()
  372. if pirstate == 1:
  373. lastUsed = time.time()
  374. inUse = True
  375. else:
  376. if(time.time() > lastUsed + timeout):
  377. inUse = False
  378. remotesignal = lirc.nextcode()
  379. print('remotesignal: ', remotesignal)
  380. if remotesignal:
  381. lastUsed = time.time() # user is active!
  382. inUse = True
  383. for code in remotesignal:
  384. print('received code:', code)
  385. if(code == "mode_disco"):
  386. setDiscoMode()
  387. if(code == "mode_work"):
  388. setWorkingMode()
  389. if(code == "mode_power"):
  390. setOnOff()
  391. if(code == "mode_music_play_1"):
  392. startMusic('1')
  393. if(code == "mode_music_play_2"):
  394. startMusic('2')
  395. if(code == "mode_music_play_3"):
  396. startMusic('3')
  397. if(code == "mode_music_play_4"):
  398. startMusic('4')
  399. if(code == "mode_music_play_5"):
  400. startMusic('5')
  401. if(code == "mode_play_fm4"):
  402. startMusic('http://185.85.29.141:8000')
  403. if(code == "mode_play_oe1"):
  404. startMusic('http://185.85.29.142:8000')
  405. if(code == "mode_music_previous"):
  406. previousSong()
  407. if(code == "mode_music_next"):
  408. nextSong()
  409. if(code == "mode_music_play"):
  410. playMusic()
  411. if(code == "mode_music_stop"):
  412. stopMusic()
  413. if(code == "mode_music_mute"):
  414. muteMusic()
  415. if(code == "mode_music_pause"):
  416. pauseMusic()
  417. if(code == "mode_music_rewind"):
  418. seek('-30')
  419. if(code == "mode_music_back"):
  420. seek('-5')
  421. if(code == "mode_music_forward"):
  422. seek('+5')
  423. if(code == "mode_music_fastforward"):
  424. seek('+30')
  425. if(code == "mode_volume_up"):
  426. changeVolume(5)
  427. if(code == "mode_volume_down"):
  428. changeVolume(-5)
  429. if(code == "mode_music_info"):
  430. getTrackInfo()
  431. if(code == "mode_record"):
  432. say("I'm sorry, I'm afraid I can't do that!")
  433. if(code == "mode_help"):
  434. tour()
  435. if(inUseBefore != inUse):
  436. print(timestamp(), "State change inUse:", inUseBefore, inUse)
  437. if inUse:
  438. initService()
  439. else:
  440. inactiveShutdown()
  441. #startTimeoutCountdown()
  442. inUseBefore = inUse
  443. # Webserver
  444. reactor.iterate()
  445. lirc.deinit() # Clean up lirc
  446. dev.close()