def __init__(self, config=None):
     cec.init()
     device_list = cec.list_devices()
     self.roku_dev = None
     for dev in device_list:
         print(device_list[dev].osd_string)
         if device_list[dev].osd_string == 'Roku' and 'rokuName' in config:
             print("Finding address for Roku %s" % config['rokuName'])
             all_devices = RokuDevice.RokuDevices()
             try:
                 self.roku_dev = all_devices.get_device(config['rokuName'])
             except:
                 print("Did not find Roku Device %s" % config['rokuName'])
     self.television = None
     if 0 in device_list:
         self.television = {"address": "0", "powerState": "standby"}
     self.receiver = None
     if 5 in device_list:
         self.receiver = {
             "address": "5",
             "powerState": "standby",
             "mute": False,
             "volume": None
         }
     self.acquire_all_status()
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")
コード例 #3
0
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")
コード例 #4
0
 def __init__(self):
     cec.init()
     self.devices = cec.list_devices()
     self.rec_controller = ReceiverController(self.devices)
     self.tv_controller = TvController(self.devices[0], self.rec_controller)
     self.player_callback = None
     cec.add_callback(self.__event_callback, cec.EVENT_COMMAND)
     cec.add_callback(log_cb, cec.EVENT_LOG)
コード例 #5
0
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()
コード例 #6
0
    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
コード例 #7
0
ファイル: main.py プロジェクト: bemcculley/pyTV
    def __init__(self):
        cec.init()
        self.tv = cec.Device(0)
        self.start_tv()
#        os.environ['DISPLAY'] = "0.0"
        self.tk = Tk()
        self.tk.attributes("-fullscreen", True)
        self.frame = Frame(self.tk)
        self.frame.pack()
コード例 #8
0
ファイル: Help.py プロジェクト: selft1/NewsBox
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
コード例 #9
0
 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("==================================")
コード例 #10
0
ファイル: __init__.py プロジェクト: olekenneth/chains
 def action_set_adapter(self, adapter):
     '''
     Set default CEC adapter
     @param  adapter  int  Default adapter ID
     '''
     cec.init(adapter)
     self.adapter = adapter
     meta = {'device': self.adapter}
     if self.location:
         meta.update({'location': self.location})
     self.sendEvent('set_adapter', {'active_adapter': {'value': self.adapter}}, meta)
コード例 #11
0
ファイル: tv.py プロジェクト: philburr/slideshow
    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()
コード例 #12
0
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)
コード例 #13
0
 def action_set_adapter(self, adapter):
     '''
     Set default CEC adapter
     @param  adapter  int  Default adapter ID
     '''
     cec.init(adapter)
     self.adapter = adapter
     meta = {'device': self.adapter}
     if self.location:
         meta.update({'location': self.location})
     self.sendEvent('set_adapter',
                    {'active_adapter': {
                        'value': self.adapter
                    }}, meta)
コード例 #14
0
ファイル: CecSingleton.py プロジェクト: Romalouz/Automation
 def init_cec(self):
     """Method to init cec adapter. Return True if cec initiated successfully"""
     if (self.initiated): return
     adapter = cec.list_adapters()
     if len(adapter) >= 1:
         try:
             cec.init()
             self.adapter = adapter.pop()
             self.devices = cec.list_devices()
             self.initiated = True
             cec.add_callback(cb, cec.EVENT_ALL & ~cec.EVENT_LOG)
             cec.add_callback(log_cb, cec.EVENT_LOG)
         except:
             self.initiated = False
コード例 #15
0
 def onInit(self):
     self.adapters = cec.list_adapters()
     if len(self.adapters) < 1:
         sys.exit('No CEC adapters found')
     else:
         self.adapter = self.adapters[0]
         log.info('Found adapter(s): %s' % str(self.adapters))
         log.info('Using adapter %s' % self.adapter)
         self.sendEvent('current_adapter', {'id': 0})
     cec.init(self.adapter)
     # Service config
     self.interval = self.config.get('interval') or 60
     self.location = self.config.get('location')
     self.cur_service = None
コード例 #16
0
def main():
    """ Inits cec and listens for remote keystrokes
    """
    print('Initializing CEC, please wait...')
    print('If this takes too long ensure the device is not already in use')
    cec.init()
    cec.add_callback(print_keycode, 2)
    print('CEC device initialized, press remote keys or hit ^C to quit')

    try:
        while True:
            sleep(1)
    except KeyboardInterrupt:
        exit(0)
コード例 #17
0
ファイル: cecdaemon.py プロジェクト: Janhouse/cecdaemon
    def __init__(self):
        self.cec = cec
        self._parse_args()
        self._setup_logging()
        logging.info('Initializing CEC device, please wait...')
        cec.init()
        logging.info('CEC Initialized')

        if os.path.isfile(self.args.conffile):
            conf = ConfigParser()
            logging.info('Using config file %s', self.args.conffile)
            conf.read(self.args.conffile)
        else:
            logging.warning('Config file not found')
            conf = None

        try:
            tvconf = conf._sections['tv']
            television = Tv(cec, tvconf)
        except (AttributeError, KeyError):
            television = Tv(cec, None)

        try:
            triggerconf = conf._sections['triggers']
            trigger = Trigger(cec, triggerconf)
        except (AttributeError, KeyError):
            logging.warning(
                'No triggers section found in config, triggers disabled')

        try:
            keymap = conf._sections['keymap']
            remote = Remote(cec, keymap)
        except (AttributeError, KeyError):
            remote = Remote(cec, None)

        if conf is not None:
            for name in [x for x in conf.sections() if x[:4] == 'cmd_']:
                logging.debug('Creating callback for %s', name)

                try:
                    cmd = conf[name]['command']
                    htime = conf[name]['holdtime']
                    key = conf[name]['key']

                    callback = (CustomCommand(cmd, htime))
                    remote.add_callback(callback.run_command, int(key))

                except (AttributeError, KeyError):
                    logging.warning(
                        'Callback for %s not created, check format', name)
コード例 #18
0
ファイル: __init__.py プロジェクト: olekenneth/chains
 def onInit(self):
     self.adapters = cec.list_adapters()
     if len(self.adapters) < 1:
         sys.exit('No CEC adapters found')
     else:
         self.adapter = self.adapters[0]
         log.info('Found adapter(s): %s' % str(self.adapters))
         log.info('Using adapter %s' % self.adapter)
         self.sendEvent('current_adapter', {'id': 0})
     cec.init(self.adapter)
     # Service config
     self.interval = self.config.get('interval') or 60
     self.location = self.config.get('location')
     self.cur_service = None
コード例 #19
0
ファイル: CecSingleton.py プロジェクト: Romalouz/Automation
 def init_cec(self):
     """Method to init cec adapter. Return True if cec initiated successfully"""
     if self.initiated:
         return
     adapter = cec.list_adapters()
     if len(adapter) >= 1:
         try:
             cec.init()
             self.adapter = adapter.pop()
             self.devices = cec.list_devices()
             self.initiated = True
             cec.add_callback(cb, cec.EVENT_ALL & ~cec.EVENT_LOG)
             cec.add_callback(log_cb, cec.EVENT_LOG)
         except:
             self.initiated = False
コード例 #20
0
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")
コード例 #21
0
ファイル: diagnostics.py プロジェクト: rasj81/screenly-ose
def get_display_power():
    """
    Queries the TV using CEC
    """
    try:
        cec.init()
    except:
        return 'CEC error'

    tv = cec.Device(cec.CECDEVICE_TV)
    try:
        tv_status = tv.is_on()
    except IOError:
        return 'Unknown'

    return tv_status
コード例 #22
0
    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()
コード例 #23
0
ファイル: TV.py プロジェクト: brad999/nikita
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, by telling a joke.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user
    """
    cec.init()
    tv = cec.Device(0)

    # !! add volume and mute functions
    if 'on' in text.lower():
        tv.power_on()
        mic.say('I', "TV powered on.")
    elif 'off' in text.lower() or 'off' in text.lower():
        tv.standby()
        mic.say('I', "TV powered off.")
    else:
        mic.say('A', "I'm sorry that command is not currently supported")
コード例 #24
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
コード例 #25
0
ファイル: lms-cec-tw.py プロジェクト: askvictor/lms-cec-tw
        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

if __name__ == '__main__':
    log.startLogging(sys.stdout)
    cec.init()
    cec.list_devices()  # necessary for volume to work
    reactor.connectTCP(config['lms_server'], config['lms_port'], LMSClientFactory())
    root = resource.Resource()
    root.putChild("vol_up", Simple())
    root.putChild("vol_down", Simple())
    root.putChild("power_on", Simple())
    root.putChild("power_off", Simple())
    root.putChild("input", Simple())
    site = server.Site(root)
    reactor.listenTCP(8080, site)
    reactor.run()
コード例 #26
0
def _init_cec():
    cec.init(config.CEC_DEVICE_NAME)
    return cec.Device(cec.CECDEVICE_TV)
コード例 #27
0
def main():
    cec.init()
    wake_pc()
    wake_tv()
    stream_games()
    turn_off_tv()
コード例 #28
0
 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()
コード例 #29
0
ファイル: rpitv.py プロジェクト: adam-stamand/IOT_PI
 def __init__(self, hdmi_source):
     cec.init()
     self.tv = cec.Device(cec.CECDEVICE_TV)
     self.select_source(hdmi_source)
コード例 #30
0
 def configure_cec(self):
     self.turn_off_tvservice()
     cec.init()
     cec.add_callback(self.cec_callback, cec.EVENT_ALL)
コード例 #31
0
 def setupUi(self, Form):
     self.kanavalista = []
     self.nytsoi = []
     self.laskuri = 0
     self.leffaToistuu = False  #kun leffa pyörii
     Form.setObjectName("Form")
     Form.resize(400, 300)
     Form.setStyleSheet("background-color:rgb(41, 85, 74); border: none;")
     self.label = QtWidgets.QLabel(Form)
     self.label.setGeometry(QtCore.QRect(30, 10, 261, 31))
     self.label.setStyleSheet("color: rgb(255, 255, 255);\n"
                              "font: 26pt \"Ubuntu Mono\";")
     self.label.setObjectName("label")
     self.listWidgetKanavalista = QtWidgets.QListWidget(Form)
     self.listWidgetMovielista = QtWidgets.QListWidget(Form)
     self.listWidgetMovielista.setStyleSheet(
         "QListView{background-color:rgb(41, 85, 74); font: 22pt \"Ubuntu Mono\"; color: white;}QListView::item:selected{background-color: rgb(75,153,134); color: yellow;};"
     )
     self.listWidgetMovielista.setHorizontalScrollBarPolicy(
         QtCore.Qt.ScrollBarAlwaysOff)
     self.listWidgetMovielista.hide()
     self.listWidgetKanavalista.setObjectName("listWidget")
     self.listWidgetKanavalista.setViewMode(QtWidgets.QListWidget.IconMode)
     self.retranslateUi(Form)
     QtCore.QMetaObject.connectSlotsByName(Form)
     self.listWidgetKanavalista.setStyleSheet(
         "QListView{font: 16pt \"Ubuntu Mono\"; color: white;}QListView::item:selected{background-color: rgb(75,153,134); color: yellow;}"
     )
     self.listWidgetKanavalista.setVerticalScrollBarPolicy(
         QtCore.Qt.ScrollBarAlwaysOff)
     self.label.move(20, 0)
     monitor = QtWidgets.QDesktopWidget().screenGeometry(
         0)  # Jos useampi monitori käytössä
     self.listWidgetKanavalista.setGeometry(
         QtCore.QRect(100, 30,
                      monitor.width() - 100,
                      monitor.height() - 10))
     self.listWidgetMovielista.setGeometry(
         QtCore.QRect(100, 30,
                      monitor.width() - 100,
                      monitor.height() - 30))
     Form.move(monitor.left(), monitor.top())
     Form.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint
                         | QtCore.Qt.CustomizeWindowHint
                         | QtCore.Qt.FramelessWindowHint)
     Form.showMaximized()
     self.listWidgetKanavalista.setIconSize(QtCore.QSize(200, 120))
     self.listWidgetKanavalista.setResizeMode(QtWidgets.QListWidget.Adjust)
     self.listWidgetKanavalista.setAttribute(
         QtCore.Qt.WA_TranslucentBackground)
     self.listWidgetKanavalista.clicked['QModelIndex'].connect(
         self.klikattuKanava)
     self.listWidgetKanavalista.activated['QModelIndex'].connect(
         self.klikattuKanava)
     self.listWidgetMovielista.clicked['QModelIndex'].connect(
         self.klikattuMovie)
     self.listWidgetMovielista.activated['QModelIndex'].connect(
         self.klikattuMovie)
     self.lueKanavat()
     self.listWidgetKanavalista.setFocus()
     self.listWidgetKanavalista.setCurrentRow(0)
     cec.add_callback(self.nappainPainettu, cec.EVENT_KEYPRESS)
     cec.init()
     self.valvoTimer = QtCore.QTimer()
     self.valvoTimer.setInterval(500)
     self.valvoTimer.timeout.connect(self.recurring_timer)
     self.valvoTimer.start()
コード例 #32
0
import cec

cec.init()

tv = cec.Device(0)
tv.standby()
avr = cec.Device(5)
avr.standby()
コード例 #33
0
ファイル: cectest.py プロジェクト: daftscience/PiPyMote
#!/usr/bin/env python

import time
import cec

adapters = cec.list_adapters()

if len(adapters) > 0:
   adapter = adapters[0]
   cec.init(adapter)

   d = cec.Device(0)

   # d.standby()
   # d.power_on()


   d.set_av_input(01)

 # echo "tx 4F 82 10 00" | cec-client -s -d 1
コード例 #34
0
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)
コード例 #35
0
def setupCECCallback():
    GPIO.setup(36, GPIO.OUT)
    cec.init('RPI')
    cec.add_callback(cb, cec.EVENT_ALL)
 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")
コード例 #37
0
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)
コード例 #38
0
ファイル: main.py プロジェクト: awsomechicken/SimpleViewer
# Main program for displaying the signage videos
# 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
コード例 #39
0
    if len(one_faux) == 2:
        # a fixed port wasn't specified, use a dynamic one
        one_faux.append(0)
    switch = fauxmo(one_faux[0],
                    u,
                    p,
                    None,
                    one_faux[2],
                    action_handler=one_faux[1])

adapters = cec.list_adapters()
dbg(adapters)

if len(adapters) > 0:
    adapter = adapters[0]
    cec.init(adapter)
else:
    cec.init()

tv = cec.Device(0)

dbg("Entering main loop\n")

while True:
    try:
        # Allow time for a ctrl-c to stop the process
        p.poll(100)
        time.sleep(0.1)
    except Exception, e:
        dbg(e)
        break