def __init__(self, device, source, destination): import cec if source is None: source = 1 if destination is None: destination = 4 if isinstance(source, (str, unicode)): source = int(source, 16) if isinstance(destination, (str, unicode)): destination = int(destination, 16) self.source = source self.destination = destination self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = "stb-tester" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.lib = cec.ICECAdapter.Create(self.cecconfig) debug("libCEC version %s loaded: %s" % (self.lib.VersionToString( self.cecconfig.serverVersion), self.lib.GetLibInfo())) if device is None: device = self.detect_adapter() if device is None: raise HdmiCecError("No adapter found") if not self.lib.Open(device): raise HdmiCecError( "Failed to open a connection to the CEC adapter") debug("Connection to CEC adapter opened")
def __init__(self, osd_name=None, device_types=None, init=True, key_press_callback=None): self.logger = logging.getLogger('CECClient') self.logger_bus = logging.getLogger('CECClient.bus') self.logger_keypress = logging.getLogger('CECClient.key') self.key_press_callback = key_press_callback self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = osd_name or "pyCecClient" self.cecconfig.bActivateSource = 0 self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT # FIXME: this does not work at all self.cecconfig.SetLogCallback(self.log_callback) self.cecconfig.SetKeyPressCallback(self.key_press_callback_proxy) if device_types: for device_type in device_types: self.cecconfig.deviceTypes.Add(device_type) else: self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.connection = cec.ICECAdapter.Create(self.cecconfig) self.connected = False self._logical_address = None self._devices = None if init: self.init()
def __init__(self, osd_name='pyCecClient', device_types=None, connect=True, key_press_callback=None, log_callback=None, port=None): self.logger = logging.getLogger('CECClient') self.logger_log = logging.getLogger('CECClient.log') self.logger_key = logging.getLogger('CECClient.key') self.cecconfig = cec.libcec_configuration() if osd_name is not None: assert len( osd_name) < 14, "Maximum length for cec device name is 14" self.cecconfig.strDeviceName = osd_name self.cecconfig.bActivateSource = 0 self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self._setup_callbacks(log_callback, key_press_callback) if device_types: for device_type in device_types: self.cecconfig.deviceTypes.Add(device_type) else: self.cecconfig.deviceTypes.Add( cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.connection = cec.ICECAdapter.Create(self.cecconfig) self.connected = False self._logical_address = None self._devices = None self.port = port if connect: self.connect()
def _init_cec(self): """ initialize CEC if available """ self._log_level = cec.CEC_LOG_WARNING self._cecconfig = cec.libcec_configuration() self._cecconfig.strDeviceName = "pvr" self._cecconfig.bActivateSource = 0 self._cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self._cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self._cecconfig.SetLogCallback(self._process_logmessage) self._cecconfig.SetKeyPressCallback(self._process_key) self._cecconfig.SetCommandCallback(self._process_command) self._controller = cec.ICECAdapter.Create(self._cecconfig) self._app.logger.msg( "DEBUG", "libCEC version " + self._controller.VersionToString(self._cecconfig.serverVersion) + " loaded: " + self._controller.GetLibInfo()) # search for adapters self._com_port = self._get_com_port() if self._com_port == None: self._app.logger.msg("ERROR", "no port") self._have_cec = False return if not self._controller.Open(self._com_port): self._app.logger.msg("ERROR", "could not open cec-adapter") self._have_cec = False else: #sems to be necessary at least with my DENON self._controller.GetActiveDevices()
def connect(self, receiver): self.receiver = receiver self.cec_config = cec.libcec_configuration() self.cec_config.strDeviceName = self.device_name self.cec_config.bActivateSource = 0 self.cec_config.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cec_config.clientVersion = cec.LIBCEC_VERSION_CURRENT self.cec_config.SetLogCallback(singleton_on_message) self.client = cec.ICECAdapter.Create(self.cec_config) logger.info("libCEC version " + self.client.VersionToString(self.cec_config.serverVersion) + " loaded: " + self.client.GetLibInfo()) if not self.client.Open(self.adapter): raise Exception("Could not connect to cec adapter") self.devices = { LOGICAL_ADDRESS_TV: CecTv(self.client, LOGICAL_ADDRESS_TV, "tv"), LOGICAL_ADDRESS_AUDIO_SYSTEM: CecAudioSystem(self.client, LOGICAL_ADDRESS_AUDIO_SYSTEM, "audio-system"), LOGICAL_ADDRESS_RECORDING_DEVICE_1: CecRecordingDevice(self.client, LOGICAL_ADDRESS_RECORDING_DEVICE_1, "recording-device-1"), LOGICAL_ADDRESS_RECORDING_DEVICE_2: CecRecordingDevice(self.client, LOGICAL_ADDRESS_RECORDING_DEVICE_2, "recording-device-2"), LOGICAL_ADDRESS_TUNER_1: CecTuner(self.client, LOGICAL_ADDRESS_TUNER_1, "tuner-1"), LOGICAL_ADDRESS_TUNER_2: CecTuner(self.client, LOGICAL_ADDRESS_TUNER_2, "tuner-2"), LOGICAL_ADDRESS_TUNER_3: CecTuner(self.client, LOGICAL_ADDRESS_TUNER_3, "tuner-3"), LOGICAL_ADDRESS_TUNER_4: CecTuner(self.client, LOGICAL_ADDRESS_TUNER_4, "tuner-4"), LOGICAL_ADDRESS_PLAYBACK_DEVICE_1: CecPlaybackDevice(self.client, LOGICAL_ADDRESS_PLAYBACK_DEVICE_1, "playback-device-1"), LOGICAL_ADDRESS_PLAYBACK_DEVICE_2: CecPlaybackDevice(self.client, LOGICAL_ADDRESS_PLAYBACK_DEVICE_2, "playback-device-2"), LOGICAL_ADDRESS_PLAYBACK_DEVICE_2_ALTERNATIVE: CecPlaybackDevice(self.client, LOGICAL_ADDRESS_PLAYBACK_DEVICE_2_ALTERNATIVE, "playback-device-2-alternative"), LOGICAL_ADDRESS_PLAYBACK_DEVICE_3: CecPlaybackDevice(self.client, LOGICAL_ADDRESS_PLAYBACK_DEVICE_3, "playback-device-3") }
def get_cec_conn(): cecconfig = cec.libcec_configuration() cecconfig.strDeviceName = "pyLibCec" cecconfig.bActivateSource = 0 cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT return cec.ICECAdapter.Create(cecconfig)
def __init__(self): self.log_level = cec.CEC_LOG_WARNING self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = "simple-radio" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_TUNER) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.cecconfig.SetLogCallback(self.process_logmessage) self.cecconfig.SetKeyPressCallback(self.process_key) self.cecconfig.SetCommandCallback(self.process_command) self.controller = cec.ICECAdapter.Create(self.cecconfig) print("libCEC version " + self.controller.VersionToString(self.cecconfig.serverVersion) + " loaded: " + self.controller.GetLibInfo()) # search for adapters self.com_port = self.get_com_port() if self.com_port == None: raise EnvironmentError((1, "Kein CEC-Adapter gefunden")) if not self.controller.Open(self.com_port): raise EnvironmentError((2, "konnte CEC-Adapter nicht öffnen"))
def __init__(self): self.APP_NAME = 'raspi-player' self.log_level = cec.CEC_LOG_WARNING self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = self.APP_NAME self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_TUNER) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.cecconfig.SetLogCallback(self.process_logmessage) # self.cecconfig.SetKeyPressCallback(self.process_key) self.cecconfig.SetCommandCallback(self.process_command) self.controller = cec.ICECAdapter.Create(self.cecconfig) print('libCEC version ' + self.controller.VersionToString(self.cecconfig.serverVersion) + ' loaded: ' + self.controller.GetLibInfo()) # search for adapters self.com_port = self.get_com_port() if self.com_port is None: raise EnvironmentError((1, 'No CEC-adapter found')) if not self.controller.Open(self.com_port): raise EnvironmentError((2, 'could not open CEC-adapter')) self.mouseSensibilitySteps = [ 10, 40, 100, 200, ] self.mouseSensibilityCurStepId = 0 self.mouseSensibility = self.mouseSensibilitySteps[self.mouseSensibilityCurStepId]
def __init__(self, device, source, destination): # On Ubuntu 18.04 `cec/__init__.py` tries to import `_cec` but can't # find it. # https://bugs.launchpad.net/ubuntu/+source/libcec/+bug/1805620 sys.path.insert(0, "/usr/lib/python2.7/dist-packages/cec") try: import cec # pylint:disable=import-error finally: sys.path.pop(0) if source is None: source = 1 if isinstance(source, string_types): source = int(source, 16) if isinstance(destination, string_types): destination = int(destination, 16) self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = to_native_str("stb-tester") self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.cecconfig.SetLogCallback(self._log_cec_message) self.lib = cec.ICECAdapter.Create(self.cecconfig) logging.info("HdmiCecControl: libCEC version %s loaded: %s", self.lib.VersionToString(self.cecconfig.serverVersion), self.lib.GetLibInfo()) self.cec_to_log_level = { cec.CEC_LOG_ERROR: logging.ERROR, cec.CEC_LOG_WARNING: logging.WARNING, cec.CEC_LOG_NOTICE: logging.INFO, cec.CEC_LOG_TRAFFIC: logging.DEBUG, cec.CEC_LOG_DEBUG: logging.DEBUG, } if device is None: device = self.detect_adapter() if device is None: raise HdmiCecFatalError("No adapter found") device = to_native_str(device) if not self.lib.Open(device): raise HdmiCecFatalError( "Failed to open a connection to the CEC adapter") logging.info("HdmiCecControl: Opened connection to CEC adapter") self.configured_destination = destination self.destination = None # set by `rescan` self.rescan() self.source = source self.press_and_hold_thread = None self.press_and_holding = False self.lock = threading.Condition()
def __init__(self, device, source, destination): # On Ubuntu 18.04 `cec/__init__.py` tries to import `_cec` but can't # find it. # https://bugs.launchpad.net/ubuntu/+source/libcec/+bug/1805620 sys.path.insert(0, "/usr/lib/python2.7/dist-packages/cec") try: import cec # pylint:disable=import-error finally: sys.path.pop(0) if source is None: source = 1 if isinstance(source, string_types): source = int(source, 16) if isinstance(destination, string_types): destination = int(destination, 16) self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = b"stb-tester" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.lib = cec.ICECAdapter.Create(self.cecconfig) debug("libCEC version %s loaded: %s" % (self.lib.VersionToString( self.cecconfig.serverVersion), self.lib.GetLibInfo())) if device is None: device = self.detect_adapter() if device is None: raise HdmiCecError("No adapter found") device = to_bytes(device) if not self.lib.Open(device): raise HdmiCecError( "Failed to open a connection to the CEC adapter") debug("Connection to CEC adapter opened") if destination is None: ds = list(self._list_active_devices()) debug("HDMI-CEC scan complete. Found %r" % ds) if len(ds) == 0: raise HdmiCecError( "Failed to find a device on the CEC bus to talk to.") # Choose the last one, the first one is likely to be a TV if there's # one plugged in destination = ds[-1] debug("HDMI-CEC: Chose to talk to device %i %r" % (destination, self.lib.GetDeviceOSDName(destination))) self.source = source self.destination = destination self.press_and_hold_thread = None self.press_and_holding = False self.lock = threading.Condition()
def __init__(self): """Initialize a new CecWrapper instance.""" self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = "pyLibCec" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.cecconfig.SetLogCallback(partial(self._log_callback)) self.lib = cec.ICECAdapter.Create(self.cecconfig) self.callback = None self._is_on = None
def __init__(self): self.log_level = cec.CEC_LOG_WARNING self.cecconfig = cec.libcec_configuration() self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.SetLogCallback(log_callback) self.cecconfig.SetKeyPressCallback(key_press_callback) CEC.instance = self self.AddGroup("Actions", ACTIONS) self.AddActionsFromList(ACTIONS) self.AddGroup("Queries", QUERIES) self.AddActionsFromList(QUERIES)
def __init__(self, device, source, destination): # On Ubuntu 18.04 `cec/__init__.py` tries to import `_cec` but can't # find it. # https://bugs.launchpad.net/ubuntu/+source/libcec/+bug/1805620 sys.path.insert(0, "/usr/lib/python2.7/dist-packages/cec") try: import cec finally: sys.path.pop(0) if source is None: source = 1 if isinstance(source, (str, unicode)): source = int(source, 16) if isinstance(destination, (str, unicode)): destination = int(destination, 16) self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = "stb-tester" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.lib = cec.ICECAdapter.Create(self.cecconfig) debug("libCEC version %s loaded: %s" % ( self.lib.VersionToString(self.cecconfig.serverVersion), self.lib.GetLibInfo())) if device is None: device = self.detect_adapter() if device is None: raise HdmiCecError("No adapter found") if not self.lib.Open(device): raise HdmiCecError("Failed to open a connection to the CEC adapter") debug("Connection to CEC adapter opened") if destination is None: ds = list(self._list_active_devices()) debug("HDMI-CEC scan complete. Found %r" % ds) if len(ds) == 0: raise HdmiCecError( "Failed to find a device on the CEC bus to talk to.") # Choose the last one, the first one is likely to be a TV if there's # one plugged in destination = ds[-1] debug("HDMI-CEC: Chose to talk to device %i %r" % ( destination, self.lib.GetDeviceOSDName(destination))) self.source = source self.destination = destination self.press_and_hold_thread = None self.press_and_holding = False self.lock = threading.Condition()
def setup_cec(self): """Creates config and opens connect to CEC (HDMI) adapter.""" cecconfig = cec.libcec_configuration() cecconfig.strDeviceName = "aptcontroller" cecconfig.bActivateSource = 0 cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT # Create, Detect, and Open adapter lib = cec.ICECAdapter.Create(cecconfig) adapters = lib.DetectAdapters() lib.Open(adapters[0].strComName) print "CEC setup successfully." return lib
def __init__(self, name: str = None, monitor_only: bool = None, activate_source: bool = None, device_type=ADDR_RECORDINGDEVICE1): super().__init__() self._adapter = None self._io_executor = ThreadPoolExecutor(1) import cec self._cecconfig = cec.libcec_configuration() if monitor_only is not None: self._cecconfig.bMonitorOnly = 1 if monitor_only else 0 self._cecconfig.strDeviceName = name if activate_source is not None: self._cecconfig.bActivateSource = 1 if activate_source else 0 self._cecconfig.deviceTypes.Add(device_type)
def __init__(self, device, source, destination): import cec if source is None: source = 1 if isinstance(source, (str, unicode)): source = int(source, 16) if isinstance(destination, (str, unicode)): destination = int(destination, 16) self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = "stb-tester" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.lib = cec.ICECAdapter.Create(self.cecconfig) debug("libCEC version %s loaded: %s" % (self.lib.VersionToString( self.cecconfig.serverVersion), self.lib.GetLibInfo())) if device is None: device = self.detect_adapter() if device is None: raise HdmiCecError("No adapter found") if not self.lib.Open(device): raise HdmiCecError( "Failed to open a connection to the CEC adapter") debug("Connection to CEC adapter opened") if destination is None: ds = list(self._list_active_devices()) debug("HDMI-CEC scan complete. Found %r" % ds) if len(ds) == 0: raise HdmiCecError( "Failed to find a device on the CEC bus to talk to.") # Choose the last one, the first one is likely to be a TV if there's # one plugged in destination = ds[-1] debug("HDMI-CEC: Chose to talk to device %i %r" % (destination, self.lib.GetDeviceOSDName(destination))) self.source = source self.destination = destination self.press_and_hold_thread = None self.press_and_holding = False self.lock = threading.Condition()
def init(self): """ initialize """ self.items = CFG.ITEMS_CEC_DEV self.libCEC = {} self.uidevice = uinput.Device(self.keymap.values()) self.cecconfig = cec.libcec_configuration() self.this_cec_name = CFG.CEC_THIS_DEV self.devices = {} self.autoinit = True if self.autoinit: self.initConfig(self.this_cec_name) self.initDefaultCB() self.initlibCEC() self.detectDevices()
def __init__(self, device, source, destination): import cec if source is None: source = 1 if isinstance(source, (str, unicode)): source = int(source, 16) if isinstance(destination, (str, unicode)): destination = int(destination, 16) self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = "stb-tester" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.lib = cec.ICECAdapter.Create(self.cecconfig) debug("libCEC version %s loaded: %s" % ( self.lib.VersionToString(self.cecconfig.serverVersion), self.lib.GetLibInfo())) if device is None: device = self.detect_adapter() if device is None: raise HdmiCecError("No adapter found") if not self.lib.Open(device): raise HdmiCecError("Failed to open a connection to the CEC adapter") debug("Connection to CEC adapter opened") if destination is None: ds = list(self._list_active_devices()) debug("HDMI-CEC scan complete. Found %r" % ds) if len(ds) == 0: raise HdmiCecError( "Failed to find a device on the CEC bus to talk to.") # Choose the last one, the first one is likely to be a TV if there's # one plugged in destination = ds[-1] debug("HDMI-CEC: Chose to talk to device %i %r" % ( destination, self.lib.GetDeviceOSDName(destination))) self.source = source self.destination = destination
def connect(self): self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = "mqtt_cec" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT def log_callback(level, time, message): try: return self.on_log(level, time, message) except Exception as e: print(e) def command_callback(cmd): try: return self.on_command(cmd) except Exception as e: print(e) self.cecconfig.SetLogCallback(log_callback) self.cecconfig.SetCommandCallback(command_callback) self.lib = cec.ICECAdapter.Create(self.cecconfig) self.log_level = cec.CEC_LOG_TRAFFIC print("libCEC version " + self.lib.VersionToString(self.cecconfig.serverVersion) + " loaded: " + self.lib.GetLibInfo()) adapter = self.detect_adapter() if adapter == None: print("No adapters found") else: if self.lib.Open(adapter): print("HDMI-CEC connection opened") return True else: print("failed to open a connection to the CEC adapter") return False
import cec logging.info("CEC module enabled") cecEnabled = True except ImportError, e: logging.info("CEC module not found, disabling CEC functions") else: logging.debug("CEC disabled in pes.ini") logging.debug("script dir is: %s" % scriptDir) logging.info("loading GUI...") pes = peslib.PES(args.window, commandFile) if cecEnabled: # set-up CEC try: logging.debug("create CEC config") cecconfig = cec.libcec_configuration() cecconfig.strDeviceName = "PES" cecconfig.bActivateSource = 0 cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT logging.debug("adding CEC callback...") cecconfig.SetKeyPressCallback(pes.handleCecEvent) lib = cec.ICECAdapter.Create(cecconfig) logging.debug("looking for CEC adapters...") adapters = lib.DetectAdapters() adapterCount = len(adapters) if adapterCount == 0: logging.warning("could not find any CEC adapters!") else: logging.debug("found %d CEC adapters, attempting to open first adapter..." % adapterCount) if lib.Open(adapters[0].strComName):
class pyCecClient: cecconfig = cec.libcec_configuration() lib = {} # don't enable debug logging by default log_level = cec.CEC_LOG_TRAFFIC # create a new libcec_configuration def SetConfiguration(self): self.cecconfig.strDeviceName = "pyLibCec" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT def SetLogCallback(self, callback): self.cecconfig.SetLogCallback(callback) def SetKeyPressCallback(self, callback): self.cecconfig.SetKeyPressCallback(callback) def SetCommandCallback(self, callback): self.cecconfig.SetCommandCallback(callback) # detect an adapter and return the com port path def DetectAdapter(self): retval = None adapters = self.lib.DetectAdapters() for adapter in adapters: print("found a CEC adapter:") print("port: " + adapter.strComName) print("vendor: " + hex(adapter.iVendorId)) print("product: " + hex(adapter.iProductId)) retval = adapter.strComName return retval # initialise libCEC def InitLibCec(self): self.lib = cec.ICECAdapter.Create(self.cecconfig) # print libCEC version and compilation information print("libCEC version " + self.lib.VersionToString(self.cecconfig.serverVersion) + " loaded: " + self.lib.GetLibInfo()) # search for adapters adapter = self.DetectAdapter() if adapter == None: print("No adapters found") else: if self.lib.Open(adapter): print("connection opened") self.MainLoop() else: print("failed to open a connection to the CEC adapter") # display the addresses controlled by libCEC def ProcessCommandSelf(self): addresses = self.lib.GetLogicalAddresses() strOut = "Addresses controlled by libCEC: " x = 0 notFirst = False while x < 15: if addresses.IsSet(x): if notFirst: strOut += ", " strOut += self.lib.LogicalAddressToString(x) if self.lib.IsActiveSource(x): strOut += " (*)" notFirst = True x += 1 print(strOut) # send an active source message def ProcessCommandActiveSource(self): self.lib.SetActiveSource() # send a standby command def ProcessCommandStandby(self): self.lib.StandbyDevices(cec.CECDEVICE_BROADCAST) # send a custom command def ProcessCommandTx(self, data): cmd = self.lib.CommandFromString(data) print("transmit " + data) if self.lib.Transmit(cmd): print("command sent") else: print("failed to send command") # scan the bus and display devices that were found def ProcessCommandScan(self): print("requesting CEC bus information ...") strLog = "CEC bus information\n===================\n" addresses = self.lib.GetActiveDevices() activeSource = self.lib.GetActiveSource() x = 0 while x < 15: if addresses.IsSet(x): vendorId = self.lib.GetDeviceVendorId(x) physicalAddress = self.lib.GetDevicePhysicalAddress(x) active = self.lib.IsActiveSource(x) cecVersion = self.lib.GetDeviceCecVersion(x) power = self.lib.GetDevicePowerStatus(x) osdName = self.lib.GetDeviceOSDName(x) strLog += "device #" + str( x) + ": " + self.lib.LogicalAddressToString(x) + "\n" strLog += "address: " + str(physicalAddress) + "\n" strLog += "active source: " + str(active) + "\n" strLog += "vendor: " + self.lib.VendorIdToString( vendorId) + "\n" strLog += "CEC version: " + self.lib.CecVersionToString( cecVersion) + "\n" strLog += "OSD name: " + osdName + "\n" strLog += "power status: " + self.lib.PowerStatusToString( power) + "\n\n\n" x += 1 print(strLog) # main loop, ask for commands def MainLoop(self): runLoop = True while runLoop: command = raw_input("Enter command:").lower() if command == 'q' or command == 'quit': runLoop = False elif command == 'self': self.ProcessCommandSelf() elif command == 'as' or command == 'activesource': self.ProcessCommandActiveSource() elif command == 'standby': self.ProcessCommandStandby() elif command == 'scan': self.ProcessCommandScan() elif command[:2] == 'tx': self.ProcessCommandTx(command[3:]) print('Exiting...') # logging callback def LogCallback(self, level, time, message): if level > self.log_level: return 0 if level == cec.CEC_LOG_ERROR: levelstr = "ERROR: " elif level == cec.CEC_LOG_WARNING: levelstr = "WARNING: " elif level == cec.CEC_LOG_NOTICE: levelstr = "NOTICE: " elif level == cec.CEC_LOG_TRAFFIC: levelstr = "TRAFFIC: " elif level == cec.CEC_LOG_DEBUG: levelstr = "DEBUG: " print(levelstr + "[" + str(time) + "] " + message) return 0 # key press callback def KeyPressCallback(self, key, duration): print("[key pressed] " + str(key)) return 0 # command received callback def CommandCallback(self, cmd): print("[command received] " + cmd) return 0 def __init__(self): self.SetConfiguration()
def setup(hass, config): """Setup CEC capability.""" global _CEC try: import cec except ImportError: _LOGGER.error("libcec must be installed") return False # Parse configuration into a dict of device name to physical address # represented as a list of four elements. flat = {} for pair in parse_mapping(config[DOMAIN].get(CONF_DEVICES, {})): flat[pair[0]] = pad_physical_address(pair[1]) # Configure libcec. cfg = cec.libcec_configuration() cfg.strDeviceName = 'HASS' cfg.bActivateSource = 0 cfg.bMonitorOnly = 1 cfg.clientVersion = cec.LIBCEC_VERSION_CURRENT # Setup CEC adapter. _CEC = cec.ICECAdapter.Create(cfg) def _power_on(call): """Power on all devices.""" _CEC.PowerOnDevices() def _standby(call): """Standby all devices.""" _CEC.StandbyDevices() def _select_device(call): """Select the active device.""" path = flat.get(call.data[ATTR_DEVICE]) if not path: _LOGGER.error("Device not found: %s", call.data[ATTR_DEVICE]) cmds = [] for i in range(1, MAX_DEPTH - 1): addr = pad_physical_address(path[:i]) cmds.append('1f:82:{}{}:{}{}'.format(*addr)) cmds.append('1f:86:{}{}:{}{}'.format(*addr)) for cmd in cmds: _CEC.Transmit(_CEC.CommandFromString(cmd)) _LOGGER.info("Selected %s", call.data[ATTR_DEVICE]) def _start_cec(event): """Open CEC adapter.""" adapters = _CEC.DetectAdapters() if len(adapters) == 0: _LOGGER.error("No CEC adapter found") return if _CEC.Open(adapters[0].strComName): hass.services.register(DOMAIN, SERVICE_POWER_ON, _power_on) hass.services.register(DOMAIN, SERVICE_STANDBY, _standby) hass.services.register(DOMAIN, SERVICE_SELECT_DEVICE, _select_device) else: _LOGGER.error("Failed to open adapter") hass.bus.listen_once(EVENT_HOMEASSISTANT_START, _start_cec) return True
class pyCecClient: cecconfig = cec.libcec_configuration() lib = {} log_level = cec.CEC_LOG_ALL help_string = "" interactive_cmd = {} stdout = sys.stdout stdin = sys.stdin @register_mainloop_command("h", "help") def PrintHelpMessage(self): """Print this help message""" print(self.help_string, file=self.stdout) # create a new libcec_configuration def __init__(self, device_name="pyLibCec", BeActiveSource=0, deviceType=cec.CEC_DEVICE_TYPE_RECORDING_DEVICE): self.cecconfig.strDeviceName = device_name self.cecconfig.bActivateSource = BeActiveSource self.cecconfig.deviceTypes.Add(deviceType) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT def SetLogCallback(self, callback): self.cecconfig.SetLogCallback(callback) def SetKeyPressCallback(self, callback): self.cecconfig.SetKeyPressCallback(callback) def SetCommandCallback(self, callback): self.cecconfig.SetCommandCallback(callback) def SetConfigurationChangedCallback(self, callback): self.cecconfig.SetConfigurationChangedCallback(callback) def SetSourceActivatedCallback(self, callback): self.cecconfig.SetSourceActivatedCallback(callback) def SetMenuStateCallback(self, callback): self.cecconfig.SetMenuStateCallback(callback) def SetAlertCallback(self, callback): self.cecconfig.SetAlertCallback(callback) def DetectAdapter(self): """ detect an adapter and return the com port path """ retval = None adapters = self.lib.DetectAdapters() for adapter in adapters: print("found a CEC adapter:", file=self.stdout) print("port: " + adapter.strComName, file=self.stdout) print("vendor: " + hex(adapter.iVendorId), file=self.stdout) print("product: " + hex(adapter.iProductId), file=self.stdout) retval = adapter.strComName return retval # initialise libCEC def InitLibCec(self): self.lib: cec.ICECAdapter = cec.ICECAdapter.Create(self.cecconfig) # print libCEC version and compilation information print("libCEC version " + self.lib.VersionToString(self.cecconfig.serverVersion) + " loaded: " + self.lib.GetLibInfo()) # search for adapters self.adapter = self.DetectAdapter() if self.adapter == None: print("No adapters found", file=self.stdout) else: if self.lib.Open(self.adapter): print("connection opened", file=self.stdout) else: print("failed to open a connection to the CEC adapter", file=self.stdout) # display the addresses controlled by libCEC @register_mainloop_command('address') def ProcessCommandSelf(self): """Display the address controled by libCEC""" addresses = self.lib.GetLogicalAddresses() strOut = "Addresses controlled by libCEC: " x = 0 notFirst = False while x < 15: if addresses.IsSet(x): if notFirst: strOut += ", " strOut += self.lib.LogicalAddressToString(x) if self.lib.IsActiveSource(x): strOut += " (*)" notFirst = True x += 1 print(strOut, file=self.stdout) # send an active source message @register_mainloop_command("be_as") def CommandActiveSource(self): """make this CEC device the active source""" return self.lib.SetActiveSource() @register_mainloop_command("be_is") def CommandInactiveSource(self): """Broadcast that this CEC device is no longer the source""" return self.lib.SetInactiveView() def GetActiveSource(self): """return the logical address of the currently active source""" return self.lib.GetActiveSource() @register_mainloop_command("sleep_tv") def sleep_TV(self): """ Turn off the TV if this is the active source """ cur_as = self.GetActiveSource() if cur_as <= 15 and cur_as >= 0: if self.lib.GetLogicalAddresses()[cur_as]: self.StandbyDevice(0) self.CommandInactiveSource() def ToggleDevicePower(self, logical_address: int): """toggle the power status of a device""" is_on = self.lib.GetDevicePowerStatus(logical_address) if is_on == cec.CEC_POWER_STATUS_STANDBY or is_on == cec.CEC_POWER_STATUS_UNKNOWN: out = self.PowerOnDevices(logical_address) self.CommandActiveSource() return out if is_on == cec.CEC_POWER_STATUS_ON: self.CommandInactiveSource() return self.StandbyDevice(logical_address) return False @register_mainloop_command("toggle_power") def ProcessToggleDevicePower(self, logical_address: str): "Toggle the power status of the device with the logical address" return self.ToggleDevicePower(str_to_logical_address(logical_address)) @register_mainloop_command("get_as") def ProcessGetActiveSource(self): """Obtain the logical address of the active source""" print(self.GetActiveSource(), file=self.stdout) def StandbyDevice(self, logical_address: int): """ put the device in standby """ return self.lib.StandbyDevices(logical_address) # send a standby command @register_mainloop_command("standby") def ProcessCommandStandby(self, logical_address: str): """Send a standby command""" if not self.StandbyDevice(str_to_logical_address(logical_address)): print("invalid destination", file=self.stdout) def SetLogicalAddress(self, logical_address: int): """set logical adress of the CEC device""" return self.lib.SetLogicalAddress(logical_address) @register_mainloop_command("set_la") def ProcessSetLogicalAddress(self, logical_address: str): """set logical adress of the CEC device""" if not self.SetLogicalAddress(str_to_logical_address(logical_address)): print("command failed", file=self.stdout) def SetHDMIPort(self, base_device_logical_address: int, Port: int): return self.lib.SetHDMIPort(base_device_logical_address, Port) @register_mainloop_command("port") def ProcessSetHDMIPort(self, base_device_logical_address: str, Port: str): "change the HDMI port number of the CEC adapter." base_dev = str_to_logical_address(base_device_logical_address) if not self.lib.SetHDMIPort(base_dev, int(Port)): print("command failed", file=self.stdout) @multidispatch(str) def CommandTx(self, cmd: str): """Send a command on the CEC line, string input""" return self.lib.Transmit(self.lib.CommandFromString(cmd)) @multidispatch(int) def CommandTx(self, cmd: int): """Send a command on the CEC line, integer input""" return self.lib.Transmit(cmd) # send a custom command @register_mainloop_command("tx", "transmit") def ProcessCommandTx(self, data): """Send a custom command""" cmd = self.lib.CommandFromString(data) print("transmit " + data, file=self.stdout) if self.lib.Transmit(cmd): print("command sent", file=self.stdout) else: print("failed to send command", file=self.stdout) # scan the bus and display devices that were found @register_mainloop_command("scan") def Scan(self): """scan the bus and display devices that were found""" print("requesting CEC bus information ...", file=self.stdout) strLog = "CEC bus information\n===================\n" addresses = self.lib.GetActiveDevices() # activeSource = self.lib.GetActiveSource() x = 0 while x < 15: if addresses.IsSet(x): vendorId = self.lib.GetDeviceVendorId(x) physicalAddress = self.lib.GetDevicePhysicalAddress(x) active = self.lib.IsActiveSource(x) cecVersion = self.lib.GetDeviceCecVersion(x) power = self.lib.GetDevicePowerStatus(x) osdName = self.lib.GetDeviceOSDName(x) strLog += ("device #" + str(x) + ": " + self.lib.LogicalAddressToString(x) + "\n") strLog += "address: " + str(hex(physicalAddress)[2:]) + "\n" strLog += "active source: " + str(active) + "\n" strLog += "vendor: " + self.lib.VendorIdToString( vendorId) + "\n" strLog += ("CEC version: " + self.lib.CecVersionToString(cecVersion) + "\n") strLog += "OSD name: " + osdName + "\n" strLog += ("power status: " + self.lib.PowerStatusToString(power) + "\n\n\n") x += 1 print(strLog, file=self.stdout) @register_mainloop_command("volup") def VolumeUp(self): """send a volume up command to the amp if present""" self.lib.VolumeUp() @register_mainloop_command("voldown") def VolumeDown(self): """send a volume down command to the amp if present""" self.lib.VolumeDown() @register_mainloop_command("mute") def AudioToggleMute(self): """send a mute/unmute command to the amp if present""" self.lib.AudioToggleMute() @register_mainloop_command("on") def PowerOnDevices(self, logical_address): """power on the device with the given logical address""" logical_address = str_to_logical_address(logical_address) self.lib.PowerOnDevices(logical_address) def loop(self): if self.adapter: runLoop = True while runLoop: command = self.stdin.readline().strip().lower() if len(command) == 0 or command.isspace(): pass elif command == "q" or command == "quit": print("Exiting...", file=self.stdout) runLoop = False else: command = command.split() if command[0] in self.interactive_cmd: self.interactive_cmd[command[0]](self, *command[1:]) else: print( "unknown command.\n Type 'help' for a list of available commands", file=self.stdout) else: print("initialize the CEC client first!", file=self.stdout) # logging callback def LogCallback(self, level, time, message): if level & self.log_level == 0: return 0 if level == cec.CEC_LOG_ERROR: levelstr = "ERROR: " elif level == cec.CEC_LOG_WARNING: levelstr = "WARNING: " elif level == cec.CEC_LOG_NOTICE: levelstr = "NOTICE: " elif level == cec.CEC_LOG_TRAFFIC: levelstr = "TRAFFIC: " elif level == cec.CEC_LOG_DEBUG: levelstr = "DEBUG: " print(levelstr + "[" + str(time) + "] " + message, file=self.stdout) return 0 # key press callback def KeyPressCallback(self, key, duration): print("[key pressed] " + str(key), file=self.stdout) return 0 def switchback_badpa(self, cmd: str): """ This callback is very specific to this library author's setup. I have an hdmi switch between the soundbar and all my other devices, and that switch is dumb and confuse the hell out of everything that is connected through it. This callback watches for that confusion, and switch the signal route into an acceptable state (for my setup) """ print("[command received] " + cmd, file=self.stdout) # print("chopped command: ", cmd[4:]) if cmd[4:] == "f:82:80:00": # print("switchback!",file=self.stdout) # self.bad_route = True # if cmd == ">> 5f:72:01": self.CommandTx("1f:82:11:00") # self.bad_route = False return 0 # command received callback def CommandCallback(self, cmd: str): print("[command received] " + str(cmd), file=self.stdout) return 0
# Do some checks if (not int(config['cec']['enabled']) == 1) and \ (not int(config['ir']['enabled']) == 1): raise Exception('IR and CEC are both disabled. Can\'t continue.') except Exception as e: print("ERROR: Could not configure:", str(e)) exit(1) ### Setup CEC ### if int(config['cec']['enabled']) == 1: print("Initialising CEC...") try: import cec cec_config = cec.libcec_configuration() cec_config.strDeviceName = "cec-ir-mqtt" cec_config.bActivateSource = 0 cec_config.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) cec_config.clientVersion = cec.LIBCEC_VERSION_CURRENT cec_config.SetLogCallback(cec_on_message) cec_client = cec.ICECAdapter.Create(cec_config) if not cec_client.Open(config['cec']['port']): raise Exception("Could not connect to cec adapter") except Exception as e: print("ERROR: Could not initialise CEC:", str(e)) exit(1) ### Setup IR ### if int(config['ir']['enabled']) == 1: print("Initialising IR...")
class ceccom(threading.Thread): cecconfig = cec.libcec_configuration() lib = {} def run(self): self.logger.info("CECcom thread started") self.commandThread.start() while True: command = self.sendqueue.get() command = '{:x}'.format(command) command = '50:7A:' + command command = self.lib.CommandFromString(command) self.lib.Transmit(command) # create a new libcec_configuration def SetConfiguration(self): self.cecconfig.strDeviceName = "BoseAudio" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_AUDIO_SYSTEM) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT def SetLogCallback(self, callback): self.cecconfig.SetLogCallback(callback) def SetKeyPressCallback(self, callback): self.cecconfig.SetKeyPressCallback(callback) def SetCommandCallback(self, callback): self.cecconfig.SetCommandCallback(callback) # detect an adapter and return the com port path def DetectAdapter(self): retval = None adapters = self.lib.DetectAdapters() for adapter in adapters: self.logger.debug("found a CEC adapter:") self.logger.debug("port: " + adapter.strComName) self.logger.debug("vendor: " + hex(adapter.iVendorId)) self.logger.debug("product: " + hex(adapter.iProductId)) retval = adapter.strComName return retval def getTV(self): self.logger.info("Getting TV address") addresses = self.lib.GetActiveDevices() x = 0 goNext = True while goNext: if addresses.IsSet(x): if (self.lib.LogicalAddressToString(x) == "TV"): self.tv = x goNext = False x += 1 if x > 15: goNext = False def getTVPower(self): self.logger.info("Getting TV power status") power = self.lib.GetDevicePowerStatus(self.tv) if (power == cec.CEC_POWER_STATUS_ON or power == cec.CEC_POWER_STATUS_IN_TRANSITION_STANDBY_TO_ON): self.tv_power = True else: self.tv_power = False # initialise libCEC def InitLibCec(self): self.lib = cec.ICECAdapter.Create(self.cecconfig) # print libCEC version and compilation information self.logger.debug( "libCEC version " + self.lib.VersionToString(self.cecconfig.serverVersion) + " loaded: " + self.lib.GetLibInfo()) # search for adapters adapter = self.DetectAdapter() if adapter == None: self.logger.info("No adapters found") else: if self.lib.Open(adapter): self.logger.info("connection opened") self.getTV() self.getTVPower() if (self.tv_power): ceccom.bosecom.TurnOn() #GET tv power else: print("failed to open a connection to the CEC adapter") # logging callback def LogCallback(self, level, time, message): breakprogram = False if level == cec.CEC_LOG_ERROR: breakprogram = True printcall = self.logger.error elif level == cec.CEC_LOG_WARNING: printcall = self.logger.warning elif level == cec.CEC_LOG_NOTICE: printcall = self.logger.info elif level == cec.CEC_LOG_TRAFFIC: printcall = self.logger.debug elif level == cec.CEC_LOG_DEBUG: printcall = self.logger.debug printcall("LIBCEC:" + message) if (breakprogram): sys.exit() return 0 # # key press callback # def KeyPressCallback(self, key, duration): # print("[Key press recieved] " + key) # return 0 # command received callback def CommandCallback(self, cmd): self.logger.debug("Command recieved: " + cmd) self.commandQueue.put(cmd) return 0 def CommandQueueHandler(self): while True: cmd = self.commandQueue.get() # cmd = re.search('(?<=>> )(.+)', cmd) # cmd = cmd.group(0) if (cmd == '>> 05:44:41'): ceccom.bosecom.VolumeUp() self.logger.info("Volume UP command recieved") elif (cmd == '>> 05:44:42'): ceccom.bosecom.VolumeDown() self.logger.info("Volume Down command recieved") elif (cmd == '>> 0f:36'): ceccom.bosecom.TurnOff() self.logger.info("Volume TurnOff command recieved") elif (cmd == '>> 05:44:43'): ceccom.bosecom.Mute() self.logger.info("Volume Mute command recieved") elif (cmd == '>> 0f:84:00:00:00'): ceccom.bosecom.TurnOn() self.logger.info("Turn On command recieved") def __init__(self, new_queue, bosecomobj, logger): threading.Thread.__init__(self, daemon=True) self.commandQueue = queue.Queue() self.SetConfiguration() ceccom.bosecom = bosecomobj self.sendqueue = new_queue self.logger = logger self.commandThread = threading.Thread(target=self.CommandQueueHandler, daemon=True)
def setup(hass, config): """Setup CEC capability.""" global _CEC try: import cec except ImportError: _LOGGER.error("libcec must be installed") return False # Parse configuration into a dict of device name to physical address # represented as a list of four elements. flat = {} for pair in parse_mapping(config[DOMAIN].get(CONF_DEVICES, {})): flat[pair[0]] = pad_physical_address(pair[1]) # Configure libcec. cfg = cec.libcec_configuration() cfg.strDeviceName = "HASS" cfg.bActivateSource = 0 cfg.bMonitorOnly = 1 cfg.clientVersion = cec.LIBCEC_VERSION_CURRENT # Setup CEC adapter. _CEC = cec.ICECAdapter.Create(cfg) def _power_on(call): """Power on all devices.""" _CEC.PowerOnDevices() def _standby(call): """Standby all devices.""" _CEC.StandbyDevices() def _select_device(call): """Select the active device.""" path = flat.get(call.data[ATTR_DEVICE]) if not path: _LOGGER.error("Device not found: %s", call.data[ATTR_DEVICE]) cmds = [] for i in range(1, MAX_DEPTH - 1): addr = pad_physical_address(path[:i]) cmds.append("1f:82:{}{}:{}{}".format(*addr)) cmds.append("1f:86:{}{}:{}{}".format(*addr)) for cmd in cmds: _CEC.Transmit(_CEC.CommandFromString(cmd)) _LOGGER.info("Selected %s", call.data[ATTR_DEVICE]) def _start_cec(event): """Open CEC adapter.""" adapters = _CEC.DetectAdapters() if len(adapters) == 0: _LOGGER.error("No CEC adapter found") return if _CEC.Open(adapters[0].strComName): hass.services.register(DOMAIN, SERVICE_POWER_ON, _power_on) hass.services.register(DOMAIN, SERVICE_STANDBY, _standby) hass.services.register(DOMAIN, SERVICE_SELECT_DEVICE, _select_device) else: _LOGGER.error("Failed to open adapter") hass.bus.listen_once(EVENT_HOMEASSISTANT_START, _start_cec) return True
def __init__(self, device, source, destination): import cec if source is None: source = 1 if destination is None: destination = 4 if isinstance(source, (str, unicode)): source = int(source, 16) if isinstance(destination, (str, unicode)): destination = int(destination, 16) self.source = source self.destination = destination self.cecconfig = cec.libcec_configuration() self.cecconfig.strDeviceName = "stb-tester" self.cecconfig.bActivateSource = 0 self.cecconfig.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE) self.cecconfig.clientVersion = cec.LIBCEC_VERSION_CURRENT self.lib = cec.ICECAdapter.Create(self.cecconfig) debug( "libCEC version %s loaded: %s" % (self.lib.VersionToString(self.cecconfig.serverVersion), self.lib.GetLibInfo()) ) if device is None: device = self.detect_adapter() if device is None: raise HdmiCecError("No adapter found") if not self.lib.Open(device): raise HdmiCecError("Failed to open a connection to the CEC adapter") debug("Connection to CEC adapter opened")