예제 #1
0
def main():
    """Do the test"""

    starttime = datetime.now()

    def on_ihc_change(ihcid, value):
        """Callback when ihc resource changes"""
        print("Resource change " + str(ihcid) + "->" + str(value) + " time: " +
              gettime())

    def gettime():
        dif = datetime.now() - starttime
        return str(dif)

    cmdline = open(".parameters", "rt").read()
    args = cmdline.split(" ")
    if len(args) != 4:
        print(
            "The '.parameters' file should contain: ihcurl username password resourceid"
        )
        exit()
    url = args[0]
    username = args[1]
    password = args[2]
    resid = int(args[3])
    if not IHCController.is_ihc_controller(url):
        print("The device in this url does not look like a IHC controller")
        exit()
    print("Url response like a IHC controller - now authenticating")

    ihc = IHCController(url, username, password)
    if not ihc.authenticate():
        print("Authenticate failed")
        exit()

    print("Authenticate succeeded\r\n")

    # read the ihc project
    project = ihc.get_project()
    if project is False:
        print("Failed to read project")
    else:
        print("Project downloaded successfully")

    log = ihc.client.get_user_log()
    if log:
        print("log: " + log)

    info = ihc.client.get_system_info()
    print(info)

    runtimevalue = ihc.get_runtime_value(resid)
    print("Runtime value: " + str(runtimevalue))
    ihc.set_runtime_value_bool(resid, not runtimevalue)
    runtimevalue = ihc.get_runtime_value(resid)
    print("Runtime value: " + str(runtimevalue))

    ihc.client.enable_runtime_notification(resid)
    changes = ihc.client.wait_for_resource_value_changes(10)
    print(repr(changes))

    ihc.add_notify_event(resid, on_ihc_change, True)

    while True:
        i = input()
        if i == "1":
            starttime = datetime.now()
            ihc.set_runtime_value_bool(resid, False)
            continue
        if i == "2":
            starttime = datetime.now()
            ihc.set_runtime_value_bool(resid, True)
            continue
        if i == "q":
            break
    ihc.disconnect()
    ihc.client.connection.session.close()
예제 #2
0
파일: ihc.py 프로젝트: idhe-dev/ihc
def main():
    def on_ihc_change(ihcid, value):
        """Callback when ihc resource changes"""
        logging.info("Resource change " + str(ihcid) + "->" + str(value))
        tmp = {}
        tmp["method"] = "updateValue"
        tmp["ResourceID"] = str(ihcid)
        tmp["Value"] = str(value)

        jeedomCom.send_change_immediate(tmp)

    url = "http://" + _controllerIP

    if not IHCController.is_ihc_controller(url):
        print("The device in this url does not look like a IHC controller")
        exit()

    ihc = IHCController(url, _controllerID, _controllerPW)
    if not ihc.authenticate():
        logging.info("Authenticate failed")
        exit()
    logging.info("Authenticate succeeded\r\n")

    def read_socket():
        global JEEDOM_SOCKET_MESSAGE
        if not JEEDOM_SOCKET_MESSAGE.empty():
            logging.debug("Message received in socket JEEDOM_SOCKET_MESSAGE")
            message = json.loads(JEEDOM_SOCKET_MESSAGE.get().decode('utf-8'))
            try:
                if message['method'] == 'IHC_Write':
                    try:
                        ihc.set_runtime_value_bool(message['resid'],
                                                   message['cmd'])
                    except Exception as e:
                        logging.error('IHC_Write error : ' + str(e))
                elif message['method'] == 'IHC_Notify':
                    try:
                        for i in range(0, len(message['resids'])):
                            ResourceId = int(
                                message['resids'][i]['ResourceID'])
                            ihc.add_notify_event(ResourceId, on_ihc_change,
                                                 True)
                    except Exception as e:
                        logging.error('IHC_Notify error : ' + str(e))
                elif message['method'] == 'IHC_Read':
                    try:
                        value = ihc.get_runtime_value(message['resid'])
                        tmp = {}
                        tmp["method"] = "updateValue"
                        tmp["ResourceID"] = message['resid']
                        tmp["Value"] = str(value)
                        jeedomCom.send_change_immediate(tmp)
                    except Exception as e:
                        logging.error('IHC_Read error : ' + str(e))
                else:
                    logging.error("unknown method:" + str(message['method']))
            except Exception as e:
                logging.error('Send command to demon error : ' + str(e))

    def listen():
        logging.debug("Start listening")
        jeedomSocket.open()
        #lastPing = 0
        #ping(lastPing)
        count = 0
        try:
            while 1:
                while count < 1500:
                    time.sleep(0.01)
                    count = count + 1
                    read_socket()
                else:
                    #lastPing = ping(lastPing)
                    time.sleep(0.01)
                    read_socket()
                    count = 0
        except KeyboardInterrupt:
            shutdown()

    def ping(lastPing):
        ping = os.system("ping -c 1 " + _controllerIP)
        if ((ping == 0) and (ping != lastPing)):
            lastPing = ping
            logging.debug("Network Active")
            tmp = {}
            tmp["method"] = "networkStatus"
            tmp["status"] = 'True'
            jeedomCom.send_change_immediate(tmp)
        if ((ping != 0) and (ping != lastPing)):
            lastPing = ping
            logging.debug("Network Error")
            tmp = {}
            tmp["method"] = "networkStatus"
            tmp["status"] = 'False'
            jeedomCom.send_change_immediate(tmp)
        return ping

    # ----------------------------------------------------------------------------

    def handler(signum=None, frame=None):
        logging.debug("Signal %i caught, exiting..." % int(signum))
        shutdown()

    def shutdown():
        logging.debug("Shutdown")
        ihc.disconnect()
        ihc.client.connection.session.close()
        logging.debug("Removing PID file " + str(_pidfile))
        try:
            os.remove(_pidfile)
        except:
            pass
        try:
            jeedomSocket.close()
        except:
            pass
        logging.debug("Exit 0")
        sys.stdout.flush()
        os._exit(0)

    # ----------------------------------------------------------------------------

    signal.signal(signal.SIGINT, handler)
    signal.signal(signal.SIGTERM, handler)

    try:
        jeedom_utils.write_pid(str(_pidfile))
        jeedomSocket = jeedom_socket(port=_socket_port, address=_socket_host)
        jeedomCom = jeedom_com(apikey=_apikey, url=_callback, cycle=_cycle)

        listen()
    except Exception as e:
        logging.error('Fatal error : ' + str(e))

    shutdown()