def test_ir_cut_off(mock_factory): forward_pin = mock_factory.pin(config.get('IR_CUTOFF_FORWARD_GPIO_BCM')) backward_pin = mock_factory.pin(config.get('IR_CUTOFF_BACKWARD_GPIO_BCM')) enabler_pin = mock_factory.pin(config.get('IR_CUTOFF_ENABLER_GPIO_BCM')) ir_cut_off = IRCutOff() # Toggle in DAY mode ir_cut_off._toggle(Sundial.DAY) assert not forward_pin.state assert backward_pin.state assert enabler_pin.state # Idle ir_cut_off.stop() assert not forward_pin.state assert not backward_pin.state assert not enabler_pin.state # Toggle Night mode ir_cut_off._toggle(Sundial.NIGHT) assert forward_pin.state assert not backward_pin.state assert enabler_pin.state ir_cut_off.stop() Singleton.destroy(IRCutOff)
def test_led(mock_factory): led_pin = mock_factory.pin(config.get('LED_GPIO_BCM')) button_pin = mock_factory.pin(config.get('BUTTON_GPIO_BCM')) chime_pin = mock_factory.pin(config.get('CHIME_GPIO_BCM')) button = Button() button.activate_led() # Force LED to be always on button._led_always_on = True button_pin.drive_low() # button is pressed assert not led_pin.state assert led_pin.state == button.led.is_lit time.sleep(0.1) button_pin.drive_high() # button is released assert led_pin.state assert led_pin.state == button.led.is_lit # Force LED to be on during the day button._led_always_on = False button_pin.drive_low() # button is pressed should_be_lit = not Sundial().is_day() assert led_pin.state is not should_be_lit time.sleep(0.1) button_pin.drive_high() # button is released assert led_pin.state is should_be_lit Singleton.destroy(Button)
def __init__(self): # ToDo it seems to work without enable PIN. test it. self.__ir_cutoff_motor = IRCutOffMotor( forward=config.get('IR_CUTOFF_FORWARD_GPIO_BCM'), backward=config.get('IR_CUTOFF_BACKWARD_GPIO_BCM'), enable=config.get('IR_CUTOFF_ENABLER_GPIO_BCM')) self.__is_day = None
def create_app(config_name): # 创建app实例对象 app = Flask(__name__) # 加载配置 app.config.from_object(config.get(config_name) or 'default') # 执行额外的初始化 print('here111') print(app.config['SQLALCHEMY_DATABASE_URI']) config.get(config_name).init_app(app) #设置debug=True,让toolbar生效 # app.debug=True # 加载扩展 # print(app.config['UPLOADED_PHOTOS_DEST']) config_extensions(app) # 配置蓝本 config_blueprint(app) # 配置全局错误处理 config_errorhandler(app) # 返回app实例对象 return app
def test_press_button_normally(mock_factory): led_pin = mock_factory.pin(config.get('LED_GPIO_BCM')) button_pin = mock_factory.pin(config.get('BUTTON_GPIO_BCM')) chime_pin = mock_factory.pin(config.get('CHIME_GPIO_BCM')) button = Button() checkpoint = button.last_pressed # Wait for threshold to expire before pressing the button time.sleep(int(config.get('BUTTON_PRESS_THRESHOLD', 1))) chime_start = chime_pin._last_change button_pin.drive_low() # button is pressed assert checkpoint != button.last_pressed # Verify Chime state changes now = time.time() # Have to wait that the thread has completed time.sleep(Chime.PAUSE_BETWEEN_STATES * 2) warm_up_offset = 0.10 expected_states = [ PinState(timestamp=0.0, state=False), PinState(timestamp=now - (chime_start + warm_up_offset), state=True), PinState(timestamp=Chime.PAUSE_BETWEEN_STATES, state=False), ] chime_pin.assert_states_and_times(expected_states) Singleton.destroy(Button)
def test_cron(app): dummy_caller_id = '123456789' call = Call() call.get_the_line(dummy_caller_id) active_call = Call.get_call() assert active_call.id is not None assert call == active_call # Simulate heartbeat missed once time.sleep(config.get('WEBRTC_CALL_HEARTBEAT_INTERVAL')) Call.cron() active_call = Call.get_call() assert active_call.id is not None call.refresh_from_db() assert call.status == Call.ON_CALL # Simulate heartbeat missed twice time.sleep(config.get('WEBRTC_CALL_HEARTBEAT_INTERVAL')) Call.cron() active_call = Call.get_call() assert active_call.id is None call.refresh_from_db() assert call.status == Call.HUNG_UP
def create_app(config_name): # 创建app实例对象 app = Flask(__name__) # 加载配置 app.config.from_object(config.get(config_name) or 'default') # 执行额外的初始化 config.get(config_name).init_app(app) # 注册蓝图路由 from app.view.admin import admin as admin_blueprint from app.view.home import home as home_blueprint from app.view.tool import tool as tool_blueprint app.register_blueprint(home_blueprint, url_prefix='/') app.register_blueprint(admin_blueprint, url_prefix="/admin") app.register_blueprint(tool_blueprint, url_prefix="/tool") # 设置debug=True,让toolbar生效 # app.debug=True # 加载数据库 db.init_app(app) migrate.init_app(app, db) # 加载邮件插件 mail.init_app(app) # 加载用户登录插件 login_manager.init_app(app) # 定义全局函数 from app.function.redis import get_explore_post_count app.add_template_global(get_explore_post_count, 'get_explore_post_count') # 返回app实例对象 app.app_context().push() return app
def __init__(self): self.url = config.get('url', None) self.username = config.get('username', None) self.password = config.get('password', None) self.headers = {'Content-Type': 'application/json'} self.payload = {'username':self.username, 'password':self.password} self.pkiFile = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'token.pki')
def __init__(self): self.__last_pressed = datetime.now() self.__button = GPIOZeroButton(config.get('BUTTON_GPIO_BCM')) self.__led = LED(config.get('LED_GPIO_BCM')) self.__button.when_pressed = self.pressed self.__button.when_released = self.released self._led_always_on = config.get('BUTTON_LED_ALWAYS_ON') # Protected to access from unit tests self.__is_day = None
def create_app(config_name): app = Flask(__name__) app.config.from_object(config.get(config_name) or 'default') config.get(config_name).init_app(app) # Set to be in debug mode app.debug = True config_extension(app) config_blueprint(app) config_api(app) return app
def test_sundial(): with patch('app.helpers.sundial.date') as mock_date: mock_date.today.return_value = date(2019, 6, 2) mock_date.side_effect = lambda *args, **kw: date(*args, **kw) sundial = Sundial() with patch('app.helpers.sundial.datetime') as mock_datetime: mock_datetime.now.return_value = sundial.sun['sunrise'] mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) assert sundial.is_day() is False assert sundial.mode == Sundial.NIGHT # DAY mode `DAY_LIGHT_OFFSET` minutes after sunrise. with patch('app.helpers.sundial.datetime') as mock_datetime: mock_datetime.now.return_value = sundial.sun['sunrise'] \ + timedelta(minutes=int(config.get('DAY_LIGHT_OFFSET'))) mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) assert sundial.is_day() is True assert sundial.mode == Sundial.DAY # NIGHT mode at sunset with patch('app.helpers.sundial.datetime') as mock_datetime: mock_datetime.now.return_value = sundial.sun['sunset'] mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) assert sundial.is_day() is False assert sundial.mode == Sundial.NIGHT # NIGHT mode `DAY_LIGHT_OFFSET` minutes before sunset with patch('app.helpers.sundial.datetime') as mock_datetime: mock_datetime.now.return_value = sundial.sun['sunset'] \ - timedelta(minutes=int(config.get('DAY_LIGHT_OFFSET'))) mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) assert sundial.is_day() is False assert sundial.mode == Sundial.NIGHT # DAY mode `DAY_LIGHT_OFFSET` minutes and 1 sec. before sunset with patch('app.helpers.sundial.datetime') as mock_datetime: mock_datetime.now.return_value = sundial.sun['sunset'] \ - timedelta(minutes=int(config.get('DAY_LIGHT_OFFSET')), seconds=1) mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw) assert sundial.is_day() is True assert sundial.mode == Sundial.DAY
def run(self): try: _, temp_path = mkstemp() if config.get('USE_MOTION') is True: response = requests.get(config.get('MOTION_EYE_SNAPSHOT_URL')) buffered_reader = BufferedReader(BytesIO(response.content)) logger.debug('Image retrieved from motionEye') with open(temp_path, 'wb') as capture: capture.write(response.content) else: command = [ config.get('WEBCAM_BIN'), '--device', config.get('WEBCAM_DEVICE', '/dev/video0'), '--resolution', config.get('WEBCAM_RESOLUTION', '1920x1080'), '--no-banner', '--delay', config.get('WEBCAM_DELAY', '2'), '--rotate', config.get('WEBCAM_ROTATE', '180'), '--jpeg', config.get('WEBCAM_JPG_COMP', '80'), temp_path ] if logger.level > logging.DEBUG: command.insert(1, '--quiet') call(command) buffered_reader = open(temp_path, 'rb') logger.debug('Image {} captured from webcam'.format(temp_path)) notification = Notification(buffered_reader) notification.run() # Move picture in place as background for WebRTC call. destination_folder = os.path.join( config.ROOT_PATH, 'app', 'www', 'mobile', 'static', 'img' ) # Create destination folder if it does not exist if not os.path.exists(destination_folder): os.mkdir(destination_folder) destination = os.path.join( destination_folder, 'capture.jpg' ) move(temp_path, destination) except Exception as e: logger.error('Camera Helper: {}'.format(str(e))) return
def read(cls, message, last_time_received): if message['action'] == cls.START: if config.get('USE_MOTION') is True: time.sleep(1) # Give some delay to WEBRTC to release the cam process = Process() process.run(['sudo', 'systemctl', 'start', 'motioneye']) elif message['action'] == cls.STOP: if config.get('USE_MOTION') is True: process = Process() process.run(['sudo', 'systemctl', 'stop', 'motioneye']) else: return False return True
def call(self): """ Simulate a notification and let us access the page with a new token. Useful for development. Should be NEVER accessible on production """ token = Token() token.save() url = 'https://{domain}:{port}?token={token}'.format( domain=config.get('WEB_APP_DOMAIN_NAME'), port=config.get('WEB_APP_PORT'), token=token.token ) return redirect(url, 301)
def test_press_button_too_fast(mock_factory): led_pin = mock_factory.pin(config.get('LED_GPIO_BCM')) button_pin = mock_factory.pin(config.get('BUTTON_GPIO_BCM')) chime_pin = mock_factory.pin(config.get('CHIME_GPIO_BCM')) button = Button() checkpoint = button.last_pressed button_pin.drive_low() # button is pressed assert checkpoint == button.last_pressed # Do not ring. Pressed too fast expected_states = [PinState(timestamp=0.0, state=False)] chime_pin.assert_states_and_times(expected_states) Singleton.destroy(Button)
def generate_trackers(video_request, vidcap): try: trackers = {} tracker_type = config.get('tracker') tracker = set_tracking_algorithm(tracker_type) frame = get_frame_at_millisecond(vidcap, video_request['initialTrackerTime']) dim = (int(video_request['videoX']), int(video_request['videoY'])) tracker_dimensions = video_request['trackerDimensions'] resized_frame = cv2.resize(frame, dim) bbox = (tracker_dimensions['x'], tracker_dimensions['y'], tracker_dimensions['width'], tracker_dimensions['height']) ok = tracker.init(resized_frame, bbox) if not ok: raise ValueError('E-1300', 'Failed to read video', '') required_times = video_request['requiredTimes'] required_times.sort() for millisecond in required_times: frame = get_frame_at_millisecond(vidcap, millisecond) if frame is not None: resized_frame = cv2.resize(frame, dim) ok, bbox = tracker.update(resized_frame) if not ok: trackers['' + str(millisecond)] = {"status": 'E-1400', "message": 'Failed to track object'} else: trackers['' + str(millisecond)] = {"status": '200', "message": 'Tracked successfully', "trackerDim": str(bbox)} else: trackers['' + str(millisecond)] = {"status": 'E-1200', "message": 'Failed to fetch frame'} return trackers except Exception as e: raise ValueError('E-5000', 'General Error', e.args[0])
def create_app(config_name): app = Flask(__name__) # 加载配置 app.config.from_object(config.get(config_name) or 'default') # 执行额外的初始化 config.get(config_name).init_app(app) # 设置debug=True,让toolbar生效 # app.debug=True # 加载扩展 extensions(app) # 配置蓝本 config_blueprint(app) # 配置全局错误处理 config_error_handler(app) # 返回app实例对象 return app
def create_app(): app = Flask(__name__) app.config.from_object(config.get('default')) app.debug = True init_blueprint(app) # db.init_app(app) return app
def pressed(self): logger.info('Button has been pressed') delta = datetime.now() - self.__last_pressed if delta.seconds >= int(config.get('BUTTON_PRESS_THRESHOLD')): chime = Chime() chime.start() notification = Notification() notification.start() camera = Camera() camera.start() self.__last_pressed = datetime.now() else: logger.debug('Button was pressed too quickly!') if not self._led_always_on: if Sundial().is_day(): self.__led.on() else: self.__led.off() else: self.__led.off() # Stop play doorbell wav file (if any) Sender.send({ 'action': SoundReceiver.STOP, 'file': 'doorbell' }, SoundReceiver.TYPE) # Start play doorbell wav file Sender.send({ 'action': SoundReceiver.START, 'file': 'doorbell' }, SoundReceiver.TYPE)
def create_app(mode=os.environ.get('FLASK_MODE', 'app.config.Development')): """ Flask application instantiation with extensions and blueprints """ app = APIFlask(__name__) # add configurations app_config = config.get(mode) app.config.from_object(app_config) app_config().init_app(app) # initialize all extensions init_extensions(app) # register blueprints # add blueprint registration statements here from app.users import users app.register_blueprint(users) # register error handlers app.register_error_handler(400, bad_request) app.register_error_handler(Forbidden, forbidden) app.register_error_handler(404, not_found) app.register_error_handler(405, method_not_supported) app.register_error_handler(APIException, conflict) return app
def execute(): try: auth_session = session['authenticate'] request_datetime = auth_session['request_datetime'] token = auth_session['token'] used = True except KeyError: request_datetime = datetime.now() - timedelta( seconds=int(config.get('AUTH_DATETIME_PADDING'))) token = request.args.get('token') used = False query = Token.select().where(Token.token == token, Token.token.is_null(False), Token.used == used, Token.created_date >= request_datetime) if not query.exists(): # Not valid, don't go further Session.clear_auth_session() return False if Session.exists(): Session.renew_auth_session() else: Session.create_auth_session(token, request_datetime) token = query.get() token.used = True token.save() return True
def login_form(): app.logger.info('In the login form processing') email = flask.request.form.get("email") app.logger.info(email) if email not in config.get('allowed_emails', []): return flask.redirect(flask.url_for('login_problem')) #app.logger.info(app.redis) # Generate login token login_token = uuid.uuid4() app.logger.info(login_token) # Save login token app.redis.hmset(login_key(login_token), {"email": email}) app.redis.expire(login_key(login_token), 120) app.logger.info(app.redis.hgetall(login_key(login_token))) # Send email app.logger.info('About to send email') send_result = emails.send_login(email, login_token) if not send_result: return flask.redirect(flask.url_for('login_problem')) return flask.redirect(flask.url_for('login_sent'))
def read(cls, message, last_time_received): try: message_datetime = datetime.fromtimestamp(message['timestamp']) delta = message_datetime - last_time_received if delta.seconds >= int(config.get('BUTTON_PRESS_THRESHOLD')): if message.get('device') == config.get( 'BACK_DOORBELL_DEVICE_MAC'): telegram = Notification(front_door=False) telegram.start() chime = Chime( times=config.get('BACK_DOORBELL_RINGS_NUMBER')) chime.run() # No need to run it as thread else: logger.debug('Relax dude! Stop pushing the button') except KeyError: logger.error('Message is invalid.') return False
def __init__(self, times=1): """ Makes the bell chimes :param times: number of times the bell must chime """ self.__times = int(times) self.__buzzer = Buzzer(config.get('CHIME_GPIO_BCM')) super().__init__()
def send(cls, message, type_): message.update({ 'type': type_, 'timestamp': time.time(), 'signature': config.get('MESSAGE_BROKER_KEY') }) host = config.get('MESSAGE_BROKER_HOST') port = int(config.get('MESSAGE_BROKER_PORT')) try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((host, port)) s.sendall(json.dumps(message).encode('utf-8')) except ConnectionRefusedError: logger.error('Could not connect to socket') return False return True
def create_app(config_name): """ 通过此函数实现Flask对象的创建,在进行对象创建的同时还需要去考虑其他组件的初始化的处理问题 本次的初始化操作组件包括: 1. 一些程序的扩展支持 2. 蓝图的加载 3. 错误页面的配置 4. 拦截器(钩子函数)的配置 5. 自定义过滤器的使用 6. CSRF校验保护 :param config_name: 定义不同的启动模式 :return: 可以直接使用的Flask对象 """ app = Flask(__name__) app.config.from_object(config.get(config_name) or "development") config.get(config_name).__init__(app) return app
def create_app(config_name): # Create the app instance object app = Flask(__name__) # Load Configuration app.config.from_object(config.get(config_name) or 'default') # Perform additional initialization config.get(config_name).init_app(app) #set debug=True,let toolbar take effect # app.debug=True # Extension Loader config_extensions(app) # Configure a blueprint config_blueprint(app) # return app Instance Objects return app
def create_app(config_name): # 创建应用实例 app = Flask(__name__) # 加载Config类里面的配置 app.config.from_object(config.get(config_name) or 'default') # 执行额外的初始化 config.get(config_name).init_app(app) # 加载拓展 config_extensions(app) # 配置蓝本 config_blueprint(app) # 配置爱全局错误处理 config_error_handler(app) # 返回实例对象 return app
def create_app(config_name): # 创建app应用 app = Flask(__name__) # 加载配置 app.config.from_object(config.get(config_name)) # 额外初始化 config.get(config_name).init_app(app) # 加载扩展 extension_config(app) # 注册蓝本 blueprint_config(app) # 错误捕捉 errors_config(app) return app
def create_app(): app = Flask(__name__, static_folder='www/mobile/static') app.config.from_object(config) MobileMod(app) CommandsLoader(app) Talisman(app, content_security_policy=config.get('CONTENT_SECURITY_POLICY'), content_security_policy_nonce_in=['script-src']) # This hook ensures that a connection is opened to handle any queries # generated by the request. @app.before_request def _db_connect(): if database.is_closed(): database.connect() # This hook ensures that the connection is closed when we've finished # processing the request. @app.teardown_request def _db_close(exc): if not database.is_closed(): database.close() @app.errorhandler(404) def page_not_found(e): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return jsonify({ 'message': 'Page not found', 'status_code': 404 }), 404 return render_template('404.html'), 404 @app.errorhandler(403) def forbidden(e): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return jsonify({ 'message': 'Access forbidden', 'status_code': 403 }), 403 return render_template('403.html'), 403 @app.errorhandler(423) def locked(e): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return jsonify({ 'message': 'Somebody already picked up the phone', 'status_code': 423 }), 423 return render_template('423.html'), 423 return app