Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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