def _threaded_output_loop(self): while BaseClass.working(): if self._loop_state: GPIO.output(self._ouput_pin, False) else: GPIO.output(self._ouput_pin, True) sleep(0.1)
def _threaded_read_input_pin(self): """" Функция в потоке проверяет сигнал с магнитной петли Сработка магнитной петли считается моментально после получения HIGH Окончание сработки считается через _N повторений цикла с учетом паузы 0.1 сек """ _N = 20 while BaseClass.working(): if GPIO.input(self._input_pin) == GPIO.HIGH: self._loop_true_signal_timer = _N # цикл срабатывает раз в 0.1с, значит через _N отсчетов пройдет _N/10 сек self._loop_state = True else: if self._loop_true_signal_timer > 0: self._loop_true_signal_timer -= 1 if self._loop_true_signal_timer == 0: self._loop_state = False if self._loop_state: # регистрируем время последнего поступившего от петли сигнала, оно обновляется с каждой итерацией self._last_loop_output_signal = datetime.now() if self._loop_state != self._prev_loop_state: # состояние петли изменилось self.logger.debug( f'Magnet loop state: {self.get_loop_state_str()}') if self._loop_state: # на петлю наехали pass else: # с петли съехали if self._cars_for_passing > 0: self._cars_for_passing -= 1 self._prev_loop_state = self._loop_state sleep(0.1)
def _condition_thread_func(self): while BaseClass.working(): self._mode = 0 if self.model.connected: self._mode = 1 if self.model.bool_get_permission: if self.model.permission: self._mode = 2 else: self._mode = 3 sleep(0.1)
def read_kbd_input(self): while BaseClass.working(): # Receive keyboard input from user. try: input_str = input() print('Enter command: ' + input_str) cmd_list = input_str.split(' ') if len(cmd_list) > 0: if 'codes' in cmd_list: print(self._db.print_open_codes()) elif 'debug' == cmd_list[0] or 'info' == cmd_list[ 0] or 'warning' == cmd_list[0]: if 'help' in cmd_list: print("Logged classes:") for cl in self.logger_level_classes: print(f" {type(cl)}") else: if len(cmd_list) == 2: self.set_level(cmd_list[0], cmd_list[1]) else: for cl in self.logger_level_classes: self.set_level(cmd_list[0], cl) elif 'settings' in cmd_list: _settings = 'Settings:\n' _settings += f'Closing by magnet loop: {self._barrier.get_closing_by_magnet_loop()}\n' _settings += f'Magnet loop delay: {self._barrier.get_magnet_loop_delay()} sec.\n' _settings += f'Closing by timer delay: {self._barrier.get_timer_delay()} sec.\n' _settings += f'Closing forcibly by timer selay: {self._barrier.get_timer_delay_forcibly()} sec.\n' print(_settings) elif 'open' in cmd_list: self._barrier.open() print('opened by keyboard...') elif 'close' in cmd_list: self._barrier.close() print('closed by keyboard...') elif 'exit' in cmd_list: self.logger.info('Bye') BaseClass.exit() elif 'reboot' in cmd_list: reboot() except: continue
def _threaded_func(self): _message_sended1 = False while BaseClass.working(): # opening algorithm if self._to_open: self.open() self._to_open = False self._magnet_loop.add_car_for_passing() self.model.reset_permission() _message_sended1 = False else: if (datetime.now() - self._last_opening_time).total_seconds() < 3 or self._magnet_loop.get_loop_state(): sleep(0.1) continue # closing by magnet loop if self._close_by_magnet_loop and self._openned\ and (datetime.now() - self._magnet_loop.get_last_loop_output_signal()).total_seconds() > self._CLOSE_BY_MAGNET_LOOP_DELAY: if self._magnet_loop.get_cars_for_passing() == 0: self.close() self.logger.info(f'Закрыл шлагбаум по магнитной петле. Задержка после проезда {self._CLOSE_BY_MAGNET_LOOP_DELAY} сек.') else: if not _message_sended1: self.logger.info(f'Не закрыл по петле, т.к. должны проехать еще {self._magnet_loop.get_cars_for_passing()} машин.') _message_sended1 = True # closing by timer if self._CLOSE_BY_TIMER_DELAY > 0 and self._openned and (datetime.now() - self._last_opening_time).total_seconds() > self._CLOSE_BY_TIMER_DELAY: self.close() self.logger.info(f'Закрыл шлагбаум по таймеру. Задержка после открытия {self._CLOSE_BY_TIMER_DELAY} сек.') # closing by timer forcibly if 7 < datetime.now().hour < 19 and 0 < self._CLOSE_BY_TIMER_DELAY_FORCIBLY < ( datetime.now() - self._closed_by_timer_forcibly_timer).total_seconds() and\ (datetime.now() - self._last_opening_time).total_seconds() > self._CLOSE_BY_TIMER_DELAY + self._CLOSE_BY_TIMER_DELAY_FORCIBLY: self._closed_by_timer_forcibly_timer = datetime.now() self.close() self.logger.info( f'Закрыл шлагбаум по таймеру принудительно. Период закрытия каждые {self._CLOSE_BY_TIMER_DELAY_FORCIBLY} сек.') sleep(0.1)
def _led_threaded_func(self): while BaseClass.working(): self._mode = 0 if self.model.connected: self._mode = 1 if self.model.bool_get_permission: if self.model.permission: self._mode = 2 else: self._mode = 3 if self._mode == 0: self.green_led.led_off() self.red_led.led_off() sleep(0.1) elif self._mode == 1: self.green_led.led_off() self.red_led.led_on() self._sleep(1000, 1) self.red_led.led_off() self._sleep(1000, 1) elif self._mode == 2: self.red_led.led_off() for k in range(0, 7): self.green_led.led_on() sleep(0.125) self.green_led.led_off() sleep(0.125) self.model.bool_get_permission = False elif self._mode == 3: self.green_led.led_off() for k in range(0, 7): self.red_led.led_on() sleep(0.125) self.red_led.led_off() sleep(0.125) self.model.bool_get_permission = False self.green_led.led_off() self.red_led.led_off()
def _get_bar_code_threaded(self): sleep(1) _last_barcode = None _time_last_wait_for_scan = datetime.now() _attempts = 0 while BaseClass.working(): _answer = "" if self.initialized: if _last_barcode != '': self.logger.info('Wait for scan barcode...') try: _answer = self.serial.readline().decode().replace('\n', '') if _answer != '': self.logger.info( f'{datetime.strftime(datetime.now(), "%d.%m.%y %H:%M:%S")}: {repr(_answer)}' ) _attempts = 0 except: self.initialized = False self.inicialize_com_port() if _answer != "": if _answer.find('t=') == -1: self.model.get_permission_by_code(_answer) else: self.logger.warning( f'Got wrong code format: {_answer}') else: sleep(0.2) if (datetime.now() - _time_last_wait_for_scan).total_seconds() < 1: _attempts += 1 else: _attempts = 0 _time_last_wait_for_scan = datetime.now() if _attempts > 50: print("need reboot") reboot()
open_codes_route = os.getenv("OPEN_CODES_ROUTE") send_open_event_route = os.getenv("SEND_OPEN_EVENTS_ROUTE") opengate_user = os.getenv("OPENGATE_USER") opengate_password = os.getenv("OPENGATE_PASS") bar_scanner_pid = os.getenv("BAR_SCANNER_PID") watchdog_pid = os.getenv("WATCHDOG_PID") telegram_api_token = os.getenv("TELEGRAM_API_TOKEN") telegram_bot_admins = os.getenv("ADMINS") GPIO.setmode(GPIO.BCM) logger.info("Let's go") logger.info('start watchdog') watchdog = WatchDog(watchdog_pid) logger.info('init database') data_base = DB() logger.info('init HTTP exchanging') http_getter = HttpGetter(data_base, opengate_server, opengate_port, open_codes_route, send_open_event_route, opengate_user, opengate_password) logger.info('init BAR scanner') scanner = BarScanner(bar_scanner_pid, http_getter) logger.info('init barrier') barrier = Barrier(http_getter) http_getter.add_observer(barrier) led_assembly = LedAssembly(http_getter) telegram_bot = Telegram_bot(telegram_api_token, barrier, telegram_bot_admins) keyboard_input = Keyboard(data_base, barrier) while BaseClass.working(): sleep(1)