示例#1
0
def gasUsage(event):
    global contractStart
    if event.oldItemState is None:
        return

    # Calculate consumption last hour
    used = float(
        str(
            PersistenceExtensions.deltaSince(ir.getItem(event.itemName),
                                             DateTime.now().minusHours(1))))
    events.postUpdate("Gas_Use_Hour", "{0:.3f}".format(used))
    gasUsage.log.info("Last Hour Gas Usage [{0:.3f} m3]".format(used / 1000))
    cost = used * GAS_PRICE_PER_DM3
    events.postUpdate("Gas_Use_Hour_Cost", "{0:.2f}".format(cost))
    summary = u"{0:.2f} m3, € {1:.2f}".format(used / 1000, cost)
    events.postUpdate("Gas_Use_Hour_Summary", summary)
    gasUsage.log.info(u"Gas Use Hour Summary [{}]".format(summary))

    # Calculate consumption today
    used = float(
        str(
            PersistenceExtensions.deltaSince(
                ir.getItem(event.itemName),
                DateTime.now().withTimeAtStartOfDay())))
    events.postUpdate("Gas_Use_Day", "{0:.3f}".format(used))
    gasUsage.log.info("Today's Gas Ussage [{0:.3f}]".format(used / 1000))
    cost = used * GAS_PRICE_PER_DM3
    events.postUpdate("Gas_Use_Day_Cost", "{0:.2f}".format(cost))
    events.postUpdate("Gas_Use_Day_Summary",
                      u"{0:.1f} m3, € {1:.2f}".format(used / 1000, cost))

    # Calculate consumption this month
    used = float(
        str(
            PersistenceExtensions.deltaSince(
                ir.getItem(event.itemName),
                DateTime.now().withTimeAtStartOfDay().withDayOfMonth(1))))
    events.postUpdate("Gas_Use_Month", "{0:.3f}".format(used))
    gasUsage.log.info("This Month's Gas Usage [{0:.3f}]".format(used / 1000))
    cost = used * GAS_PRICE_PER_DM3
    events.postUpdate("Gas_Use_Month_Cost", "{0:.2f}".format(cost))
    events.postUpdate("Gas_Use_Month_Summary",
                      u"{0:.0f} m3, € {1:.2f}".format(used / 1000, cost))

    # Calculate consumption this year
    used = float(
        str(
            PersistenceExtensions.deltaSince(ir.getItem(event.itemName),
                                             contractStart)))
    if used is None:
        used = float(str(event.itemState)) - 7374000
        gasUsage.log.info(
            "Fix for missing year data, pre-fill [{}]".format(used))
    events.postUpdate("Gas_Use_Year", str(used))
    gasUsage.log.info("This Contract Year's Gas Usage [{0:.3f}]".format(used /
                                                                        1000))
    cost = used * GAS_PRICE_PER_DM3
    events.postUpdate("Gas_Use_Year_Cost", str(cost))
    events.postUpdate("Gas_Use_Year_Summary",
                      u"{0:.0f} m3, € {1:.2f}".format(used / 1000, cost))
示例#2
0
文件: utils.py 项目: jpg0/oh-config
def getLastUpdate(item_or_item_name):
    """
    Returns the Item's last update datetime as an 'org.joda.time.DateTime <http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html>`_.

    Args:
        item_or_item_name (Item or str): name of the Item

    Returns:
        DateTime: DateTime representing the time of the Item's last update
    """
    try:
        item = itemRegistry.getItem(item_or_item_name) if isinstance(
            item_or_item_name, basestring) else item_or_item_name
        lastUpdate = PersistenceExtensions.lastUpdate(item)
        if lastUpdate is None:
            log.warning(
                "No existing lastUpdate data for item: [{}], so returning 1970-01-01T00:00:00Z"
                .format(item.name))
            return DateTime(0)
        return lastUpdate.toDateTime()
    except:
        # There is an issue using the StartupTrigger and saving scripts over SMB, where changes are detected before the file
        # is completely written. The first read breaks because of a partial file write and the second read succeeds.
        log.warning(
            "Exception when getting lastUpdate data for item: [{}], so returning 1970-01-01T00:00:00Z"
            .format(item.name))
        return DateTime(0)
示例#3
0
def solarSummary(event):
    if isinstance(items[event.itemName],
                  UnDefType) or event.oldItemState is None:
        return
    else:
        solarSummary.log.info(
            "Calculate Solar Summary, triggered by [{}]".format(
                event.itemName))

    price = powerPriceDict.get("T" +
                               str(items["Power_Tariff"])).get("return_price")
    cost = float(event.itemState.toString()) * float(price)
    summary = "{:.1f} kWh, EUR {:.2f}".format(
        float(str(event.itemState)) / 1000, cost)
    costItem = ir.getItem(event.itemName + "_Cost")
    events.postUpdate(costItem, str(cost))
    summaryItem = ir.getItem(event.itemName + "_Summary")
    events.postUpdate(summaryItem.name, summary)

    if (str(event.itemName) == "Solar_Prod_Day"):
        solarDelta = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Solar_Prod_Day"),
                    DateTime.now().minusHours(1))))
        solarSummary.log.info(
            "Calculate last hours solar production: [{}]".format(solarDelta))
        events.postUpdate("Solar_Prod_Hour", str(solarDelta))
        cost = float(solarDelta) * float(price)
        summary = "{:.1f} kWh, EUR {:.2f}".format(solarDelta / 1000, cost)
        events.postUpdate("Solar_Prod_Hour_Summary", summary)
示例#4
0
def getLastUpdate(item_or_item_name):
    """
    Returns the Item's last update datetime as an ``org.joda.time.DateTime``.
    If Joda is missing it will return a ``java.time.ZonedDateTime`` instead.

    Args:
        item_or_item_name (Item or str): name of the Item

    Returns:
        DateTime: Joda DateTime representing the time of the Item's last update
        ZonedDateTime: ZonedDateTime representing the time of the Item's last update
    """
    LOG.warn("The 'core.utils.getLastUpdate' function is pending deprecation.")
    try:
        from core.actions import PersistenceExtensions
        item = itemRegistry.getItem(item_or_item_name) if isinstance(
            item_or_item_name, basestring) else item_or_item_name
        last_update = PersistenceExtensions.lastUpdate(item)
        if last_update is not None:
            return to_joda_datetime(
                last_update) if JodaDateTime else to_java_zoneddatetime(
                    last_update)
        LOG.warning(
            u"No existing lastUpdate data for item: '{}', so returning 1970-01-01T00:00:00Z"
            .format(item.name))
    except:
        # There is an issue using the StartupTrigger and saving scripts over SMB, where changes are detected before the file
        # is completely written. The first read breaks because of a partial file write and the second read succeeds.
        LOG.warning(
            u"Exception when getting lastUpdate data for item: '{}', so returning 1970-01-01T00:00:00Z"
            .format(item.name))
    return JodaDateTime(0) if JodaDateTime else ZonedDateTime(0)
def mainsEnergyMonitor(event):
    lastThreeWeeksUsage = float(
        str(
            PersistenceExtensions.sumSince(
                ir.getItem("HEM1_Total_Energy_Delta"),
                DateTime.now().minusDays(21))))  # blue yellow
    if lastThreeWeeksUsage > 200:  # green
        logDebug(
            "Demo8", "Send alert - {} => {}".format(event.itemName,
                                                    str(event.itemState)))
 def getLastUpdate(self):
     '''
     Returns the sensors last update time (if available).
     type is 'org.joda.time.DateTime', http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html
     '''
     try:
         lastUpdate = PersistenceExtensions.lastUpdate(
             scope.itemRegistry.getItem(self.name)).toDateTime()
     except:
         lastUpdate = DateTime(0)
         self.log.info(
             u"Could not retrieve persistence data for sensor: {}".format(
                 self.name.decode('utf8')))
     return lastUpdate
示例#7
0
def mode_or_lux_change(event):
    """
    This rule iterates through all triggering groups and replays all actions
    for groups that are currently active, using the current mode and lux level.
    """
    #start_time = DateTime.now().getMillis()
    mode_change_or_system_start = (event.itemName == MODE_ITEM) if event is not None else True
    # get a list of active trigger groups (or all of them, if system started)
    for trigger_group in [group for group in itemRegistry.getItem("gArea_Trigger").members]:
        trigger_type = "active" if trigger_group.state in [ON, OPEN] else "inactive"
        action_groups = itemRegistry.getItems(trigger_group.name.replace("_Trigger", "_Action"))
        if action_groups:
            for action_group in action_groups:# there should be only 1 or None
                for item in action_group.members:
                    item_metadata = get_metadata(item.name, "area_triggers_and_actions")
                    action_function_names = item_metadata.configuration.keys() if item_metadata else [DEFAULT_ACTION_FUNCTION]
                    if DEFAULT_ACTION_FUNCTION in action_function_names:
                        light_action_metadata = get_key_value(item.name, "area_triggers_and_actions", DEFAULT_ACTION_FUNCTION)
                        lux_item_name = light_action_metadata.get("lux_item_name", AREA_TRIGGERS_AND_ACTIONS_CONFIGURATION.get(DEFAULT_ACTION_FUNCTION, {}).get("lux_item_name"))
                        if mode_change_or_system_start:
                            start_new_thread(start_action, (item, trigger_group.state in [ON, OPEN], DEFAULT_ACTION_FUNCTION))
                            mode_or_lux_change.log.debug(u"Mode change or System start light adjustment: {}: {}: {}".format(items[MODE_ITEM], action_group.name, item.name))
                        else:
                            if lux_item_name == event.itemName and not isinstance(event.itemState, UnDefType):
                                # the lux Item associated with the action Item has changed state
                                lux_current = event.itemState.intValue()
                                lux_previous = event.oldItemState.intValue()
                            elif lux_item_name is not None and lux_item_name == AREA_TRIGGERS_AND_ACTIONS_CONFIGURATION.get(DEFAULT_ACTION_FUNCTION, {}).get("lux_item_name") and not isinstance(items[lux_item_name], UnDefType):
                                # this action Item is associated to the default lux Item
                                lux_current = items[lux_item_name].intValue()
                                lux_previous = PersistenceExtensions.previousState(itemRegistry.getItem(lux_item_name), True).state.intValue()
                            else:
                                # this action Item is not associated to a lux Item and there is no default lux_item_name configured in AREA_TRIGGERS_AND_ACTIONS_CONFIGURATION
                                break
                            lux_trigger = light_action_metadata.get(trigger_type, {}).get("modes", {}).get(items[MODE_ITEM].toString(), {}).get("lux_trigger", AREA_TRIGGERS_AND_ACTIONS_CONFIGURATION[DEFAULT_ACTION_FUNCTION]["default_levels"][trigger_type]["lux_trigger"])
                            if min(lux_previous, lux_current) < lux_trigger < max(lux_previous, lux_current):
                                start_new_thread(start_action, (item, trigger_group.state in [ON, OPEN], DEFAULT_ACTION_FUNCTION))
                                mode_or_lux_change.log.debug(u"Lux change light adjustment: {}: {}: current: '{}', previous: '{}'".format(action_group.name, item.name, lux_current, lux_previous))
示例#8
0
def powerSummary(event):
    global contractStart
    if event.oldItemState is None:
        return
    else:
        events.postUpdate("DSMR_Watchdog", "ON")

    # Define variables
    usedHour = 0
    usedDay = 0
    usedMonth = 0
    usedYear = 0
    usedContract = 0
    returnedHour = 0
    returnedDay = 0
    returnedMonth = 0
    returnedYear = 0
    returnedContract = 0
    kWhPrice = float(
        powerPriceDict.get("T" + str(items["Power_Tariff"])).get("use_price"))

    # Calculate multiple periods of power consumption
    if not isinstance(ir.getItem("Power_Use_Total"), UnDefType):
        usedHour = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Power_Use_Total"),
                    DateTime.now().minusHours(1))))
        events.postUpdate("Power_Use_Hour", "{0:.3f}".format(usedHour))
        usedDay = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Power_Use_Total"),
                    DateTime.now().withTimeAtStartOfDay())))
        events.postUpdate("Power_Use_Day", "{0:.3f}".format(usedDay))
        usedMonth = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Power_Use_Total"),
                    DateTime.now().withTimeAtStartOfDay().withDayOfMonth(1))))
        usedYear = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Power_Use_Total"),
                    DateTime.now().withTimeAtStartOfDay().withMonthOfYear(
                        1).withDayOfMonth(1))))
        usedContract = float(
            str(
                PersistenceExtensions.deltaSince(ir.getItem("Power_Use_Total"),
                                                 contractStart)))

    # Calculate multiple periods power return
    if not isinstance(ir.getItem("Power_Ret_Total"), UnDefType):
        returnedHour = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Power_Ret_Total"),
                    DateTime.now().minusHours(1))))
        events.postUpdate("Power_Ret_Hour", "{0:.3f}".format(returnedHour))
        returnedDay = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Power_Ret_Total"),
                    DateTime.now().withTimeAtStartOfDay())))
        events.postUpdate("Power_Ret_Day", "{0:.3f}".format(returnedDay))
        returnedMonth = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Power_Ret_Total"),
                    DateTime.now().withTimeAtStartOfDay().withDayOfMonth(1))))
        returnedYear = float(
            str(
                PersistenceExtensions.deltaSince(
                    ir.getItem("Power_Ret_Total"),
                    DateTime.now().withTimeAtStartOfDay().withMonthOfYear(
                        1).withDayOfMonth(1))))
        returnedContract = float(
            str(
                PersistenceExtensions.deltaSince(ir.getItem("Power_Ret_Total"),
                                                 contractStart)))

    # Calculate last hour's power delta usage and price
    delta = usedHour - returnedHour
    deltaPrice = (usedHour * kWhPrice) - (returnedHour * kWhPrice)
    powerSummary.log.debug(
        "Last hours power use/return/delta [{0:.3f}/{1:.3f}/{2:.3f}]; net cost [{3:.2f}]"
        .format(usedHour, returnedHour, delta, deltaPrice))
    events.postUpdate("Power_Delta_Hour", "{0:.3f}".format(delta))
    events.postUpdate("Power_Delta_Hour_Cost", "{0:.2f}".format(deltaPrice))
    events.postUpdate(
        "Power_Delta_Hour_Summary",
        u"{0:.3f} kWh, € {1:.2f}".format(delta / 1000, deltaPrice))

    # Calculate today's power delta
    delta = usedDay - returnedDay
    deltaPrice = (usedDay * kWhPrice) - (returnedDay * kWhPrice)
    powerSummary.log.debug(
        "Todays power use/return/delta [{0:.3f}/{1:.3f}/{2:.3f}]; net cost [{3:.2f}]"
        .format(usedDay / 1000, returnedDay / 1000, delta / 1000, deltaPrice))
    events.postUpdate("Power_Delta_Day", str(delta))
    events.postUpdate("Power_Delta_Day_Cost", str(deltaPrice))
    events.postUpdate(
        "Power_Delta_Day_Summary",
        u"{0:.2f} kWh, € {1:.2f}".format(delta / 1000, deltaPrice))

    # Calculate this month's power delta
    delta = usedMonth - returnedMonth
    deltaPrice = (usedMonth * kWhPrice) - (returnedMonth * kWhPrice)
    powerSummary.log.debug(
        "This months power use/return/delta [{}/{}/{}]; net cost [{}]".format(
            usedMonth, returnedMonth, delta, deltaPrice))
    events.postUpdate("Power_Delta_Month", str(delta))
    events.postUpdate("Power_Delta_Month_Cost", str(deltaPrice))
    events.postUpdate(
        "Power_Delta_Month_Summary",
        u"{0:.0f} kWh, € {1:.2f}".format(delta / 1000, deltaPrice))

    # Calculate this year's power delta
    delta = usedYear - returnedYear
    deltaPrice = (usedYear * kWhPrice) - (returnedYear * kWhPrice)
    powerSummary.log.debug(
        "This years power use/return/delta [{}/{}/{}]; net cost [{}]".format(
            usedYear, returnedYear, delta, deltaPrice))
    events.postUpdate("Power_Delta_Year", str(delta))
    events.postUpdate("Power_Delta_Year_Cost", str(deltaPrice))
    events.postUpdate(
        "Power_Delta_Year_Summary",
        u"{0:.0f} kWh, € {1:.2f}".format(delta / 1000, deltaPrice))

    # Calculate this contract period's power delta
    delta = usedContract - returnedContract
    deltaPrice = (usedContract * kWhPrice) - (returnedContract * kWhPrice)
    powerSummary.log.debug(
        "This contract period's power use/return/delta [{}/{}/{}]; net cost [{}]"
        .format(usedContract, returnedContract, delta, deltaPrice))
    events.postUpdate("Power_Delta_Contract", str(delta))
    events.postUpdate("Power_Delta_Contract_Cost", str(deltaPrice))
    events.postUpdate(
        "Power_Delta_Contract_Summary",
        u"{0:.0f} kWh, € {1:.2f}".format(delta / 1000, deltaPrice))