You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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