本文整理匯總了Python中repeated_timer.RepeatedTimer.start方法的典型用法代碼示例。如果您正苦於以下問題:Python RepeatedTimer.start方法的具體用法?Python RepeatedTimer.start怎麽用?Python RepeatedTimer.start使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類repeated_timer.RepeatedTimer
的用法示例。
在下文中一共展示了RepeatedTimer.start方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import start [as 別名]
class DashieSampler:
def __init__(self, app, interval):
self._app = app
self._timer = RepeatedTimer(interval, self._sample)
def stop(self):
self._timer.stop()
def start(self):
self._timer.start()
def name(self):
"""
Child class implements this function
"""
return "UnknownSampler"
def sample(self):
"""
Child class implements this function
"""
return {}
def _send_event(self, widget_id, body):
body["id"] = widget_id
body["updatedAt"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S +0000")
formatted_json = "data: %s\n\n" % (json.dumps(body))
self._app.last_events[widget_id] = formatted_json
for event_queue in self._app.events_queue.values():
event_queue.put(formatted_json)
def _sample(self):
data = self.sample()
if data:
self._send_event(self.name(), data)
示例2: __init__
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import start [as 別名]
class HandCockpit:
MIN_VALUE = 0
MAX_VALUE = 1
INITIAL_SET = 0
SCAN_INTERVAL_SEC = 0.1
# 操作対象用インデックス
WAIST = 0 # 左右に回転する部分
BOOM = 1 # 台座から伸びる部分。left servo
ARM = 2 # boomからcrawまでの部分。right servo
CRAW = 3 # バケットに相當する部分。先端の爪
# 物理的な可動範囲[min, max] 0〜180の範囲內であること
# サンプルを參考にする
# see: https://www.mearm.com/blogs/news/74739717-mearm-on-the-raspberry-pi-work-in-progress
RANGE = (
(0, 180), # waist
(60, 165), # boom
(40, 180), # arm
(60, 180), # craw
)
# コントローラーの感度係數
SENSITIVITY = (
-50.0, # waist
-50.0, # boom
50.0, # arm
50.0, # craw
)
# 定義済み位置(WAIST, BOOM, ARM, CRAW) 0〜180の範囲
PRESET = (
(90, 112, 90, 60), # initial position
(20, 30, 40, 50), # topキー用
)
def __init__(self, controller, pad):
# initial servo position
self.position = list(HandCockpit.PRESET[HandCockpit.INITIAL_SET])
# controllerはapplyメソッドを持っている必要がある
self.controller = controller
self.pad = pad
self.lastUpdateAt = time.time()
self.isStartedAxisScanThread = False
self.isEnabledDebugPad = True
# 初期位置設定
self._apply()
def update(self, powerList, delay):
for index in self.controller.getIndexes():
self.position[index] += powerList[index] * delay * HandCockpit.SENSITIVITY[index]
if self.position[index] < HandCockpit.RANGE[index][HandCockpit.MIN_VALUE]:
self.position[index] = HandCockpit.RANGE[index][HandCockpit.MIN_VALUE]
elif self.position[index] > HandCockpit.RANGE[index][HandCockpit.MAX_VALUE]:
self.position[index] = HandCockpit.RANGE[index][HandCockpit.MAX_VALUE]
self._apply()
def usePreset(self, number):
self.position = list(HandCockpit.PRESET[number])
self._apply()
def _apply(self):
self.controller.apply(self.position)
def startAxisScanThread(self):
pygame.event.set_blocked(pygame.JOYAXISMOTION)
self.axisScanThread = RepeatedTimer(HandCockpit.SCAN_INTERVAL_SEC, self.scanAxis)
self.axisScanThread.start()
self.isStartedAxisScanThread = True
def stopAxisScanThread(self):
if True == self.isStartedAxisScanThread:
self.isStartedAxisScanThread = False
self.axisScanThread.cancel()
pygame.event.set_blocked(None)
def scanAxis(self):
now = time.time()
delay = now - self.lastUpdateAt
self.lastUpdateAt = now
x1 = self.pad.getAnalog(PS3PadPygame.L3_AX)
y1 = self.pad.getAnalog(PS3PadPygame.L3_AY)
x2 = self.pad.getAnalog(PS3PadPygame.R3_AX)
y2 = self.pad.getAnalog(PS3PadPygame.R3_AY)
if self.isEnabledDebugPad:
log = ('delay: %.3f, x1: %.3f, y1: %.3f, x2: %.3f, y2: %.3f' % (delay, x1, y1, x2, y2))
print log
# バックホーの操作レバー割當はJIS方式だと以下のようになっている
# (左レバー) (右レバー)
# アーム伸ばし ブーム下げ
# 左旋回 ○ 右旋回 バケット掘削 ○ バケット開放
# アーム曲げ ブーム上げ
#.........這裏部分代碼省略.........
示例3: BettingDisplay
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import start [as 別名]
class BettingDisplay():
def __init__(self, parent, meeting):
self.parent = parent
self.display_type = 'odds'
self.date = datetime.date.today().strftime("%Y-%m-%d") #Currently will need to be restarted each day
self.meeting = meeting #PLACEHOLDER
self.schedule = Schedule(self.date, self.meeting)
self.races = self.schedule.meetings[0].races
self.next_race = None
self.set_next_race()
self.odds_var = StringVar()
self.title_var = StringVar()
self.dets_var = StringVar()
self.build_display()
self.start_timer()
print("STARTED SUCCESSFULLY")
def set_next_race(self):
next_race = None
found = False
for race in self.races:
cur_time = int(datetime.datetime.now().strftime("%H%M%S"))
race_time = int(re.sub('[:]', '', race.time))
if race_time > cur_time and not found:
next_race = race
found = True
if next_race is not self.next_race:
self.next_race = next_race
def start_timer(self):
self.threading_timer = RepeatedTimer(3, self.refresh)
self.threading_timer.start()
def refresh(self):
if self.display_type == 'odds':
self.set_next_race()
self.next_race.load_odds()
#---TEMP---#
horse_nums = ['']*20
for i in range(min(20, len(self.next_race.entries))):
horse_nums[i] = str(self.next_race.entries[i].number)
horse_names = ['']*20
for i in range(min(20, len(self.next_race.entries))):
horse_names[i] = str(self.next_race.entries[i].name)
win_odds = ['']*20
for i in range(min(20, len(self.next_race.entries))):
win_odds[i] = str(self.next_race.entries[i].odds_win)
lst = horse_nums + horse_names + win_odds
odds_str = TEST_TEMPLATE.format(lst)
title_str = TITLE_TEMPLATE.format(name=self.next_race.name)
dets_str = TIME_TEMPLATE.format(time=self.next_race.time, venue=self.next_race.meeting.venue, meet_no=self.next_race.meeting.number, country=self.next_race.meeting.country)
self.title_var.set(title_str)
self.dets_var.set(dets_str)
self.odds_var.set(odds_str)
#---TEMP END---#
elif self.display_type == 'test':
self.title_var.set('test')
self.dets_var.set('')
self.odds_var.set('')
def build_display(self):
#----TEMP----
self.cur_race_name = StringVar()
self.cur_race_time = StringVar()
self.title_text = Label(self.parent, fg="white", bg="black", font=("Courier", 40, "bold"), textvariable=self.title_var)
self.title_text.place(relx = 0.5, rely = 0, anchor=N, height = 80, width=1100)
self.dets_text = Label(self.parent, textvariable=self.dets_var, fg="white", bg="black", font=("Courier", 20, "bold"))
self.dets_text.place(relx = 0.5, y = 80, anchor=N, height = 30, width=1100)
self.odds_text = Label(self.parent, textvariable=self.odds_var, fg="white", bg="black", font=("Courier", 20, "bold"))
self.odds_text.place(relx = 0.5, y = 110, anchor=N, width=1100, height = 600)
self.quitbutton = Button(self.parent, text='quit', command=self.quitclick)
self.quitbutton.place(relx = 0.5, rely = 1, anchor=S)
#---TEMP END ---#
def quitclick(self):
self.threading_timer.stop()
self.parent.destroy()
示例4: OpenSlides
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import start [as 別名]
class OpenSlides(tk.Tk):
cmd_runner = None
server_running = False
gui_settings_path = None
gui_initialized = False
backupdb_enabled = False
backupdb_destination = ""
backupdb_interval = 15
backupdb_interval_unit = "minutes"
last_backup = None
backup_timer = None
_host = "0.0.0.0"
_port = "8000"
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.title(self, 'OpenSlides')
tk.Tk.resizable(self, width=False, height=False)
self.protocol('WM_DELETE_WINDOW', self.on_close_app)
self.root = tk.Frame(self, bg=self.cget('bg'))
self.root.pack(side="top", fill="both", expand = True)
self.btn_settings = None
self.btn_db_backup = None
self.btn_sync_db = None
self.btn_reset_admin = None
self.chb_auto_svr = None
self.btn_server = None
self.backup_timer = RepeatedTimer(self.on_backup_timer)
self.lbl_host = None
self.lbl_port = None
if not self.initialize_gui():
self.quit()
self.createMenuBar()
self.createMainframe()
def initialize_gui(self):
# Set path for gui settings to default user data according to the
# OpenSlides type. This does not depend on any argument the user might
# type in.
openslides_type = detect_openslides_type()
try:
default_user_data_path = get_default_user_data_path(openslides_type)
except PortableDirNotWritable:
messagebox.showerror(
_("Error: Portable directory not writable"),
_("The portable directory is not writable. Please copy the "
"openslides portable to a writeable location and start it "
"again from there")
)
return False
self.gui_settings_path = os.path.join(
default_user_data_path, 'openslides', 'gui_settings.json')
self.load_gui_settings()
self.apply_backup_settings()
return True
def load_gui_settings(self):
if self.gui_settings_path is None:
return
try:
f = open(self.gui_settings_path, "r", encoding="utf-8")
except IOError as e:
if e.errno == errno.ENOENT:
return
raise
with f:
settings = json.load(f)
def setattr_unless_none(attr, value):
if not value is None:
setattr(self, attr, value)
backup_settings = settings.get("database_backup", {})
setattr_unless_none("backupdb_enabled", backup_settings.get("enabled"))
setattr_unless_none(
"backupdb_destination", backup_settings.get("destination"))
setattr_unless_none(
"backupdb_interval", backup_settings.get("interval"))
setattr_unless_none(
"backupdb_interval_unit", backup_settings.get("interval_unit"))
last_backup = backup_settings.get("last_backup")
if not last_backup is None:
self.last_backup = datetime.datetime.strptime(
#.........這裏部分代碼省略.........
示例5: main
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import start [as 別名]
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()))
#.........這裏部分代碼省略.........
示例6: __init__
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import start [as 別名]
class RPiServoblasterController:
# ServoBlasterへの反映間隔
COMMIT_INTERVAL_SEC = 0.1
# ./servodを実行した時のピン番號を使う(GPIOの番號でも、物理位置番號でもない)
WAIST_SERVO_PIN = 7
BOOM_SERVO_PIN = 6
ARM_SERVO_PIN = 5
CRAW_SERVO_PIN = 4
# 操作対象とピン番號のマップ
PIN_MAP = {
0: WAIST_SERVO_PIN,
1: BOOM_SERVO_PIN,
2: ARM_SERVO_PIN,
3: CRAW_SERVO_PIN,
}
def __init__(self):
# GPIO番號でピンを指定
# ServoBlasterの起動(rootで実行する必要あり)
# 50%指定時の中間位置を--maxで調整する。--max=200がちょうどよかった
os.system('sudo /home/pi/PiBits/ServoBlaster/user/servod --idle-timeout=2000 --max=200')
self.servos = []
for index in RPiServoblasterController.PIN_MAP.iterkeys():
pin = RPiServoblasterController.PIN_MAP[index]
# サーボを作る
self.servos.append(SG90Servoblaster(pin, self.getPartName(index)))
# self.positionの內容を定期的にcommit()を使ってservoblasterで反映する
self.positions = []
self.timer = RepeatedTimer(RPiServoblasterController.COMMIT_INTERVAL_SEC, self.commit)
self.timer.start()
# 直接同期的にservoblasterを呼ぶのではなく、
# 一度內容をインスタンス変數に格納しておき、定期的にservoblasterで反映させる
def apply(self, positions):
self.positions = positions
def shutdown(self):
# if self.timer is not None:
self.timer.cancel()
def getIndexes(self):
return RPiServoblasterController.PIN_MAP.keys()
def switchDebugPosition(self):
for index in RPiServoblasterController.PIN_MAP.iterkeys():
self.servos[index].switchDebugPosition()
# マルチスレッド下でタイマーから実行される
def commit(self):
if 0 == len(self.positions):
return
for index in RPiServoblasterController.PIN_MAP.iterkeys():
degree = self.positions[index]
self.servos[index].rotateTo(degree)
def getPartName(self, index):
if(0 == index):
return 'WAIST'
elif(1 == index):
return 'BOOM'
elif(2 == index):
return 'ARM'
elif(3 == index):
return 'CRAW'
else:
return 'unknown'
示例7: __init__
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import start [as 別名]
class RPiPCA9685Controller:
# 反映間隔
COMMIT_INTERVAL_SEC = 0.1
# ./servodを実行した時のピン番號を使う(GPIOの番號でも、物理位置番號でもない)
WAIST_SERVO_PIN = 0
BOOM_SERVO_PIN = 1
ARM_SERVO_PIN = 2
CRAW_SERVO_PIN = 3
# 操作対象とピン番號のマップ
PIN_MAP = {
0: WAIST_SERVO_PIN,
1: BOOM_SERVO_PIN,
2: ARM_SERVO_PIN,
3: CRAW_SERVO_PIN,
}
def __init__(self, address=0x40):
# I2C経由でのコントロール用ライブラリ
# https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git
self.pwm = Adafruit_PCA9685.PCA9685(address, busnum=1)
self.pwm.set_pwm_freq(SG90PCA9685.PWM_FREQ)
self.servos = []
for index in RPiPCA9685Controller.PIN_MAP.iterkeys():
pin = RPiPCA9685Controller.PIN_MAP[index]
# サーボを作る
self.servos.append(SG90PCA9685(pin, self.getPartName(index), self.pwm))
# self.positionの內容を定期的にcommit()を使ってservoblasterで反映する
self.positions = []
self.timer = RepeatedTimer(RPiPCA9685Controller.COMMIT_INTERVAL_SEC, self.commit)
self.timer.start()
# 直接同期的にservoblasterを呼ぶのではなく、
# 一度內容をインスタンス変數に格納しておき、定期的にservoblasterで反映させる
def apply(self, positions):
self.positions = positions
def shutdown(self):
# if self.timer is not None:
self.timer.cancel()
def getIndexes(self):
return RPiPCA9685Controller.PIN_MAP.keys()
def switchDebugPosition(self):
for index in RPiPCA9685Controller.PIN_MAP.iterkeys():
self.servos[index].switchDebugPosition()
# マルチスレッド下でタイマーから実行される
def commit(self):
if 0 == len(self.positions):
return
for index in RPiPCA9685Controller.PIN_MAP.iterkeys():
degree = self.positions[index]
self.servos[index].rotateTo(degree)
def getPartName(self, index):
if(0 == index):
return 'WAIST'
elif(1 == index):
return 'BOOM'
elif(2 == index):
return 'ARM'
elif(3 == index):
return 'CRAW'
else:
return 'unknown'