Beispiel #1
0
def actionSwitchTurnon(resultFile, iterNum=100, interval=1, timeLimit=1000):
    resultFd = open(resultFile, "a")
    testUuid = uuid.uuid4()
    startTime = time.time()
    bind = "0.0.0.0:{}".format(10085)
    switchName = "WeMo Switch"
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    wemoController.turnoffSwitch(switchName)
    for index in range(iterNum):
        currTimeCost = time.time() - startTime
        if currTimeCost > timeLimit:
            print("time out, quit")
            return
        if not wemoController.isSwitchOn(switchName):
            time.sleep(interval)
            continue
        actionTime = datetime.datetime.now()
        statStr = "testUuid: {}->actionResultObservedTime: {}->sheet".format(
            testUuid, actionTime.strftime(datetimeFormat))
        print(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()
        wemoController.turnoffSwitch(switchName)
        time.sleep(interval)
    resultFd.close()
    pass
def triggerWemoTurnon(resultFile, iterNum=100, interval=1, timeLimit=1000):
    resultFd = open(resultFile, "a")
    testUuid = uuid.uuid4()
    bind = "0.0.0.0:{}".format(10085)
    switchName = "WeMo Switch"
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    startTime = time.time()
    for index in range(iterNum):
        currTimeCost = time.time() - startTime
        if currTimeCost > timeLimit:
            print("time out, quit")
            return
        wemoController.turnonSwitch(switchName)
        triggerTime = datetime.datetime.now()
        print("send out voice command to alexa")
        statStr = "testUuid: {}->triggerGeneratedTime: {}->hueBed".format(
            testUuid, triggerTime.strftime(datetimeFormat))
        print(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()
        time.sleep(1)
        wemoController.turnoffSwitch(switchName)
        time.sleep(interval)
    resultFd.close()
    pass
Beispiel #3
0
def testAlexaWemoRecipe(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("resultFile")
    parser.add_argument("-timeLimit", default=120, type=int)
    parser.add_argument("-wemoport", type=int, default=10085)
    parser.add_argument("-interval", default=0.1, type=float)
    options = parser.parse_args(argv)
    audioFile = "alexa/audioFiles/AlexaTriggerTurnOnSwitch.wav"
    alexaController = alexa.AlexaController()
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch"
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    wemoController.turnoffSwitch(switchName)
    time.sleep(3)
    resultStatList = []
    index = -1
    overallStartTime = time.time()
    while True:
        index += 1
        currTime = time.time()
        if currTime - overallStartTime >= options.timeLimit:
            break
        print("start test iteration {}".format(index))
        alexaController.saySomething(audioFile)
        print("alexa phrase said")
        startTime = datetime.datetime.now()
        while (True):
            if wemoController.isSwitchOn(switchName):
                break
            time.sleep(options.interval)
        endTime = datetime.datetime.now()
        timeDiff = endTime - startTime
        timeCost = timeDiff.seconds + timeDiff.microseconds / float(1000000)
        statStr = "time cost for iter {} is {} seconds".format(index, timeCost)
        print(statStr)
        resultStatList.append(statStr)
        wemoController.turnoffSwitch(switchName)
        print("sleep before next test")
        time.sleep(5)
    open(options.resultFile, "w").write("\n".join(resultStatList) + "\n")
Beispiel #4
0
def testWemoWebRecipe(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("resultFile", type=str)
    parser.add_argument("-timeLimit", default=50, type=int)
    parser.add_argument("-triggerInterval", default=1, type=int)
    parser.add_argument("-wemoport", type=int, default=10085)
    options = parser.parse_args(argv)
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch1"
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    switchThread = BurstWemoThread(wemoController,
                                   switchName,
                                   interval=options.triggerInterval)
    switchThread.start()
    actionBurstList = []
    startTime = time.time()
    while True:
        currTime = time.time()
        if currTime >= startTime + options.timeLimit:
            break
        time.sleep(1)
    switchThread.isStop = True
    switchThread.join()
    eventList = []
    eventList.extend(switchThread.triggerList)
    sortedEventList = sorted(eventList, key=lambda item: item[0])
    with open(options.resultFile, mode="w", encoding="utf-8") as fd:
        for event in sortedEventList:
            timeStr = event[1]
            type = event[2]
            fd.write("{}: {}\n".format(type, timeStr))
Beispiel #5
0
def testWemoHueLocalRecipe(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("-iterNum", default = 5, type = int)
    parser.add_argument("-lightId", default = 2, type = int)
    parser.add_argument("-wemoport", type = int, default = 10085)
    options = parser.parse_args(argv)
    hueController = hue.HueController()
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch1"
    lightId = options.lightId
    wemoController = wemo.WemoController(bind = bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
      print("error to locate the switch")
      sys.exit(1)
    else:
      print("switch discoverred")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    hueController.turnonLight(lightId)
    time.sleep(3)
    for index in range(options.iterNum):
      print("start test iteration {}".format(index))
      hueController.turnoffLight(lightId)
      wemoController.turnoffSwitch(switchName)

      #generate trigger event: turn on switch
      wemoController.turnonSwitch(switchName)
      print("switch turned one")
      startTime = datetime.datetime.now()
      while (True):
        if hueController.isLightOn(lightId):
          break
        time.sleep(0.5)
      endTime = datetime.datetime.now()
      timeDiff = endTime - startTime
      print("time cost for iter {} is {} seconds and microseconds {}".format(index, timeDiff.seconds, timeDiff.microseconds))
      print("sleep before next test")
      time.sleep(5)
Beispiel #6
0
def triggerMonitor(argv):
    parser = argparse.ArgumentParser("trigger monitor")
    parser.add_argument("resultFile", type=str)
    parser.add_argument("-targetDeviceId",
                        default=None,
                        choices=list(deviceIdDict.keys()),
                        type=int)
    parser.add_argument("-targetDeviceState", default=None, type=int)
    parser.add_argument("-isRealTime", action="store_true")
    parser.add_argument("-timeLimit", default=None, type=int)
    parser.add_argument("-interval", default=1, type=float)
    options = parser.parse_args(argv)
    hueController = hue.HueController()
    bind = "0.0.0.0:10087"
    wemoController = wemo.WemoController(bind=bind)
    switchName = "WeMo Switch"
    switch = wemoController.discoverSwitch(switchName, timeout=60)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    deviceMonitorDict = {
        1: wemoController,
        2: hueController,
        3: hueController,
    }
    resultFile = options.resultFile
    targetDeviceState = options.targetDeviceState
    targetDeviceId = options.targetDeviceId
    pollInterval = options.interval
    timeLimit = options.timeLimit
    isRealTime = options.isRealTime

    #configure logger
    formatter = logging.Formatter(logFormat)
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    streamHandler.setLevel(logging.DEBUG)
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)
    logger.info("start to monitor trigger events locally")

    startTime = time.time()
    if targetDeviceId is None:
        deviceListToMonitor = list(deviceIdDict.keys())
    else:
        deviceListToMonitor = [targetDeviceId]
    logger.info("targets are %s", deviceListToMonitor)
    preStateDict = {}
    statList = []
    resultFd = open(resultFile, "a")
    while True:
        try:
            #check possible timeout
            if timeLimit is not None:
                currTime = time.time()
                if currTime - startTime > timeLimit:
                    logger.info("time out, quit monitoring")
                    break
            #check latest states for the given list of devices
            for deviceId in deviceListToMonitor:
                monitor = deviceMonitorDict[deviceId]
                deviceLocalId = deviceIdDict[deviceId]
                deviceState = monitor.getState(deviceLocalId)
                #logger.debug("current device status is %d", deviceState)
                #initial state, no checking, no updates
                if deviceId not in preStateDict:
                    preStateDict[deviceId] = deviceState
                    continue
                preState = preStateDict[deviceId]
                isUpdate = False
                if targetDeviceState is None and deviceState != preState:
                    isUpdate = True
                if targetDeviceState is not None:
                    if targetDeviceState != preState and targetDeviceState == deviceState:
                        isUpdate = True

                #log update time, send updates to server, send realtime notification if needed
                if isUpdate:
                    updateUuid = uuid.uuid4()
                    updateTime = datetime.datetime.now()
                    tempStat = "triggerUUID: {}->triggerEventObservedTime: {}->deviceId: {}->devicePreState: {}->deviceNewState: {}".format(
                        updateUuid, updateTime.strftime(datetimeFormat),
                        deviceId, preState, deviceState)
                    statList.append(tempStat)
                    resultFd.write(tempStat + "\n")
                    resultFd.flush()
                    logger.info(tempStat)
                    preStateDict[deviceId] = deviceState
                    #send updates to server
                    sendUpdateResult = ssu.sendEvent2Server(
                        deviceId, deviceState)
                    if sendUpdateResult == False:
                        logger.warning("error when sending updates to server")
                        continue
                    updateSentTime = datetime.datetime.now()
                    tempStat = "triggerUUID: {}->triggerEventSyncedTime: {}->deviceId: {}->devicePreState: {}->deviceNewState: {}".format(
                        updateUuid, updateSentTime.strftime(datetimeFormat),
                        deviceId, preState, deviceState)
                    statList.append(updateTime)
                    resultFd.write(tempStat + "\n")
                    resultFd.flush()
                    logger.info(tempStat)

                    #send realtime notification if enabled
                    triggerIdentity = triggerIdentityDict[deviceId]
                    if isRealTime and triggerIdentity is not None:
                        realtimeResult = ssu.realtimeApi([triggerIdentity])
                        if realtimeResult == False:
                            logger.warning(
                                "error when sending realtime notifications")
                            continue
                        realtimeSentTime = datetime.datetime.now()
                        tempStat = "triggerUUID: {}->realTimeSentTime: {}->deviceId: {}->devicePreState: {}->deviceNewState: {}".format(
                            updateUuid,
                            realtimeSentTime.strftime(datetimeFormat),
                            deviceId, preState, deviceState)
                        statList.append(updateTime)
                        resultFd.write(tempStat + "\n")
                        resultFd.flush()
                        logger.info(tempStat)
                preStateDict[deviceId] = deviceState
            time.sleep(pollInterval)
        except Exception as e:
            logger.error("exception occurred: %s", traceback.format_exc())
            continue
    resultFd.close()
Beispiel #7
0
def actionMonitor(argv):
    parser = argparse.ArgumentParser("action monitor")
    parser.add_argument("resultFile", type=str)
    parser.add_argument("-targetDeviceId",
                        default=None,
                        choices=list(deviceIdDict.keys()),
                        type=int)
    parser.add_argument("-targetDeviceState", default=None, type=int)
    parser.add_argument("-timeLimit", default=None, type=int)
    parser.add_argument("-interval", default=1, type=float)
    options = parser.parse_args(argv)
    hueController = None
    wemoController = None
    hueController = hue.HueController()
    bind = "0.0.0.0:10088"
    wemoController = wemo.WemoController(bind=bind)
    switchName = "WeMo Switch"
    switch = wemoController.discoverSwitch(switchName, timeout=60)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    deviceMonitorDict = {
        1: wemoController,
        2: hueController,
        3: hueController,
    }
    resultFile = options.resultFile
    targetDeviceState = options.targetDeviceState
    targetDeviceId = options.targetDeviceId
    pollInterval = options.interval
    timeLimit = options.timeLimit

    #configure logger
    formatter = logging.Formatter(logFormat)
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    streamHandler.setLevel(logging.DEBUG)
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)

    startTime = time.time()
    preStateDict = {}
    statList = []
    resultFd = open(resultFile, "a")
    while True:
        try:
            #check possible timeout
            if timeLimit is not None:
                currTime = time.time()
                if currTime - startTime > timeLimit:
                    logger.info("time out, quit monitoring")
                    break
            #check latest states for the given list of devices
            newActionList = ssu.getActionFromServer(
                deviceId=targetDeviceId, deviceState=targetDeviceState)
            if len(newActionList) <= 0:
                time.sleep(pollInterval)
                continue
            #logger.debug("got those new actions %s", newActionList)
            #try to execute those ,4
            for action in newActionList:
                actionUuid = uuid.uuid4()
                deviceId = int(action["deviceId"])
                deviceState = int(action["deviceState"])
                actionId = int(action["id"])
                actionCreateTime = action["createTime"]
                deviceMonitor = deviceMonitorDict[deviceId]
                deviceLocalId = deviceIdDict[deviceId]

                #execute the action command
                actionResult = True
                actionResult = deviceMonitor.setState(deviceLocalId,
                                                      deviceState)
                if actionResult == False:
                    logger.warning("error when executing action command")
                    continue
                actionTime = datetime.datetime.now()
                tempStat = "actionUUID: {}->actionCreateTime: {}->deviceId: {}->deviceState: {}->actionId: {}".format(
                    actionUuid, actionCreateTime, deviceId, deviceState,
                    actionId)
                statList.append(tempStat)
                resultFd.write(tempStat + "\n")
                resultFd.flush()
                logger.info(tempStat)
                tempStat = "actionUUID: {}->actionDetectTime: {}->deviceId: {}->deviceState: {}->actionId: {}".format(
                    actionUuid, actionTime.strftime(datetimeFormat), deviceId,
                    deviceState, actionId)
                statList.append(tempStat)
                resultFd.write(tempStat + "\n")
                resultFd.flush()
                logger.info(tempStat)

                #send action results to server
                actionIdList = [actionId]
                actionStateList = [1]
                actionSyncResult = ssu.updateActionResult2Server(
                    actionIdList, actionStateList)
                if actionSyncResult == False:
                    logger.warning(
                        "error when sync action results to server side")
                    continue
                actionSyncTime = datetime.datetime.now()
                tempStat = "actionUUID: {}->actionSyncTime: {}->deviceId: {}->deviceState: {}->actionId: {}".format(
                    actionUuid, actionSyncTime.strftime(datetimeFormat),
                    deviceId, deviceState, actionId)
                statList.append(tempStat)
                resultFd.write(tempStat + "\n")
                resultFd.flush()
                logger.info(tempStat)
            time.sleep(pollInterval)
        except Exception as e:
            logger.error("exception occurred: %s", traceback.format_exc())
            continue
    resultFd.close()
Beispiel #8
0
def testWemoHueRecipe(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("resultFile", type=str)
    parser.add_argument("-iterNum", default=5, type=int)
    parser.add_argument("-actionDuration", default=10, type=int)
    parser.add_argument("-triggerInterval", default=10, type=int)
    parser.add_argument("-lightId", default=2, type=int)
    parser.add_argument("-actionInterval", default=0.5, type=float)
    parser.add_argument("-wemoport", type=int, default=10085)
    options = parser.parse_args(argv)
    hueController = hue.HueController()
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch1"
    lightId = options.lightId
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    hueController.turnonLight(lightId)
    time.sleep(3)
    hueController.turnoffLight(lightId)
    switchThread = BurstWemoThread(wemoController,
                                   switchName,
                                   interval=options.triggerInterval)
    switchThread.start()
    actionBurstList = []
    for index in range(options.iterNum):
        print("start test iteration {}".format(index))
        oneBurst = []
        hueController.turnoffLight(lightId)
        overallStartTime = datetime.datetime.now()
        lastTime = None
        while (True):
            if lastTime != None:
                timeDiff = datetime.datetime.now() - lastTime
                if timeDiff.seconds >= options.actionDuration:
                    burstEndTime = lastTime
                    break
            if hueController.isLightOn(lightId):
                actionTime = datetime.datetime.now()
                timeStr = actionTime.strftime("%Y-%M-%d %H:%M:%S:%f")
                print("new action at time ", timeStr)
                oneBurst.append((actionTime, timeStr, "action"))
                if lastTime is None:
                    burstStartTime = actionTime
                lastTime = actionTime
                hueController.turnoffLight(lightId)
            time.sleep(options.actionInterval)
        overallEndTime = datetime.datetime.now()
        overallTimeDiff = overallEndTime - overallStartTime
        overallTimeDiff = overallTimeDiff.seconds + overallTimeDiff.microseconds / 1000000
        burstDuration = burstEndTime - burstStartTime
        burstDuration = burstDuration.seconds + burstDuration.microseconds / 1000000
        actionBurstList.append((oneBurst, overallTimeDiff, burstDuration))
        print(
            "iteration: {}, overall: {:.2f} seconds, burst: {:.2f} seconds, actions: {}"
            .format(index, overallTimeDiff, burstDuration, len(oneBurst)))
    switchThread.isStop = True
    switchThread.join()
    eventList = []
    for burstTuple in actionBurstList:
        burst = burstTuple[0]
        for action in burst:
            eventList.append(action)
    eventList.extend(switchThread.triggerList)
    sortedEventList = sorted(eventList, key=lambda item: item[0])
    with open(options.resultFile, mode="w", encoding="utf-8") as fd:
        for event in sortedEventList:
            timeStr = event[1]
            type = event[2]
            fd.write("{}: {}\n".format(type, timeStr))
Beispiel #9
0
            self.eventList.append(datetime.now())
        if len(self.triggerStateList) == self.queueSize:
            self.triggerStateList.pop(0)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-lightId", default=2, type=int)
    parser.add_argument("-sleep", default=1, type=float)
    parser.add_argument("-wemoport", type=int, default=10085)
    options = parser.parse_args()
    hueController = hue.HueController()
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch1"
    lightId = options.lightId
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    hueController.turnonLight(lightId)
    time.sleep(3)
    hueController.turnoffLight(lightId)
    recipe = WemoHueRecipe(wemoController, hueController, switchName, lightId)
    recipeList = [recipe]
    while True:
        time.sleep(options.sleep)
        for recipe in recipeList:
Beispiel #10
0
def testWemoHueRecipe(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("resultFile")
    parser.add_argument("-timeLimit", default=100, type=int)
    parser.add_argument("-lightId", default=2, type=int)
    parser.add_argument("-interval", default=1, type=float)
    parser.add_argument("-wemoport", type=int, default=10085)
    options = parser.parse_args(argv)
    resultFile = options.resultFile
    hueController = hue.HueController()
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch"
    lightId = options.lightId
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    hueController.turnonLight(lightId)
    time.sleep(3)
    resultStatList = []
    resultFd = open(resultFile, "a")
    index = -1
    overallStartTime = time.time()
    while True:
        index += 1
        currTime = time.time()
        if currTime - overallStartTime >= options.timeLimit:
            break
        print("start test iteration {}".format(index))
        hueController.turnoffLight(lightId)
        wemoController.turnoffSwitch(switchName)
        time.sleep(5)

        #generate trigger event: turn on switch
        wemoController.turnonSwitch(switchName)
        print("switch turned one")
        triggerGeneratedTime = datetime.datetime.now()
        startTime = datetime.datetime.now()
        while (True):
            if hueController.isLightOn(lightId):
                break
            time.sleep(options.interval)
        endTime = datetime.datetime.now()
        timeDiff = endTime - startTime
        timeCost = timeDiff.seconds + timeDiff.microseconds / float(1000000)
        testUuid = uuid.uuid4()
        statStr = "testUuid: {}->triggerGeneratedTime: {}->wemo_hue".format(
            testUuid, triggerGeneratedTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "testUuid: {}->actionResultObservedTime: {}->wemo_hue".format(
            testUuid, endTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "testUuid: {}->time cost for wemo_hue iter {} is {} seconds".format(
            testUuid, index, timeCost)
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()
        time.sleep(5)
    resultFd.close()
    hueController.turnoffLight(lightId)
    wemoController.turnoffSwitch(switchName)
Beispiel #11
0
def testWemoGoogleSheetRecipe(argv):
    '''
    test the following recipe:
    If You say "Alexa trigger turn on hue light", then turn on lights in  Living room
    '''
    parser = argparse.ArgumentParser()
    parser.add_argument("resultFile")
    parser.add_argument("-timeLimit", default=100, type=int)
    parser.add_argument("-interval", default=1, type=float)
    parser.add_argument("-wemoport", type=int, default=10085)
    spreadsheetId = "1TwPsEXIQ0tZPnFABwKqePshDw3x0kFozaP69Nsw95ug"
    sheetName = "Sheet1"
    options = parser.parse_args(argv)
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch"
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    sheetController = GoogleSheetController()
    spreadsheet = sheetController.getSpreadSheet(spreadsheetId)
    print("got spreadsheet: ", sheetController.getSpreadSheet(spreadsheetId))
    retrievedSheetName = spreadsheet["sheets"][0]["properties"]["title"]
    print("title of first sheet is ",
          spreadsheet["sheets"][0]["properties"]["title"])
    if retrievedSheetName != sheetName:
        print(
            "sheet name doesn't match, use retrieved one: preconfigured one: {}, retrieved one {}"
            .format(sheetName, retrievedSheetName))
        sheetName = retrievedSheetName
    currentRowList = sheetController.getRowList(spreadsheetId, range=sheetName)
    print("current row list", currentRowList)
    resultStatList = []
    wemoController.turnoffSwitch(switchName)
    resultFd = open(options.resultFile, "a")
    #test recipe: when wemo switch is truned on, write a log to the google spreadsheet
    index = -1
    overallStartTime = time.time()
    while True:
        index += 1
        currTime = time.time()
        if currTime - overallStartTime >= options.timeLimit:
            break
        time.sleep(5)
        wemoController.turnonSwitch(switchName)
        triggerGeneratedTime = datetime.datetime.now()
        print("switch turned on")
        startTime = datetime.datetime.now()
        while (True):
            latestRowList = sheetController.getRowList(spreadsheetId,
                                                       range=sheetName)
            if latestRowList is not None and len(latestRowList) > len(
                    currentRowList):
                print(latestRowList[-1])
                currentRowList = latestRowList
                break
            if latestRowList is None:
                print("error when requesting latest row list")
            time.sleep(options.interval)
        endTime = datetime.datetime.now()
        timeDiff = endTime - startTime
        timeCost = timeDiff.seconds + timeDiff.microseconds / float(1000000)
        testUuid = uuid.uuid4()
        statStr = "testUuid: {}->triggerGeneratedTime: {}->wemo_sheet".format(
            testUuid, triggerGeneratedTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "testUuid: {}->actionResultObservedTime: {}->wemo_sheet".format(
            testUuid, endTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "testUuid: {}->time cost for iter {} is {} seconds".format(
            testUuid, index, timeCost)
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()
        wemoController.turnoffSwitch(switchName)
        #generate trigger event: speak to alexa: change a music
    resultFd.close()
    print(resultStatList)
def testWemoGoogleSheetRecipe(argv):
    '''
    test the following recipe:
    If You say "Alexa trigger turn on hue light", then turn on lights in  Living room
    '''
    parser = argparse.ArgumentParser()
    parser.add_argument("resultFile")
    parser.add_argument("-iterNum", default=5, type=int)
    parser.add_argument("-interval", default=1, type=float)
    parser.add_argument("-wemoport", type=int, default=10085)
    spreadsheetId = "1TwPsEXIQ0tZPnFABwKqePshDw3x0kFozaP69Nsw95ug"
    sheetName = "Sheet1"
    options = parser.parse_args(argv)
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch"
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    sheetController = GoogleSheetController()
    spreadsheet = sheetController.getSpreadSheet(spreadsheetId)
    print("got spreadsheet: ", sheetController.getSpreadSheet(spreadsheetId))
    retrievedSheetName = spreadsheet["sheets"][0]["properties"]["title"]
    print("title of first sheet is ",
          spreadsheet["sheets"][0]["properties"]["title"])
    if retrievedSheetName != sheetName:
        print(
            "sheet name doesn't match, use retrieved one: preconfigured one: {}, retrieved one {}"
            .format(sheetName, retrievedSheetName))
        sheetName = retrievedSheetName
    resultStatList = []
    resultFd = open(options.resultFile, "a")
    #test recipe: when wemo switch is truned on, write a log to the google spreadsheet
    preSwitchState = wemoController.getState(switchName)
    for index in range(options.iterNum):
        while True:
            currSwitchState = wemoController.getState(switchName)
            if currSwitchState == 1 and currSwitchState != preSwitchState:
                preSwitchState = currSwitchState
                triggerObservedTime = datetime.datetime.now()
                break
            preSwitchState = currSwitchState
            time.sleep(options.interval)

        print("switch turned on is observed")
        nowDate = datetime.datetime.now()
        nowStr = nowDate.strftime("%Y-%m-%d %H-%M-%S")
        values = [
            ["switch turned on", nowStr],
        ]
        responseAppend = sheetController.appendFile(spreadsheetId,
                                                    range="Sheet1",
                                                    valueList=values)
        endTime = datetime.datetime.now()
        timeDiff = endTime - triggerObservedTime
        timeCost = timeDiff.seconds + timeDiff.microseconds / float(1000000)
        testUuid = uuid.uuid4()
        statStr = "testUuid: {}->triggerObservedTime: {}->wemo_sheet".format(
            testUuid, triggerObservedTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "testUuid: {}->actionExecutionTime: {}->wemo_sheet".format(
            testUuid, endTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "testUuid: {}->time cost for iter {} is {} seconds".format(
            testUuid, index, timeCost)
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()
        #generate trigger event: speak to alexa: change a music
    resultFd.close()
    print(resultStatList)
def testWemoHueRecipe(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("resultFile")
    parser.add_argument("-iterNum", default=5, type=int)
    parser.add_argument("-lightId", default=2, type=int)
    parser.add_argument("-interval", default=1, type=float)
    parser.add_argument("-wemoport", type=int, default=10085)
    options = parser.parse_args(argv)
    resultFile = options.resultFile
    hueController = hue.HueController()
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch"
    lightId = options.lightId
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    time.sleep(3)
    resultStatList = []
    resultFd = open(resultFile, "a")
    preState = wemoController.getState(switchName)
    for index in range(options.iterNum):
        print("start test iteration {}".format(index))

        #monitor trigger event
        while (True):
            currState = wemoController.getState(switchName)
            if currState != preState and currState == 1:
                triggerObservedTime = datetime.datetime.now()
                preState = currState
                break
            preState = currState
            time.sleep(options.interval)
        hueController.turnonLight(lightId)
        print("light turned one")
        endTime = datetime.datetime.now()
        timeDiff = endTime - triggerObservedTime
        timeCost = timeDiff.seconds + timeDiff.microseconds / float(1000000)
        testUuid = uuid.uuid4()
        statStr = "executionUuid: {}->triggerObservedTime: {}->wemo_hue".format(
            testUuid, triggerObservedTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "testUuid: {}->actionExecutionTime: {}->wemo_hue".format(
            testUuid, endTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "testUuid: {}->time cost for wemo_hue iter {} is {} seconds".format(
            testUuid, index, timeCost)
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()
        time.sleep(5)
    resultFd.close()
def testGmailHueWemoRecipe(argv):
    '''
    test the following recipe:
    If You say "Alexa trigger turn on hue light", then turn on lights in  Living room
    '''
    parser = argparse.ArgumentParser()
    parser.add_argument("resultFile")
    parser.add_argument("-iterNum", default=5, type=int)
    parser.add_argument("-gmailSenderName", default="senmuxing", type=str)
    parser.add_argument("-gmailName", default="xianghangmi", type=str)
    parser.add_argument("-lightId", default=2, type=int)
    parser.add_argument("-interval", default=1, type=float)
    parser.add_argument("-wemoport", type=int, default=10085)
    options = parser.parse_args(argv)
    hueController = hue.HueController()
    lightId = options.lightId
    gmailController = GmailController(options.gmailName)
    gmailSenderController = GmailController(options.gmailSenderName)
    bind = "0.0.0.0:{}".format(options.wemoport)
    switchName = "WeMo Switch"
    wemoController = wemo.WemoController(bind=bind)
    switch = wemoController.discoverSwitch(switchName)
    if switch is None:
        print("error to locate the switch")
        sys.exit(1)
    else:
        print("switch discoverred")
    resultStatList = []
    hueController.turnoffLight(lightId)
    resultFd = open(options.resultFile, "a")
    #test recipe: when wemo switch is truned on, turn on lights in living room
    for index in range(options.iterNum):
        time.sleep(5)
        hueController.clearAlert(lightId)
        wemoController.turnoffSwitch(switchName)
        preMsgList = gmailController.listMessagesMatchingQuery()
        nowDate = datetime.datetime.now()
        nowStr = nowDate.strftime("%Y-%m-%d %H-%M-%S")
        #send email from [email protected] to [email protected]
        subject = "ifttt test at {}".format(nowStr)
        messageBody = subject
        message = GmailController.create_message(sender="*****@*****.**",
                                                 to="*****@*****.**",
                                                 subject=subject,
                                                 message_text=messageBody)
        gmailSenderController.sendMessage(message)
        sentTime = datetime.datetime.now()
        print("sent email at ", sentTime.strftime("%Y-%m-%d %H-%M-%S"))
        triggerGeneratedTime = datetime.datetime.now()

        #detect reception of the email
        while True:
            latestMsgList = gmailController.listMessagesMatchingQuery()
            latestMsgId = latestMsgList[0]["id"]
            preMsgId = preMsgList[0]["id"]
            if latestMsgId == preMsgId:
                time.sleep(options.interval)
                continue
            else:
                preMsgList = latestMsgList
                receiveTime = datetime.datetime.now()
                break
        print("receive email at ", receiveTime.strftime("%Y-%m-%d %H-%M-%S"))
        actionHue = False
        actionWemo = False
        actionHueTime = None
        actionWemoTime = None
        while (True):
            if actionHue == False and hueController.isLightAlert(lightId):
                print("got hue action")
                hueController.clearAlert(lightId)
                actionHueTime = datetime.datetime.now()
                actionHue = True
            if actionWemo == False and wemoController.isSwitchOn(switchName):
                actionWemo = True
                print("got wemo action")
                actionWemoTime = datetime.datetime.now()
                wemoController.turnoffSwitch(switchName)
            if actionHue and actionWemo:
                break
            time.sleep(options.interval)
        endTime = datetime.datetime.now()
        timeDiffSent = receiveTime - sentTime
        timeDiff = endTime - sentTime
        timeCostForSend = timeDiffSent.seconds + timeDiffSent.microseconds / float(
            1000000)
        timeCost = timeDiff.seconds + timeDiff.microseconds / float(1000000)
        testUuid = uuid.uuid4()
        statStr = "1testUuid: {}->triggerGeneratedTime: {}->gmail".format(
            index, triggerGeneratedTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

        statStr = "2testUuid: {}->actionResultObservedTime: {}->hue".format(
            index, actionHueTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()
        statStr = "3testUuid: {}->actionResultObservedTime: {}->wemo".format(
            index, actionWemoTime.strftime(datetimeFormat))
        print(statStr)
        resultStatList.append(statStr)
        resultFd.write(statStr + "\n")
        resultFd.flush()

    resultFd.close()