INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
extract holiday and weekend: class: ~ekmmeters. Schedule from meter object buffer.
def extractHolidayWeekendSchedules(self): """ extract holiday and weekend :class:`~ekmmeters.Schedule` from meter object buffer. Returns: tuple: Holiday and weekend :class:`~ekmmeters.Schedule` values, as strings. ======= ====================================== Holiday :class:`~ekmmeters.Schedule` as string Weekend :class:`~ekmmeters.Schedule` as string ======= ====================================== """ result = namedtuple("result", ["Weekend", "Holiday"]) result.Weekend = self.m_hldy["Weekend_Schd"][MeterData.StringValue] result.Holiday = self.m_hldy["Holiday_Schd"][MeterData.StringValue] return result
Recommended call to read all meter settings at once.
def readSettings(self): """Recommended call to read all meter settings at once. Returns: bool: True if all subsequent serial calls completed with ACK. """ success = (self.readHolidayDates() and self.readMonthTariffs(ReadMonths.kWh) and self.readMonthTariffs(ReadMonths.kWhReverse) and self.readSchedules(ReadSchedules.Schedules_1_To_4) and self.readSchedules(ReadSchedules.Schedules_5_To_6)) return success
Internal method to set the command result string.
def writeCmdMsg(self, msg): """ Internal method to set the command result string. Args: msg (str): Message built during command. """ ekm_log("(writeCmdMsg | " + self.getContext() + ") " + msg) self.m_command_msg = msg
Password step of set commands
def serialCmdPwdAuth(self, password_str): """ Password step of set commands This method is normally called within another serial command, so it does not issue a termination string. Any default password is set in the caller parameter list, never here. Args: password_str (str): Required password. Returns: bool: True on completion and ACK. """ result = False try: req_start = "0150310228" + binascii.hexlify(password_str) + "2903" req_crc = self.calc_crc16(req_start[2:].decode("hex")) req_str = req_start + req_crc self.m_serial_port.write(req_str.decode("hex")) if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06": ekm_log("Password accepted (" + self.getContext() + ")") result = True else: ekm_log("Password call failure no 06(" + self.getContext() + ")") except: ekm_log("Password call failure by exception(" + self.getContext() + ")") ekm_log(traceback.format_exc(sys.exc_info())) return result
Initialize: class: ~ekmmeters. SerialBlock for V3 read.
def initWorkFormat(self): """ Initialize :class:`~ekmmeters.SerialBlock` for V3 read. """ self.m_blk_a["reserved_10"] = [1, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Model] = [2, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.Firmware] = [1, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.Meter_Address] = [12, FieldType.String, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.kWh_Tot] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.kWh_Tariff_1] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.kWh_Tariff_2] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.kWh_Tariff_3] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.kWh_Tariff_4] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Tot] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Tariff_1] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Tariff_2] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Tariff_3] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Tariff_4] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.RMS_Volts_Ln_1] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.RMS_Volts_Ln_2] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.RMS_Volts_Ln_3] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.Amps_Ln_1] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.Amps_Ln_2] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.Amps_Ln_3] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.RMS_Watts_Ln_1] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.RMS_Watts_Ln_2] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.RMS_Watts_Ln_3] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.RMS_Watts_Tot] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Cos_Theta_Ln_1] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Cos_Theta_Ln_2] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Cos_Theta_Ln_3] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Max_Demand] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, True] self.m_blk_a[Field.Max_Demand_Period] = [1, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.Meter_Time] = [14, FieldType.String, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.CT_Ratio] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.Pulse_Cnt_1] = [8, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Pulse_Cnt_2] = [8, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Pulse_Cnt_3] = [8, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Pulse_Ratio_1] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.Pulse_Ratio_2] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.Pulse_Ratio_3] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.State_Inputs] = [3, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a["reserved_11"] = [19, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Status_A] = [1, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a["reserved_12"] = [4, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a["crc16"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Power_Factor_Ln_1] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_a[Field.Power_Factor_Ln_2] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_a[Field.Power_Factor_Ln_3] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False]
Required request () override for v3 and standard method to read meter.
def request(self, send_terminator = False): """Required request() override for v3 and standard method to read meter. Args: send_terminator (bool): Send termination string at end of read. Returns: bool: CRC request flag result from most recent read """ self.m_a_crc = False start_context = self.getContext() self.setContext("request[v3A]") try: self.m_serial_port.write("2f3f".decode("hex") + self.m_meter_address + "210d0a".decode("hex")) self.m_raw_read_a = self.m_serial_port.getResponse(self.getContext()) unpacked_read_a = self.unpackStruct(self.m_raw_read_a, self.m_blk_a) self.convertData(unpacked_read_a, self.m_blk_a, 1) self.m_a_crc = self.crcMeterRead(self.m_raw_read_a, self.m_blk_a) if send_terminator: self.serialPostEnd() self.calculateFields() self.makeReturnFormat() except: ekm_log(traceback.format_exc(sys.exc_info())) self.setContext(start_context) return self.m_a_crc
Strip reserved and CRC for m_req: class: ~ekmmeters. SerialBlock.
def makeReturnFormat(self): """ Strip reserved and CRC for m_req :class:`~ekmmeters.SerialBlock`. """ for fld in self.m_blk_a: compare_fld = fld.upper() if not "RESERVED" in compare_fld and not "CRC" in compare_fld: self.m_req[fld] = self.m_blk_a[fld] pass
Insert to: class: ~ekmmeters. MeterDB subclass.
def insert(self, meter_db): """ Insert to :class:`~ekmmeters.MeterDB` subclass. Please note MeterDB subclassing is only for simplest-case. Args: meter_db (MeterDB): Instance of subclass of MeterDB. """ if meter_db: meter_db.dbInsert(self.m_req, self.m_raw_read_a, self.m_raw_read_b) else: ekm_log("Attempt to insert when no MeterDB assigned.") pass
Fire update method in all attached observers in order of attachment.
def updateObservers(self): """ Fire update method in all attached observers in order of attachment. """ for observer in self.m_observers: try: observer.update(self.m_req) except: ekm_log(traceback.format_exc(sys.exc_info()))
Return: class: ~ekmmeters. Field content scaled and formatted.
def getField(self, fld_name): """ Return :class:`~ekmmeters.Field` content, scaled and formatted. Args: fld_name (str): A :class:`~ekmmeters.Field` value which is on your meter. Returns: str: String value (scaled if numeric) for the field. """ result = "" if fld_name in self.m_req: result = self.m_req[fld_name][MeterData.StringValue] else: ekm_log("Requested nonexistent field: " + fld_name) return result
Initialize A read: class: ~ekmmeters. SerialBlock.
def initFormatA(self): """ Initialize A read :class:`~ekmmeters.SerialBlock`.""" self.m_blk_a["reserved_1"] = [1, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Model] = [2, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.Firmware] = [1, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.Meter_Address] = [12, FieldType.String, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.kWh_Tot] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Reactive_Energy_Tot] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Tot] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.kWh_Ln_1] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.kWh_Ln_2] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.kWh_Ln_3] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Ln_1] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Ln_2] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Rev_kWh_Ln_3] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Resettable_kWh_Tot] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.Resettable_Rev_kWh_Tot] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_a[Field.RMS_Volts_Ln_1] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.RMS_Volts_Ln_2] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.RMS_Volts_Ln_3] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.Amps_Ln_1] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.Amps_Ln_2] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.Amps_Ln_3] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_a[Field.RMS_Watts_Ln_1] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.RMS_Watts_Ln_2] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.RMS_Watts_Ln_3] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.RMS_Watts_Tot] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Cos_Theta_Ln_1] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Cos_Theta_Ln_2] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Cos_Theta_Ln_3] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Reactive_Pwr_Ln_1] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Reactive_Pwr_Ln_2] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Reactive_Pwr_Ln_3] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Reactive_Pwr_Tot] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Line_Freq] = [4, FieldType.Float, ScaleType.Div100, "", 0, False, False] self.m_blk_a[Field.Pulse_Cnt_1] = [8, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Pulse_Cnt_2] = [8, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Pulse_Cnt_3] = [8, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.State_Inputs] = [1, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.State_Watts_Dir] = [1, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.State_Out] = [1, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a[Field.kWh_Scale] = [1, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_a["reserved_2"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Meter_Time] = [14, FieldType.String, ScaleType.No, "", 0, False, False] self.m_blk_a["reserved_3"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a["reserved_4"] = [4, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a["crc16"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_a[Field.Power_Factor_Ln_1] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_a[Field.Power_Factor_Ln_2] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_a[Field.Power_Factor_Ln_3] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False] pass
Initialize B read: class: ~ekmmeters. SerialBlock.
def initFormatB(self): """ Initialize B read :class:`~ekmmeters.SerialBlock`.""" self.m_blk_b["reserved_5"] = [1, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.Model] = [2, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Firmware] = [1, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Meter_Address] = [12, FieldType.String, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.kWh_Tariff_1] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_b[Field.kWh_Tariff_2] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_b[Field.kWh_Tariff_3] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_b[Field.kWh_Tariff_4] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_b[Field.Rev_kWh_Tariff_1] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_b[Field.Rev_kWh_Tariff_2] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_b[Field.Rev_kWh_Tariff_3] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_b[Field.Rev_kWh_Tariff_4] = [8, FieldType.Float, ScaleType.KWH, "", 0, False, False] self.m_blk_b[Field.RMS_Volts_Ln_1] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_b[Field.RMS_Volts_Ln_2] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_b[Field.RMS_Volts_Ln_3] = [4, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_b[Field.Amps_Ln_1] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_b[Field.Amps_Ln_2] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_b[Field.Amps_Ln_3] = [5, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_b[Field.RMS_Watts_Ln_1] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.RMS_Watts_Ln_2] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.RMS_Watts_Ln_3] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.RMS_Watts_Tot] = [7, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.Cos_Theta_Ln_1] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.Cos_Theta_Ln_2] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.Cos_Theta_Ln_3] = [4, FieldType.PowerFactor, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.RMS_Watts_Max_Demand] = [8, FieldType.Float, ScaleType.Div10, "", 0, False, False] self.m_blk_b[Field.Max_Demand_Period] = [1, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Pulse_Ratio_1] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Pulse_Ratio_2] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Pulse_Ratio_3] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.CT_Ratio] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Max_Demand_Interval_Reset] = [1, FieldType.Int, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.Pulse_Output_Ratio] = [4, FieldType.Int, ScaleType.No, "", 0, False, True] self.m_blk_b["reserved_7"] = [53, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.Status_A] = [1, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Status_B] = [1, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Status_C] = [1, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Meter_Time] = [14, FieldType.String, ScaleType.No, "", 0, False, False] self.m_blk_b["reserved_8"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_b["reserved_9"] = [4, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_b["crc16"] = [2, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.Net_Calc_Watts_Ln_1] = [7, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_b[Field.Net_Calc_Watts_Ln_2] = [7, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_b[Field.Net_Calc_Watts_Ln_3] = [7, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_b[Field.Net_Calc_Watts_Tot] = [7, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_b[Field.Power_Factor_Ln_1] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_b[Field.Power_Factor_Ln_2] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False] self.m_blk_b[Field.Power_Factor_Ln_3] = [4, FieldType.Int, ScaleType.No, "0", 0, True, False] pass
Initialize lookup table for string input of LCD fields
def initLcdLookup(self): """ Initialize lookup table for string input of LCD fields """ self.m_lcd_lookup["kWh_Tot"] = LCDItems.kWh_Tot self.m_lcd_lookup["Rev_kWh_Tot"] = LCDItems.Rev_kWh_Tot self.m_lcd_lookup["RMS_Volts_Ln_1"] = LCDItems.RMS_Volts_Ln_1 self.m_lcd_lookup["RMS_Volts_Ln_2"] = LCDItems.RMS_Volts_Ln_2 self.m_lcd_lookup["RMS_Volts_Ln_3"] = LCDItems.RMS_Volts_Ln_3 self.m_lcd_lookup["Amps_Ln_1"] = LCDItems.Amps_Ln_1 self.m_lcd_lookup["Amps_Ln_2"] = LCDItems.Amps_Ln_2 self.m_lcd_lookup["Amps_Ln_3"] = LCDItems.Amps_Ln_3 self.m_lcd_lookup["RMS_Watts_Ln_1"] = LCDItems.RMS_Watts_Ln_1 self.m_lcd_lookup["RMS_Watts_Ln_2"] = LCDItems.RMS_Watts_Ln_2 self.m_lcd_lookup["RMS_Watts_Ln_3"] = LCDItems.RMS_Watts_Ln_3 self.m_lcd_lookup["RMS_Watts_Tot"] = LCDItems.RMS_Watts_Tot self.m_lcd_lookup["Power_Factor_Ln_1"] = LCDItems.Power_Factor_Ln_1 self.m_lcd_lookup["Power_Factor_Ln_2"] = LCDItems.Power_Factor_Ln_2 self.m_lcd_lookup["Power_Factor_Ln_3"] = LCDItems.Power_Factor_Ln_3 self.m_lcd_lookup["kWh_Tariff_1"] = LCDItems.kWh_Tariff_1 self.m_lcd_lookup["kWh_Tariff_2"] = LCDItems.kWh_Tariff_2 self.m_lcd_lookup["kWh_Tariff_3"] = LCDItems.kWh_Tariff_3 self.m_lcd_lookup["kWh_Tariff_4"] = LCDItems.kWh_Tariff_4 self.m_lcd_lookup["Rev_kWh_Tariff_1"] = LCDItems.Rev_kWh_Tariff_1 self.m_lcd_lookup["Rev_kWh_Tariff_2"] = LCDItems.Rev_kWh_Tariff_2 self.m_lcd_lookup["Rev_kWh_Tariff_3"] = LCDItems.Rev_kWh_Tariff_3 self.m_lcd_lookup["Rev_kWh_Tariff_4"] = LCDItems.Rev_kWh_Tariff_4 self.m_lcd_lookup["Reactive_Pwr_Ln_1"] = LCDItems.Reactive_Pwr_Ln_1 self.m_lcd_lookup["Reactive_Pwr_Ln_2"] = LCDItems.Reactive_Pwr_Ln_2 self.m_lcd_lookup["Reactive_Pwr_Ln_3"] = LCDItems.Reactive_Pwr_Ln_3 self.m_lcd_lookup["Reactive_Pwr_Tot"] = LCDItems.Reactive_Pwr_Tot self.m_lcd_lookup["Line_Freq"] = LCDItems.Line_Freq self.m_lcd_lookup["Pulse_Cnt_1"] = LCDItems.Pulse_Cnt_1 self.m_lcd_lookup["Pulse_Cnt_2"] = LCDItems.Pulse_Cnt_2 self.m_lcd_lookup["Pulse_Cnt_3"] = LCDItems.Pulse_Cnt_3 self.m_lcd_lookup["kWh_Ln_1"] = LCDItems.kWh_Ln_1 self.m_lcd_lookup["Rev_kWh_Ln_1"] = LCDItems.Rev_kWh_Ln_1 self.m_lcd_lookup["kWh_Ln_2"] = LCDItems.kWh_Ln_2 self.m_lcd_lookup["Rev_kWh_Ln_2"] = LCDItems.Rev_kWh_Ln_2 self.m_lcd_lookup["kWh_Ln_3"] = LCDItems.kWh_Ln_3 self.m_lcd_lookup["Rev_kWh_Ln_3"] = LCDItems.Rev_kWh_Ln_3 self.m_lcd_lookup["Reactive_Energy_Tot"] = LCDItems.Reactive_Energy_Tot self.m_lcd_lookup["Max_Demand_Rst"] = LCDItems.Max_Demand_Rst self.m_lcd_lookup["Rev_kWh_Rst"] = LCDItems.Rev_kWh_Rst self.m_lcd_lookup["State_Inputs"] = LCDItems.State_Inputs self.m_lcd_lookup["Max_Demand"] = LCDItems.Max_Demand
Combined A and B read for V4 meter.
def request(self, send_terminator = False): """ Combined A and B read for V4 meter. Args: send_terminator (bool): Send termination string at end of read. Returns: bool: True on completion. """ try: retA = self.requestA() retB = self.requestB() if retA and retB: self.makeAB() self.calculateFields() self.updateObservers() return True except: ekm_log(traceback.format_exc(sys.exc_info())) return False
Issue an A read on V4 meter.
def requestA(self): """Issue an A read on V4 meter. Returns: bool: True if CRC match at end of call. """ work_context = self.getContext() self.setContext("request[v4A]") self.m_serial_port.write("2f3f".decode("hex") + self.m_meter_address + "3030210d0a".decode("hex")) self.m_raw_read_a = self.m_serial_port.getResponse(self.getContext()) unpacked_read_a = self.unpackStruct(self.m_raw_read_a, self.m_blk_a) self.convertData(unpacked_read_a, self.m_blk_a) self.m_kwh_precision = int(self.m_blk_a[Field.kWh_Scale][MeterData.NativeValue]) self.m_a_crc = self.crcMeterRead(self.m_raw_read_a, self.m_blk_a) self.setContext(work_context) return self.m_a_crc
Issue a B read on V4 meter.
def requestB(self): """ Issue a B read on V4 meter. Returns: bool: True if CRC match at end of call. """ work_context = self.getContext() self.setContext("request[v4B]") self.m_serial_port.write("2f3f".decode("hex") + self.m_meter_address + "3031210d0a".decode("hex")) self.m_raw_read_b = self.m_serial_port.getResponse(self.getContext()) unpacked_read_b = self.unpackStruct(self.m_raw_read_b, self.m_blk_b) self.convertData(unpacked_read_b, self.m_blk_b, self.m_kwh_precision) self.m_b_crc = self.crcMeterRead(self.m_raw_read_b, self.m_blk_b) self.setContext(work_context) return self.m_b_crc
Munge A and B reads into single serial block with only unique fields.
def makeAB(self): """ Munge A and B reads into single serial block with only unique fields.""" for fld in self.m_blk_a: compare_fld = fld.upper() if not "RESERVED" in compare_fld and not "CRC" in compare_fld: self.m_req[fld] = self.m_blk_a[fld] for fld in self.m_blk_b: compare_fld = fld.upper() if not "RESERVED" in compare_fld and not "CRC" in compare_fld: self.m_req[fld] = self.m_blk_b[fld] pass
Write calculated fields for read buffer.
def calculateFields(self): """Write calculated fields for read buffer.""" pf1 = self.m_blk_b[Field.Cos_Theta_Ln_1][MeterData.StringValue] pf2 = self.m_blk_b[Field.Cos_Theta_Ln_2][MeterData.StringValue] pf3 = self.m_blk_b[Field.Cos_Theta_Ln_3][MeterData.StringValue] pf1_int = self.calcPF(pf1) pf2_int = self.calcPF(pf2) pf3_int = self.calcPF(pf3) self.m_blk_b[Field.Power_Factor_Ln_1][MeterData.StringValue] = str(pf1_int) self.m_blk_b[Field.Power_Factor_Ln_2][MeterData.StringValue] = str(pf2_int) self.m_blk_b[Field.Power_Factor_Ln_3][MeterData.StringValue] = str(pf3_int) self.m_blk_b[Field.Power_Factor_Ln_1][MeterData.NativeValue] = pf1_int self.m_blk_b[Field.Power_Factor_Ln_2][MeterData.NativeValue] = pf2_int self.m_blk_b[Field.Power_Factor_Ln_3][MeterData.NativeValue] = pf2_int rms_watts_1 = self.m_blk_b[Field.RMS_Watts_Ln_1][MeterData.NativeValue] rms_watts_2 = self.m_blk_b[Field.RMS_Watts_Ln_2][MeterData.NativeValue] rms_watts_3 = self.m_blk_b[Field.RMS_Watts_Ln_3][MeterData.NativeValue] sign_rms_watts_1 = 1 sign_rms_watts_2 = 1 sign_rms_watts_3 = 1 direction_byte = self.m_blk_a[Field.State_Watts_Dir][MeterData.NativeValue] if direction_byte == DirectionFlag.ForwardForwardForward: # all good pass if direction_byte == DirectionFlag.ForwardForwardReverse: sign_rms_watts_3 = -1 pass if direction_byte == DirectionFlag.ForwardReverseForward: sign_rms_watts_2 = -1 pass if direction_byte == DirectionFlag.ReverseForwardForward: sign_rms_watts_1 = -1 pass if direction_byte == DirectionFlag.ForwardReverseReverse: sign_rms_watts_2 = -1 sign_rms_watts_3 = -1 pass if direction_byte == DirectionFlag.ReverseForwardReverse: sign_rms_watts_1 = -1 sign_rms_watts_3 = -1 pass if direction_byte == DirectionFlag.ReverseReverseForward: sign_rms_watts_1 = -1 sign_rms_watts_2 = -1 pass if direction_byte == DirectionFlag.ReverseReverseReverse: sign_rms_watts_1 = -1 sign_rms_watts_2 = -1 sign_rms_watts_3 = -1 pass net_watts_1 = rms_watts_1 * sign_rms_watts_1 net_watts_2 = rms_watts_2 * sign_rms_watts_2 net_watts_3 = rms_watts_3 * sign_rms_watts_3 net_watts_tot = net_watts_1 + net_watts_2 + net_watts_3 self.m_blk_b[Field.Net_Calc_Watts_Ln_1][MeterData.NativeValue] = net_watts_1 self.m_blk_b[Field.Net_Calc_Watts_Ln_2][MeterData.NativeValue] = net_watts_2 self.m_blk_b[Field.Net_Calc_Watts_Ln_3][MeterData.NativeValue] = net_watts_3 self.m_blk_b[Field.Net_Calc_Watts_Tot][MeterData.NativeValue] = net_watts_tot self.m_blk_b[Field.Net_Calc_Watts_Ln_1][MeterData.StringValue] = str(net_watts_1) self.m_blk_b[Field.Net_Calc_Watts_Ln_2][MeterData.StringValue] = str(net_watts_2) self.m_blk_b[Field.Net_Calc_Watts_Ln_3][MeterData.StringValue] = str(net_watts_3) self.m_blk_b[Field.Net_Calc_Watts_Tot][MeterData.StringValue] = str(net_watts_tot) pass
Single call wrapper for LCD set.
def setLCDCmd(self, display_list, password="00000000"): """ Single call wrapper for LCD set." Wraps :func:`~ekmmeters.V4Meter.setLcd` and associated init and add methods. Args: display_list (list): List composed of :class:`~ekmmeters.LCDItems` password (str): Optional password. Returns: bool: Passthrough from :func:`~ekmmeters.V4Meter.setLcd` """ result = False try: self.initLcd() item_cnt = len(display_list) if (item_cnt > 45) or (item_cnt <= 0): ekm_log("LCD item list must have between 1 and 40 items") return False for display_item in display_list: self.addLcdItem(int(display_item)) result = self.setLCD(password) except: ekm_log(traceback.format_exc(sys.exc_info())) return result
Serial call to set relay.
def setRelay(self, seconds, relay, status, password="00000000"): """Serial call to set relay. Args: seconds (int): Seconds to hold, ero is hold forever. See :class:`~ekmmeters.RelayInterval`. relay (int): Selected relay, see :class:`~ekmmeters.Relay`. status (int): Status to set, see :class:`~ekmmeters.RelayState` password (str): Optional password Returns: bool: True on completion and ACK. """ result = False self.setContext("setRelay") try: self.clearCmdMsg() if len(password) != 8: self.writeCmdMsg("Invalid password length.") self.setContext("") return result if seconds < 0 or seconds > 9999: self.writeCmdMsg("Relay duration must be between 0 and 9999.") self.setContext("") return result if not self.requestA(): self.writeCmdMsg("Bad read CRC on setting") else: if not self.serialCmdPwdAuth(password): self.writeCmdMsg("Password failure") else: req_str = "" req_str = ("01573102303038" + binascii.hexlify(str(relay)).zfill(2) + "28" + binascii.hexlify(str(status)).zfill(2) + binascii.hexlify(str(seconds).zfill(4)) + "2903") req_str += self.calc_crc16(req_str[2:].decode("hex")) self.m_serial_port.write(req_str.decode("hex")) if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06": self.writeCmdMsg("Success: 06 returned.") result = True self.serialPostEnd() except: ekm_log(traceback.format_exc(sys.exc_info())) self.setContext("") return result
Send termination string to implicit current meter.
def serialPostEnd(self): """ Send termination string to implicit current meter.""" ekm_log("Termination string sent (" + self.m_context + ")") try: self.m_serial_port.write("0142300375".decode("hex")) except: ekm_log(traceback.format_exc(sys.exc_info())) pass
Serial call to set pulse input ratio on a line.
def setPulseInputRatio(self, line_in, new_cnst, password="00000000"): """Serial call to set pulse input ratio on a line. Args: line_in (int): Member of :class:`~ekmmeters.Pulse` new_cnst (int): New pulse input ratio password (str): Optional password Returns: """ result = False self.setContext("setPulseInputRatio") try: if not self.requestA(): self.writeCmdMsg("Bad read CRC on setting") else: if not self.serialCmdPwdAuth(password): self.writeCmdMsg("Password failure") else: req_const = binascii.hexlify(str(new_cnst).zfill(4)) line_const = binascii.hexlify(str(line_in - 1)) req_str = "01573102303041" + line_const + "28" + req_const + "2903" req_str += self.calc_crc16(req_str[2:].decode("hex")) self.m_serial_port.write(req_str.decode("hex")) if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06": self.writeCmdMsg("Success: 06 returned.") result = True self.serialPostEnd() except: ekm_log(traceback.format_exc(sys.exc_info())) self.setContext("") return result
Serial call to zero resettable kWh registers.
def setZeroResettableKWH(self, password="00000000"): """ Serial call to zero resettable kWh registers. Args: password (str): Optional password. Returns: bool: True on completion and ACK. """ result = False self.setContext("setZeroResettableKWH") try: if not self.requestA(): self.writeCmdMsg("Bad read CRC on setting") else: if not self.serialCmdPwdAuth(password): self.writeCmdMsg("Password failure") else: req_str = "0157310230304433282903" req_str += self.calc_crc16(req_str[2:].decode("hex")) self.m_serial_port.write(req_str.decode("hex")) if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06": self.writeCmdMsg("Success: 06 returned.") result = True self.serialPostEnd() except: ekm_log(traceback.format_exc(sys.exc_info())) self.setContext("") return result
Serial call to set LCD using meter object bufer.
def setLCD(self, password="00000000"): """ Serial call to set LCD using meter object bufer. Used with :func:`~ekmmeters.V4Meter.addLcdItem`. Args: password (str): Optional password Returns: bool: True on completion and ACK. """ result = False self.setContext("setLCD") try: self.clearCmdMsg() if len(password) != 8: self.writeCmdMsg("Invalid password length.") self.setContext("") return result if not self.request(): self.writeCmdMsg("Bad read CRC on setting") else: if not self.serialCmdPwdAuth(password): self.writeCmdMsg("Password failure") else: req_table = "" fill_len = 40 - len(self.m_lcd_items) for lcdid in self.m_lcd_items: append_val = binascii.hexlify(str(lcdid).zfill(2)) req_table += append_val for i in range(0, fill_len): append_val = binascii.hexlify(str(0).zfill(2)) req_table += append_val req_str = "015731023030443228" + req_table + "2903" req_str += self.calc_crc16(req_str[2:].decode("hex")) self.m_serial_port.write(req_str.decode("hex")) if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06": self.writeCmdMsg("Success: 06 returned.") result = True self.serialPostEnd() except: ekm_log(traceback.format_exc(sys.exc_info())) self.setContext("") return result
Recursively iterate over all DictField sub - fields.
def iterate_fields(fields, schema): """Recursively iterate over all DictField sub-fields. :param fields: Field instance (e.g. input) :type fields: dict :param schema: Schema instance (e.g. input_schema) :type schema: dict """ schema_dict = {val['name']: val for val in schema} for field_id, properties in fields.iteritems(): if 'group' in schema_dict[field_id]: for _field_schema, _fields in iterate_fields(properties, schema_dict[field_id]['group']): yield (_field_schema, _fields) else: yield (schema_dict[field_id], fields)
Recursively iterate over all schema sub - fields.
def iterate_schema(fields, schema, path=None): """Recursively iterate over all schema sub-fields. :param fields: Field instance (e.g. input) :type fields: dict :param schema: Schema instance (e.g. input_schema) :type schema: dict :path schema: Field path :path schema: string """ for field_schema in schema: name = field_schema['name'] if 'group' in field_schema: for rvals in iterate_schema(fields[name] if name in fields else {}, field_schema['group'], None if path is None else '{}.{}'.format(path, name)): yield rvals else: if path is None: yield (field_schema, fields) else: yield (field_schema, fields, '{}.{}'.format(path, name))
Random paragraphs.
def paragraphs(quantity=2, separator='\n\n', wrap_start='', wrap_end='', html=False, sentences_quantity=3, as_list=False): """Random paragraphs.""" if html: wrap_start = '<p>' wrap_end = '</p>' separator = '\n\n' result = [] for i in xrange(0, quantity): result.append(wrap_start + sentences(sentences_quantity) + wrap_end) if as_list: return result else: return separator.join(result)
Random text.
def text(length=None, at_least=10, at_most=15, lowercase=True, uppercase=True, digits=True, spaces=True, punctuation=False): """ Random text. If `length` is present the text will be exactly this chars long. Else the text will be something between `at_least` and `at_most` chars long. """ base_string = '' if lowercase: base_string += string.ascii_lowercase if uppercase: base_string += string.ascii_uppercase if digits: base_string += string.digits if spaces: base_string += ' ' if punctuation: base_string += string.punctuation if len(base_string) == 0: return '' if not length: length = random.randint(at_least, at_most) result = '' for i in xrange(0, length): result += random.choice(base_string) return result
Add arguments to the parser for collection in app. args.
def add_arguments(cls, parser): """Add arguments to the parser for collection in app.args. Args: parser: `argparse.ArgumentParser`. Parser. Arguments added here are server on self.args. """ parser.add_argument( '-c', '--create-missing-tasks', action='store_true', dest='create_missing_tasks', help="[sync] create asana tasks for issues without tasks" ) parser.add_argument( '-l', '--sync-labels', action='store_true', dest='sync_labels', help="[sync] sync labels and milestones for each issue" )
Applies task numbers to an issue.
def apply_tasks_to_issue(self, issue, tasks, issue_body=None): """Applies task numbers to an issue.""" issue_body = issue_body or issue.body task_numbers = transport.format_task_numbers_with_links(tasks) if task_numbers: new_body = transport.ASANA_SECTION_RE.sub('', issue_body) new_body = new_body + "\n## Asana Tasks:\n\n%s" % task_numbers transport.issue_edit(issue, body=new_body) return new_body return issue_body
Creates a local map of github labels/ milestones to asana tags.
def sync_labels(self, repo): """Creates a local map of github labels/milestones to asana tags.""" logging.info("syncing new github.com labels to tags") # create label tag map ltm = self.app.data.get("label-tag-map", {}) # loop over labels, if they don't have tags, make them for label in repo.get_labels(): tag_id = ltm.get(label.name, None) if tag_id is None: tag = self.app.asana.tags.create(name=label.name, workspace=self.asana_ws_id, notes="gh: %s" % label.url ) logging.info("\t%s => tag %d", label.name, tag['id']) ltm[label.name] = tag['id'] # loop over milestones, if they don't have tags, make them for ms in repo.get_milestones(state="all"): tag_id = ltm.get(_ms_label(ms.id), None) if tag_id is None: tag = self.app.asana.tags.create(name=ms.title, workspace=self.asana_ws_id, notes="gh: %s" % ms.url ) logging.info("\t%s => tag %d", ms.title, tag['id']) ltm[_ms_label(ms.id)] = tag['id'] self.app.data['label-tag-map'] = ltm return ltm
Return output for the combined time and result summary statistics.
def statistics(self, elapsed, result): """ Return output for the combined time and result summary statistics. """ return "\n".join((self.timing(elapsed), self.result_summary(result)))
Color some text in the given ANSI color.
def color(self, color, text): """ Color some text in the given ANSI color. """ return "{escape}{text}{reset}".format( escape=self.ANSI[color], text=text, reset=self.ANSI["reset"], )
Write the text to the stream and flush immediately.
def show(self, text): """ Write the text to the stream and flush immediately. """ self.stream.write(text) self.stream.flush()
Return a summary of the results.
def result_summary(self, result): """ Return a summary of the results. """ return "{} examples, {} errors, {} failures\n".format( result.testsRun, len(result.errors), len(result.failures), )
Parse some arguments using the parser.
def parse(argv=None): """ Parse some arguments using the parser. """ if argv is None: argv = sys.argv[1:] # Evade http://bugs.python.org/issue9253 if not argv or argv[0] not in {"run", "transform"}: argv = ["run"] + argv arguments = _clean(_parser.parse_args(argv)) return arguments
Setup the environment for an example run.
def setup(config): """ Setup the environment for an example run. """ formatter = config.Formatter() if config.verbose: formatter = result.Verbose(formatter) if config.color: formatter = result.Colored(formatter) current_result = result.ExampleResult(formatter) ivoire.current_result = ivoire._manager.result = current_result
Time to run.
def run(config): """ Time to run. """ setup(config) if config.exitfirst: ivoire.current_result.failfast = True ivoire.current_result.startTestRun() for spec in config.specs: try: load_by_name(spec) except Exception: ivoire.current_result.addError( _ExampleNotRunning(), sys.exc_info() ) ivoire.current_result.stopTestRun() sys.exit(not ivoire.current_result.wasSuccessful())
Run in transform mode.
def transform(config): """ Run in transform mode. """ if transform_possible: ExampleLoader.register() args, sys.argv[1:] = sys.argv[1:], config.args try: return runpy.run_path(config.runner, run_name="__main__") finally: sys.argv[1:] = args
with describe ( thing ) as it:...
def visit_With(self, node): """ with describe(thing) as it: ... | v class TestThing(TestCase): ... """ withitem, = node.items context = withitem.context_expr if context.func.id == "describe": describes = context.args[0].id example_group_name = withitem.optional_vars.id return self.transform_describe(node, describes, example_group_name) else: return node
Transform a describe node into a TestCase.
def transform_describe(self, node, describes, context_variable): """ Transform a describe node into a ``TestCase``. ``node`` is the node object. ``describes`` is the name of the object being described. ``context_variable`` is the name bound in the context manager (usually "it"). """ body = self.transform_describe_body(node.body, context_variable) return ast.ClassDef( name="Test" + describes.title(), bases=[ast.Name(id="TestCase", ctx=ast.Load())], keywords=[], starargs=None, kwargs=None, body=list(body), decorator_list=[], )
Transform the body of an ExampleGroup.
def transform_describe_body(self, body, group_var): """ Transform the body of an ``ExampleGroup``. ``body`` is the body. ``group_var`` is the name bound to the example group in the context manager (usually "it"). """ for node in body: withitem, = node.items context_expr = withitem.context_expr name = context_expr.args[0].s context_var = withitem.optional_vars.id yield self.transform_example(node, name, context_var, group_var)
Transform an example node into a test method.
def transform_example(self, node, name, context_variable, group_variable): """ Transform an example node into a test method. Returns the unchanged node if it wasn't an ``Example``. ``node`` is the node object. ``name`` is the name of the example being described. ``context_variable`` is the name bound in the context manager (usually "test"). ``group_variable`` is the name bound in the surrounding example group's context manager (usually "it"). """ test_name = "_".join(["test", group_variable] + name.split()) body = self.transform_example_body(node.body, context_variable) return ast.FunctionDef( name=test_name, args=self.takes_only_self(), body=list(body), decorator_list=[], )
Transform the body of an Example into the body of a method.
def transform_example_body(self, body, context_variable): """ Transform the body of an ``Example`` into the body of a method. Replaces instances of ``context_variable`` to refer to ``self``. ``body`` is the body. ``context_variable`` is the name bound in the surrounding context manager to the example (usually "test"). """ for node in body: for child in ast.walk(node): if isinstance(child, ast.Name): if child.id == context_variable: child.id = "self" yield node
Return an argument list node that takes only self.
def takes_only_self(self): """ Return an argument list node that takes only ``self``. """ return ast.arguments( args=[ast.arg(arg="self")], defaults=[], kw_defaults=[], kwonlyargs=[], )
Register the path hook.
def register(cls): """ Register the path hook. """ cls._finder = FileFinder.path_hook((cls, [cls.suffix])) sys.path_hooks.append(cls._finder)
Transform the source code then return the code object.
def source_to_code(self, source_bytes, source_path): """ Transform the source code, then return the code object. """ node = ast.parse(source_bytes) transformed = ExampleTransformer().transform(node) return compile(transformed, source_path, "exec", dont_inherit=True)
Apply the argument parser.
def apply_argument_parser(argumentsParser, options=None): """ Apply the argument parser. """ if options is not None: args = argumentsParser.parse_args(options) else: args = argumentsParser.parse_args() return args
Load a spec from either a file path or a fully qualified name.
def load_by_name(name): """ Load a spec from either a file path or a fully qualified name. """ if os.path.exists(name): load_from_path(name) else: __import__(name)
Load a spec from a given path discovering specs if a directory is given.
def load_from_path(path): """ Load a spec from a given path, discovering specs if a directory is given. """ if os.path.isdir(path): paths = discover(path) else: paths = [path] for path in paths: name = os.path.basename(os.path.splitext(path)[0]) imp.load_source(name, path)
Discover all of the specs recursively inside path.
def discover(path, filter_specs=filter_specs): """ Discover all of the specs recursively inside ``path``. Successively yields the (full) relative paths to each spec. """ for dirpath, _, filenames in os.walk(path): for spec in filter_specs(filenames): yield os.path.join(dirpath, spec)
Construct a function that checks a directory for process configuration
def checker(location, receiver): """Construct a function that checks a directory for process configuration The function checks for additions or removals of JSON process configuration files and calls the appropriate receiver methods. :param location: string, the directory to monitor :param receiver: IEventReceiver :returns: a function with no parameters """ path = filepath.FilePath(location) files = set() filesContents = {} def _check(path): currentFiles = set(fname for fname in os.listdir(location) if not fname.endswith('.new')) removed = files - currentFiles added = currentFiles - files for fname in added: contents = path.child(fname).getContent() filesContents[fname] = contents receiver.add(fname, contents) for fname in removed: receiver.remove(fname) same = currentFiles & files for fname in same: newContents = path.child(fname).getContent() oldContents = filesContents[fname] if newContents == oldContents: continue receiver.remove(fname) filesContents[fname] = newContents receiver.add(fname, newContents) files.clear() files.update(currentFiles) return functools.partial(_check, path)
Construct a function that checks a directory for messages
def messages(location, receiver): """Construct a function that checks a directory for messages The function checks for new messages and calls the appropriate method on the receiver. Sent messages are deleted. :param location: string, the directory to monitor :param receiver: IEventReceiver :returns: a function with no parameters """ path = filepath.FilePath(location) def _check(path): messageFiles = path.globChildren('*') for message in messageFiles: if message.basename().endswith('.new'): continue receiver.message(message.getContent()) message.remove() return functools.partial(_check, path)
Add a process.
def add(places, name, cmd, args, env=None, uid=None, gid=None, extras=None, env_inherit=None): """Add a process. :param places: a Places instance :param name: string, the logical name of the process :param cmd: string, executable :param args: list of strings, command-line arguments :param env: dictionary mapping strings to strings (will be environment in subprocess) :param uid: integer, uid to run the new process as :param gid: integer, gid to run the new process as :param extras: a dictionary with additional parameters :param env_inherit: a list of environment variables to inherit :returns: None """ args = [cmd]+args config = filepath.FilePath(places.config) fle = config.child(name) details = dict(args=args) if env is not None: newEnv = {} for thing in env: name, value = thing.split('=', 1) newEnv[name] = value details['env'] = newEnv if uid is not None: details['uid'] = uid if gid is not None: details['gid'] = gid if env_inherit is not None: details['env_inherit'] = env_inherit if extras is not None: details.update(extras) content = _dumps(details) fle.setContent(content)
Remove a process
def remove(places, name): """Remove a process :params places: a Places instance :params name: string, the logical name of the process :returns: None """ config = filepath.FilePath(places.config) fle = config.child(name) fle.remove()
Restart a process
def restart(places, name): """Restart a process :params places: a Places instance :params name: string, the logical name of the process :returns: None """ content = _dumps(dict(type='RESTART', name=name)) _addMessage(places, content)
Call results. func on the attributes of results
def call(results): """Call results.func on the attributes of results :params result: dictionary-like object :returns: None """ results = vars(results) places = Places(config=results.pop('config'), messages=results.pop('messages')) func = results.pop('func') func(places, **results)
Return a service which monitors processes based on directory contents
def get(config, messages, freq, pidDir=None, reactor=None): """Return a service which monitors processes based on directory contents Construct and return a service that, when started, will run processes based on the contents of the 'config' directory, restarting them if file contents change and stopping them if the file is removed. It also listens for restart and restart-all messages on the 'messages' directory. :param config: string, location of configuration directory :param messages: string, location of messages directory :param freq: number, frequency to check for new messages and configuration updates :param pidDir: {twisted.python.filepath.FilePath} or None, location to keep pid files :param reactor: something implementing the interfaces {twisted.internet.interfaces.IReactorTime} and {twisted.internet.interfaces.IReactorProcess} and :returns: service, {twisted.application.interfaces.IService} """ ret = taservice.MultiService() args = () if reactor is not None: args = reactor, procmon = procmonlib.ProcessMonitor(*args) if pidDir is not None: protocols = TransportDirectoryDict(pidDir) procmon.protocols = protocols procmon.setName('procmon') receiver = process_events.Receiver(procmon) confcheck = directory_monitor.checker(config, receiver) confserv = internet.TimerService(freq, confcheck) confserv.setServiceParent(ret) messagecheck = directory_monitor.messages(messages, receiver) messageserv = internet.TimerService(freq, messagecheck) messageserv.setServiceParent(ret) procmon.setServiceParent(ret) return ret
Return a service based on parsed command - line options
def makeService(opt): """Return a service based on parsed command-line options :param opt: dict-like object. Relevant keys are config, messages, pid, frequency, threshold, killtime, minrestartdelay and maxrestartdelay :returns: service, {twisted.application.interfaces.IService} """ ret = get(config=opt['config'], messages=opt['messages'], pidDir=opt['pid'], freq=opt['frequency']) pm = ret.getServiceNamed("procmon") pm.threshold = opt["threshold"] pm.killTime = opt["killtime"] pm.minRestartDelay = opt["minrestartdelay"] pm.maxRestartDelay = opt["maxrestartdelay"] return ret
Adds or refreshes a particular node in the nodelist attributing the current time with the node_id.
def refresh_session(self, node_id=None): """ Adds or refreshes a particular node in the nodelist, attributing the current time with the node_id. :param string node_id: optional, the connection id of the node whose session should be refreshed """ if not node_id: node_id = self.conn.id self.conn.client.hset(self.nodelist_key, node_id, int(time.time() * 1000.))
Detects connections that have held a reference for longer than its process_ttl without refreshing its session. This function does not actually removed them from the hash. ( See remove_expired_nodes. )
def find_expired_nodes(self, node_ids=None): """ Detects connections that have held a reference for longer than its process_ttl without refreshing its session. This function does not actually removed them from the hash. (See remove_expired_nodes.) :param list node_ids: optional, a list of ids to check to see if they have expired. If node_ids is not passed in, all nodes in the hash will be checked. """ if node_ids: nodes = zip(node_ids, [int(t) for t in self.conn.client.hmget(self.nodelist_key, node_ids)]) else: nodes = self.get_all_nodes().items() expiration_delta = self.conn.PROCESS_TTL * 1000. now = int(time.time() * 1000.) return [node_id for (node_id, last_updated) in nodes if (now - last_updated) > expiration_delta]
Removes all expired nodes from the nodelist. If a set of node_ids is passed in those ids are checked to ensure they haven t been refreshed prior to a lock being acquired.
def remove_expired_nodes(self, node_ids=None): """ Removes all expired nodes from the nodelist. If a set of node_ids is passed in, those ids are checked to ensure they haven't been refreshed prior to a lock being acquired. Should only be run with a lock. :param list node_ids: optional, a list of node_ids to remove. They will be verified to ensure they haven't been refreshed. """ nodes = self.find_expired_nodes(node_ids) if nodes: self.conn.client.hdel(self.nodelist_key, *nodes)
Removes a particular node from the nodelist.
def remove_node(self, node_id=None): """ Removes a particular node from the nodelist. :param string node_id: optional, the process id of the node to remove """ if not node_id: node_id = self.conn.id self.conn.client.hdel(self.nodelist_key, node_id)
Returns the time a particular node has been last refreshed.
def get_last_updated(self, node_id=None): """ Returns the time a particular node has been last refreshed. :param string node_id: optional, the connection id of the node to retrieve :rtype: int :returns: Returns a unix timestamp if it exists, otherwise None """ if not node_id: node_id = self.conn.id dt = self.conn.client.hget(self.nodelist_key, node_id) return int(dt) if dt else None
Returns all nodes in the hash with the time they were last refreshed as a dictionary.
def get_all_nodes(self): """ Returns all nodes in the hash with the time they were last refreshed as a dictionary. :rtype: dict(string, int) :returns: A dictionary of strings and corresponding timestamps """ nodes = self.conn.client.hgetall(self.nodelist_key) return {node_id: int(dt) for (node_id, dt) in nodes.items()}
Update the session for this node. Specifically ; lock on the reflist then update the time this node acquired the reference.
def refresh_session(self): """ Update the session for this node. Specifically; lock on the reflist, then update the time this node acquired the reference. This method should only be called while the reference is locked. """ expired_nodes = self.nodelist.find_expired_nodes() if expired_nodes: self.nodelist.remove_expired_nodes(expired_nodes) self.nodelist.refresh_session()
Increments the number of times this resource has been modified by all processes.
def increment_times_modified(self): """ Increments the number of times this resource has been modified by all processes. """ rc = self.conn.client.incr(self.times_modified_key) self.conn.client.pexpire(self.times_modified_key, phonon.s_to_ms(TTL))
: returns: The total number of times increment_times_modified has been called for this resource by all processes.: rtype: int
def get_times_modified(self): """ :returns: The total number of times increment_times_modified has been called for this resource by all processes. :rtype: int """ times_modified = self.conn.client.get(self.times_modified_key) if times_modified is None: return 0 return int(times_modified)
: returns: The total number of elements in the reference list.: rtype: int
def count(self): """ :returns: The total number of elements in the reference list. :rtype: int """ references = self.conn.client.get(self.refcount_key) if references is None: return 0 return int(references)
This method should only be called while the reference is locked.
def dereference(self, callback=None, args=None, kwargs=None): """ This method should only be called while the reference is locked. Decrements the reference count for the resource. If this process holds the only reference at the time we finish dereferencing it; True is returned. Operating on the resource after it has been dereferenced is undefined behavior. Dereference queries the value stored in the backend, if any, iff (if and only if) this instance is the last reference to that resource. e.g. self.count() == 0 :param function callback: A function to execute iff it's determined this process holds the only reference to the resource. When there is a failure communicating with the backend in the cleanup step the callback function will be called an additional time for that failure and each subsequent one thereafter. Ensure your callback handles this properly. :param tuple args: Positional arguments to pass your callback. :param dict kwargs: keyword arguments to pass your callback. :returns: Whether or not there are no more references among all processes. True if this was the last reference. False otherwise. :rtype: bool """ if args is None: args = tuple() if kwargs is None: kwargs = {} client = self.conn.client should_execute = False if self.force_expiry: should_execute = True if not should_execute: self.nodelist.remove_node(self.conn.id) self.nodelist.remove_expired_nodes() updated_refcount = client.incr(self.refcount_key, -1) should_execute = (updated_refcount <= 0) # When we force expiry this will be -1 try: if callable(callback) and should_execute: callback(*args, **kwargs) finally: if should_execute: client.delete(self.resource_key, self.nodelist.nodelist_key, self.times_modified_key, self.refcount_key) self.conn.remove_from_registry(self.resource_key) return should_execute
Returns a list of tokens interleaved with the delimiter.
def delimit(values, delimiter=', '): "Returns a list of tokens interleaved with the delimiter." toks = [] if not values: return toks if not isinstance(delimiter, (list, tuple)): delimiter = [delimiter] last = len(values) - 1 for i, value in enumerate(values): toks.append(value) if i < last: toks.extend(delimiter) return toks
check which processes need to be restarted
def check(path, start, now): """check which processes need to be restarted :params path: a twisted.python.filepath.FilePath with configurations :params start: when the checker started running :params now: current time :returns: list of strings """ return [child.basename() for child in path.children() if _isbad(child, start, now)]
Parse configuration
def parseConfig(opt): """Parse configuration :params opt: dict-like object with config and messages keys :returns: restarter, path """ places = ctllib.Places(config=opt['config'], messages=opt['messages']) restarter = functools.partial(ctllib.restart, places) path = filepath.FilePath(opt['config']) return restarter, path
Make a service
def makeService(opt): """Make a service :params opt: dictionary-like object with 'freq', 'config' and 'messages' :returns: twisted.application.internet.TimerService that at opt['freq'] checks for stale processes in opt['config'], and sends restart messages through opt['messages'] """ restarter, path = parseConfig(opt) now = time.time() checker = functools.partial(check, path, now) beatcheck = tainternet.TimerService(opt['freq'], run, restarter, checker, time.time) beatcheck.setName('beatcheck') return heart.wrapHeart(beatcheck)
Generate a basic error to include the current state.
def expected_error(self, expected: str) -> str: """Generate a basic error to include the current state. A parser can supply only a representation of what it is expecting to this method and the reader will provide the context, including the index to the error. Args: expected: A representation of what the parser is currently expecting Returns: A full error message """ if self.finished: return 'Expected {} but found end of source'.format(expected) else: return 'Expected {} but found {} at index {}'.format(expected, self.next_token(), self.position)
Generate an error to indicate that infinite recursion was encountered.
def recursion_error(self, repeated_parser: str): """Generate an error to indicate that infinite recursion was encountered. A parser can supply a representation of itself to this method and the reader will supply the context, including the location where the parser stalled. Args: repeated_parser: A representation of the repeated parser Returns: A full error message """ if self.finished: return 'Infinite recursion detected in {}; empty string was matched and will be matched forever at ' \ 'end of source'.format(repeated_parser) else: return 'Infinite recursion detected in {}; empty string was matched and will be matched forever at ' \ 'index {} before {}'.format(repeated_parser, self.position, self.next_token())
Generate a basic error to include the current state.
def expected_error(self, expected: str) -> str: """Generate a basic error to include the current state. A parser can supply only a representation of what it is expecting to this method and the reader will provide the context, including the line and character positions. Args: expected: A representation of what the parser is currently expecting Returns: A full error message """ if self.finished: return super().expected_error(expected) else: line_index, character_index, line, pointer = self.current_line() return 'Expected {} but found {}\nLine {}, character {}\n\n{}{}'.format( expected, repr(self.next_token()), line_index, character_index, line, pointer)
Generate an error to indicate that infinite recursion was encountered.
def recursion_error(self, repeated_parser: str): """Generate an error to indicate that infinite recursion was encountered. A parser can supply a representation of itself to this method and the reader will supply the context, including the location where the parser stalled. Args: repeated_parser: A representation of the repeated parser Returns: A full error message """ if self.finished: return super().recursion_error(repeated_parser) else: line_index, character_index, line, pointer = self.current_line() return 'Infinite recursion detected in {}; empty string was matched and will be matched forever\n' \ 'Line {}, character {}\n\n{}{}'.format(repeated_parser, line_index, character_index, line, pointer)
Merge the failure message from another status into this one.
def merge(self, status: 'Status[Input, Output]') -> 'Status[Input, Output]': """Merge the failure message from another status into this one. Whichever status represents parsing that has gone the farthest is retained. If both statuses have gone the same distance, then the expected values from both are retained. Args: status: The status to merge into this one. Returns: This ``Status`` which may have ``farthest`` and ``expected`` updated accordingly. """ if status is None or status.farthest is None: # No new message; simply return unchanged pass elif self.farthest is None: # No current message to compare to; use the message from status self.farthest = status.farthest self.expected = status.expected elif status.farthest.position < self.farthest.position: # New message is not farther; keep current message pass elif status.farthest.position > self.farthest.position: # New message is farther than current message; replace with new message self.farthest = status.farthest self.expected = status.expected else: # New message and current message are equally far; merge messages self.expected = status.expected + self.expected return self
Query to test if a value exists.
def exists(value): "Query to test if a value exists." if not isinstance(value, Token): raise TypeError('value must be a token') if not hasattr(value, 'identifier'): raise TypeError('value must support an identifier') if not value.identifier: value = value.__class__(**value.__dict__) value.identifier = 'v' ident = Identifier(value.identifier) return Query([ OptionalMatch(value), Return(Predicate(ident, 'IS NOT NULL')), Limit(1), ])
Query to get the value.
def get(value): "Query to get the value." if not isinstance(value, Token): raise TypeError('value must be a token') if not hasattr(value, 'identifier'): raise TypeError('value must support an identifier') if not value.identifier: value = value.__class__(**value.__dict__) value.identifier = 'v' ident = Identifier(value.identifier) return Query([ Match(value), Return(ident) ])
Produce a function that always returns a supplied value.
def constant(x: A) -> Callable[..., A]: """Produce a function that always returns a supplied value. Args: x: Any object. Returns: A function that accepts any number of positional and keyword arguments, discards them, and returns ``x``. """ def constanted(*args, **kwargs): return x return constanted
Convert a function taking multiple arguments into a function taking a single iterable argument.
def splat(f: Callable[..., A]) -> Callable[[Iterable], A]: """Convert a function taking multiple arguments into a function taking a single iterable argument. Args: f: Any function Returns: A function that accepts a single iterable argument. Each element of this iterable argument is passed as an argument to ``f``. Example: $ def f(a, b, c): $ return a + b + c $ $ f(1, 2, 3) # 6 $ g = splat(f) $ g([1, 2, 3]) # 6 """ def splatted(args): return f(*args) return splatted
Convert a function taking a single iterable argument into a function taking multiple arguments.
def unsplat(f: Callable[[Iterable], A]) -> Callable[..., A]: """Convert a function taking a single iterable argument into a function taking multiple arguments. Args: f: Any function taking a single iterable argument Returns: A function that accepts multiple arguments. Each argument of this function is passed as an element of an iterable to ``f``. Example: $ def f(a): $ return a[0] + a[1] + a[2] $ $ f([1, 2, 3]) # 6 $ g = unsplat(f) $ g(1, 2, 3) # 6 """ def unsplatted(*args): return f(args) return unsplatted
Run a process return a deferred that fires when it is done
def runProcess(args, timeout, grace, reactor): """Run a process, return a deferred that fires when it is done :params args: Process arguments :params timeout: Time before terminating process :params grace: Time before killing process after terminating it :params reactor: IReactorProcess and IReactorTime :returns: deferred that fires with success when the process ends, or fails if there was a problem spawning/terminating the process """ deferred = defer.Deferred() protocol = ProcessProtocol(deferred) process = reactor.spawnProcess(protocol, args[0], args, env=os.environ) def _logEnded(err): err.trap(tierror.ProcessDone, tierror.ProcessTerminated) print(err.value) deferred.addErrback(_logEnded) def _cancelTermination(dummy): for termination in terminations: if termination.active(): termination.cancel() deferred.addCallback(_cancelTermination) terminations = [] terminations.append(reactor.callLater(timeout, process.signalProcess, "TERM")) terminations.append(reactor.callLater(timeout+grace, process.signalProcess, "KILL")) return deferred
Make scheduler service
def makeService(opts): """Make scheduler service :params opts: dict-like object. keys: frequency, args, timeout, grace """ ser = tainternet.TimerService(opts['frequency'], runProcess, opts['args'], opts['timeout'], opts['grace'], tireactor) ret = service.MultiService() ser.setName('scheduler') ser.setServiceParent(ret) heart.maybeAddHeart(ret) return ret
Consume reader and return Success only on complete consumption.
def completely_parse_reader(parser: Parser[Input, Output], reader: Reader[Input]) -> Result[Output]: """Consume reader and return Success only on complete consumption. This is a helper function for ``parse`` methods, which return ``Success`` when the input is completely consumed and ``Failure`` with an appropriate message otherwise. Args: parser: The parser doing the consuming reader: The input being consumed Returns: A parsing ``Result`` """ result = (parser << eof).consume(reader) if isinstance(result, Continue): return Success(result.value) else: used = set() unique_expected = [] for expected_lambda in result.expected: expected = expected_lambda() if expected not in used: used.add(expected) unique_expected.append(expected) return Failure(result.farthest.expected_error(' or '.join(unique_expected)))
Match a literal sequence.
def lit(literal: Sequence[Input], *literals: Sequence[Sequence[Input]]) -> Parser: """Match a literal sequence. In the `TextParsers`` context, this matches the literal string provided. In the ``GeneralParsers`` context, this matches a sequence of input. If multiple literals are provided, they are treated as alternatives. e.g. ``lit('+', '-')`` is the same as ``lit('+') | lit('-')``. Args: literal: A literal to match *literals: Alternative literals to match Returns: A ``LiteralParser`` in the ``GeneralContext``, a ``LiteralStringParser`` in the ``TextParsers`` context, and an ``AlternativeParser`` if multiple arguments are provided. """ if len(literals) > 0: return AlternativeParser(options.handle_literal(literal), *map(options.handle_literal, literals)) else: return options.handle_literal(literal)
Optionally match a parser.
def opt(parser: Union[Parser, Sequence[Input]]) -> OptionalParser: """Optionally match a parser. An ``OptionalParser`` attempts to match ``parser``. If it succeeds, it returns a list of length one with the value returned by the parser as the only element. If it fails, it returns an empty list. Args: parser: Parser or literal """ if isinstance(parser, str): parser = lit(parser) return OptionalParser(parser)
Match a parser one or more times repeatedly.
def rep1(parser: Union[Parser, Sequence[Input]]) -> RepeatedOnceParser: """Match a parser one or more times repeatedly. This matches ``parser`` multiple times in a row. If it matches as least once, it returns a list of values from each time ``parser`` matched. If it does not match ``parser`` at all, it fails. Args: parser: Parser or literal """ if isinstance(parser, str): parser = lit(parser) return RepeatedOnceParser(parser)
Match a parser zero or more times repeatedly.
def rep(parser: Union[Parser, Sequence[Input]]) -> RepeatedParser: """Match a parser zero or more times repeatedly. This matches ``parser`` multiple times in a row. A list is returned containing the value from each match. If there are no matches, an empty list is returned. Args: parser: Parser or literal """ if isinstance(parser, str): parser = lit(parser) return RepeatedParser(parser)
Match a parser one or more times separated by another parser.
def rep1sep(parser: Union[Parser, Sequence[Input]], separator: Union[Parser, Sequence[Input]]) \ -> RepeatedOnceSeparatedParser: """Match a parser one or more times separated by another parser. This matches repeated sequences of ``parser`` separated by ``separator``. If there is at least one match, a list containing the values of the ``parser`` matches is returned. The values from ``separator`` are discarded. If it does not match ``parser`` at all, it fails. Args: parser: Parser or literal separator: Parser or literal """ if isinstance(parser, str): parser = lit(parser) if isinstance(separator, str): separator = lit(separator) return RepeatedOnceSeparatedParser(parser, separator)
Match a parser zero or more times separated by another parser.
def repsep(parser: Union[Parser, Sequence[Input]], separator: Union[Parser, Sequence[Input]]) \ -> RepeatedSeparatedParser: """Match a parser zero or more times separated by another parser. This matches repeated sequences of ``parser`` separated by ``separator``. A list is returned containing the value from each match of ``parser``. The values from ``separator`` are discarded. If there are no matches, an empty list is returned. Args: parser: Parser or literal separator: Parser or literal """ if isinstance(parser, str): parser = lit(parser) if isinstance(separator, str): separator = lit(separator) return RepeatedSeparatedParser(parser, separator)
Check all processes
def check(settings, states, location): """Check all processes""" children = {child.basename(): child for child in location.children()} last = set(states) current = set(children) gone = last - current added = current - last for name in gone: states[name].close() del states[name] for name in added: states[name] = State(location=children[name], settings=settings) return [name for name, state in six.iteritems(states) if state.check()]
Make a service
def makeService(opt): """Make a service :params opt: dictionary-like object with 'freq', 'config' and 'messages' :returns: twisted.application.internet.TimerService that at opt['freq'] checks for stale processes in opt['config'], and sends restart messages through opt['messages'] """ restarter, path = beatcheck.parseConfig(opt) pool = client.HTTPConnectionPool(reactor) agent = client.Agent(reactor=reactor, pool=pool) settings = Settings(reactor=reactor, agent=agent) states = {} checker = functools.partial(check, settings, states, path) httpcheck = tainternet.TimerService(opt['freq'], run, restarter, checker) httpcheck.setName('httpcheck') return heart.wrapHeart(httpcheck)
Discard data and cancel all calls.
def close(self): """Discard data and cancel all calls. Instance cannot be reused after closing. """ if self.closed: raise ValueError("Cannot close a closed state") if self.call is not None: self.call.cancel() self.closed = True
Check the state of HTTP
def check(self): """Check the state of HTTP""" if self.closed: raise ValueError("Cannot check a closed state") self._maybeReset() if self.url is None: return False return self._maybeCheck()
Make a service
def makeService(): """Make a service :returns: an IService """ configJSON = os.environ.get('NCOLONY_CONFIG') if configJSON is None: return None config = json.loads(configJSON) params = config.get('ncolony.beatcheck') if params is None: return None myFilePath = filepath.FilePath(params['status']) if myFilePath.isdir(): name = os.environ['NCOLONY_NAME'] myFilePath = myFilePath.child(name) heart = Heart(myFilePath) ret = tainternet.TimerService(params['period']/3, heart.beat) return ret
Add a heart to a service collection
def maybeAddHeart(master): """Add a heart to a service collection Add a heart to a service.IServiceCollector if the heart is not None. :params master: a service.IServiceCollector """ heartSer = makeService() if heartSer is None: return heartSer.setName('heart') heartSer.setServiceParent(master)
Wrap a service in a MultiService with a heart
def wrapHeart(service): """Wrap a service in a MultiService with a heart""" master = taservice.MultiService() service.setServiceParent(master) maybeAddHeart(master) return master