def main(): # Create cec control cec.init() # Ceate speech recognizer object r = sr.Recognizer() # Create infinite loop while True: # Record sound with sr.Microphone() as source: print("Recording") audio = r.listen(source) try: # Try to recognize the audio command = r.recognize(audio) print(("Detected speech:{0}".format(command))) # Check the current command if TURN_TV_ON in command.lower(): # Get tv device and turn it on tv = cec.Device(0) tv.power_on() elif TURN_TV_OFF in command.lower(): # Get tv device and turn it off tv = cec.Device(0) tv.standby() elif CLOSE_PROGRAM in command.lower(): # Stop program break except LookupError: # In case of an exception print("Could not translate audio")
def TV_On(): cec.init() TV = cec.Device(0) SoundSystem = cec.Device(5) SoundSystem.power_on() time.sleep(3) TV.power_on() time.sleep(1) return
def set_television_status(self, power_state=None, television_state=None): if self.television is None: return if television_state != None and "powerState" in television_state: power_state = television_state["powerState"] 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_television_status() if power_state != None and power_state != self.television["powerState"]: tv = cec.Device(cec.CECDEVICE_TV) if power_state == "standby": if self.roku_dev is not None: self.roku_dev.keypress('Back') time.sleep(1) self.roku_dev.keypress('Home') time.sleep(1) print("TV Standby") retry_count = 0 while retry_count < 5: try: tv.standby() break except: print("Exception with TV Standby") retry_count += 1 print("Retrying %d" % retry_count) else: print("TV Power On") tv.power_on() self.television["powerState"] = power_state return
def tvCommand(command="standby"): import cec cec.init() tv = cec.Device(cec.CECDEVICE_TV) if command == "power_on": return tv.power_on() elif command == "standby": return tv.standby()
def __init__(self): """ This method initializes the class TV_CEC. NO inputs """ cec.init() self.tv = cec.Device(cec.CECDEVICE_TV) self.mute_val = False #False means Unmuted, True means Muted
def broadcast_power_off(self): if self.roku_dev is not None: self.roku_dev.keypress('Back') time.sleep(1) self.roku_dev.keypress('Home') time.sleep(1) broadcast = cec.Device(cec.CECDEVICE_BROADCAST) broadcast.standby() self.acquire_all_status()
def get_display_power(): """ Queries the TV using CEC """ tv = cec.Device(cec.CECDEVICE_TV) try: tv_status = tv.is_on() except IOError: return 'Unknown' return tv_status
def init(self): try: cec.init() # AttributeError: 'module' object has no attribute 'init' self.tv = cec.Device(cec.CECDEVICE_TV) self.serviceRunner.services["MotionSensor"].addCallback( self.callback) self.callback(True) except Exception as e: print("==================================") print("Cannot take control of TV: ", e) print("==================================")
def __init__(self): cec.init() # Force TV to turn on/off self.scheduled_state = self.__should_be_on() self.current_state = not self.scheduled_state self.tv = cec.Device(cec.CECDEVICE_TV) cec.add_callback(self.__response_handler, cec.EVENT_COMMAND) self.running = True self.thr = threading.Thread(target = self.__check_tv) self.thr.start()
def init(): cec.init() global tv tv = cec.Device(0) global on try: if tv.is_on(): on = 1 # avoids polling the tv all the time and causing libCEC errors. else: on = 0 except: on = 0 cec.add_callback(listener, cec.EVENT_LOG)
def cec_reset(): import cec cec.init() tv = cec.Device(cec.CECDEVICE_TV) tv.standby() print("waiting for tv to power off.", end='', flush=True) while tv.is_on() == True: sleep(0.5) print(".", end='', flush=True) print("\n \n waiting for tv to power on.", end='', flush=True) tv.power_on() while tv.is_on() == False: sleep(0.5) print(".", end='', flush=True) print("\n")
def __init__(self): self.event_id = None DBusGMainLoop(set_as_default=True) cec.init() self.sound_bar = cec.Device(cec.CECDEVICE_AUDIOSYSTEM) self.bus = dbus.SystemBus() self.address = '/org/bluez/hci0/dev_' + MAC_ADDRESS.replace(":", "_") self.proxy = self.bus.get_object('org.bluez', self.address) self.device = dbus.Interface(self.proxy, "org.bluez.Device1") self.device.connect_to_signal("PropertiesChanged", self.handle_device_change, dbus_interface=PROPERTIES) self.init_loop() GLib.MainLoop().run()
def picture_update(dt): global image_at global current_picture global images global config while image_at < len(images): current_picture = pic(config.basePath + config.pathSeparator + images[image_at]) if not current_picture.valid(): image_at += 1 else: break now = datetime.datetime.now().time() startt = datetime.time(hour=8, minute=0) endt = datetime.time(hour=23, minute=30) if cecAvailable: istvon = False try: global cec tv = cec.Device(0) istvon = tv.is_on() if startt <= now and endt >= now: if not istvon: tv.power_on() print("Powering TV on...") else: if istvon: tv.standby() istvon = False print("Powering TV off...") except exc: print("Exception in CEC TV handling: ", sys.exc_info()[0]) istvon = False else: istvon = True if istvon: image_at += 1 if image_at >= len(images): images_load() image_at = 0
def current_screentime(): from crontab import CronTab import cec cec.init() tv = cec.Device(cec.CECDEVICE_TV) # CEC initialisieren cron = CronTab(user=True) # finde Cronjob mit "CEC" im Comment iter = cron.find_comment('CEC') for job in iter: if job: return 1 # wenn es einen solchen Cronjob gibt, muss eine Bildschirmzeit existieren try: if(tv.is_on()): # wenn der Fernseher an ist, muss er zwangsl. kontinuierlich eingeschaltet sein return 2 else: # wenn nicht, dann muss er kontinuierlich ausgeschaltet sein return 0 except OSError: return False
def do_POST(self): print("received request.") ctype, pdict = cgi.parse_header(self.headers.get('content-type')) # refuse to receive non-json content if ctype != 'application/json': self.send_response(400) self.end_headers() return # read the message and convert it into a python dictionary length = int(self.headers.get('content-length')) message = json.loads(self.rfile.read(length)) if message.get("command") == "on": try: tv = cec.Device(cec.CECDEVICE_TV) tv.power_on() cec.set_active_source() except e: print(e) self._set_headers() self.wfile.write(json.dumps({"statusMsg": "Success"}).encode("utf8"))
time.sleep(10) os.system("/sbin/reboot") else: print("Restart non necessaire") os.remove(UPDATE_FILE) update() control_mode = get_control_mode() if control_mode == "lg-serial": import serial elif control_mode == "cec": import cec # On initialise le CEC cec.init() tv = cec.Device(0) cec.set_active_source(1) while 1: # Boucle qui pool toutes les 1 min, on utilise pas cron car la connexion au CEC est longue et pas faites pour rester que quelques secondes. Elle est faite pour rester connectee. print "Start Pooling" # Construction du JSON de donnees monitoring jsonData = {} jsonData["temperature"] = round(getCPUtemperature(), 1) #jsonData["heure"] = round(time.time(), 0) load = os.getloadavg() jsonData["load"] = str(load[0]) + " " + str(load[1]) + " " + str(load[2]) jsonData["tv_screen_on"] = False jsonData["ip"] = commands.getoutput( 'hostname -I | awk \'{print $1}\'').strip() jsonData["hostname"] = commands.getoutput('hostname').strip()
def __init__(self): self.cast = pychromecast.Chromecast(self.SPEAKER_IP) self.phue = Bridge(self.BRIDGE_IP) self.hdmi = cec.Device(cec.CECDEVICE_TV) cec.init()
# Simple Signage project # using omxplayer-wrapper try: from omxplayer.player import OMXPlayer except Exception as e: print( "OMXPlayer wrapper not found, please install: \n\t~$ pip3 install omxplayer-wrapper\n\nSee:\n\thttps://python-omxplayer-wrapper.readthedocs.io/en/latest/" ) # using python-CEC # https://github.com/trainman419/python-cec/ try: import cec cec.init() # start the CEC daemon tv = cec.Device(cec.CECDEVICE_TV) except Exception as e: print( "Python-CEC Not found, pleae install using the instructions found here:\n\thttps://github.com/trainman419/python-cec/" ) print( "If install fails, the package may not be installed in PyPI yet, try installing using:\n\tpip install git+https://github.com/trainman419/[email protected]#egg=cec" ) from pathlib import Path # configuration parser library, included as part of python # https://docs.python.org/3/library/configparser.html import configparser import time, datetime, pytz, os, sys, requests, random, string, shutil, json # Configuration object:
def __init__(self): tv = cec.Device(0)
def _init_cec(): cec.init(config.CEC_DEVICE_NAME) return cec.Device(cec.CECDEVICE_TV)
def wake_tv(): tv = cec.Device(0) print("Turning on TV...") tv.power_on()
import cec from fauxmo.plugins import FauxmoPlugin cec.init() stereo = cec.Device(CECDEVICE_AUDIOSYSTEM) broadcast = cec.Device(CECDEVICE_BROADCAST) class cecplugin(FauxmoPlugin): def __init__(self, name: str, port: int, on_cmd: str, off_cmd: str, state_cmd: str = None) -> None: self.on_cmd = on_cmd self.off_cmd = off_cmd self.state_cmd = state_cmd super().__init__(name=name, port=port) def run_cmd(self, cmd: str) -> bool: """Partialmethod to run command. Args: cmd: Command to be run Returns: True if command seems to have run without error """ cmds = cmd.split(",")
import cec cec.init() tv = cec.Device(0) tv.standby() avr = cec.Device(5) avr.standby()
def TV_Off(): SoundSystem = cec.Device(5) TV = cec.Device(0) TV.standby() SoundSystem.standby() return
def turn_off_tv(): tv = cec.Device(0) print("Turning off TV...") tv.standby()
def _init_cec_connection(self): self.logger.debug("Initializing HDMI CEC connection...") cec.init() self.hdmi_cec_device = cec.Device(cec.CECDEVICE_TV) self.standby() self.logger.info("Successfully initialized HDMI CEC connection")
import cec cec.init() avr = cec.Device(5) avr.set_av_input(2) avr.set_audio_input(2)
def get_tv_state(): # devices = cec.list_devices() tv = cec.Device(0) # Assume TV is first device return tv.is_on()
def __init__(self, hdmi_source): cec.init() self.tv = cec.Device(cec.CECDEVICE_TV) self.select_source(hdmi_source)
broker = 'homeassistant' # MQTT broker user credentials username = '******' clientname = 'stereoclient' # appropriate MQTT topics power_state_topic = 'home/stereo/power/state' power_command_topic = 'home/stereo/power/cmd' airplay_state_topic = 'home/stereo/airplay/state' airplay_command_topic = 'home/stereo/airplay/cmd' availability_topic = 'home/stereo/availability' # Number of minutes between checking power state of audio reciever via CEC check_status_interval_minutes = 1 # define CEC device handles stereo = cec.CECDEVICE_AUDIOSYSTEM broadcast = cec.CECDEVICE_BROADCAST stereo_device = cec.Device(stereo) # Initialize CEC adapter cec.init() # Read in MQTT Broker user password from file file = open('pass', 'r') password = file.read().rstrip() file.close() # TODO Setup proper logging, currently being handled by Systemd service #file = open('./mqtt-cec.log') # Method for checking power status of HDMI audio Receiver def check_power_status(): sleep(60 * check_status_interval_minutes) if stereo_device.is_on(): client.publish(power_state_topic, payload='ON')