Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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