Exemplo n.º 1
0
    def run_game_loop(self):
        self.frame_rendered(0)

        self.timer = RepeatedTimer(0.1, self.tick)

        while self.loop:
            key = self.kp.read_single_keypress().lower()

            if key == 'a':
                self.move_paddle(0, -1)
            elif key == 's':
                self.move_paddle(0, 1)
            elif key == 'k':
                self.move_paddle(1, -1)
            elif key == 'l':
                self.move_paddle(1, 1)
            elif key == 'r':
                self.init_game()
            elif not config.HAS_GUI and key == 'q':
                break

        self.led_strip.register_callback(
            self.led_strip.CALLBACK_FRAME_RENDERED, None)
        self.timer.stop()
        self.kp.stop()
Exemplo n.º 2
0
 def on_complete(self):
     self.animation_loader.on_complete()
     self.interval_animation.stop()
     if os.path.isfile(self.NODE_JS_BINARY_TARFILE_FULL_PATH):
         os.remove(self.NODE_JS_BINARY_TARFILE_FULL_PATH)
     node_js = NodeJS()
     npm = NPM()
     self.animation_loader = AnimationLoader([
         "[=     ]", "[ =    ]", "[   =  ]", "[    = ]", "[     =]",
         "[    = ]", "[   =  ]", "[ =    ]"
     ], 0.067, "Installing npm dependencies ")
     self.interval_animation = RepeatedTimer(self.animation_loader.sec,
                                             self.animation_loader.animate)
     try:
         npm.getCurrentNPMVersion(True)
     except Exception as e:
         print("Error: " + traceback.format_exc())
     try:
         npm.install_all()
     except Exception as e:
         #print("Error: "+traceback.format_exc())
         pass
     self.animation_loader.on_complete()
     self.interval_animation.stop()
     if node_js.getCurrentNodeJSVersion(True) == self.NODE_JS_VERSION:
         sublime.active_window().status_message(
             "Node.js " + self.NODE_JS_VERSION +
             " installed correctly! NPM version: " +
             npm.getCurrentNPMVersion(True))
     else:
         sublime.active_window().status_message(
             "Can't install Node.js! Something went wrong during installation."
         )
Exemplo n.º 3
0
 def start(self):
     self.thread = threading.Thread(target=self.download,
                                    name="DownloadNodeJS")
     self.thread.setDaemon(True)
     self.thread.start()
     if self.animation_loader:
         self.interval_animation = RepeatedTimer(
             self.animation_loader.sec, self.animation_loader.animate)
Exemplo n.º 4
0
    def initializeTimerTask(self):
        # 1 - Timer essential properties
        self._timerInterval = 1

        # 2 - Start Timer
        self._rt = RepeatedTimer(
            self._timerInterval,
            self.doTimerTask)  # it auto-starts, no need of rt.start()
Exemplo n.º 5
0
 def __init__(self, exmoApiModel):
     self.__exmoApiModel = exmoApiModel
     self.__timer = RepeatedTimer(self.REFRESH_INTERVAL_SEC, self.__step)
     self.__data = []
     self.__lastOperation = self.OPERATION_NONE
     self.__math = SimpleMath()
     self.__currentRate = 0
     self.__lastRate = 0
     self.__printCurrentBalance()
Exemplo n.º 6
0
def run_spread_logger(seconds_interval=60):
    header_row = ["Timestamp", "Currency", "Buy Exchange", "Profit", "Return"]

    with open('./spread_logger.csv', 'a') as f:
        w = csv.writer(f)
        w.writerow(header_row)

    print("starting...\n")
    RepeatedTimer(seconds_interval, fetch_price_spread, seconds_interval)
Exemplo n.º 7
0
 def __init__(self,
              estimation: ComplementarityEstimation,
              cluster: Cluster,
              update_interval=60):
     self.queue = []
     self.estimation = estimation
     self.cluster = cluster
     self._timer = RepeatedTimer(update_interval, self.update_estimation)
     self.scheduler_lock = Lock()
     self.started_at = None
     self.stopped_at = None
     self.print_estimation = False
def start_asteroid_creation_timer(ai_settings, screen, stats, sb, ship,
                                  asteroids):
    if stats.level >= stats.MIN_HARD_LEVEL:
        timer = RepeatedTimer(
            ai_settings.base_asteroids_timer_interval / stats.level,
            create_asteroid,
            ai_settings,
            screen,
            asteroids,
        )
        timer.start()
        return timer
    return None
Exemplo n.º 9
0
    def __init__(self, ui, timer_secs, use_timer, sim_mode, competition_mode):
        super(Referee, self).__init__()

        # Setup my UI
        self.ui = RefereeUI(ui, sim_mode, use_timer, competition_mode)

        # Connect to ROS things
        ball_topic = '/ball/truth' if sim_mode else 'vision/ball'
        rospy.Subscriber(ball_topic, Pose2D, self._handle_vision_ball)

        self.pub_game_state = rospy.Publisher('game_state',
                                              GameState,
                                              queue_size=10,
                                              latch=True)
        self.sim_mode = sim_mode
        self.game_started = False

        # Create a GameState msg that will be continually updated and published
        self.game_state = GameState()
        self.ballIsStillInGoal = False

        # Set up a 100ms timer event loop
        self.timer = RepeatedTimer(0.1, self._timer_handler)
        self.ui.reset_timer(timer_secs)

        # Populate team names into comboboxes. If sim_mode, these will come from
        # the catkin_ws packages. If not, these need to come from .. a YAML?
        self.ui.populate_team_names(sim_mode)

        # Connect Qt Buttons
        self.ui.btn_play.clicked.connect(self._btn_play)
        self.ui.btn_reset_field.clicked.connect(self._btn_reset_field)
        self.ui.btn_next_half.clicked.connect(self._btn_next_half)
        self.ui.btn_reset_clock.clicked.connect(self._btn_reset_clock)
        self.ui.btn_start_game.clicked.connect(self._btn_start_game)

        # Penalty buttons
        self.ui.btn_home_penalty.clicked.connect(
            lambda: self._handle_penalty(home=True))
        self.ui.btn_away_penalty.clicked.connect(
            lambda: self._handle_penalty(home=False))

        # Score +/- buttons
        self.ui.btn_home_inc_score.clicked.connect(
            lambda: self._handle_score(home=True, inc=True))
        self.ui.btn_home_dec_score.clicked.connect(
            lambda: self._handle_score(home=True, inc=False))
        self.ui.btn_away_inc_score.clicked.connect(
            lambda: self._handle_score(home=False, inc=True))
        self.ui.btn_away_dec_score.clicked.connect(
            lambda: self._handle_score(home=False, inc=False))
 def __init__(self, estimation: ComplementarityEstimation, cluster: Cluster, update_interval=60):
     self.queue = []
     self.estimation = estimation
     self.cluster = cluster
     self._timer = RepeatedTimer(update_interval, self.update_estimation)
     self.scheduler_lock = Lock()
     self.started_at = None
     self.stopped_at = None
     self.print_estimation = False
     self.waiting_time = {}
     self.scheduled_apps_num = 0
     self.jobs_to_peek = self.jobs_to_peek_arg
     self.random_arrival_rate = [0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 0, 2, 0, 2,
                                 1, 0, 2, 2, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]
Exemplo n.º 11
0
    def __init__(self, ipcon, key_queue):
        if not config.UID_DUAL_BUTTON_BRICKLET[0]:
            print("Not Configured: Dual Button 1")

        if not config.UID_DUAL_BUTTON_BRICKLET[1]:
            print("Not Configured: Dual Button 2")

        self.key_queue = key_queue
        self.ipcon = ipcon

        if config.UID_DUAL_BUTTON_BRICKLET[0]:
            self.db1 = DualButton(config.UID_DUAL_BUTTON_BRICKLET[0],
                                  self.ipcon)
        else:
            self.db1 = None

        if config.UID_DUAL_BUTTON_BRICKLET[1]:
            self.db2 = DualButton(config.UID_DUAL_BUTTON_BRICKLET[1],
                                  self.ipcon)
        else:
            self.db2 = None

        if self.db1:
            try:
                self.db1.get_button_state()
                print("Found: Dual Button 1 ({0})").format(
                    config.UID_DUAL_BUTTON_BRICKLET[0])
            except:
                self.db1 = None
                print("Not Found: Dual Button 1 ({0})").format(
                    config.UID_DUAL_BUTTON_BRICKLET[0])

        if self.db2:
            try:
                self.db2.get_button_state()
                print("Found: Dual Button 2 ({0})").format(
                    config.UID_DUAL_BUTTON_BRICKLET[1])
            except:
                self.db2 = None
                print("Not Found: Dual Button 2 ({0})").format(
                    config.UID_DUAL_BUTTON_BRICKLET[1])

        if self.db1:
            self.db1.register_callback(self.db1.CALLBACK_STATE_CHANGED,
                                       self.cb_state_changed1)
        if self.db2:
            self.db2.register_callback(self.db2.CALLBACK_STATE_CHANGED,
                                       self.cb_state_changed2)

        self.press_timer = RepeatedTimer(0.1, self.press_tick)
Exemplo n.º 12
0
 def play(self, sound_file):
     """ Play a file and configure the rest of the window accordingly. """
     # (But first check if there's a timer
     # currently running and if so, stop it.)
     if hasattr(self, 'timer'):
         self.timer.stop()
     self.position_slider.set(0)
     self.controller.sound_object.play(sound_file)
     self.current_time.move_timer(0)
     self.total_time.move_timer(self.controller.sound_object.get_length())
     self.time_left.move_timer(self.controller.sound_object.get_length())
     self.timer = RepeatedTimer(1, self.increment_timers)
     self.button_pause["state"] = "normal"
     self.button_pause.config(relief=tk.RAISED)
     self.paused = False
     self.song_now_playing = sound_file
     self.path_now_playing = self.file_display.get_current_path()
Exemplo n.º 13
0
def updateNPMDependencies():
    npm = NPM()
    try:
        npm.getCurrentNPMVersion(True)
    except Exception as e:
        print("Error: " + traceback.format_exc())
        return

    animation_loader = AnimationLoader([
        "[=     ]", "[ =    ]", "[   =  ]", "[    = ]", "[     =]", "[    = ]",
        "[   =  ]", "[ =    ]"
    ], 0.067, "Updating npm dependencies ")
    interval_animation = RepeatedTimer(animation_loader.sec,
                                       animation_loader.animate)
    try:
        npm.update_all(False)
    except Exception as e:
        pass
    animation_loader.on_complete()
    interval_animation.stop()
Exemplo n.º 14
0
    def __init__(self, ipcon, key_queue):
        if not config.UID_MULTI_TOUCH_BRICKLET:
            print("Not Configured: Multi Touch")
            return

        self.key_queue = key_queue
        self.ipcon = ipcon
        self.mt = MultiTouch(config.UID_MULTI_TOUCH_BRICKLET, self.ipcon)

        try:
            self.mt.get_electrode_sensitivity()
            print("Found: Multi Touch ({0})").format(
                config.UID_MULTI_TOUCH_BRICKLET)
        except:
            print("Not Found: Multi Touch ({0})").format(
                config.UID_MULTI_TOUCH_BRICKLET)
            return

        self.mt.set_electrode_sensitivity(100)
        self.mt.register_callback(self.mt.CALLBACK_TOUCH_STATE,
                                  self.cb_touch_state)

        self.touch_timer = RepeatedTimer(0.1, self.touch_tick)
Exemplo n.º 15
0
    def __init__(self, serverId, addr, peers, dataDir):
        super()

        if not os.path.exists(dataDir):
            os.makedirs(dataDir)

        self.serverId = serverId
        self.addr = addr
        self.database = DBEngine(dataDir)
        self.miner = MinerThreading()
        self.daemonTimer = RepeatedTimer(0.5, self.daemon)

        self.peers = peers
        self.stubs = []
        for peer in self.peers:
            logging.info('added peer {}'.format(peer))
            channel = grpc.insecure_channel(peer)
            self.stubs.append(db_pb2_grpc.BlockChainMinerStub(channel))
            self.stubs[-1].addr = peer

        self.miner.daemon = True
        self.miner.start()
        self.daemonTimer.start()
Exemplo n.º 16
0
def updateNPMDependencies():
    npm = NPM()
    try:
        npm.getCurrentNPMVersion(True)
    except Exception as e:
        if node_variables.NODE_JS_OS == "win":
            sublime.active_window().status_message(
                "Can't use \"npm\"! To use features that requires \"npm\", you must install it! Download it from https://nodejs.org site"
            )
        print("Error: " + traceback.format_exc())
        return

    animation_loader = AnimationLoader([
        "[=     ]", "[ =    ]", "[   =  ]", "[    = ]", "[     =]", "[    = ]",
        "[   =  ]", "[ =    ]"
    ], 0.067, "Updating npm dependencies ")
    interval_animation = RepeatedTimer(animation_loader.sec,
                                       animation_loader.animate)
    try:
        npm.update_all(False)
    except Exception as e:
        pass
    animation_loader.on_complete()
    interval_animation.stop()
Exemplo n.º 17
0
 def on_complete(self):
     self.animation_loader.on_complete()
     self.interval_animation.stop()
     if os.path.isfile(self.NODE_JS_BINARY_TARFILE_FULL_PATH):
         os.remove(self.NODE_JS_BINARY_TARFILE_FULL_PATH)
     node_js = NodeJS()
     npm = NPM()
     self.animation_loader = AnimationLoader([
         "[=     ]", "[ =    ]", "[   =  ]", "[    = ]", "[     =]",
         "[    = ]", "[   =  ]", "[ =    ]"
     ], 0.067, "Installing npm dependencies ")
     self.interval_animation = RepeatedTimer(self.animation_loader.sec,
                                             self.animation_loader.animate)
     try:
         npm.getCurrentNPMVersion()
     except Exception as e:
         if node_variables.NODE_JS_OS == "win":
             sublime.error_message(
                 "Can't use \"npm\"! To use features that requires \"npm\", you must install it! Download it from https://nodejs.org site"
             )
         print(e)
     try:
         npm.install_all()
     except Exception as e:
         pass
     self.animation_loader.on_complete()
     self.interval_animation.stop()
     if node_js.getCurrentNodeJSVersion() == self.NODE_JS_VERSION:
         sublime.active_window().status_message(
             "Node.js " + self.NODE_JS_VERSION +
             " installed correctly! NPM version: " +
             npm.getCurrentNPMVersion())
     else:
         sublime.active_window().status_message(
             "Can't install Node.js! Something went wrong during installation."
         )
Exemplo n.º 18
0
 def pause(self):
     """ Toggle between a "paused" and "non-paused" state. """
     if self.paused:
         self.button_pause.config(relief=tk.RAISED)
         # Theoretically, if the user pauses and unpauses
         # many times during the same song, the timers
         # could get thrown off. So adjust the timers.
         if not self.jump_pending:
             self.current_time.move_timer(
                 self.controller.sound_object.get_position())
             self.time_left.move_timer(
                 self.controller.sound_object.get_length() -
                 self.controller.sound_object.get_position())
             self.position_slider.set(
                 self.current_time.timer_seconds /
                 self.controller.sound_object.get_length() * 100)
         self.jump_pending = False
         self.controller.sound_object.unpause()
         self.timer = RepeatedTimer(1, self.increment_timers)
     else:
         self.button_pause.config(relief=tk.SUNKEN)
         self.controller.sound_object.pause()
         self.timer.stop()
     self.paused = not self.paused
Exemplo n.º 19
0
    tlc_serial = oasis_serial.OasisSerial("/dev/ttyS2",
                                          debug_mode=DEBUG_MODE,
                                          debug_tx_port=TLC_TX_PORT,
                                          debug_rx_port=TLC_RX_PORT)

    tlc = TLC(tlc_serial)
    rover = roverio.Rover(packet_manager, fm)
    laser = laserio.Laser(oasis_serial=rover_serial)

    spectrometer = spectrometerio.Spectrometer(serial=rover_serial,
                                               file_manager=fm)

    def log_timer_callback():
        """This is the callback function that repeatedly logs the current status to the status log."""
        status_array = rover.get_status_array(laser.states_laser,
                                              spectrometer.states_spectrometer,
                                              tlc.get_temperatures(),
                                              tlc.get_duty_cycles(),
                                              active_errors,
                                              past_two_commands[1])
        fm.log_status(status_array, 0)

    log_data_timer = RepeatedTimer(LOGGING_INTERVAL, log_timer_callback)
    log_data_timer.start()

    while True:
        main_loop()

    packet_manager.running = False
Exemplo n.º 20
0
def main():
    global _motion_timer
    _motion_timer = RepeatedTimer(_motion_timer_period, _handle_motion_timer)
    _motion_timer.start()

    global _odom_timer
    _odom_timer = RepeatedTimer(_odom_timer_period, _handle_odom_timer)
    _odom_timer.start()

    global _ctrl_timer
    _ctrl_timer = RepeatedTimer(_ctrl_timer_period, _handle_ctrl_timer)
    _ctrl_timer.start()

    use_rcv3 = os.environ['USE_RCV3'] == 'true'
    w.init(use_rcv3=use_rcv3)

    # TODO: Okay, so Controller.init(None) will automagically load in some PID 
    # values for each of the x, y, theta position controllers. However, since
    # `teleop` is run in real life on different robots, really it should read
    # the correct YAML robot config file and load in the PID constants and
    # pass them into Controller.init(gains) as in the controller_node.py.
    # Two ways to do this: (1) do like os.environ['USE_RCV3'], where the odroid_setup.bash
    # script loads up the PID constants as environment variables (this seems messy).
    # (2) find a python YAML reading library and just read the file directly from here
    # based on which robot this is (you can use os.environ['ROBOT'])
    Controller.init()
    
    print 'Started.'


    global _velocities, _set_speed, _smooth, _odom_on, _previous_action, _ctrl_on

    while(1):
        action = get_action()
        if action == 'UP':
            _set_speed = True
            _velocities = (0, _vy, 0)

        elif action == 'DOWN':
            _set_speed = True
            _velocities = (0, -_vy, 0)

        elif action == 'RIGHT':
            _set_speed = True
            _velocities = (_vx, 0, 0)

        elif action == 'LEFT':
            _set_speed = True
            _velocities = (-_vx, 0, 0)

        elif action == 'SPIN_CW':
            _set_speed = True
            _velocities = (0, 0, _w)

        elif action == 'SPIN_CCW':
            _set_speed = True
            _velocities = (0, 0, -_w)

        elif action == 'SET_HOME':
            Odometry.init()

        elif action == 'GO_HOME':
            _motion_timer.stop()
            motion.stop()
            time.sleep(1)

            _go_home()

            time.sleep(1)
            _set_speed = True
            _velocities = (0, 0, 0)
            _motion_timer.start()

        elif action == 'GO_TO_POINT':
            _toggle_timers(False)
            motion.stop()
            time.sleep(1)

            _ask_for_point()

            time.sleep(1)
            _ctrl_on = True
            _odom_on = True
            _toggle_timers(True)

        elif action == 'TOGGLE_CNTRL':
            _ctrl_on = not _ctrl_on
            print("Controller: {}".format(_ctrl_on))

        elif action == 'TOGGLE_SMOOTH':
            _smooth = not _smooth
            print("Smooth: {}".format(_smooth))

        elif action == 'TOGGLE_ODOM':
            _odom_on = not _odom_on
            print("Odom: {}".format(_odom_on))

        elif action == 'BATTERY':
            print("\n\r*** Battery: {} ***\n\r".format(get_battery()))

        elif action == 'BREAKPOINT':
            _toggle_timers(False)
            import ipdb; ipdb.set_trace()
            _toggle_timers(True)

        elif action == 'CALIBRATION_MODE':
            _toggle_timers(False)

            _deal_with_calibration()

            time.sleep(1)
            _toggle_timers(True)

        elif action == 'DIE':
            _toggle_timers(False)
            motion.stop()
            w.kill()
            return sys.exit(0)

        else:
            _set_speed = True
            _velocities = (0, 0, 0)

        # handle stopping before changing directions
        if _action_requires_stop(action):
            _set_speed = False
            motion.stop()
            time.sleep(0.4)
            _set_speed = True

        _previous_action = action

        print "{}\r".format(_velocities)
Exemplo n.º 21
0
 def __init__(self, app, interval):
     self._app = app
     self._timer = RepeatedTimer(interval, self._sample)
Exemplo n.º 22
0
def fun_reminder():
    user = users.find()
    current_time = datetime.datetime.now().time()
    day = weekday_now(datetime.date.today().weekday() + 1)
    for i in user:
        _id = i['_id']
        if current_time.hour == i['daily_warn_time'][
                'h'] and current_time.minute == i['daily_warn_time']['m']:
            time = timers.find_one({'_id': _id})
            if time:
                time = time.get(day)
                if time:
                    send_reminder_mess(_id, {day: time})


rt_warnings = RepeatedTimer(60, fun_warnings)
rt_reminders = RepeatedTimer(60, fun_reminder)

print('Work hard, play hard!')


#Обработка команды старт.
@bot.message_handler(commands=['start'])
def send_start(message):
    try:
        _id = message.chat.id
        user_id = {'_id': _id}
        if not dict_users.get(_id):
            dict_users[_id] = User(id=_id)
        if not users.find_one(user_id):
            user_id.update({
Exemplo n.º 23
0
def video_start():
    t.start()


def video_stop():
    #cap.release()
    t.stop()


#================================Functions==================================================

#================================Main Program===============================================
cap = cv2.VideoCapture(0)
Gray_1 = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY)
t = RepeatedTimer(0.01, video)
Values = [0 for x in range(100)]
#===========================================================================================

#=================================GUI Section=============================================
root = Tk()
root.geometry('1000x700')

f = Figure(figsize=(4, 4), dpi=50)
axis = f.add_subplot(111)
canvas = FigureCanvasTkAgg(f, master=root)
canvas.get_tk_widget().place(x=10, y=30)
frame2 = Frame(root)
frame2.place(x=20, y=300)
X_Axis = pylab.arange(0, 100, 1)
plotFigure = Figure(figsize=(4, 4), dpi=50)
Exemplo n.º 24
0
 def start(self, GAME_KEEPER):
     self.TASKS.append(RepeatedTimer(20,
                                     GAME_KEEPER.create_games_for_queue))
     self.TASKS.append(RepeatedTimer(10, GAME_KEEPER.check_current_games))
Exemplo n.º 25
0
 def start(self):
     self.thread = create_and_start_thread(self.download, "DownloadNodeJS")
     if self.animation_loader:
         self.interval_animation = RepeatedTimer(
             self.animation_loader.sec, self.animation_loader.animate)
Exemplo n.º 26
0
clock = pygame.time.Clock()
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Insofar')
exit = False

player = Player()

lasers = []
asteroids = []

stars_x = random.sample(range(0, SCREEN_WIDTH), NUM_STARS)
stars_y = random.sample(range(0, SCREEN_HEIGHT), NUM_STARS)

asteroid_timer = RepeatedTimer(ASTEROID_SPAWN_RATE, spawn, asteroids)

death = False
death_text = CenterText('You died!', (255, 255, 0))

while exit is False:

    joystick_count = pygame.joystick.get_count()

    if joystick_count == 0:
        print('Missing joystick!')
        exit = True

    else:
        move_joystick = pygame.joystick.Joystick(0)
        move_joystick.init()
Exemplo n.º 27
0
    print ("GATT application ip address %s" % ip_address, flush=True)
    ble_app.services[SYSTEM_SERVICE_INDEX].set_ip_address(ip_address)

def shouldShutdown():
    if not shutdown_button.value:
        print('Should shutdown system..', flush=True)
        shutdown()

# execution
ble_app = BleApplication()
ble_app.add_service(WeatherService(WEATHER_SERVICE_INDEX))
ble_app.add_service(RgbColorService(RGB_COLOR_SERVICE_INDEX))
ble_app.add_service(SystemService(SYSTEM_SERVICE_INDEX))
ble_app.register()

ble_adv = WeatherStationAdvertisement(0)
ble_adv.register()

timer_update = RepeatedTimer(DELAY_WEATHER_REQUEST, updateWeather)
timer_system = RepeatedTimer(DELAY_DETECT_MANUAL_SHUTDOWN, shouldShutdown)

try:
    print('GATT application running')
    fetchIpAddress()
    ble_app.run()
except KeyboardInterrupt:
    ble_app.quit()
    pass

stop()
 def start_timer(self):
     self.threading_timer = RepeatedTimer(3, self.refresh)
     self.threading_timer.start()
Exemplo n.º 29
0
    def run(self):
        # get the first pending update_id, this is so we can skip over it in case
        # we get an "Unauthorized" exception.
        try:
            self.update_id = self.bot.get_updates()[0].update_id
        except IndexError:
            self.update_id = None

        # Create repeated timer to check for new file
        if self.bot_log_enabled:
            new_file_timer = RepeatedTimer(self.check_file_ts,
                                           self.new_file_timer_callback)
            new_file_timer.start()

        line_count = 0
        info_ready = False
        info_msg = ""
        loss_list = []
        # Loop checking for user message and new useful log line
        while True:
            try:
                if self.log_file_found and self.bot_log_enabled:
                    logging.info("Check log")
                    message = ""
                    figure_name = ""
                    while len(message) < 100 * 40:
                        where = self.log_file.tell()
                        line = self.log_file.readline()
                        if line:
                            if line_count < 35:
                                #TODO: check if line == "Done!" for support network with different layers number
                                info_msg += line
                                line_count += 1
                                if line_count > 34:
                                    try:
                                        self.bot.sendMessage(
                                            self.chat_id, info_msg)
                                    except:
                                        logging.info(
                                            "Failed to send INFO message!")
                            else:
                                # Check if the row match the ITER lane
                                data_match = re.findall(self.line_regex, line)

                                if data_match:
                                    # Lane report ITER result
                                    data_match = data_match[0]
                                    iter_n = int(data_match[0])
                                    loss_v = float(data_match[1])
                                    loss_list.append(loss_v)
                                    logging.info("ITERATION NUMBER: " +
                                                 str(iter_n))

                                    if iter_n == 1 or (
                                            iter_n % self.log_evry_iter) == 0:
                                        loss_np = np.asarray(loss_list,
                                                             dtype=np.float32)

                                        # Create training loss graph
                                        figure_name = self.bkup_folder + "/iter" + data_match[
                                            0] + ".png"
                                        plt.clf()
                                        plt.plot(loss_np, 'o-')
                                        plt.title('Iteration: ' +
                                                  data_match[0])
                                        plt.ylabel('Loss')
                                        plt.xlabel('Iteration')
                                        #plt.show()
                                        plt.savefig(figure_name,
                                                    bbox_inches='tight')
                                        message += "|----> ITER " + data_match[
                                            0] + "\n"
                                        message += "|  |--> loss " + data_match[
                                            1] + "\n"
                                        message += "|  |--> avg  " + data_match[
                                            2] + "\n"
                                        message += "|  |--> sec  " + data_match[
                                            4] + "\n"
                                        message += "|  '--> img  " + data_match[
                                            5] + "\n"

                        else:
                            self.log_file.seek(where)
                            if len(message) > 0:
                                logging.info("Sending ITERATION message!")
                                try:
                                    self.bot.sendMessage(self.chat_id, message)
                                except:
                                    logging.info(
                                        "Iteratino message skipped can not send!"
                                    )
                            break

                    time.sleep(1)
                    logging.info("check file in backup folder")
                    try:
                        self.echo()
                    except NetworkError:
                        logging.info("NETWORK ERROR")
                        sleep(1)
                    except Unauthorized:
                        # The user has removed or blocked the bot.
                        logging.info("UNAUTHORIZED")
                        update_id += 1
            except KeyboardInterrupt:
                # TODO: maybe add a big could be needed to ensure all file are loaded
                logging.info("ctrl C caught terminating")
                break
        new_file_timer.stop()
        self.log_file.close()
Exemplo n.º 30
0
 def start_reception(self):
     self.timer = RepeatedTimer(1, self.receive_signal)