Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

533 righe
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 = "Disco in use!"
  21. else:
  22. statustext = "Ready to Disco!"
  23. html = '<html><body style="min-height:100vh;display:flex;flex-grow:1;align-items:center;justify-content:center;"><div style="display:flex;font-size:10vw">%s</div></body></html>' % statustext
  24. return html.encode('utf-8')
  25. # GPIO
  26. pin_kugel = 2
  27. pin_sun = 4
  28. pin_pir = 0
  29. pin_door = 11
  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 closeService(sleepsecs=0):
  279. setSun('off')
  280. sleep(0.3)
  281. setKugel('off')
  282. setDmxScene('black')
  283. for x in range(0, 20):
  284. changeVolume(-5)
  285. sleep(0.1)
  286. stopMusic()
  287. inUseBefore = False # Pfusch pfusch!
  288. setMode('off')
  289. sleep(sleepsecs)
  290. def initService():
  291. startMusic('0', True) # start intro music
  292. setDiscoMode(True)
  293. global volume
  294. global defaultvolume
  295. global uservolume
  296. try:
  297. client.setvol(defaultvolume)
  298. except Exception:
  299. client.connect("localhost", 6600)
  300. client.setvol(defaultvolume)
  301. volume = defaultvolume
  302. uservolume = defaultvolume
  303. global starttime
  304. starttime = time.time()
  305. def say(text, lang="en"):
  306. originalvol = getMpdVolume()
  307. setMpdVolume(10)
  308. tts.say(text, lang)
  309. setMpdVolume(originalvol)
  310. def setOnOff():
  311. global mode
  312. stopMusic()
  313. if mode is not 'work':
  314. setWorkingMode()
  315. else:
  316. initService()
  317. def doorShutdown():
  318. tts.say(random.choice(bye_sayings), "en")
  319. # sleep to give user some time to close the door
  320. # (pir sensor also stays up for 2 sec)
  321. closeService(5)
  322. def bootstrap():
  323. wiringpi.wiringPiSetup()
  324. wiringpi.pinMode(pin_kugel, 1) # set Relay Disokugel mode to OUTPUT
  325. wiringpi.pinMode(pin_door, 0) # set Circuit Door mode to INPUT
  326. wiringpi.pinMode(pin_sun, 1) # set Relay Sun mode to OUTPUT # TODO: Set pin!
  327. wiringpi.pinMode(pin_pir, 0) # set PIR Sensor mode to INPUT
  328. def timestamp(stamp=time.time()):
  329. return datetime.fromtimestamp(stamp).strftime('%Y-%m-%d %H:%M:%S')
  330. dmxScene = 0
  331. bootstrap()
  332. dev = pyudmx.uDMXDevice()
  333. dev.open()
  334. client = mpd.MPDClient()
  335. client.connect("localhost", 6600)
  336. tts = talkey.Talkey(
  337. preferred_languages=['en'],
  338. engine_preference=['pico'],
  339. )
  340. site = server.Site(Simple())
  341. reactor.listenTCP(8080, site)
  342. reactor.startRunning(False)
  343. lirc.init("disco", "~/discobert/lircrc", blocking=False)
  344. starttime = time.time() # helper for doorshutdown
  345. lastUsed = time.time() # helper for timeout
  346. inUse = False # is toilet in use?
  347. inUseBefore = False # helper to check statechanges
  348. mode = "off" # can be: disco, work, off
  349. timeout = 2 * 60 - 10 # timeout since last user interaction
  350. defaultvolume = 90 # Volume when user enters the toilet
  351. volume = 90 # Global for actual volume
  352. uservolume = 90 # Global for user volume (ignores mute state)
  353. setSun('off')
  354. print(timestamp(), "Ready!")
  355. # Main event loop ...
  356. while True:
  357. sleep(0.25)
  358. pirstate = wiringpi.digitalRead(pin_pir)
  359. doorstate = wiringpi.digitalRead(pin_door)
  360. #print('pirstate: ', pirstate)
  361. #print('doorstate: ', doorstate)
  362. # 0 => door closed
  363. # 1 => door open
  364. if doorstate == 1:
  365. if (time.time() > (starttime + 15) and inUse == True):
  366. doorShutdown()
  367. if pirstate == 1:
  368. lastUsed = time.time()
  369. inUse = True
  370. else:
  371. if(time.time() > lastUsed + timeout):
  372. inUse = False
  373. remotesignal = lirc.nextcode()
  374. #print('remotesignal: ', remotesignal)
  375. if remotesignal:
  376. lastUsed = time.time() # user is active!
  377. inUse = True
  378. for code in remotesignal:
  379. print('received code:', code)
  380. if(code == "mode_disco"):
  381. setDiscoMode()
  382. if(code == "mode_work"):
  383. setWorkingMode()
  384. if(code == "mode_power"):
  385. setOnOff()
  386. if(code == "mode_music_play_1"):
  387. startMusic('1')
  388. if(code == "mode_music_play_2"):
  389. startMusic('2')
  390. if(code == "mode_music_play_3"):
  391. startMusic('3')
  392. if(code == "mode_music_play_4"):
  393. startMusic('4')
  394. if(code == "mode_music_play_5"):
  395. startMusic('5')
  396. if(code == "mode_play_fm4"):
  397. startMusic('http://185.85.29.141:8000')
  398. if(code == "mode_play_oe1"):
  399. startMusic('http://185.85.29.142:8000')
  400. if(code == "mode_music_previous"):
  401. previousSong()
  402. if(code == "mode_music_next"):
  403. nextSong()
  404. if(code == "mode_music_play"):
  405. playMusic()
  406. if(code == "mode_music_stop"):
  407. stopMusic()
  408. if(code == "mode_music_mute"):
  409. muteMusic()
  410. if(code == "mode_music_pause"):
  411. pauseMusic()
  412. if(code == "mode_music_rewind"):
  413. seek('-30')
  414. if(code == "mode_music_back"):
  415. seek('-5')
  416. if(code == "mode_music_forward"):
  417. seek('+5')
  418. if(code == "mode_music_fastforward"):
  419. seek('+30')
  420. if(code == "mode_volume_up"):
  421. changeVolume(5)
  422. if(code == "mode_volume_down"):
  423. changeVolume(-5)
  424. if(code == "mode_music_info"):
  425. getTrackInfo()
  426. if(code == "mode_record"):
  427. say("I'm sorry, I'm afraid I can't do that!")
  428. if(code == "mode_help"):
  429. tour()
  430. if(inUseBefore != inUse):
  431. print(timestamp(), "State change inUse:", inUseBefore, inUse)
  432. if inUse:
  433. initService()
  434. else:
  435. startTimeoutCountdown()
  436. inUseBefore = inUse
  437. # Webserver
  438. reactor.iterate()
  439. lirc.deinit() # Clean up lirc
  440. dev.close()