Пример #1
0
def nefitGasHistory(event):
    httpHeader = {'Content-Type': 'application/json'}
    # Get the number of gas usage pages from Nefit server
    response = requests.get(NEFIT_BRIDGE_URL +
                            "/ecus/rrc/recordings/gasusagePointer",
                            headers=httpHeader)
    if response.status_code != 200:
        nefitGasHistory.log.warn(
            "NefitEasy - Invalid API status response [{}]".format(response))
        events.sendCommand("CV_Retry_GasUsage", "ON")  #Set retry switch
    else:
        nefitGasHistory.log.debug("Received Pages JSON data [{}]".format(
            response.json()))
        page = int(math.ceil((float(response.json()["value"]) - 1) / 32))
        # Get the last web page for yesterdays data
        response = requests.get(NEFIT_BRIDGE_URL +
                                "/ecus/rrc/recordings/gasusage?page=" +
                                str(page),
                                headers=httpHeader)
        if response.status_code != 200:
            nefitGasHistory.log.warn(
                "NefitEasy - Invalid API status response [{}]".format(
                    response))
            events.sendCommand("CV_Retry_GasUsage", "ON")  #Set retry switch
        else:
            # Walk through JSON Array and find yesterday's entry.
            yesterday = DateTime.now().minusDays(1).toString("dd-MM-yyyy")
            for g in response.json()['value']:
                if g['d'] == yesterday:
                    hotWater = "{0:.3f}".format(
                        float(g['hw']) * GAS_CONVERSION)
                    centralHeating = "{0:.3f}".format(
                        float(g['ch']) * GAS_CONVERSION)
                    influxTimestamp = DateTime.now().withTimeAtStartOfDay(
                    ).minusSeconds(1).millis
                    nefitGasHistory.log.info(
                        "Yesterdays Hot Water [{}], Central Heating [{}]".
                        format(hotWater, centralHeating))
                    cmd = "/bin/sh@@-c@@/usr/bin/curl -s -X POST " + INFLUXDB_URL + "write?db=" + INFLUXDB + "\\&precision=ms --data-binary '" + NEFIT_HW_SERIES + " value=" + hotWater + " " + str(
                        influxTimestamp) + "'"
                    response = Exec.executeCommandLine(cmd, 4000)
                    if response != "":
                        nefitGasHistory.log.warn(
                            "Error writing " + NEFIT_HW_SERIES +
                            " value to InfluxDB [{}]".format(response))
                    cmd = "/bin/sh@@-c@@/usr/bin/curl -s -X POST " + INFLUXDB_URL + "write?db=" + INFLUXDB + "\\&precision=ms --data-binary '" + NEFIT_CH_SERIES + " value=" + centralHeating + " " + str(
                        influxTimestamp) + "'"
                    Exec.executeCommandLine(cmd, 4000)
                    if response != "":
                        nefitGasHistory.log.warn(
                            "Error writing " + NEFIT_HW_SERIES +
                            " value to InfluxDB [{}]".format(response))
                    return
            nefitGasHistory.log.warn(
                "No historic gas usage entry found for [{}]".format(yesterday))
Пример #2
0
        def cb():
            global logTitle
            current_state = str(things.get(ThingUID(binding_thing_name)).status)
            if current_state == "ONLINE":
                LogAction.logInfo(logTitle, u"No need to restart {} (status={})".format(binding_name, current_state))
                if notify_restart is True:
                    NotificationAction.sendBroadcastNotification(u"Auto restart canceled for {} (status={})".format(binding_name, current_state))
            else:
                LogAction.logInfo(logTitle, u"Will now restart {} (status={})".format(binding_name, current_state))
                # Keep track of binding restarts
                restart_counter = binding_restarts.get(binding_id)
                if restart_counter is None:
                    binding_restarts[binding_id] = 1
                else:
                    binding_restarts[binding_id] = int(restart_counter) + 1

                if notify_restart is True:
                    NotificationAction.sendBroadcastNotification(u"Auto restart of {} (status={})".format(binding_name, current_state))
                # Restart the binding (use the 'openhab-karaf' entry in ssh config file)
                Exec.executeCommandLine("/bin/sh@@-c@@ssh openhab-karaf bundle:restart {}".format(binding_id))
            timers[binding_id] = None
Пример #3
0
def tts_converter(content):
    LOG.debug(u"start:\n{}".format(content).decode('utf-8'))
    
    # Get the file object for the appropriate prefix sound and if the content
    # always changes, then don't save the file (recycle it)
    openhab_conf = System.getenv("OPENHAB_CONF")
    alert_prefix = File.separator.join([openhab_conf, "html", "TTS", "Alert_Prefix.mp3"])
    recycled = False
    if "Weather Alert:" in content:
        alert_prefix = File.separator.join([openhab_conf, "html", "TTS", "Alert_Weather.mp3"])
        recycled = True
    elif any(alert_type in content for alert_type in FLITE_TTS_CONFIGURATION["recycle"]):
        recycled = True
    file_name = "recycled.wav"
    if not recycled:
        # Since the file is being saved, truncate the filename to 150 allowed characters
        file_name = re.sub("[^a-zA-Z0-9_.-]", "", content)
        if len(file_name) > 149:
            file_name = file_name[0:149]
        file_name = "{}.wav".format(file_name)
    
    # Substitute text to help TTS pronounce some words
    content_scrubbed = content
    for key, value in FLITE_TTS_CONFIGURATION["substitutions"].items():
        content_scrubbed = content_scrubbed.replace(key, value)
    
    # Set paths and files, creating them if they do not exist
    voice = File(FLITE_TTS_CONFIGURATION["path_to_voice"]).getName()
    directory_path_name = File.separator.join([openhab_conf, "html", "TTS", voice])
    directory_path = File(directory_path_name)
    if not directory_path.exists():
        directory_path.mkdir()
    file_path_name = File.separator.join([directory_path_name, file_name])
    file_path = File(file_path_name.replace(".wav", ".mp3"))
    
    # If it does not yet exist, generate the TTS
    if recycled or not file_path.exists():
        Exec.executeCommandLine(u"{}@@-voice@@{}@@-t@@{}@@-o@@{}".format(FLITE_TTS_CONFIGURATION["path_to_flite"], FLITE_TTS_CONFIGURATION["path_to_voice"], content_scrubbed, file_path_name), 60000)
        Exec.executeCommandLine(u"{}@@-y@@-i@@{}@@-af@@volume=10, highpass=f=500, lowpass=f=3000@@{}".format(FLITE_TTS_CONFIGURATION["path_to_ffmpeg"], file_path_name, file_path_name.replace(".wav", ".mp3")), 60000)
        Exec.executeCommandLine(u"{} -y -i \"concat:{}|{}\" -c copy {}".format(FLITE_TTS_CONFIGURATION["path_to_ffmpeg"], alert_prefix, file_path_name.replace(".wav", ".mp3"), file_path_name.replace(".wav", ".combined.mp3")), 60000)
    
    # Create the URL used in the PlayURI
    result = "http://{}:{}/static/TTS/{}/{}".format(HOST_PORT_CONFIGURATION.get("openhab").get("host"), HOST_PORT_CONFIGURATION.get("openhab").get("port"), voice, file_name.replace(".wav", ".combined.mp3"))
    LOG.debug(u"complete:\n{}".format(content).decode('utf-8'))
    return result
Пример #4
0
def deleteRediscoverZwaveThings(event):
    deleteRediscoverZwaveThings.log.debug("Delete Z-Wave Things: Start")
    statusMap = {
        "DeletionSuccess": 0,
        "DeletionFailure": 0,
        "DiscoveryFailure": 0,
        "ThingsAdded": 0,
        "ThingsNotAdded": 0
    }
    thingUIDList = Exec.executeCommandLine(
        "/bin/sh@@-c@@/usr/bin/curl -s --connect-timeout 10 -m 10 -X GET --header \"Accept: application/json\" \"http://*****:*****@@-c@@/usr/bin/curl -o /dev/null -s -w \"%{{http_code}}\" --connect-timeout 10 -m 10 -X DELETE --header \"Accept: application/json\" \"http://*****:*****@@-c@@/usr/bin/curl -s --connect-timeout 10 -m 10 -X GET --header \"Accept: application/json\" \"http://*****:*****@@-c@@/usr/bin/curl -o /dev/null -s -w \"%{http_code}\" --connect-timeout 10 -m 10 -X POST --header \"Content-Type: application/json\" --header \"Accept: text/plain\" \"http://*****:*****@@-c@@/usr/bin/curl -s --connect-timeout 10 -m 10 -X GET --header \"Accept: application/json\" \"http://*****:*****@@-c@@/usr/bin/curl -o /dev/null -s -w \"%{{http_code}}\" --connect-timeout 10 -m 10 -X POST --header \"Content-Type: text/plain\" --header \"Accept: application/json\" -d \"{}\" \"http://localhost:8080/rest/inbox/{}/approve\""
                .format(inboxList[index + 1],
                        inboxList[index]), 10000)  # approve Thing in Inbox
            deleteRediscoverZwaveThings.log.debug(
                "Delete Z-Wave Things: Inbox approval: approvalResponse=[{}], Thing=[{}], label=[{}]"
                .format(approvalResponse, inboxList[index],
                        inboxList[index + 1]))
            if approvalResponse == "200":
                statusMap["ThingsAdded"] += 1
            else:
                statusMap["ThingsNotAdded"] += 1
    else:
        deleteRediscoverZwaveThings.log.debug(
            "Delete Z-Wave Things: {} Z-Wave Things were not deleted, so did not start Z-Wave Discovery. thingUIDList=[{}]"
            .format(len(thingUIDList), thingUIDList))
    deleteRediscoverZwaveThings.log.debug(
        "Delete Z-Wave Things: End: {}".format(statusMap))
Пример #5
0
def getSnapshotImage(url, img):
    tmpFile = "/tmp/" + img + ".png"
    Exec.executeCommandLine("wget -O " + tmpFile + " \"" + url + "\"", 12000)
    with open(tmpFile, "rb") as f:
        return "data:image/png;base64," + base64.b64encode(f.read())