def __init__(self, screen_resolution=(320, 240)): log.info(f"Init {type(self).__name__}") if HAS_GPIO: # Backlight GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) self.backlight = GPIO.PWM(18, 1000) self.backlight_value = 100 self.backlight.start(self.backlight_value) self.button_1 = 17 self.button_2 = 22 self.button_3 = 23 self.button_4 = 27 GPIO.setup(self.button_1, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.button_2, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.button_3, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.button_4, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(self.button_1, GPIO.FALLING, callback=self.handle_button_1, bouncetime=200) GPIO.add_event_detect(self.button_2, GPIO.FALLING, callback=self.handle_button_2, bouncetime=200) GPIO.add_event_detect(self.button_3, GPIO.FALLING, callback=self.handle_button_3, bouncetime=200) GPIO.add_event_detect(self.button_4, GPIO.FALLING, callback=self.handle_button_4, bouncetime=200) os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' # os.environ["SDL_FBDEV"] = "/dev/fb1" # os.environ["SDL_VIDEODRIVER"] = "fbcon" status = pygame.init() info = pygame.display.Info() log.info(f"SDL init status: {status}") log.info("Available display modes:") log.info(pygame.display.list_modes()) log.info(f"Display resolution: ({info.current_w}, {info.current_h})") log.info(f"Display driver: {pygame.display.get_driver()}") log.info(f"Display bitsize: {info.bitsize}, bytesize: {info.bytesize}") if screen_resolution is None: self.screen_resolution = np.array([pygame.display.Info().current_w, pygame.display.Info().current_h]) else: self.screen_resolution = np.array(screen_resolution) self.surface = pygame.display.set_mode(self.screen_resolution) pygame.display.set_caption("Treblig Clock") if HAS_GPIO: pygame.mouse.set_visible(False) else: pygame.mouse.set_visible(True) pygame.font.init() self.pyg_clock = pygame.time.Clock() self.clock_style = ClockStyleSimple(surface=self.surface, screen_resolution=screen_resolution) self.alarm = Alarm() self.angles = [0, 0, 0] self.now = datetime.datetime.now() # todo: remove hard coded wake-up time. self.alarm.add(7, 0) self.is_running = False self.page = Clock.PAGE_CLOCK self.mouse = None log.debug(f"Info:") log.debug("\n" + str(pygame.display.Info()))
def test_check_with_too_low_pressure(self, test_sensor_class): test_sensor_instance = Mock() test_sensor_instance.sample_pressure.return_value = 15 test_sensor_class.return_value = test_sensor_instance alarm = Alarm() alarm.check() self.assertTrue(alarm.is_alarm_on)
def __init__(self): self.newwindow = Toplevel() self.newwindow.title("Running Scheduler") #geometry of the window self.newwindow.geometry("400x400+200+200") self.newwindow.configure(bg='#87ceeb') self.schedule = Alarm() self.l = self.schedule.Checkalarm() if (self.l is None): self.runninglabel = Label(self.newwindow, text="Running...", bg='#87ceeb', font='bold', fg='green').pack() else: self.runninglabel = Label(self.newwindow, text=self.l, bg='#87ceeb', font='bold', fg='red').pack() self.btn = Button(self.newwindow, text="Close", fg="white", bg="red", command=closeIt)
def __init__(self): self.newwindow = Toplevel() self.newwindow.title("Running Scheduler") self.newwindow.geometry("400x400+200+200") self.newwindow.configure(bg="#87ceeb") self.schedule = Alarm() self.l = self.schedule.Checkalarm() # print(self.l) if (not self.l): self.runninglabel = Label(self.newwindow, text="Running...", bg='#87ceeb', font='bold', fg='green').pack() os.system("cmd /k python alarm.py -r") else: self.runninglabel = Label(self.newwindow, text=self.l, bg='#87ceeb', font='bold', fg='red').pack() self.btn = Button(self.newwindow, text="Close", fg="white", bg="red", command=self.closeIt).place(x=170, y=300)
def test_single_yields_that(self): composite = AlarmComposite() alarm = Alarm() composite.add_alarm(alarm) alarm.add_target_day(Days.MONDAY) self.assertEqual(Days.MONDAY, composite.next_day)
def main(): parser = argparse.ArgumentParser() parser.add_argument("--debug", action="store_true") parser.add_argument("-c", "--config") args = parser.parse_args() try: config = os.path.abspath(args.config) pool = AlarmPool(config) logger.info("script starting up @ %s" % str(get_date())) Alarm.set_volume(90) # should be between 100 and 85 pool.load() if args.debug: logger.info("*** running debug mode... ***") pool.debug() else: pool.run() except KeyboardInterrupt: logger.exception("keyboard interrupt") except: logger.exception("exception occured") raise logger.info("script finishing up @ %s" % str(get_date()))
def confirm(self): alarm = Alarm(name=self.name_entry.get()) alarm.set_at(hour=self.at.get_hours(), minute=self.at.get_minutes()) self.alarm_manager.add_alarm(alarm) self.pack_forget() alarms = ui.alarms.Alarms(self.container) alarms.pack()
def __init__(self): # load the config file self.config = config() self.ui = gui.Gui(self.config.setting["resolution"], self.config.setting["fg_color"], self.config.setting["bg_color"], self.config.setting["show_mouse_cursor"]) locale.setlocale(locale.LC_ALL, self.config.setting["locale"] + ".utf8") self.musicplayer = MusicPlayer(self.config.setting["mopidy_host"]) self.alarm = Alarm(self.config.setting["alarmtime"], self.config.setting["enable_alarm"]) self.alarm.alarm_active = False self.player_primed = False self.is_idle = False self.time_last_idle = time.time() self.check_idle_thread = threading.Thread(target=self.check_idle) self.check_idle_thread.daemon = True self.check_idle_thread.start() self.old_time = 0 self.current_screen = self.idlescreen self.switch_to_defaultscreen() self.loop()
def test_high_pressure_with_monkeypatch(self, test_sensor_class): test_sensor_instance = Mock() test_sensor_instance.sample_pressure.return_value = 22 test_sensor_class.return_value = test_sensor_instance alarm = Alarm() alarm.check() self.assertTrue(alarm.is_alarm_on)
def test_check_with_too_high_pressure(self): with patch('alarm.Sensor') as test_sensor_class: test_sensor_instance = Mock() test_sensor_instance.sample_pressure.return_value = 22 test_sensor_class.return_value=test_sensor_instance alarm = Alarm() alarm.check() self.assertTrue(alarm.is_alarm_on)
def test_calls_play_sound_then_time_is_over(self): player = SoundPlayer() player.play = MagicMock() alarm = Alarm(0, player) alarm.check() player.play.assert_called()
def test_check_with_too_high_pressure_sounds_alarm(self): with patch('alarm.Sensor') as test_sensor_class: test_sensor_instance = Mock() test_sensor_instance.sample_pressure.return_value = 22 test_sensor_class.return_value = test_sensor_instance alarm = Alarm() alarm.check() self.assertTrue(alarm.is_alarm_on)
def test_single_yields_that(self): composite = AlarmComposite() alarm = Alarm() composite.add_alarm(alarm) self.assertEqual(0, composite.target_minute) alarm.target_minute = 30 self.assertEqual(30, composite.target_minute)
def test_alarm_no_activated(self): attrs = {'pop_next_pressure_psi_value.return_value': 21} sensor = Mock(spec=Sensor, **attrs) display = Mock(spec=Display) self._alarm = Alarm(sensor, display) self._alarm.check() display.print.assert_not_called()
def test_alarm_with_too_low_pressure(test_sensor_class): test_sensor_instance = Mock() test_sensor_instance.sample_pressure.return_value = 16 test_sensor_class.return_value = test_sensor_instance alarm = Alarm() alarm.check() assert alarm.is_alarm_on
def test_alarm_with_monkey_patching(): with patch('alarm.Sensor') as test_sensor_class: test_sensor_instance = Mock() test_sensor_instance.sample_pressure.return_value = 22 test_sensor_class.return_value = test_sensor_instance alarm = Alarm() alarm.check() assert alarm.is_alarm_on
def test_alarm_with_monkey_patching_different(test_sensor_class): test_sensor_instance = Mock() test_sensor_instance.sample_pressure.return_value = 16 test_sensor_class.return_value = test_sensor_instance alarm = Alarm() alarm.check() assert alarm.is_alarm_on
def test_single_yields_that(self): composite = AlarmComposite() alarm = Alarm() composite.add_alarm(alarm) self.assertEqual(0, composite.target_hour) alarm.target_hour = 5 self.assertEqual(5, composite.target_hour)
def test__alarm__re_inserting_alarm__performs_update(temp_db): alarm = Alarm() alarm.target_days = utilities.Days.MONDAY temp_db.add_alarm(alarm) alarm.target_days = utilities.Days.SUNDAY temp_db.add_alarm(alarm) result = temp_db.get_alarms()[0].target_days assert result == utilities.Days.SUNDAY
def __init__(self, coin, exchange, asset_pair, refresh, default_label): self.coin = coin # reference to main object self.alarm = Alarm(self) # alarm self.exchange = self.coin.find_exchange_by_code(exchange).get('class')(self) self.exchange.set_asset_pair_from_code(asset_pair) self.refresh_frequency = refresh self.default_label = default_label self.prices = {} self.latest_response = 0 # helps with discarding outdated responses
def test__alarm__db_insert_alarm_already_inserted__calls_db_update( temp_db, mocker): alarm = Alarm() alarm.target_days = utilities.Days.MONDAY temp_db.add_alarm(alarm) mock = mocker.patch.object(temp_db, "_update_alarm") temp_db.add_alarm(alarm) mock.assert_called_with(database.DBAlarm(alarm))
def test__alarm__re_inserting_alarm__updates_rather_than_re_inserting(temp_db): # pytest.skip("broken") alarm = Alarm() alarm.target_days = utilities.Days.MONDAY temp_db.add_alarm(alarm) alarm.target_days = utilities.Days.SUNDAY temp_db.add_alarm(alarm) assert len(temp_db.get_alarms()) == 1
def __init__(self, frameList): self.frameList = frameList # 设置帧列表, frameList为一个list, 每一个成员均为surface self.maxFrame = len(self.frameList) # 动画帧数量 self.currentFrameIdx = 0 # 当前动画帧id self.frameDurationMsec = 0 # 播放动画时使用的帧间隔 self.pos = [0, 0] # 动画发生地点, 单位为像素 self.surface = None # 动画发生的surface self.repeat = 0 # 循环次数 0-无限循环 self.state = ANIME_READY # 动画就绪 self.alarm = Alarm() self.playTimes = 0 # 动画被播放的次数
def onSocketReconnect(self): self.server.emit("raspberry:module:new", { "name": "alarm", "status": "PAUSED" }); LOGGER.info("Getting alarms api/modules/alarms/raspberries/" + self.name); res = None res = self.serverHttpRequest.get("api/modules/alarms/raspberries/" + self.name); if "status" in res and res["status"] == "success" and "data" in res and "items" in res["data"]: Alarm.setAlarmsFromJSON(res["data"]["items"]); else: LOGGER.info("invalid data");
def __init__(self, alarm=None, id=None): if alarm is not None: Alarm.__init__(self, **alarm.__dict__) else: alarm = Alarm() Alarm.__init__(self, **alarm.__dict__) # implicitly call base constructor if id: self.id = id else: self.id = DBAlarm.get_id(alarm)
def test_add_alarm(self): self.assertFalse(self.dm.has_any_alarms()) alarm = Alarm('7:30') alarm.set_at(hour='7', minute='30') self.dm.add_alarm(alarm) self.assertEqual(self.dm.get_count_alarms(), 1) candidate = self.dm.get_alarm_by_name('7:30') self.assertTrue(candidate is not None) self.assertEqual(candidate.get_hour(), '7') self.assertEqual(candidate.get_minute(), '30')
def __init__(self, coin, unique_id, exchange, asset_pair, refresh, default_label): self.coin = coin # reference to main program self.unique_id = unique_id self.alarm = Alarm(self) self.exchange = self.coin.find_exchange_by_code(exchange)(self) self.exchange.set_asset_pair_from_code(asset_pair) self.refresh_frequency = refresh self.default_label = default_label self.asset_selection_window = None self.alarm_settings_window = None self.prices = {} self.latest_response = 0 # helps with discarding outdated responses
def start_alarm(): if request.method == "POST": t = request.form["time"] hm = t.split(":") h = hm[0] m = hm[1] a = Alarm(int(h), int(m)) a.start() return ("", 204)
class Animation: def __init__(self, frameList): self.frameList = frameList # 设置帧列表, frameList为一个list, 每一个成员均为surface self.maxFrame = len(self.frameList) # 动画帧数量 self.currentFrameIdx = 0 # 当前动画帧id self.frameDurationMsec = 0 # 播放动画时使用的帧间隔 self.pos = [0, 0] # 动画发生地点, 单位为像素 self.surface = None # 动画发生的surface self.repeat = 0 # 循环次数 0-无限循环 self.state = ANIME_READY # 动画就绪 self.alarm = Alarm() self.playTimes = 0 # 动画被播放的次数 def setFrameDuration(self, duration_msec): self.frameDurationMsec = duration_msec def setPostion(self, surface, pos): # 设置动画发生的地点 self.pos = pos self.surface = surface def setRepeat(self, repeat): # 设置循环模式, 0-无限循环, >0-循环几次 self.repeat = repeat def draw(self): # 周期性的调用此函数即可进行动画描画 if self.state == ANIME_READY: self.state = ANIME_RUNNING self.alarm.setTimeout(self.frameDurationMsec) self.alarm.start() elif self.state == ANIME_RUNNING: if self.alarm.isTimeout(): self.currentFrameIdx += 1 if self.currentFrameIdx == self.maxFrame: self.currentFrameIdx = 0 if self.repeat != 0: # 不是无限循环 self.playTimes += 1 if self.playTimes == self.repeat: # 到达播放次数 self.state = ANIME_FINISHED self.surface.blit(self.frameList[self.currentFrameIdx], self.pos) else: pass # 不做任何事 def isAlive(self): # 判断动画是否存活 if self.state == ANIME_FINISHED: return False return True
def __init__(self, screen): self.screen = screen self.ctrlList = [] # 创建导演 self.director = Director(self.screen) # 创建定时器 self.alarm = Alarm() self.alarm.setTimeout(1000) self.alarm.start() # 创建调试信息 self.debugInfo = DebugInfo(screen) # fps相关 self.fps_count = 0 self.fps = 0
class TestAlarm(TestCase): def setUp(self): self.sensor = FakeSensor() self.alarm = Alarm(self.sensor) def test_alarm_is_off_by_default(self): self.assertFalse(self.alarm.is_on) def test_alarm_is_off_for_normal_readout(self): self.sensor.set_value(40) self.alarm.check_readout() self.assertFalse(self.alarm.is_on) def test_alarm_is_on_for_high_readout(self): self.sensor.set_value(100) self.alarm.check_readout() self.assertTrue(self.alarm.is_on) def test_alarm_is_on_for_low_readout(self): self.sensor.set_value(5) self.alarm.check_readout() self.assertTrue(self.alarm.is_on) def test_sensor_get_value_is_called_only_once(self): self.alarm.check_readout() self.assertEqual(1, self.sensor.called)
def ring_alarm(): global alarm_ringing alarm_ringing = True beat() code = randint(1000, 9999) # inclusive at both ends print('code: '+str(code)) begin_dial(code) Thread(target=call_controller, args=(code,)).start() alarm = Alarm(alarm_ringing) alarm.ring() alarm_ringing = False Thread(target=beat_controller).start() time.sleep(60) Thread(target=time_checker).start()
def test__alarm__db_close_and_repone__returns_same_data(temp_db): alarm = Alarm() alarm.target_days = utilities.Days.MONDAY | utilities.Days.FRIDAY alarm.target_hour = 6 alarm.target_minute = 5 temp_db.add_alarm(alarm) expected_id = temp_db.get_alarms()[0].id temp_db._close() temp_db._open() reloaded_alarm = temp_db.get_alarms()[0] expected_alarm = database.DBAlarm(alarm) expected_alarm.id = expected_id assert expected_alarm == reloaded_alarm
def __init__(self, queue_size, initial_max_temp): super(App_model, self).__init__() #======================================================================= # Initialize the temperature parameters (max temp, current temp, alarm, # temperature queue) and connects everything. #======================================================================= #app = App_Logic(alarm, max_temp, current_temp, temp_queue) self.alarm = Alarm() self.max_temp = Max_temp() self.current_temp = Current_temp() self.temp_queue = Temperature_queue(queue_size = 20) self.max_temp.set_temperature(int(initial_max_temp)) #======================================================================= # Serial Port listener # Initialize the HW listener... it runs in a different thread. #======================================================================= self.ser_comm = Serial_communication() # When a new temperature value is read, update the view's current temp self.ser_comm.value_read_signal.connect(self.update_current_temp) ''' In order to be able to read the port, without making the UI freeze, the port listener must run in a different thread. ''' t = threading.Thread(target = self.ser_comm.read_from_port) t.daemon = True # Not a main thread t.start() print "Serial Listener started!"
def __init__(self, app): Gtk.ApplicationWindow.__init__(self, title=_("Clocks"), application=app, hide_titlebar_when_maximized=True) action = Gio.SimpleAction.new("new", None) action.connect("activate", self._on_new_activated) self.add_action(action) app.add_accelerator("<Primary>n", "win.new", None) action = Gio.SimpleAction.new("about", None) action.connect("activate", self._on_about_activated) self.add_action(action) css_provider = Gtk.CssProvider() css_provider.load_from_path(os.path.join(Dirs.get_data_dir(), "gtk-style.css")) context = Gtk.StyleContext() context.add_provider_for_screen(Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) self.set_size_request(640, 480) self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.embed = Embed(self.vbox) self.add(self.embed) self.notebook = Gtk.Notebook() self.notebook.set_show_tabs(False) self.notebook.set_show_border(False) self.world = World() self.alarm = Alarm() self.stopwatch = Stopwatch() self.timer = Timer() self.views = (self.world, self.alarm, self.stopwatch, self.timer) self.toolbar = ClocksToolbar(self.views, self.embed) self.vbox.pack_start(self.toolbar, False, False, 0) self.single_evbox = Gtk.EventBox() self.vbox.pack_end(self.notebook, True, True, 0) for view in self.views: self.notebook.append_page(view, None) self.notebook.append_page(self.single_evbox, None) self.world.connect("show-standalone", self._on_show_standalone) self.alarm.connect("show-standalone", self._on_show_standalone) self.toolbar.connect("view-clock", self._on_view_clock) self.vbox.show_all() self.show_all() self.toolbar.show_overview_toolbar()
def decode_alarm_obj(self, obj): try: alarm = Alarm(str(obj["id"]), int(obj["hour"]), int(obj["minute"]), tag=str(obj["tag"]), editable=bool(obj["editable"])) if "days" in obj: alarm.days = Alarm.from_day_str(str(obj["days"])) if ("day" in obj) and \ ("month" in obj) and \ ("year" in obj): alarm.date = date(int(obj["year"]), int(obj["month"]), int(obj["day"])) return alarm except KeyError: raise ValueError
def __clientRPC(self, function, params): """ internal library for pvAccess channel RPC. """ alarm = Alarm() timeStamp = TimeStamp() ntnv = NTNameValue(function,params) # now do issue + wait channelRPC = ChannelRPC(self.channelname,"record[process=true]field()") channelRPC.issueConnect() if not channelRPC.waitConnect(1.0) : print channelRPC.getMessage() raise Exception(channelRPC.getMessage()) channelRPC.issueRequest(ntnv.getNTNameValue(),False) result = channelRPC.waitRequest() if(result==None) : print channelRPC.getMessage() raise Exception(channelRPC.getMessage()) nttable = NTTable(result) nttable.getAlarm(alarm.getAlarmPy()) nttable.getTimeStamp(timeStamp.getTimeStampPy()) return nttable
def default(self, obj): if isinstance(obj, Alarm): out = {"id": obj.alarm_id, "hour": obj.time.hour, "minute": obj.time.minute, "tag": obj.tag, "editable": obj.editable} if obj.days != 0: out["days"] = Alarm.to_day_str(obj.days) if obj.date: out["day"] = obj.date.day out["month"] = obj.date.month out["year"] = obj.date.year return {"alarm": out} else: return super(CommonJSONEncoder, self).default(self, obj)
class Channel: def __init__(self, dequeLength=100): """Initialize channel info""" #initialize voltage and time data arrays self.data = deque( [0.0]*dequeLength, dequeLength ) self.time = deque( [0.0]*dequeLength, dequeLength ) # intialize alarm to None; assign when set self.alarm = None # prepare variable for buffer size self.dequeLength = dequeLength def set_alarm(self, valueToTrack): self.alarm = Alarm( valueToTrack ) def check_alarms(self, valueToCheck): """checks each alarm in alarms array""" if self.alarm: return self.alarm.check_alarm( valueToCheck ) else: return False def remove_alarm(self): self.alarm = None def append_data(self, dataPoint, timePoint): """Handle data received from Arduino""" # add the data-processed value to the dataDeque self.data.append(dataPoint) self.time.append(timePoint) # return alarm status # check data to add against alarms return self.check_alarms( dataPoint ) def set_deque_length(self, newLength): #Create new data and time deques with newly specified length using # data from previous deque self.dequeLength = newLength self.data = deque( self.data, self.dequeLength ) self.time = deque( self.time, self.dequeLength )
def main(): root = Tk() a = Alarm(root) a.pack(side="bottom") textbox = Entry(root) textbox.pack(side="left") start = Button(root, text="Start",command= lambda: a.startTimer(int(textbox.get()), start, stop, textbox)) start.pack(side="left") stop = Button(root, text="Stop",command= lambda: a.stop(start,stop)) stop.config(state="disabled") stop.pack(side="left") reset = Button(root, text="Reset", command= lambda: a.reset(start,stop,textbox)) reset.pack(side="left") root.mainloop()
class App_model(QObject): ''' This class is the Model component of the MVC pattern. ''' update_current_temp_signal = Signal(int) def __init__(self, queue_size, initial_max_temp): super(App_model, self).__init__() #======================================================================= # Initialize the temperature parameters (max temp, current temp, alarm, # temperature queue) and connects everything. #======================================================================= #app = App_Logic(alarm, max_temp, current_temp, temp_queue) self.alarm = Alarm() self.max_temp = Max_temp() self.current_temp = Current_temp() self.temp_queue = Temperature_queue(queue_size = 20) self.max_temp.set_temperature(int(initial_max_temp)) #======================================================================= # Serial Port listener # Initialize the HW listener... it runs in a different thread. #======================================================================= self.ser_comm = Serial_communication() # When a new temperature value is read, update the view's current temp self.ser_comm.value_read_signal.connect(self.update_current_temp) ''' In order to be able to read the port, without making the UI freeze, the port listener must run in a different thread. ''' t = threading.Thread(target = self.ser_comm.read_from_port) t.daemon = True # Not a main thread t.start() print "Serial Listener started!" #=========================================================================== def compare_temperatures(self): ''' This method compares the current temperature and the max temperature defined. If the current is greater than the max temperature, an alarm will sound. ''' if self.current_temp.get_temperature() >= self.max_temp.get_temperature(): self.alarm_turn_on() #elif self.alarm.is_alarm(): #=========================================================================== def alarm_turn_off(self): #Signal to stop alarm self.alarm.set_alarm_status(False) #=========================================================================== def alarm_turn_on(self): #Signal to sound alarm self.alarm.set_alarm_status(True) #=========================================================================== def update_current_temp(self, new_value): new_value = int(new_value) new_value = self.adjust_temp_value(new_value) print "Updating current temperature value:", new_value self.update_current_temp_signal.emit(new_value) self.current_temp.set_temperature(new_value) self.temp_queue.put_in_queue(new_value) self.compare_temperatures() #=========================================================================== def adjust_temp_value(self, outdated_value): updated_value = int(outdated_value / 102.4) return updated_value
def test_check_temp_ok_with_mock(self): test_sensor = MagicMock(Sensor) test_sensor.sample_temperature.return_value = 20 alarm = Alarm(sensor=test_sensor) alarm.check() self.assertFalse(alarm.is_alarm_on)
def __init__(self, msecs = 1000): self.shown =0 Alarm.__init__(self,parent, msecs)
def test_check_too_high_pressure_sounds_alarm(self): alarm = Alarm(sensor=TestSensor(22)) alarm.check() self.assertTrue(alarm.is_alarm_on)
def test_check_normal_pressure_doesnt_sound_alarm(self): alarm = Alarm(sensor=TestSensor(18)) alarm.check() self.assertFalse(alarm.is_alarm_on)
def test_check_too_low_pressure_sounds(low_sensor): alarm = Alarm(low_sensor) alarm.check() assert alarm.is_alarm_on
def set_alarm(self, valueToTrack): self.alarm = Alarm( valueToTrack )
def __repr__(self): return "value=%s alarm=%s severity=%s flag=%s mask=%s time=%s" % \ (self.value, Alarm.nameOf(self.alarm), Severity.nameOf(self.severity), self.flag, self.mask, self.time)
def setUp(self): self.sensor = FakeSensor() self.alarm = Alarm(self.sensor)
def test_alarm_is_on_for_high_readout_using_MM(self): with patch.object(RealSensor, "get_value", return_value=100): alarm = Alarm() alarm.check_readout() self.assertTrue(alarm.is_on)
from argparse import ArgumentParser from datetime import datetime from flask import Flask, request, render_template from alarm import Alarm app = Flask(__name__) alarm = Alarm(alarm_t=datetime.now(), active=False) @app.route('/') def index(): return render_template('index.html', status=alarm.status(), alarm_t=alarm.time()) @app.route('/set_alarm', methods=['POST']) def set_alarm(): hour, minute = [int(n) for n in request.form['alarm_time'].split(':')] alarm.set_alarm( datetime( 2000, 1, 1, hour, minute ) ) return render_template('index.html', status=alarm.status(), alarm_t=alarm.time()) @app.route('/deactivate') def deactivate(): alarm.deactivate()
def test_check_normal_pressure_doesnt_sound_alarm(normal_sensor): alarm = Alarm(normal_sensor) alarm.check() assert not alarm.is_alarm_on
def test_check_normal_pressure_doesnt_sound_alarm_with_mock(mocker): test_sensor = Mock(Sensor) test_sensor.sample_pressure.return_value = 18 alarm = Alarm(test_sensor) alarm.check() assert not alarm.is_alarm_on
def test_check_too_high_pressure_sounds(high_sensor): alarm = Alarm(high_sensor) alarm.check() assert alarm.is_alarm_on
def test_check_normal_temp_doesnt_sounds_alarm(self): alarm = Alarm(sensor=TestSensor(20)) alarm.check() self.assertFalse(alarm.is_alarm_on)
def test_check_too_low_temp_sounds_alarm(self): alarm = Alarm(sensor=TestSensor(2)) # arrange alarm.check() # act self.assertTrue(alarm.is_alarm_on) # assert
class Window(Gtk.ApplicationWindow): def __init__(self, app): Gtk.ApplicationWindow.__init__(self, title=_("Clocks"), application=app, hide_titlebar_when_maximized=True) action = Gio.SimpleAction.new("new", None) action.connect("activate", self._on_new_activated) self.add_action(action) app.add_accelerator("<Primary>n", "win.new", None) action = Gio.SimpleAction.new("about", None) action.connect("activate", self._on_about_activated) self.add_action(action) css_provider = Gtk.CssProvider() css_provider.load_from_path(os.path.join(Dirs.get_data_dir(), "gtk-style.css")) context = Gtk.StyleContext() context.add_provider_for_screen(Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) self.set_size_request(640, 480) self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.embed = Embed(self.vbox) self.add(self.embed) self.notebook = Gtk.Notebook() self.notebook.set_show_tabs(False) self.notebook.set_show_border(False) self.world = World() self.alarm = Alarm() self.stopwatch = Stopwatch() self.timer = Timer() self.views = (self.world, self.alarm, self.stopwatch, self.timer) self.toolbar = ClocksToolbar(self.views, self.embed) self.vbox.pack_start(self.toolbar, False, False, 0) self.single_evbox = Gtk.EventBox() self.vbox.pack_end(self.notebook, True, True, 0) for view in self.views: self.notebook.append_page(view, None) self.notebook.append_page(self.single_evbox, None) self.world.connect("show-standalone", self._on_show_standalone) self.alarm.connect("show-standalone", self._on_show_standalone) self.toolbar.connect("view-clock", self._on_view_clock) self.vbox.show_all() self.show_all() self.toolbar.show_overview_toolbar() def show_clock(self, view): self.toolbar.activate_view(view) def _on_show_standalone(self, widget, d): def show_standalone_page(): widget = d.get_standalone_widget() self.toolbar.show_standalone_toolbar(widget) self.single_evbox.add(widget) self.notebook.set_current_page(-1) if self.notebook.get_current_page() != len(self.views): self.embed.spotlight(show_standalone_page) def _on_view_clock(self, button, view): def show_clock_view(): for child in self.single_evbox.get_children(): self.single_evbox.remove(child) view.unselect_all() self.notebook.set_current_page(self.views.index(view)) self.toolbar.show_overview_toolbar() if self.single_evbox.get_children(): self.embed.spotlight(show_clock_view) else: show_clock_view() def _on_new_activated(self, action, param): self.toolbar.current_view.open_new_dialog() def _on_about_activated(self, action, param): about = Gtk.AboutDialog() about.set_title(_("About Clocks")) about.set_program_name(_("GNOME Clocks")) about.set_logo_icon_name("clocks") about.set_version(__version__) about.set_copyright(COPYRIGHTS) about.set_comments( _("Utilities to help you with the time.")) about.set_authors(AUTHORS) about.set_translator_credits(_("translator-credits")) about.set_website("http://live.gnome.org/GnomeClocks") about.set_website_label(_("GNOME Clocks")) about.set_wrap_license("true") about.set_license_type(Gtk.License.GPL_2_0) about.set_license("GNOME Clocks is free software;" " you can redistribute it and/or modify it under the terms" " of the GNU General Public License as published by the" " Free Software Foundation; either version 2 of the" " License, or (at your option) any later version.\n" " \n" "GNOME Clocks is distributed in the hope that it will be" " useful, but WITHOUT ANY WARRANTY; without even the" " implied warranty of MERCHANTABILITY or FITNESS FOR" " A PARTICULAR PURPOSE. See the GNU General Public" " License for more details.\n" " \n" "You should have received a copy of the GNU General" " Public License along with GNOME Clocks; if not, write" " to the Free Software Foundation, Inc., 51 Franklin" " Street, Fifth Floor, Boston, MA 02110-1301 USA\n") about.connect("response", lambda w, r: about.destroy()) about.set_modal(True) about.set_transient_for(self) about.show()
def test_alarm_is_on_for_low_readout_using_MM(self): sensor = MagicMock(RealSensor) sensor.get_value.return_value = 5 alarm = Alarm(sensor) alarm.check_readout() self.assertTrue(alarm.is_on)
def test_check_with_pressure_ok_with_mock_fw(self): test_sensor = Mock(Sensor) test_sensor.sample_pressure.return_value = 18 alarm = Alarm(test_sensor) alarm.check() self.assertFalse(alarm.is_alarm_on)