Пример #1
0
    def __init__(self, queries):

        self.app = None
        self.command = None
        self.arguments = []
        self.queries = queries

        """
        cache found items
        """
        self.found = {
            'app': None,
            'command': None,
            'arguments': None
        }

        """
        parse queries string
        get app,command,arguments from it
        and push this to local proxy
        """
        self.parse(queries)

        """
        logging query run records
        """
        helper.debug('run command with queries: %s' % queries)
Пример #2
0
 def home_screen(self):
     U = self.data["voltage"]
     I = self.data["current"]
     T = self.data["temperature"]
     SOH = self.data["SOH"]
     SOC = self.data["SOC"]
     time_now = datetime.now().strftime("%H:%M")
     try:
         with canvas(self.device) as draw:
             draw.text((0, 10), "Breedlife", font=self.font, fill=255)
             draw.text((60, 10), time_now, font=self.font, fill=255)
             draw.text((0, 22),
                       "U: " + str(U) + "V",
                       font=self.font,
                       fill=255)
             draw.text((60, 22),
                       "I: " + str(I) + "A",
                       font=self.font,
                       fill=255)
             draw.text((0, 34),
                       "T: " + str(T) + "C",
                       font=self.font,
                       fill=255)
             draw.text((0, 46),
                       "SOH: " + str(SOH) + "%",
                       font=self.font,
                       fill=255)
             draw.text((60, 46),
                       "SOC: " + str(SOC) + "%",
                       font=self.font,
                       fill=255)
     except Exception as e:
         debug(e)
Пример #3
0
    def run(self):
        driver_serial.run()
        driver_oled.run()
        driver_oled.control_led(1)

        thread_send_data_to_server = threading.Thread(
            target=self.task_send_data_to_server)
        thread_log_data = threading.Thread(target=self.task_log_data)
        # thread_take_sample_soh = threading.Thread(target=self.task_take_sample_soh)
        # thread_save_calc_soh = threading.Thread(target=self.task_save_calc_soh)

        thread_send_data_to_server.start()
        thread_log_data.start()
        # thread_take_sample_soh.start()
        # thread_save_calc_soh.start()

        try:
            while self.run_event.is_set():
                time.sleep(0.01)
                self.refresh_station()
        except KeyboardInterrupt:
            debug("[EXCEPT] KEYBOARD INTERRUPT")
            self.run_event.clear()
            driver_serial.stop()
            driver_oled.stop()
            debug("[EXCEPT] STOP APPLICATION")
            sys.exit()
Пример #4
0
    def info_screen(self):
        title = ""
        if self.index_screen == 1:
            title = "4G"
        else:
            title = "3G"

        if self.index_screen >= self.num_current_meter:
            return

        U = self.data["voltage"]
        I = self.data["current_item"][self.index_screen - 1]
        P = round(
            self.data["voltage"] *
            self.data["current_item"][self.index_screen - 1], 1)

        try:
            with canvas(self.device) as draw:
                draw.text((0, 10), title, font=self.font, fill=255)
                draw.text((0, 22),
                          "U: " + str(U) + "V",
                          font=self.font,
                          fill=255)
                draw.text((60, 22),
                          "I: " + str(I) + "A",
                          font=self.font,
                          fill=255)
                draw.text((0, 34),
                          "P: " + str(P) + "W",
                          font=self.font,
                          fill=255)
        except Exception as e:
            debug(e)
Пример #5
0
 def get_num_of_error_send(self):
     try:
         result = self.session.query(StationErrorSend).all()
         return len(result)
     except Exception as e:
         debug(e.message)
         self.session.rollback()
         return 0
def during(event_start,
           event_end,
           window_start,
           window_end,
           until=UNTIL,
           time_zone=TIME_ZONE):
    """
    Determines if an event occurs within a time window within the reporting period.

    :param event_start: datetime -- incident start
    :param event_end: datetime -- incident end
    :param window_start: string in ISO 8601 extended time format -- off-hours start time
    :param window_end: string in ISO 8601 extended time format -- off-hours end time
    :param until: string in ISO 8601 combined datetime format -- the end of the reporting window
    :returns: boolean -- true if, and only if, event is within the window
    """

    debug(
        'Checking if ' + event_start.strftime(ISO_8601_COMBINED_FORMAT) +
        ' to ' + event_end.strftime(ISO_8601_COMBINED_FORMAT) +
        ' falls between ' + window_start + '-' + window_end, 3)

    if event_end - event_start >= datetime.timedelta(days=1):
        return True
    else:
        if event_start.toordinal() == event_end.toordinal():
            if window_start < window_end:
                check_day = event_start.strftime(ISO_8601_DATE_FORMAT)

                window_start_dt = add_date_to_time(check_day, window_start)
                window_end_dt = add_date_to_time(check_day, window_end)

                return (window_start_dt < event_start < window_end_dt
                        or window_start_dt < event_end < window_end_dt)
            else:
                return (during(event_start, event_end, '00:00:00', window_end)
                        or during(event_start, event_end, window_start,
                                  '23:59:59'))
        else:
            if window_start < window_end:
                end_of_day = event_start.replace(hour=23, minute=59, second=59)
                beginning_of_day = event_end.replace(hour=0,
                                                     minute=0,
                                                     second=0)

                return (during(event_start, end_of_day, window_start,
                               window_end)
                        or during(beginning_of_day, event_end, window_start,
                                  window_end))
            else:
                start_day = event_start.strftime(ISO_8601_DATE_FORMAT)
                end_day = event_end.strftime(ISO_8601_DATE_FORMAT)

                window_start_dt = add_date_to_time(start_day, window_start)
                window_end_dt = add_date_to_time(end_day, window_end)

                return (window_start_dt < event_start < window_end_dt
                        or window_start_dt < event_end < window_end_dt)
Пример #7
0
 def update_station_info(self, data):
     try:
         self.session.query(StationInfo).update(data)
         self.session.commit()
         return True
     except Exception as e:
         debug("[ERROR] Error when update station info")
         debug(e)
         return False
Пример #8
0
 def connect(self):
     while constant.CHECK_OLED:
         try:
             self.device = ssd1306(port=1, address=0x3C)
             break
         except Exception as e:
             debug("[ERROR] OLED NOT CONNECTED")
             debug(e)
             sleep(5)
Пример #9
0
 def clear_table_calc_soh(self):
     try:
         self.session.query(StationCalcSOH).update({"wattage": "[]"})
         self.session.commit()
         return True
     except Exception as e:
         debug(e)
         self.session.rollback()
         return False
Пример #10
0
 def wrapper():
     if self.flag_calc_soh:
         # DEBUG SOH
         debug("[INFO] TASK SAVE SOH")
         # END DEBUG
         self.sql.log_calc_soh(self.temp_wattage,
                               self.station_info.num_current_meter)
         self.temp_wattage = array_zeros(
             self.station_info.num_current_meter)
         debug("[INFO] END TASK SAVE SOH")
Пример #11
0
 def send_to_port(self):
     while self.run_event.is_set():
         sleep(0.01)
         if self.queue_serial.empty():
             continue
         data = self.queue_serial.get()
         try:
             self.serial_port.write(data.encode())
         except Exception as e:
             debug(e)
def report():
    """
    Connects to the PagerDuty API, collects incidents within the reporting window,
    and prints a summary report of the incident collection.
    """

    pager = pygerduty.v2.PagerDuty(PAGERDUTY_TOKEN)
    debug('Connecting to PagerDuty...\n')
    incidents = collate_incidents(pager)
    print_summary(incidents)
Пример #13
0
 def get_station_info(self):
     try:
         station_info = self.session.query(StationInfo).first()
         if station_info:
             return dict2obj(station_info.__dict__)
         else:
             return False
     except Exception as e:
         debug("[ERROR] Error when get station info")
         debug(e.message)
         return False
Пример #14
0
 def pop_error_send(self):
     try:
         result = self.session.query(StationErrorSend).first()
         if result:
             self.session.query(StationErrorSend).filter_by(id=result.id).delete()
             self.session.commit()
         return result
     except Exception as e:
         debug(e.message)
         self.session.rollback()
         return False
Пример #15
0
 def get_last_wattage(self):
     try:
         result = self.session.query(StationCalcSOH).first()
         if result:
             return json.loads(result.wattage)
         else:
             return False
     except Exception as e:
         debug(e.message)
         self.session.rollback()
         return False
Пример #16
0
 def log_data(self, data):
     station_data = StationData(
         data=json.dumps(data)
     )
     try:
         self.session.add(station_data)
         self.session.commit()
         return True
     except Exception as e:
         debug(e.message)
         self.session.rollback()
         return False
Пример #17
0
    def write_reg(self, reg, value):
        if not config.emulate_instrument:
            try:
                self.instrument.write_register(reg, value)
            except (ValueError, IOError, Exception) as err:
                err_text = u"write_reg(): Ошибка передачи данных modbus RS485."
                logging.error(unicode(err) + "\r\n" + err_text)

            logging.info(u"write_reg(): " + hex(reg) + u", value= " +
                         helper.debug(value))
        else:
            logging.info(u"Emulated write_reg(): " + hex(reg) + u", value= " +
                         helper.debug(value))
Пример #18
0
 def push_error_send(self, error_type, data):
     try:
         error_send = StationErrorSend(
             type=error_type,
             data=data
         )
         self.session.add(error_send)
         self.session.commit()
         return True
     except Exception as e:
         debug(e.message)
         self.session.rollback()
         return False
Пример #19
0
 def template_task(self, timer, target):
     count = 0
     while self.run_event.is_set():
         time.sleep(1)
         count += 1
         if count < timer:
             continue
         count = 0
         try:
             target()
         except Exception as e:
             debug("[ERROR] Error when run task")
             debug(e)
             pass
Пример #20
0
 def config_screen(self):
     LLVD = self.data["llvd"]
     HHTT = self.data["hhtt"]
     try:
         with canvas(self.device) as draw:
             draw.text((0, 10), "Settings:", font=self.font, fill=255)
             draw.text((0, 22),
                       "LLVD: " + str(LLVD) + "V",
                       font=self.font,
                       fill=255)
             draw.text((0, 36),
                       "FanActive: " + str(HHTT) + "C",
                       font=self.font,
                       fill=255)
     except Exception as e:
         debug(e)
def during_peak_sleep(incident):
    """
    Checks if the given incident occurred during peak sleep hours.

    :param incident: incident -- generated by pygerduty.incidents()
    :returns: boolean -- whether or not the incident occurred during peak sleep hours.
    """

    if incident.urgency != 'low':
        debug('Checking if during peak sleep...', 2)
        if during(dateutil.parser.parse(incident.created_at),
                  end_datetime(incident, UNTIL), START_PEAK, END_PEAK):
            debug('Occurred during peak sleep!', 3)
            return True
    else:
        return False
Пример #22
0
def cp2000_communication_test(instrument=None):
    time.sleep(0.1)
    logging.info(u"cp2000_communication_test()")

    if instrument is None:
        inst = CP2000.get_instrument(config.PORT, config.ADDRESS,
                                     config.minimalmodbus_mode)
    else:
        inst = instrument

    if inst is not None:
        logging.info(
            u"Соединение с контроллером CP2000 по RS485 установленно.")

        inst.debug = True

        result = inst.read_register(const.REG_FREQUENCY_COMMAND)
        logging.info(u"Read REG_FREQUENCY_COMMAND - " + helper.debug(result))

        inst.write_register(0x2002, 0b10)
        inst.write_register(0x2001, 100)  # Hz * 100 = Hz00

        inst.write_register(0x2000, 0b10011111110010)

        time.sleep(5)

        result = inst.read_register(0x2102)
        logging.info(u"Read 0x2102 - " + helper.debug(result))

        result = inst.read_register(0x2103)
        logging.info(u"Read 0x2103 - " + helper.debug(result))

        result = inst.read_register(0x210C)
        logging.info(u"Read 0x210C - " + helper.debug(result))

        inst.write_register(0x2000, 0b10011111101001)
        logging.info(hex(0x2000))

        inst.debug = config.minimalmodbus_debug
        if instrument is None:
            inst.serial.close()
        logging.info(u"cp2000_communication_test(): Выполнен.")
    else:
        logging.info(
            u"cp2000_communication_test(): Ошибка соединение RS485 с контроллером CP2000."
        )
Пример #23
0
 def connect(self):
     while constant.CHECK_SERIAL:
         try:
             self.serial_port = serial.Serial(constant.SERIAL_PORT,
                                              constant.SERIAL_BAUD,
                                              parity=serial.PARITY_NONE,
                                              stopbits=serial.STOPBITS_ONE,
                                              bytesize=serial.EIGHTBITS,
                                              timeout=0)
             self.run_event.set()
             return
         except Exception as e:
             debug(e.message)
             debug(
                 "[ERROR] SERIAL NOT WORKING. PORT: %s, BAUD: %d. Try again..."
                 % (constant.SERIAL_PORT, constant.SERIAL_BAUD))
             sleep(5)
Пример #24
0
    def load_config(self):
        debug("[INFO] LOAD CONFIG FROM SQL")
        # Load from SQL
        station_info = self.sql.get_station_info()
        # DEBUG
        debug(station_info)
        # END DEBUG
        if not station_info:
            debug("[ERROR] Can't load config")
            while True:
                time.sleep(5)
            return

        station_info.soh_item = json.loads(station_info.soh_item)

        if len(station_info.soh_item) != station_info.num_current_meter:
            soh_item = []
            for i in range(0, station_info.num_current_meter):
                soh_item.append(100)
            station_info.soh_item = soh_item
        soh = 0
        if len(station_info.soh_item):
            soh = int(sum(station_info.soh_item) / len(station_info.soh_item))
        station_info.soh = soh
        json.dumps(station_info.soh_item)
        self.sql.update_station_info(
            {"soh_item": json.dumps(station_info.soh_item)})
        self.station_info = station_info
        return
Пример #25
0
    def log_calc_soh(self, data, num_current_meter):
        last_wattage = self.get_last_wattage()
        next_wattage = data

        try:
            if last_wattage != False:
                if len(last_wattage) == num_current_meter:
                    for i in range(0, num_current_meter):
                        next_wattage[i] = round(next_wattage[i] + last_wattage[i], 3)
        except Exception as e:
            debug(e.message)
            self.session.rollback()
            return False
        try:
            if last_wattage != False:
                self.session.query(StationCalcSOH).update({"wattage": json.dumps(next_wattage)})
                self.session.commit()
            else:
                station_calc_soh = StationCalcSOH(
                    wattage=json.dumps(next_wattage)
                )
                self.session.add(station_calc_soh)
                self.session.commit()
            return True
        except Exception as e:
            debug("[ERROR] Error when log calc soh")
            debug(e.message)
            self.session.rollback()
            return False
Пример #26
0
    def handle_frame(self):
        while self.run_event.is_set():
            sleep(0.01)
            if self.state == "END_FRAME":
                raw_data = self.data
                raw_checksum = self.checksum
                self.data = ""
                self.checksum = ""
                self.state = "IDLE"
                try:
                    checksum = 0
                    for ch in raw_data:
                        checksum ^= ord(ch)
                    checksum ^= ord("$")
                    checksum = hex(checksum)[2::]
                    if len(checksum) == 1:
                        checksum = "0" + checksum

                    if checksum != raw_checksum:
                        debug("[WARNING] Invalid checksum %s != %s" %
                              (checksum, raw_checksum))
                        continue

                    data = raw_data.split(",")
                    # print data
                    if len(data) != 21:
                        debug("[WARNING] Invalid data. Length: %d != 21" %
                              len(data))
                        continue

                    current_item = range(0, 13)

                    voltage = self.convert_data.convert_voltage(
                        float(data[0 + 1]))

                    for i in range(0, 13):
                        current_item[i] = self.convert_data.convert_current(
                            float(data[i + 2]))

                    fire = self.convert_data.convert_fire(float(data[13 + 2]))
                    temperature = self.convert_data.convert_temperature(
                        float(data[14 + 2]))
                    door = int(float(data[15 + 2]))
                    water = int(float(data[16 + 2]))

                    data = {
                        "voltage": voltage,
                        "current_item": current_item,
                        "temperature": temperature,
                        "fire": fire,
                        "door": door,
                        "water": water
                    }

                    if self.callback_data:
                        self.callback_data(data)

                except Exception as e:
                    debug(e.message)
Пример #27
0
    def refresh_station(self):
        self.calc_summary_current()
        self.calc_soc()
        self.calc_state()
        self.re_update_dry_contact()
        self.re_update_led_status()

        driver_oled.update_data({
            "SOC": self.SOC,
            "current_item": self.current_item,
            "current": self.current,
            "voltage": self.voltage,
            "temperature": self.temperature,
            "fire": self.fire,
            "water": self.water,
            "door": self.door
        })

        # Check state to handle
        if self.state != self.last_state:
            debug("[INFO] STATE CHANGE: %s to %s" %
                  (self.last_state, self.state))
            state_action = self.get_state_action()
            # Check SOH
            if state_action == 1:
                # Mat dien
                # Run task timer
                self.flag_calc_soh = 1
                self.temp_wattage = array_zeros(
                    self.station_info.num_current_meter)
                # DEBUG
                debug("[INFO] TASK CALC SOH RUNNING")
                # END DEBUG
            elif state_action == 2:
                # Co dien
                self.flag_calc_soh = 0
                self.temp_wattage = array_zeros(
                    self.station_info.num_current_meter)
                # Clear table calc soh
                self.sql.clear_table_calc_soh()
                debug("[INFO] TASK CALC SOH STOPPING")

            # Check notify
            if self.last_state == constant.CHARGE or self.last_state == constant.FULL:
                if self.state == constant.DISCHARGE or self.state == constant.NO_LOAD:
                    thread_notify = threading.Thread(target=self.push_notify,
                                                     args=(1, ))
                    thread_notify.start()
            elif self.last_state == constant.DISCHARGE or self.last_state == constant.NO_LOAD or \
                    self.last_state == constant.BAT_OFF:
                if self.state == constant.FULL or self.state == constant.CHARGE:
                    thread_notify = threading.Thread(target=self.push_notify,
                                                     args=(0, ))
                    thread_notify.start()

            # Update last_state
            self.last_state = self.state
Пример #28
0
    def bat_screen(self):
        title = ""
        if self.index_screen == 3:
            title = "BAT 1"
        else:
            title = "BAT 2"

        if self.index_screen > self.num_current_meter:
            return

        U = self.data["voltage"]
        I = self.data["current_item"][self.index_screen - 1]
        SOH = self.data["soh_item"][self.index_screen - 1]
        SOC = self.data["SOC"]

        try:
            with canvas(self.device) as draw:
                draw.text((0, 10), title, font=self.font, fill=255)
                draw.text((0, 22),
                          "U: " + str(U) + "V",
                          font=self.font,
                          fill=255)
                draw.text((60, 22),
                          "I: " + str(I) + "A",
                          font=self.font,
                          fill=255)
                draw.text((0, 34),
                          "SOH: " + str(SOH) + "%",
                          font=self.font,
                          fill=255)
                draw.text((60, 34),
                          "SOC: " + str(SOC) + "%",
                          font=self.font,
                          fill=255)
        except Exception as e:
            debug(e)
Пример #29
0
    def read_reg(self, reg):
        result = 0xFFFF
        if not config.emulate_instrument:
            try:
                result = self.instrument.read_register(reg)
            except (ValueError, IOError, Exception) as err:
                err_text = u"read_reg(): Ошибка передачи данных modbus RS485."
                logging.error(unicode(err) + "\r\n" + err_text)

            logging.info(u"read_reg(): " + hex(reg) + u", value= " +
                         helper.debug(result))
        else:
            pass
            # logging.info(u"Emulated read_reg(): " + hex(reg))
        return result
Пример #30
0
 def connect(self):
     while constant.CHECK_SQL:
         try:
             debug("[INFO] Starting connect to SQL ...")
             # engine = create_engine("sqlite:///%s" % constant.MYSQL_DB)
             engine = create_engine("mysql+pymysql://root:1@localhost/breedlife?charset=utf8mb4")
             DBSession = sessionmaker(bind=engine, autoflush=False)
             event.listen(StationInfo.__table__, "after_create", self.event_after_create_station_info)
             event.listen(StationCalcSOH.__table__, "after_create", self.event_after_create_station_calc_soh)
             self.session = DBSession()
             Base.metadata.create_all(engine)
             debug("[INFO] Connected to SQL")
             return
         except Exception as e:
             debug("[ERROR] Error when connect to SQL... Try again after 5s...")
             debug(e.message)
             sleep(5)