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.

530 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 getNewestPodcastUrl(xml):
  135. podcast = xml
  136. podcast_string = requests.get(podcast).text
  137. tree = ET.fromstring(podcast_string)
  138. return tree.find('.//enclosure').get('url')
  139. def playMusic():
  140. try:
  141. client.play()
  142. except Exception:
  143. client.connect("localhost", 6600)
  144. client.play()
  145. def pauseMusic():
  146. try:
  147. client.pause()
  148. except Exception:
  149. client.connect("localhost", 6600)
  150. client.pause()
  151. def stopMusic():
  152. try:
  153. client.stop()
  154. except Exception:
  155. client.connect("localhost", 6600)
  156. client.stop()
  157. def nextSong():
  158. try:
  159. client.next()
  160. except Exception:
  161. client.connect("localhost", 6600)
  162. client.next()
  163. def previousSong():
  164. try:
  165. client.previous()
  166. except Exception:
  167. client.connect("localhost", 6600)
  168. client.previous()
  169. def muteMusic():
  170. global uservolume
  171. if getMpdVolume() != 0: # if not muted
  172. setMpdVolume(0)
  173. else:
  174. setMpdVolume(uservolume)
  175. def changeVolume(change=5):
  176. global uservolume
  177. global volume
  178. newvol = uservolume + change
  179. if newvol > 100:
  180. newvol = 100
  181. if newvol < 0:
  182. newvol = 0
  183. try:
  184. client.setvol(newvol)
  185. except Exception:
  186. client.connect("localhost", 6600)
  187. client.setvol(newvol)
  188. uservolume = newvol
  189. volume = newvol
  190. def setMode(string):
  191. global mode
  192. global inUse
  193. mode = string
  194. if mode == "off":
  195. inUse = False
  196. def setDiscoMode(startup=False):
  197. setKugel('on')
  198. if startup:
  199. setStartupDmxScene()
  200. else:
  201. setUserDmxScene()
  202. sleep(0.3)
  203. setSun('off')
  204. setMode('disco')
  205. def getMpdVolume():
  206. try:
  207. vol = int(client.status()['volume'])
  208. except Exception:
  209. client.connect("localhost", 6600)
  210. vol = int(client.status()['volume'])
  211. if vol != 0: #only if not muted
  212. global uservolume
  213. uservolume = vol
  214. return vol
  215. def setMpdVolume(vol):
  216. try:
  217. client.setvol(vol)
  218. except Exception:
  219. client.connect("localhost", 6600)
  220. client.setvol(vol)
  221. if vol != 0: #only if not muted
  222. global uservolume
  223. uservolume = vol
  224. return True
  225. def seek(secs):
  226. try:
  227. client.seekcur(secs)
  228. except Exception:
  229. client.connect("localhost", 6600)
  230. client.seekcur(secs)
  231. return True
  232. def getTrackInfo():
  233. try:
  234. currentsong = client.currentsong()
  235. except Exception:
  236. client.connect("localhost", 6600)
  237. currentsong = client.currentsong()
  238. print(currentsong)
  239. volume = getMpdVolume()
  240. setMpdVolume(10)
  241. try:
  242. tts.say(currentsong['artist'] + ', ' + currentsong['title'])
  243. except Exception:
  244. tts.say('Willkommen am Discoklo!', 'de')
  245. setMpdVolume(volume)
  246. def setWorkingMode():
  247. setSun('on')
  248. sleep(0.3)
  249. setKugel('off')
  250. setDmxScene('black')
  251. setMode('work')
  252. def startTimeoutCountdown():
  253. global lastUsed
  254. global inUse
  255. tts.say('Timeout in')
  256. countdown = [5,4,3,2,1] #10,9,8,7,6,
  257. for sec in countdown:
  258. tts.say(str(sec))
  259. sleep(0.5)
  260. remotesignal = lirc.nextcode()
  261. if wiringpi.digitalRead(pin_pir) == 1 or remotesignal:
  262. lastUsed = time.time()
  263. tts.say('Timeout cancelled!')
  264. inUse = True
  265. toilet = lirc.nextcode()
  266. break
  267. if not inUse:
  268. tts.say('Shutting down now.', 'en')
  269. closeService()
  270. def closeService(sleepsecs=0):
  271. setSun('off')
  272. sleep(0.3)
  273. setKugel('off')
  274. setDmxScene('black')
  275. for x in range(0, 20):
  276. changeVolume(-5)
  277. sleep(0.1)
  278. stopMusic()
  279. inUseBefore = False # Pfusch pfusch!
  280. setMode('off')
  281. sleep(sleepsecs)
  282. # function when user arrives
  283. def initService():
  284. startMusic('0', True) # start intro music
  285. setDiscoMode(True)
  286. global volume
  287. global defaultvolume
  288. global uservolume
  289. try:
  290. client.setvol(defaultvolume)
  291. except Exception:
  292. client.connect("localhost", 6600)
  293. client.setvol(defaultvolume)
  294. volume = defaultvolume
  295. uservolume = defaultvolume
  296. global starttime
  297. starttime = time.time()
  298. def say(text, lang="en"):
  299. originalvol = getMpdVolume()
  300. setMpdVolume(10)
  301. tts.say(text, lang)
  302. setMpdVolume(originalvol)
  303. def setOnOff():
  304. global mode
  305. stopMusic()
  306. if mode is not 'work':
  307. setWorkingMode()
  308. else:
  309. initService()
  310. def doorShutdown():
  311. tts.say(random.choice(bye_sayings), "en")
  312. # sleep to give user some time to close the door
  313. # (pir sensor also stays up for 2 sec)
  314. closeService(5)
  315. def bootstrap():
  316. wiringpi.wiringPiSetup()
  317. wiringpi.pinMode(pin_kugel, 1) # set Relay Disokugel mode to OUTPUT
  318. wiringpi.pinMode(pin_door, 0) # set Circuit Door mode to INPUT
  319. wiringpi.pinMode(pin_sun, 1) # set Relay Sun mode to OUTPUT # TODO: Set pin!
  320. wiringpi.pinMode(pin_pir, 0) # set PIR Sensor mode to INPUT
  321. def timestamp(stamp=time.time()):
  322. return datetime.fromtimestamp(stamp).strftime('%Y-%m-%d %H:%M:%S')
  323. dmxScene = 0
  324. bootstrap()
  325. dev = pyudmx.uDMXDevice()
  326. dev.open()
  327. client = mpd.MPDClient()
  328. client.connect("localhost", 6600)
  329. tts = talkey.Talkey(
  330. preferred_languages=['en'],
  331. engine_preference=['pico'],
  332. )
  333. site = server.Site(Simple())
  334. reactor.listenTCP(8080, site)
  335. reactor.startRunning(False)
  336. lirc.init("disco", "~/discobert/lircrc", blocking=False)
  337. starttime = time.time() # helper for doorshutdown
  338. lastUsed = time.time() # helper for timeout
  339. inUse = False # is toilet in use?
  340. inUseBefore = False # helper to check statechanges
  341. mode = "off" # can be: disco, work, off
  342. timeout = 5 * 60 - 5 # timeout since last user interaction
  343. defaultvolume = 90 # Volume when user enters the toilet
  344. volume = 90 # Global for actual volume
  345. uservolume = 90 # Global for user volume (ignores mute state)
  346. setSun('off')
  347. print(timestamp(), "Ready!")
  348. # Main event loop ...
  349. while True:
  350. sleep(0.25)
  351. pirstate = wiringpi.digitalRead(pin_pir)
  352. doorstate = wiringpi.digitalRead(pin_door)
  353. #print('pirstate: ', pirstate)
  354. #print('doorstate: ', doorstate)
  355. # 0 => door closed
  356. # 1 => door open
  357. if doorstate == 1:
  358. # don't do a doorShutdown when user comes in
  359. # or when door stays open after user left
  360. if (time.time() > (starttime + 15) and inUse == True):
  361. doorShutdown()
  362. if pirstate == 1:
  363. lastUsed = time.time()
  364. inUse = True
  365. else:
  366. if(time.time() > lastUsed + timeout):
  367. inUse = False
  368. remotesignal = lirc.nextcode()
  369. #print('remotesignal: ', remotesignal)
  370. if remotesignal:
  371. lastUsed = time.time() # user is active!
  372. inUse = True
  373. for code in remotesignal:
  374. print('received code:', code)
  375. if(code == "mode_disco"):
  376. setDiscoMode()
  377. if(code == "mode_work"):
  378. setWorkingMode()
  379. if(code == "mode_power"):
  380. setOnOff()
  381. if(code == "mode_music_play_1"):
  382. startMusic('1')
  383. if(code == "mode_music_play_2"):
  384. startMusic('2')
  385. if(code == "mode_music_play_3"):
  386. startMusic('3')
  387. if(code == "mode_music_play_4"):
  388. startMusic('4')
  389. if(code == "mode_music_play_5"):
  390. startMusic('5')
  391. if(code == "mode_play_fm4"):
  392. startMusic('http://185.85.29.141:8000')
  393. if(code == "mode_play_oe1"):
  394. startMusic('http://185.85.29.142:8000')
  395. if(code == "mode_music_previous"):
  396. previousSong()
  397. if(code == "mode_music_next"):
  398. nextSong()
  399. if(code == "mode_music_play"):
  400. playMusic()
  401. if(code == "mode_music_stop"):
  402. stopMusic()
  403. if(code == "mode_music_mute"):
  404. muteMusic()
  405. if(code == "mode_music_pause"):
  406. pauseMusic()
  407. if(code == "mode_music_rewind"):
  408. seek('-30')
  409. if(code == "mode_music_back"):
  410. seek('-5')
  411. if(code == "mode_music_forward"):
  412. seek('+5')
  413. if(code == "mode_music_fastforward"):
  414. seek('+30')
  415. if(code == "mode_volume_up"):
  416. changeVolume(5)
  417. if(code == "mode_volume_down"):
  418. changeVolume(-5)
  419. if(code == "mode_music_info"):
  420. getTrackInfo()
  421. if(code == "mode_record"):
  422. say("I'm sorry, I'm afraid I can't do that!")
  423. if(code == "mode_news"):
  424. oejournalUrl = getNewestPodcastUrl('https://files.orf.at/podcast/oe1/oe1_journale.xml')
  425. startMusic(oejournalUrl)
  426. if(inUseBefore != inUse):
  427. print(timestamp(), "State change inUse:", inUseBefore, inUse)
  428. if inUse:
  429. initService()
  430. else:
  431. startTimeoutCountdown()
  432. inUseBefore = inUse
  433. # Webserver
  434. reactor.iterate()
  435. lirc.deinit() # Clean up lirc
  436. dev.close()