def dataReceived(self, data): command = unquote(data.decode().strip()).split() log.msg("Command received %s" % command) if command[0] == config['player_mac'] and command[1] == 'playlist': if command[2] == 'play' or (command[2] == 'pause' and command[3] == '0'): log.msg("play command received") receiver = cec.Device(config['cec_output']) if not receiver.is_on(): if receiver.power_on(): log.msg("turned receiver on") else: log.msg("couldn't turn receiver on") if receiver.set_av_input(config['cec_input']): log.msg("set input on receiver") else: log.msg("couldn't set input on receiver") if 'default_volume' in config: if command[0] == config['player_mac'] and command[1] == 'mixer' and command[2] == 'volume': if command[3][0] == '+': log.msg("volume up") self.transport.write(b'%s mixer volume %s\n' % (config['player_mac'], config['default_volume'])) cec.volume_up() elif command[3][0] == '-': log.msg("volume down") self.transport.write(b'%s mixer volume %s\n' % (config['player_mac'], config['default_volume'])) cec.volume_down()
def new_cast_status(self, status): if MIRROR_VOLUME: if self.volume_level is None: if status.volume_level == 0: self.volume_level = 0.1 elif status.volume_level == 1: self.volume_level = 0.9 else: self.volume_level = status.volume_level else: print(f"cc: {status.volume_level}, self: {self.volume_level}") if status.volume_level > self.volume_level: #volume up print("vol up") if status.volume_level == 1: self.cast.volume_down( ) # to get around max volume problem else: self.volume_level = status.volume_level cec.volume_up() elif status.volume_level < self.volume_level: #volume down print(f"vol down") if status.volume_level == 0: self.cast.volume_up( ) # to get around min volume problem else: self.volume_level = status.volume_level cec.volume_down() if status.status_text: print('app connection: ', status.status_text) self.cancel_timer() else: # no app connection print('no app connection; starting timer') self.start_timer()
def updatehdmivol(self): self.vol2 = self.player.getVolume() if self.hdmivol == "false": self.vol1 = self.player.getVolume() self.hdmivol = "true" counter = 0 if self.vol2 > self.vol1: while counter <= (abs(self.vol1 -self.vol2) * int(constants.VOLFACTOR)): cec.volume_up() self.hdmivol = "false" counter = counter + 1 elif self.vol2 < self.vol1: while counter <= (abs(self.vol1 -self.vol2) * int(constants.VOLFACTOR)): cec.volume_down() self.hdmivol = "false" counter = counter + 1 elif self.vol2 == self.vol1: pass
def render_GET(self, request): response_data = "OK" request.setResponseCode(200) receiver = cec.Device(config['cec_output']) if request.path == "/vol_up": cec.volume_up() elif request.path == "/vol_down": cec.volume_down() elif request.path == "/power_on": receiver.power_on() elif request.path == "/power_off": receiver.standby() elif request.prepath[0] == "input": receiver.set_av_input(int(request.postpath[0])) else: response_data = "unknown command" request.setResponseCode(404) request.responseHeaders.addRawHeader(b"content-type", b"text/plain") return response_data
def updatehdmivol(self): self.vol2 = self.player.getVolume() if self.hdmivol == "false": self.vol1 = self.player.getVolume() self.hdmivol = "true" counter = 0 if self.vol2 > self.vol1: while counter <= (abs(self.vol1 - self.vol2) * int(constants.VOLFACTOR)): cec.volume_up() self.hdmivol = "false" counter = counter + 1 elif self.vol2 < self.vol1: while counter <= (abs(self.vol1 - self.vol2) * int(constants.VOLFACTOR)): cec.volume_down() self.hdmivol = "false" counter = counter + 1 elif self.vol2 == self.vol1: pass
print("Got event", event, "with data", args) # arguments: iils def log_cb(event, level, time, message): print("CEC Log message:", message) cec.add_callback(cb, cec.EVENT_ALL & ~cec.EVENT_LOG) cec.add_callback(log_cb, cec.EVENT_LOG) print("Callback added") sleep(2) if cec.HAVE_CEC_ADAPTER_DESCRIPTOR: print("CEC has cec_adapter_descriptor"); else: print("CEC does not have cec_adapter_descriptor"); print("Initializing CEC library") cec.init() print("Creating Device object for TV") tv = cec.Device(0) print("Turning on TV") tv.power_on() print("Volume Up") cec.volume_up() print("Volume Down") cec.volume_down() print("SUCCESS!")
def onClick( self, control ): if self.running: #get the thread lock so we're only communicating one thing at a time to the player with self.lock: actionSqueeze = '' buttonName = '' #directCommand is set to true if we're not sending it as a simple button event directCommand = False try: buttonName = BUTTON_NAMES[control] actionSqueeze = SQUEEZE_CODES[buttonName] except: pass log ("onClick() event, Control is: [" + str(control) +"], buttonName is [" + buttonName + "] actionSqueeze is: [" + str(actionSqueeze) + "]") ####Sliding the progress bar to seek in a track #### NOT CURRENTLY WORKING!! if control == constants.CURRENTPROGRESS: #protect this block in case the control is missing... try: trackElapsed, trackRemaining, trackLength, percent = self.calculateTrackPostionandPercent() newPercent = self.getControl( constants.CURRENTPROGRESS ).getPercent() newPosition = trackLength * (newPercent / 100.0) log("Slider event: CURRENTPROGRESS, track length [" +str(trackLength) +"] percent [" + str(newPercent) + "] new position [" + str(newPosition) + "]") self.player.seek(newPosition) self.getControl( constants.CURRENTPROGRESS ).setPercent(newPercent) except: pass ####DEFAULT - the playback controls - everything slips through to here else: #define handlers for each of the controls to determine the correct #squeezebox code to seend if (control == constants.BUTTONSKIPBACK): log("Button event: SKIPBACK") if (control == constants.BUTTONREWIND): log("Button event: REWIND") directCommand = True self.player.rewind() if (control == constants.BUTTONPLAYPAUSE): log("Button event: PLAYPAUSE") if (control == constants.BUTTONSTOP): log("Button event: STOP") if (control == constants.BUTTONFASTFORWARD): log("Button event: FASTFORWARD") directCommand = True self.player.forward() if (control == constants.BUTTONSKIPFORWARD): log("Button event: SKIPFORWARD") if (control == constants.BUTTONSHUFFLE): log("Button event: SHUFFLE") directCommand = True self.player.setShuffle() if (control == constants.BUTTONREPEAT): log("Button event: REPEAT") directCommand = True self.player.setRepeat() if (control == constants.BUTTONCHOOSER): log("Button event: CHOOSER") directCommand = True log("### Starting Chooser...") xbmc.executebuiltin("ActivateWindow(Programs,plugin://plugin.program.xsqueezechooser/?mode=0&callerid=" + str(self.windowID) + ")") if (control == constants.BUTTONEXIT): log("Button event: EXIT") self.exitXSqueeze() #hdmi support if (control == constants.BUTTONVOLUP) and constants.CECSUPPORT == 'true' and constants.ADJUSTVOL == "true": if self.vol1 < 100: i = 0 for i in range(int(constants.VOLFACTOR)): cec.volume_up() self.hdmivol = "false" if (control == constants.BUTTONVOLDN) and constants.CECSUPPORT == 'true' and constants.ADJUSTVOL == "true" : if self.vol1 > 0: i = 0 for i in range(int(constants.VOLFACTOR)): cec.volume_down() self.hdmivol = "false" #ok now actually send the command through if it is a squeeze command if (actionSqueeze != '') and not directCommand: actionSqueeze = self.modifyActionSqueeze(actionSqueeze) log("Sending button to LMS: " + actionSqueeze) self.player.button(actionSqueeze) #make volume a bit quickcer...send the signal twice.. if actionSqueeze=="volup" or actionSqueeze =="voldown": self.player.button(actionSqueeze) #...else user has probably hammered the close button...tell them to cool their jets... else: notify("Cool your jets.","I'm cleaning up before exiting...") pass
def onClick(self, control): if self.running: #get the thread lock so we're only communicating one thing at a time to the player with self.lock: actionSqueeze = '' buttonName = '' #directCommand is set to true if we're not sending it as a simple button event directCommand = False try: buttonName = BUTTON_NAMES[control] actionSqueeze = SQUEEZE_CODES[buttonName] except: pass log("onClick() event, Control is: [" + str(control) + "], buttonName is [" + buttonName + "] actionSqueeze is: [" + str(actionSqueeze) + "]") ####Sliding the progress bar to seek in a track #### NOT CURRENTLY WORKING!! if control == constants.CURRENTPROGRESS: #protect this block in case the control is missing... try: trackElapsed, trackRemaining, trackLength, percent = self.calculateTrackPostionandPercent( ) newPercent = self.getControl( constants.CURRENTPROGRESS).getPercent() newPosition = trackLength * (newPercent / 100.0) log("Slider event: CURRENTPROGRESS, track length [" + str(trackLength) + "] percent [" + str(newPercent) + "] new position [" + str(newPosition) + "]") self.player.seek(newPosition) self.getControl( constants.CURRENTPROGRESS).setPercent(newPercent) except: pass ####DEFAULT - the playback controls - everything slips through to here else: #define handlers for each of the controls to determine the correct #squeezebox code to seend if (control == constants.BUTTONSKIPBACK): log("Button event: SKIPBACK") if (control == constants.BUTTONREWIND): log("Button event: REWIND") directCommand = True self.player.rewind() if (control == constants.BUTTONPLAYPAUSE): log("Button event: PLAYPAUSE") if (control == constants.BUTTONSTOP): log("Button event: STOP") if (control == constants.BUTTONFASTFORWARD): log("Button event: FASTFORWARD") directCommand = True self.player.forward() if (control == constants.BUTTONSKIPFORWARD): log("Button event: SKIPFORWARD") if (control == constants.BUTTONSHUFFLE): log("Button event: SHUFFLE") directCommand = True self.player.setShuffle() if (control == constants.BUTTONREPEAT): log("Button event: REPEAT") directCommand = True self.player.setRepeat() if (control == constants.BUTTONCHOOSER): log("Button event: CHOOSER") directCommand = True log("### Starting Chooser...") xbmc.executebuiltin( "ActivateWindow(Programs,plugin://plugin.program.xsqueezechooser/?mode=0&callerid=" + str(self.windowID) + ")") if (control == constants.BUTTONEXIT): log("Button event: EXIT") self.exitXSqueeze() #hdmi support if ( control == constants.BUTTONVOLUP ) and constants.CECSUPPORT == 'true' and constants.ADJUSTVOL == "true": if self.vol1 < 100: i = 0 for i in range(int(constants.VOLFACTOR)): cec.volume_up() self.hdmivol = "false" if ( control == constants.BUTTONVOLDN ) and constants.CECSUPPORT == 'true' and constants.ADJUSTVOL == "true": if self.vol1 > 0: i = 0 for i in range(int(constants.VOLFACTOR)): cec.volume_down() self.hdmivol = "false" #ok now actually send the command through if it is a squeeze command if (actionSqueeze != '') and not directCommand: actionSqueeze = self.modifyActionSqueeze(actionSqueeze) log("Sending button to LMS: " + actionSqueeze) self.player.button(actionSqueeze) #make volume a bit quickcer...send the signal twice.. if actionSqueeze == "volup" or actionSqueeze == "voldown": self.player.button(actionSqueeze) #...else user has probably hammered the close button...tell them to cool their jets... else: notify("Cool your jets.", "I'm cleaning up before exiting...") pass
def volumeDown(): cec.volume_down()
def main(): parser = argparse.ArgumentParser( description='Control a home theater system') parser.add_argument('-c', '--config', help="Config File (yaml)", default="theater.yaml") parser.add_argument('-n', '--name', help="Lirc name", default="theater_control") parser.add_argument('-w', '--wait', help='time in seconds to wait before stating', default='0.0') args = parser.parse_args() timeout = float(args.wait) if timeout: print("Waiting '{0}' seconds before starting...".format(timeout)) time.sleep(timeout) print("Loading config file from '{0}'...".format(args.config)) config = yaml.load(open(args.config)) # CEC setup print("Initializing CEC...") cec.init() if 'avr_port' in config: cec.set_port(config['avr'], config['avr_port']) devices = [cec.Device(i) for i in config['other_devices']] tv = cec.Device(config['tv']) avr = cec.Device(config['avr']) # Lirc setup lircname = args.name lirctmp = os.path.join(tempfile.mkdtemp(), 'lirc.conf') print "Lirc config temporary: %s" % (lirctmp) with open(lirctmp, "w") as lircconf: lircconf.write("""begin button = %s prog = %s config = power end """ % (config['power_button'], lircname)) lircconf.write("""begin button = %s prog = %s config = volup end """ % (config['volup_button'], lircname)) lircconf.write("""begin button = %s prog = %s config = home end """ % (config['home'], lircname)) lircconf.write("""begin button = %s prog = %s config = voldown end """ % (config['voldown_button'], lircname)) lircconf.write("""begin button = %s prog = %s config = volmute end """ % (config['volmute_button'], lircname)) for i in config['inputs']: print i lircconf.write("""begin button = %s prog = %s config = %s end """ % (i, lircname, i)) lirc.init(lircname, lirctmp) inputs = config['inputs'] p = None subprocess.Popen(os.path.join(os.path.dirname(__file__), 'notify.py'), shell=True) os.environ['XBMC_HOME'] = "/opt/plexhometheater/share/XBMC" while True: print("here") codes = lirc.nextcode() for code in codes: print code if code == 'power': tv_is_on = False try: tv_is_on = tv.is_on() except IOError as exc: print('%s' % exc) continue if tv_is_on: method = cec.Device.standby print "TV is on; turning it off" else: method = cec.Device.power_on print "TV is off; turning it on" method(tv) method(avr) for d in devices: method(d) elif code == 'volup': print "Volume up" cec.volume_up() elif code == 'voldown': print "Volume down" cec.volume_down() elif code == 'volmute': print "Volume mute toggle" cec.toggle_mute() elif code in inputs: i = inputs[code] print i if 'av_input' in i: avr.set_av_input(i['av_input']) if 'audio_input' in i: avr.set_audio_input(i['audio_input']) elif code == 'home': if p is not None: print("killing plex") p.terminate() if p.poll() is None: threading.Timer(3.0, p.kill).start() p.wait() p = None else: print("starting new plex") p = subprocess.Popen( ['/opt/plexhometheater/bin/plexhometheater'], shell=False)
def main(): parser = argparse.ArgumentParser(description='Control a home theater system') parser.add_argument('-c', '--config', help="Config File (yaml)", default="theater.yaml") parser.add_argument('-n', '--name', help="Lirc name", default="theater_control") parser.add_argument('-w', '--wait', help='time in seconds to wait before stating', default='0.0') args = parser.parse_args() timeout = float(args.wait) if timeout: print("Waiting '{0}' seconds before starting...".format(timeout)) time.sleep(timeout) print("Loading config file from '{0}'...".format(args.config)) config = yaml.load(open(args.config)) # CEC setup print("Initializing CEC...") cec.init() if 'avr_port' in config: cec.set_port(config['avr'], config['avr_port']) devices = [ cec.Device(i) for i in config['other_devices'] ] tv = cec.Device(config['tv']) avr = cec.Device(config['avr']) # Lirc setup lircname = args.name lirctmp = os.path.join(tempfile.mkdtemp(), 'lirc.conf') print "Lirc config temporary: %s"%(lirctmp) with open(lirctmp, "w") as lircconf: lircconf.write("""begin button = %s prog = %s config = power end """%(config['power_button'], lircname)) lircconf.write("""begin button = %s prog = %s config = volup end """%(config['volup_button'], lircname)) lircconf.write("""begin button = %s prog = %s config = home end """%(config['home'], lircname)) lircconf.write("""begin button = %s prog = %s config = voldown end """%(config['voldown_button'], lircname)) lircconf.write("""begin button = %s prog = %s config = volmute end """%(config['volmute_button'], lircname)) for i in config['inputs']: print i lircconf.write("""begin button = %s prog = %s config = %s end """%(i, lircname, i)) lirc.init(lircname, lirctmp) inputs = config['inputs'] p = None subprocess.Popen(os.path.join(os.path.dirname(__file__), 'notify.py'), shell=True) os.environ['XBMC_HOME'] = "/opt/plexhometheater/share/XBMC" while True: print("here") codes = lirc.nextcode() for code in codes: print code if code == 'power': tv_is_on = False try: tv_is_on = tv.is_on() except IOError as exc: print('%s' % exc) continue if tv_is_on: method = cec.Device.standby print "TV is on; turning it off" else: method = cec.Device.power_on print "TV is off; turning it on" method(tv) method(avr) for d in devices: method(d) elif code == 'volup': print "Volume up" cec.volume_up() elif code == 'voldown': print "Volume down" cec.volume_down() elif code == 'volmute': print "Volume mute toggle" cec.toggle_mute() elif code in inputs: i = inputs[code] print i if 'av_input' in i: avr.set_av_input(i['av_input']) if 'audio_input' in i: avr.set_audio_input(i['audio_input']) elif code == 'home': if p is not None: print("killing plex") p.terminate() if p.poll() is None: threading.Timer(3.0, p.kill).start() p.wait() p = None else: print("starting new plex") p = subprocess.Popen(['/opt/plexhometheater/bin/plexhometheater'], shell=False)
def set_receiver_status(self, power_state=None, mute=None, volume=None, receiver_state=None): if self.receiver is None: return if receiver_state != None: if "powerState" in receiver_state: power_state = receiver_state["powerState"] if "mute" in receiver_state: mute = receiver_state["mute"] if "volume" in receiver_state: volume = receiver_state["volume"] if power_state != None and power_state != "standby" and power_state != "on": raise Exception( "Valid power_state values are 'standby' or 'on' (%s given)" % power_state) self.acquire_receiver_status() if power_state != None and power_state != self.receiver["powerState"]: receiver = cec.Device(cec.CECDEVICE_AUDIOSYSTEM) retry_count = 0 if power_state == "standby": while retry_count < 5: try: receiver.standby() break except: print( "Error setting audio system power state to standby" ) retry_count += 1 print("retrying %d" % retry_count) else: while retry_count < 5: try: receiver.power_on() break except: print("Error setting audio system power state to on") retry_count += 1 print("retrying %d" % retry_count) self.receiver["powerState"] = power_state if mute != None and mute != self.receiver["mute"]: retry_count = 0 if mute: while retry_count < 5: try: cec.toggle_mute() break except: print("Error setting audio system mute") retry_count += 1 print("retrying %d" % retry_count) else: while retry_count < 5: try: cec.toggle_mute() break except: print("Error setting audio system mute (first)") retry_count += 1 print("retrying %d" % retry_count) self.receiver["mute"] = mute if volume != None and self.receiver["volume"] != None and \ volume != self.receiver["volume"] and volume != -1: if volume < self.receiver["volume"]: while volume < self.receiver["volume"]: self.receiver["volume"] = self.get_volume_info( cec.volume_down())["volume"] if volume > self.receiver["volume"]: while volume > self.receiver["volume"]: self.receiver["volume"] = self.get_volume_info( cec.volume_up())["volume"] return
# arguments: iils def log_cb(event, level, time, message): print("CEC Log message:", message) cec.add_callback(cb, cec.EVENT_ALL & ~cec.EVENT_LOG) cec.add_callback(log_cb, cec.EVENT_LOG) print("Callback added") sleep(2) if cec.HAVE_CEC_ADAPTER_DESCRIPTOR: print("CEC has cec_adapter_descriptor") else: print("CEC does not have cec_adapter_descriptor") print("Initializing CEC library") cec.init() print("Creating Device object for TV") tv = cec.Device(0) print("Turning on TV") tv.power_on() print("Volume Up") cec.volume_up() print("Volume Down") cec.volume_down() print("SUCCESS!")