def handle_key(self, key_code): if key_code in self.key_handlers: return self.key_handlers[key_code]() or True # Retutn something if handler exists elif 'any' in self.key_handlers: return self.key_handlers['any']() or True # Retutn something if handler exists else: curses.flushinp() # Flush all input buffers to empty all unexpected input
def poll_event(self): """ Waits for an event to happen and returns a string related to the event. If the event is a normal (letter) key press, the letter is returned (case sensitive) :return: Event type """ # Flush all inputs before this one that were done since last poll curses.flushinp() ch = self.screen.getch() if ch == 27: return EVENT_ESC elif ch == -1 or ch == curses.KEY_RESIZE: return EVENT_RESIZE elif ch == 10 or ch == curses.KEY_ENTER: return EVENT_ENTER elif ch == 127 or ch == curses.KEY_BACKSPACE: return EVENT_BACKSPACE elif ch == curses.KEY_UP: return EVENT_UP elif ch == curses.KEY_DOWN: return EVENT_DOWN elif ch == curses.KEY_LEFT: return EVENT_LEFT elif ch == curses.KEY_RIGHT: return EVENT_RIGHT elif ch == 3: return EVENT_CTRL_C elif 0 <= ch < 256: return chr(ch) else: return EVENT_UNHANDLED
def main(): signal.signal(signal.SIGINT, signal_handler) locale.setlocale(locale.LC_ALL, "") # Use system's default encoding stdscr = curses.initscr() # Initialize curses.cbreak() # Enter cbreak mode curses.noecho() # Don't echo any characters curses.curs_set(0) # Make cursor invisible stdscr.nodelay(1) # Make getch() non-blocking stdscr.keypad(1) # Interpret escape sequences snk = Snake(stdscr.getmaxyx()) # Initialize our Snake!! ch = None while ch != curses.ascii.ESC: stdscr.clear() direction = None if ch == curses.KEY_UP: direction = Direction.north elif ch == curses.KEY_DOWN: direction = Direction.south elif ch == curses.KEY_LEFT: direction = Direction.west elif ch == curses.KEY_RIGHT: direction = Direction.east snk.move(stdscr, direction) snk.draw(stdscr) stdscr.refresh() curses.napms(200) ch = stdscr.getch() curses.flushinp() curses.endwin()
def mainloop(): ch = window.getch() curses.flushinp() if ch > 0: chatbox.add_message(chr(ch)) cl.sendMessage(chr(ch)) display_win.refresh()
def connect_to_live(scr, args): conn = None while conn == None: scr.clear() center_addstr(scr, 0, 'Connecting to Ableton Live...', curses.color_pair(colors.connecting)) scr.refresh() try: conn = rpyc.connect(args.host, args.port) except IOError: center_addstr(scr, 0, 'Connection to Ableton Live failed', curses.color_pair(colors.error)) center_addstr(scr, 1, 'Press any key to retry') scr.refresh() curses.flushinp() scr.getch() scr.clear() live = conn.root.Live.Application.get_application() center_addstr(scr, 0, 'Connected to to Ableton Live %s.%s.%s' % (live.get_major_version(), live.get_minor_version(), live.get_bugfix_version()), curses.color_pair(colors.success)) return conn
def run(self): rfds = [sys.stdin, self.player.notifier] while True: try: rl, wl, el = select(rfds, [], [], self.timeout) if sys.stdin in rl: self.keypress(self.windows.active.getkey()) curses.flushinp() if self.player.notifier in rl: self.apply_state() # set current state self.player.notifier.get() # clear notifier queue if self.playing: self.handle("playing") except Exception as err: try: self.keypress(self.windows.root.getkey()) except: continue finally: log.error(err) type, value, trace = sys.exc_info() log.error("".join(traceback.format_exception(type, value, trace))) continue
def cleaning(window, warwin, flag): '''Simple local function for readability and not repeating myself.''' warwin.refresh() warwin.getch() curses.flushinp() warwin.destroy() del warwin curses.curs_set(1) if flag: curses.noecho() else: curses.echo() window.touchwin() # This is for registration form, # if passwords don't match, then clean both fields if y == 13: # 13 is y position for password window.move(15, x) # 15 is y position for confirm password window.clrtoeol() window.move(y, x) window.clrtoeol() window.box() window.refresh()
def handle_input(self): key = self.win.getch() if key is 27 or key >= 128 and key < 256: # Handle special keys like ALT+X or unicode here: keys = [key] previous_load_mode = self.load_mode self.set_load_mode(True) for n in range(4): getkey = self.win.getch() if getkey is not -1: keys.append(getkey) if len(keys) == 1: keys.append(-1) if self.settings.xterm_alt_key: if len(keys) == 2 and keys[1] in range(127, 256): keys = [27, keys[1] - 128] self.handle_keys(*keys) self.set_load_mode(previous_load_mode) if self.settings.flushinput and not self.console.visible: curses.flushinp() else: # Handle simple key presses, CTRL+X, etc here: if key > 0: if self.settings.flushinput and not self.console.visible: curses.flushinp() if key == curses.KEY_MOUSE: self.handle_mouse() elif key == curses.KEY_RESIZE: self.update_size() else: if not self.fm.input_is_blocked(): self.handle_key(key)
def __subreddit_menu(self): """ Switch to buffered input and prompt for subreddit name :return: void """ #flush input buffer flushinp() str_input_subreddit = "subreddit:" self.stdscr.addstr( self.__max_y - self.__MARGIN_Y, self.__FLUSH, str_input_subreddit ) # disable cinput mode and enter buffered input mode and echo nocbreak() echo() input_buffer = self.stdscr.getstr() if input_buffer == "back": # enable cinput mode and disable echo cbreak() noecho() else: self.__posts_menu(input_buffer)
def run(self): print('display starting...') sleep(3) self.screen = curses.initscr() # map arrow keys to special v1alues # turn off input echoing curses.noecho() # respond to keys immediately (don't wait for enter) curses.cbreak() curses.curs_set(0) # map arrow keys to special v1alues self.screen.keypad(True) self.screen.timeout(100) self.screen.clear() while self.data.cycling: curses.flushinp() self.screen.clear() self.screen.addstr(0, 0, '1-4:mode ARROWS:move q:quit') self.screen.addstr(1, 0, 'a-z:speed h:horn y.u.i.o.p:speach') self.screen.addstr(5, 0, 'mode: ' + str(self.data.mode)) self.screen.addstr(6, 0, 'move: ' + str(self.data.move)) self.screen.addstr(7, 0, 'sound: ' + str(self.data.sound)) self.screen.addstr(8, 0, 'dist: ' + str(self.data.distance)) self.screen.addstr(8, 30, 'speed: ' + str(self.data.speed)) #getch returns -1 if timeout self.data.input = self.screen.getch()
def game_start(stdscr): """ Houses the game-loop. draws sleeps , calls collide to check """ global birdy curses.flash()#flash the screen curses.curs_set(0)#set the cursor invisible stdscr.nodelay(1) while True: stdscr.erase() draw_border(stdscr,score) draw_bird(stdscr) draw_pipes(stdscr) #if collide()==True: # game_over(stdscr,score) # pass up=stdscr.getch() if up==ord(' '): if birdy<=10: birdy=10 pass else: birdy-=1 pass pass else: y,x=stdscr.getmaxyx() if birdy>=y-10: birdy=y-10 pass else: birdy+=1 pass curses.flushinp() curses.napms(20)
def get_input(self): while 1: #loop until getch sends exit() screen = self.screen c = screen.getch() cursor_y, cursor_x = self.current_cursor if c == ord('q') or c == 27: #exit curses exit() elif c in [curses.KEY_LEFT, ord('a'), ord('h')]: #cursor left self.move_cursor(screen, (cursor_y, cursor_x - 1)) elif c in [curses.KEY_RIGHT, ord('d'), ord('l')]: #cursor right self.move_cursor(screen, (cursor_y, cursor_x + 1)) elif c in [curses.KEY_UP, ord('w'), ord('k')]: #cursor up self.move_cursor(screen, (cursor_y - 1, cursor_x)) elif c in [curses.KEY_DOWN, ord('s'), ord('j')]: #cursor down self.move_cursor(screen, (cursor_y + 1, cursor_x)) elif c == 10 or c == 32: #paint cell self.draw_cell((cursor_y, cursor_x)) elif c == ord('i'): #display info self.display_help(screen) elif c == ord('g'): #step self.step() curses.flushinp() #cancel buffer: no lag on holding down key elif c == ord('r'): #run self.run(screen) elif c == ord('-'): #tick delay up (+) self.increment_wait(Decimal('-0.01')) elif c == ord('='): #tick delay down (-) self.increment_wait(Decimal('0.01')) elif c == ord('f'): #write pattern to file self.save_dialog(screen) elif c == ord('e'): #clear board self.clear() self.refresh_border()
def run(screen=None): screen = curses_init() widget = Curses(screen) # {{{ Main event loop while True: widget.redraw() sleep(0.1) event = screen.getch() curses.flushinp() if event == curses.ERR: continue elif event == ord("q"): break elif event == ord("r"): widget.invalidate() elif event == curses.KEY_RESIZE: widget.invalidate() continue # }}} curses_fini(curses, screen) return 0
def check_for_death(self): if self.player.isDead == True: self.port.write("$$$ALL,OFF\r") self.port.write("ded, score: " + str(self.score)) curses.flushinp() curses.endwin() sys.exit(0)
def select(self): ''' Make the user perform the selection, return selected index ''' maxLen = max([len(i) for i in self.elems] + [self.minWidth]) height = max(len(self.elems), self.minHeight) self.draw(maxLen+2, height+2) self.win.keypad(1) self.curidx = 0 self.drawList() curses.flushinp() while True: key = self.win.getch() if key in (curses.KEY_ENTER, ord('\n')): break elif key == curses.KEY_UP: if self.curidx > 0: self.curidx -= 1 self.drawList() elif key == curses.KEY_DOWN: if self.curidx < len(self.elems) - 1: self.curidx += 1 self.drawList() self.undraw() return self.curidx
def getstr(self): self.win.move(self.y, self.x) self.win.clrtoeol() self.win.refresh() self.startend = (0, 0) curses.flushinp() curses.noecho() curses.curs_set(1) s = unicode() i = 0 while True: (y, x) = self.win.getyx() c = self.win.getch() if c == 0x0a: break # \n elif c in (curses.KEY_BACKSPACE, 0x08): if i <= 0: continue s = s[:i - 1] + s[i:] i -= 1 self.rewrite_text(s, i) elif c == curses.KEY_DC: s = s[:i] + s[i + 1:] self.rewrite_text(s, i) elif c == curses.KEY_LEFT: if i <= 0: continue i -= 1 self.rewrite_text(s, i) elif c == curses.KEY_RIGHT: if i >= len(s): continue i += 1 self.rewrite_text(s, i) elif curses.KEY_MIN <= c <= curses.KEY_MAX: pass else: # UTF-8 input if c & 0x80: f = c << 1 while f & 0x80: f <<= 1 c <<= 8 c += (self.win.getch() & 0xff) c = ctools.utf2ucs(c) if ctools.isascii(c) and not ctools.isprintable(c): continue s = u"%s%s%s" % (s[:i], c, s[i:]) i += 1 self.rewrite_text(s, i) curses.curs_set(0) return s
def Go(self) : self.init() self.DoSplashScreen() curses.flushinp() self.win.getch() self.DoMainLoop() curses.flushinp() self.Stop()
def curses_set(): global scrn scrn = curses.initscr() curses.noecho() curses.cbreak() curses.flushinp() scrn.keypad(1) scrn.nodelay(1)
def h_display_help(self, input): if self.help == None: return if self.name: help_name="%s Help" %(self.name) else: help_name=None curses.flushinp() select.ViewText(self.help, name=help_name) self.display() return True
def loop(): ch = window.getch() curses.flushinp() if ch > 0: control.accept(ch) zone.tick() statbox.tick() fps.inc() display_win.refresh()
def h_display_help(self, input): if self.help == None: return if self.name: help_name="%s Help" %(self.name) else: help_name=None curses.flushinp() util_viewhelp.view_help(self.help, title=help_name, autowrap=self.WRAP_HELP) #select.ViewText(self.help, name=help_name) self.display() return True
def show_splash(self): screen_size = self.stdscr.getmaxyx() splash_window = curses.newwin(10, 30, screen_size[0]/2 - 5, screen_size[1]/2 - 15) splash_window.box() splash_window.addstr(2, 10, "Welcome to") splash_window.addstr(4, 8, "T E X T R I S") splash_window.addstr(6, 4, "Press any key to play") splash_window.refresh() a=self.input_window.getch() curses.flushinp()
def main_loop(self): deltaTimer = time.time() if not self.player.isJumpingNextFrame: self.player.isJumpingNextFrame = self.handle_input() if deltaTimer - self.timer > C_TICKSPEED: self.timer = time.time() self.update() self.draw() curses.flushinp()
def get_input(): global _screen, _keymap if _screen: c = _screen.getch() curses.flushinp() if c == 27: return "escape" elif c == "\b": return "backspace" #for mac elif c == 10 or c == 13: return "enter" elif c > 0 and c < 256: return "%c"%c elif c in _keymap: return _keymap[c] return None
def __init__(self, window, buff): global STATUSLINE_IDX, g_trace_dir, g_my_codec # #self.txt = SBStrList(['Edit this string\n', 'This is line2\n'])# single line of text self.txt = SBStrList(buff) oldmouse = curses.mousemask(curses.BUTTON1_CLICKED) (max_y, max_x) = window.getmaxyx() self.framewin = window.subwin(max_y - MENU_LINES - 1 , max_x, MENU_LINES + 1, 0) self.scrn = window.subwin(max_y - MENU_LINES - 3, max_x - 2, MENU_LINES + 2, 1) self.line_ptr = 0 # THIS SHOULD BE IN txt.l self.scrn.keypad(1) curses.flushinp() self.framewin.border() self.framewin.refresh() self.scrn.refresh() # pointasdf has a crazy name so that end-users don't # access it by mistake. Users should use the porcelain # commands. self.pointasdf = 0 # This is the main point. Don't change this directly # the main point is now in self.txt.get_point and set_point self.width = self.scrn.getmaxyx()[1] self.height = self.scrn.getmaxyx()[0] - YFUDGE STATUSLINE_IDX = self.height - 1 + YFUDGE self.menuscrn = window.derwin(MENU_LINES, max_x, 0, 0) self.menuscrn.addstr(0,0, 'This program can be used to test the ' + 'SBString object. It is a one-line text editor.') self.menuscrn.refresh() # self.statusscrn = window.subwin(1, max_x, max_y - 1, 0) # setup required for curses to use unicode locale.setlocale(locale.LC_ALL, '') # use 'code' with str.encode() for curses display? g_my_codec = locale.getpreferredencoding() # # Initialize the display buffer that will hold # text according to lrecl # cursor location, based on physical window, not logical window self.winrow_idx = 0 #self.winmintxtrow_idx self.wincol_idx = 0 #self.winmintxtcol_idx # #self.displayscreen(self.startbuffrow_idx) #w_vp = self.get_wintxt_vp() (max_y, max_x) = self.scrn.getmaxyx() max_y -= YFUDGE self.scrn.clear() self.winrow_idx = 0 self.wincol_idx = 0 self.scrn.move(TOPROW , self.wincol_idx) self.display_line() ##self.vbuff.display_screen(0, self.scrn) if g_trace_dir != '': self.trace_init()
def main(): wrapper = find_wrapper() selected = 0 scr, wrapper_list_win = init_scr() wrapper_list_start = 0 while True: draw_info(scr, wrapper) draw_wrapper(wrapper_list_win, wrapper, wrapper_list_start, selected) curses.flushinp() c = scr.getch() if c == curses.ascii.ESC: break elif c == curses.ascii.SP or c == curses.ascii.NL or c == curses.ascii.TAB or c == curses.ascii.BS: wrapper[selected].compress = not wrapper[selected].compress elif c == curses.KEY_DOWN: if selected < len(wrapper) - 1: selected += 1 elif c == curses.KEY_UP: if selected > 0: selected -= 1 elif c == ord('n'): if wrapper_list_start <= len(wrapper): wrapper_list_start += 1 elif c == ord('p'): if wrapper_list_start > 1: wrapper_list_start -= 1 elif c == ord('d'): to_compress = filter(lambda x: x.compress, wrapper) to_compress_count = len(to_compress) counter = 0 scr.addstr(1, 25, "deploying...") scr.refresh() for w in to_compress: w.start_compress() counter += 1 scr.addstr(1, 25, "deployed: %d/%d" % (counter, to_compress_count)) scr.refresh() elif c == ord('r'): wrapper[selected].remove() curses.endwin() return 0
def main(w): curses.halfdelay(10) frontend.connect() y,x = w.getmaxyx() mem = w.derwin(4,20,9,0) query_mem(mem) load = w.derwin(5,20,5,0) query_load(load) conn = w.derwin(4,20,2,0) align(2,conn,1,frontend.host) align(2,conn,2,"%s:%d" % frontend.socket.getpeername()) conn.border(curses.ACS_VLINE, curses.ACS_VLINE, curses.ACS_HLINE, curses.ACS_HLINE, curses.ACS_LTEE, curses.ACS_RTEE, curses.ACS_LTEE, curses.ACS_RTEE) time = w.derwin(3,20,0,0) query_time(time) loc = w.derwin(13,x-20,0,19) loc.timeout(1) while True: a = None s = None try: query_time(time) query_load(load) query_loc(loc) query_mem(mem) align(1,w,0,' MythFrontend Remote Socket Interface ') curses.doupdate() a = w.getch() curses.flushinp() frontend.key[a] except KeyboardInterrupt: break except EOFError: break except MythError: print "Remote side closed connection..." break except ValueError: # assume an frontend stalled, opening a file pass except: raise
def interactive_screen(self, win): try: import curses except ImportError: print("Could not import curses. Please install: http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses") exit(1) self.curses_screen = win curses.noecho() curses.cbreak() curses.curs_set(False) self.curses_screen.keypad(1) self.curses_screen.nodelay(1) self.curses_screen.timeout(1000) counter = 1 # draw screen self.curses_screen.box() self.curses_screen.addstr(0, 1, " {} ".format(Simr.program_description)) self.curses_screen.addstr(4, 1, "Press up, down, or q") y, x = self.curses_screen.getmaxyx() self.curses_screen.hline(2, 1, curses.ACS_HLINE, x - 2) # flush any input curses.flushinp() while 1: self.curses_screen.addstr(1, 1, "Max workers: {}".format(self.max_workers)) self.curses_screen.addstr(3, 1, "Counter: {}".format(counter)) self.curses_screen.refresh() c = self.curses_screen.getch() if c == ord('q'): self.curses_screen.clear() return 0 elif c == curses.KEY_UP: self.max_workers += 1 if self.max_workers > self.processing_units: self.max_workers = self.processing_units elif c == curses.KEY_DOWN: self.max_workers -= 1 if self.max_workers < 0: self.max_workers = 0 pass counter += 1
def help(self): """Display help text popup window. """ help_txt = (" Save and exit : F2 or Ctrl-x\n" " (Enter if in single-line entry mode)\n" " Exit (no save) : F3, Ctrl-c or ESC\n" " Cursor movement : Arrow keys/Ctrl-f/b/n/p\n" " Beginning of line : Home/Ctrl-a\n" " End of line : End/Ctrl-e\n" " Page Up/Page Down : PgUp/PgDn\n" " Backspace/Delete : Backspace/Ctrl-h\n" " Delete current char : Del/Ctrl-d\n" " Insert line at cursor : Enter\n" " Paste block of text : Ctrl-v\n" " Delete to end of line : Ctrl-k\n" " Delete to BOL : Ctrl-u\n") help_txt_no = (" Quit : q,F2,F3,ESC,Ctrl-c or Ctrl-x\n" " Cursor movement : Arrow keys/j-k/Ctrl-n/p\n" " Page Up/Page Down : J/K/PgUp/PgDn/Ctrl-b/n\n") if self.edit is False: help_txt = help_txt_no txt = help_txt.splitlines() try: curses.curs_set(0) except _curses.error: pass lines = len(txt) + 2 cols = max([len(i) for i in txt]) + 2 # Only print help text if the window is big enough try: popup = curses.newwin(lines, cols, self.win_location_y, self.win_location_x) addstr(popup, 1, 0, "\n".join(txt)) popup.box() except _curses.error: pass else: while not popup.getch(): pass finally: # Turn back on the cursor if self.pw_mode is False and self.edit is True: curses.curs_set(1) # flushinp Needed to prevent spurious F1 characters being written # to line curses.flushinp() self.box_init()
def manual_control(self): """Navigates the robot to the provided point.""" condition = True while condition and not rospy.is_shutdown(): vel = Twist() vel.linear.y = 0.0 vel.linear.x = 0.0 vel.angular.z = 0.0 try: key = stdscr.getkey() #rospy.loginfo(key) curses.flushinp() if key == "KEY_LEFT" or key == "a": vel.angular.z = self.linear_speed elif key == "KEY_RIGHT" or key == "d": vel.angular.z = -self.linear_speed elif key == "KEY_UP" or key == "w": vel.linear.x = self.linear_speed elif key == "KEY_DOWN" or key == "s": vel.linear.x = -self.linear_speed elif key == "q": vel.linear.x = self.linear_speed vel.angular.z = self.linear_speed elif key == "e": vel.linear.x = self.linear_speed vel.angular.z = -self.linear_speed elif key == "c": vel.linear.x = -self.linear_speed vel.angular.z = self.linear_speed elif key == "z": vel.linear.x = -self.linear_speed vel.angular.z = -self.linear_speed elif key == "=": self.linear_speed += 0.1 elif key == "-": self.linear_speed = max(0.1, self.linear_speed - 0.1) except: pass #self.log("publishing {vel}".format(vel=vel)) self.vel_pub.publish(vel) self.rate.sleep() stop_vel = Twist() stop_vel.angular.z = 0 stop_vel.linear.x = 0 self.vel_pub.publish(stop_vel)
def main(stdscr): i = 0 s = '' for per in xrange(0, 101): stdscr.addstr(0, 0, '下载A: {}%'.format(per) + ' ' + '=' * 1000, curses.color_pair(1) | curses.A_BOLD) stdscr.addstr(1, 0, '下载A: {}%'.format(per), curses.color_pair(2) | curses.A_UNDERLINE) stdscr.addstr(2, 0, '用户输入为: {}'.format(s)) stdscr.move(3, 0) # stdscr.clrtoeol() stdscr.refresh() time.sleep(1) # 输入一个字符 curses.echo() # 打开回显 curses.nocbreak() # 回车确认 stdscr.nodelay(False) # 等待用户输入 # https://www.thinbug.com/q/16809304 curses.flushinp() # 丢弃缓冲区 s = stdscr.getstr() # 获取输入字符串 curses.noecho() # 关闭回显 (y, x) = stdscr.getyx() # 查看y, x stdscr.move(y - 1, 0) # 移动到用户输入的哪一行 stdscr.clrtoeol() # 清除用户输入
def main(stdscr): stdscr.clear() curses.halfdelay(1) curses.curs_set(False) # Turn off the cursor, we won't be needing it. ball = { 'x': 0, 'y': 0, # A dict of attributes about the ball 'dx': 0, 'dy': 0, 'inPlay': 0, 'score': 0 } ball['x'] = dimx // 2 # Ball's initial X position. ball['y'] = dimy // 2 # Starts at screen center. ball['dx'] = random.choice([-1, 1]) # The ball's slope components ball['dy'] = random.choice([-1, 1]) ball['inPlay'] = 1 # Status of game paddle = {'x': 0, 'y': [0, 0, 0]} # a dict of attributes about paddle paddle['x'] = 0 # Starting x and y of the paddle paddle['y'] = [dimy // 2 + i for i in (1, 0, -1)] # lowest to highest, visually stdscr.addch(ball['y'], ball['x'], 'O') updatePaddle(stdscr, paddle) stdscr.refresh() while ball['inPlay']: ball = updateBall(stdscr, ball, paddle) updatePaddle(stdscr, paddle) stdscr.refresh() stdscr.clear() curses.cbreak(True) curses.flushinp() curses.curs_set(True)
def get_input(self, prompt="> "): """Handles user input key by key : - [esc] or "q" to quit the calculator - [enter] to duplicate last stack element or to lauch the command being constituted - [backspace] to remove last stack element - +, -, * and / operands to execute the operation - any other key to constitute the command or a stack element""" result = "" prompt_y = self.STATUS_LINE_Y + 1 + self.STACK_SIZE while True: self.stdscr.addstr(prompt_y, self.STACK_X, " ") self.stdscr.addstr(prompt_y, self.STACK_X, prompt + result) curses.flushinp() key = self.stdscr.getch() if key == 27 or (chr(key) == "q" and result == ""): result = "q" break elif key == 127 or key == 263: if result == "": result = "drop" break else: result = result[:-1] elif key == 13 or key == 10: break elif chr(key) in ["+", "-", "*", "/", "!"]: if result == "": result = chr(key) else: result += " " + chr(key) break else: result += chr(key) self.message_line = "" return result
def drawTitle(stdscr): maxyx = stdscr.getmaxyx() title = [ "'##::::'##::::'###::::'########:'########:", " ###::'###:::'## ##:::..... ##:: ##.....::", " ####'####::'##:. ##:::::: ##::: ##:::::::", " ## ### ##:'##:::. ##:::: ##:::: ######:::", " ##. #: ##: #########::: ##::::: ##...::::", " ##:.:: ##: ##.... ##:: ##:::::: ##:::::::", " ##:::: ##: ##:::: ##: ########: ########:", "..:::::..::..:::::..::........::........::" ] for num, i in enumerate(range(int(0 - len(title) / 2), int(len(title) / 2))): stdscr.move(math.trunc(maxyx[0] / 2 + i), math.trunc(maxyx[1] / 2 - math.trunc(len(title[num]) / 2))) stdscr.addstr(title[num], curses.color_pair(4)) stdscr.refresh() time.sleep(1) curses.flushinp() frame = 0 while (stdscr.getch() == curses.ERR and frame < 60): frame += 1 time.sleep(0.016)
def handle_messages(self, conn): while True: raw = yield from conn.recv() log.debug('< ' + raw) msg = m.Message.parse(raw) if isinstance(msg, m.Line): self.writeline(msg.text, halign=msg.halign) if isinstance(msg, m.Page): self.writepage(msg.text, halign=msg.halign, valign=msg.valign) if isinstance(msg, m.Cls): self.clear() if isinstance(msg, m.ReadLine): curses.flushinp() curses.echo() text = yield from self.getstr() curses.noecho() yield from conn.send(str(m.LineRead(text))) if isinstance(msg, m.ReadKey): curses.flushinp() if msg.echo: curses.echo() key = yield from self.getkey() curses.noecho() yield from conn.send(str(m.KeyRead(key)))
def Ast0RetC(): """ this function waits for a char to be pressed and returns the character if pressed it will exit of the loop as long the char is not prressed C - The character pressed ord code """ C = -1 stdscr.nodelay(1) while stdscr.getch == -1: curses.flushinp() pass curses.halfdelay(1) C = stdscr.getch() curses.flushinp() stdscr.nodelay(0) curses.flushinp() return C
def end_curses(self): curses.nocbreak() self.screen.keypad(False) curses.echo() curses.flushinp() curses.endwin()
def msg_loop(stdscr): global x, y, z, i, l, m msg_head = '' curses.echo() while (1): curses.flushinp() stdscr.clear() msg = '\n'.join(initial_msg) + '\n\n' stdscr.addstr(msg) x = int(stdscr.getstr()) if 0 < x < num_max: # curses.flushinp() # stdscr.clear() # msg = '** ' + initial_msg[x] + '\n\n' # msg += 'このステップから後のいくつのステップを実行しますか?\n' # msg += '0: cancel, 1~: number of steps\n' # stdscr.addstr(msg) # y = int(stdscr.getstr()) # if y > 0: curses.flushinp() stdscr.clear() msg = '** ' + initial_msg[x] + '\n\n' msg = json.dumps(model_dirs, indent=2) + '\n' msg += '以下のファイルが上書きされる可能性があります。実行しますか? [ y / n ]\n' for path in model_dirs.values(): if os.path.exists(path): msg += path + '\n' stdscr.addstr(msg) z = stdscr.getstr() if z == '' or z == 'y': break curses.flushinp() stdscr.clear() else: curses.flushinp() stdscr.clear() msg = ' ** 注 ** ' + str(num_max) + 'までの値を入力して下さい。\n' stdscr.addstr(msg) curses.flushinp() stdscr.clear() if x == 1: while True: msg = '** ' + initial_msg[x] + '\n\n' msg += '以下を選択して下さい。\n' msg += '1: さいしょからはじめる、2: つづきからはじめる\n' stdscr.addstr(msg) i = int(stdscr.getstr()) curses.flushinp() stdscr.clear() if i <= 2: break else: msg = ' ** 注 ** 1 ~ 2 までの値を入力して下さい。\n' stdscr.addstr(msg) if x == 3: while True: msg = '** ' + initial_msg[x] + '\n\n' msg += '\n'.join(labeltype_msg) + '\n' stdscr.addstr(msg) l = int(stdscr.getstr()) stdscr.clear() msg = '** ' + initial_msg[x] + '\n' msg += '** ' + labeltype_msg[l] + '\n\n' msg += '以下から予測モデルに利用するモデルを選択して下さい.\n' msg += '1: SdA_regression, 2: DBN, 3: SdA_RNN, 4:RNNRBM_MLP, 5:RNNRBM_DBN\n' stdscr.addstr(msg) m = int(stdscr.getstr()) curses.flushinp() stdscr.clear() if l <= 4 and m <= 5: break else: print ' ** 注 ** 適切な値を入力して下さい。\n'
def curses_main(scr, interval, typing, escape, noframe): curses.start_color() curses.use_default_colors() # use default colors curses.curs_set(0) # make the cursor invisible if not escape: curses.raw() if interval == None: interval = INTERVAL if typing: global OVERALL_Y global OVERALL_X scr.addstr(OVERALL_Y + MOKUGYO_Y, OVERALL_X + 26, 'Typing anythig...') scr.refresh() if not noframe: draw_frame(scr) MOKUGYO[0].encode(code) scr.addstr(OVERALL_Y + MOKUGYO_Y, OVERALL_X + MOKUGYO_X, \ MOKUGYO[0].encode(code)) scr.refresh() x = 60 y = 2 cnt = 1 prev_key = None for s in HANNYA_SHINGYO: for uc in s: try: if typing: curr_key = scr.getkey() while prev_key == curr_key: curr_key = scr.getkey() prev_key = curr_key else: time.sleep(interval) if uc != u' ': scr.addstr(OVERALL_Y + y, OVERALL_X + x, uc.encode(code)) scr.addstr(OVERALL_Y + MOKUGYO_Y, OVERALL_X + MOKUGYO_X, \ MOKUGYO[cnt % len(MOKUGYO)].encode(code)) scr.refresh() y += 1 cnt += 1 except KeyboardInterrupt: return # exit x -= 3 y = 2 scr.addstr(OVERALL_Y + MOKUGYO_Y, OVERALL_X + MOKUGYO_X, \ MOKUGYO[0].encode(code)) msg_x = MOKUGYO_X while msg_x > 0: scr.addstr(OVERALL_Y + MOKUGYO_Y, msg_x, MESSAGE.encode(code)) scr.refresh() time.sleep(float(AFTER_SLEEP) / float(MOKUGYO_X)) scr.addstr(OVERALL_Y + MOKUGYO_Y, msg_x, ' ' * len(MESSAGE)) msg_x -= 1 curses.flushinp()
def main(stdscr): # Required to be global for buggy resize windows, requires reassignment of values global MAP_HEIGHT, MAP_WIDTH y = 1 x = 1 midy = int(MAP_HEIGHT / 2) # FIXME: mid points break on too small maps midx = int(MAP_WIDTH / 2) # Colours for different objects curses.start_color() curses.use_default_colors() curses.init_pair(1, 57, 234) # Wall curses.init_pair(2, 35, 0) # Player curses.init_pair(3, 60, 0) # Floor curses.curs_set(0) game_objects = {} while not game_objects: game_objects = menu() mapsize = game_objects['mapsize'] # make a second window for getch and for displaying the map, this reduces flickering on getch refreshes stats_y = 2 stats_x = MAP_WIDTH + 2 stats = curses.newwin(5, 15, stats_y, MAP_WIDTH + 1) win = curses.newwin(WIN_HEIGHT, WIN_WIDTH, 0, 0) map = curses.newwin(MAP_HEIGHT, MAP_WIDTH, 0, 0) map.border(0) map.nodelay(True) win.nodelay(True) # Makes getch non blocking win.keypad(True) map.keypad(True) # Main ncurses loop, draw map, accept user input, shift map drawing while True: # Get keyboard input c = win.getch() curses.flushinp() # cleans extra getch characters if c == ord('a') or c == curses.KEY_LEFT: # Move left if game_objects[get_yx_key(y + midy, x + midx - 1)].ch != WALLCH: x -= 1 elif c == ord('d') or c == curses.KEY_RIGHT: # Move right if game_objects[get_yx_key(y + midy, x + midx + 1)].ch != WALLCH: x += 1 elif c == ord('s') or c == curses.KEY_DOWN: # Move down if game_objects[get_yx_key(y + midy + 1, x + midx)].ch != WALLCH: y += 1 elif c == ord('w') or c == curses.KEY_UP: # Move up if game_objects[get_yx_key(y + midy - 1, x + midx)].ch != WALLCH: y -= 1 elif False and c == ord( "+" ): # Buggy resize of screen (experimental feature, may break stuff) stats.clear() win.clear() map.clear() stdscr.clear() MAP_HEIGHT += 5 MAP_WIDTH += 10 stats.mvwin(stats_y, MAP_WIDTH + 2) stats.refresh() win.refresh() map.refresh() stdscr.refresh() elif False and c == ord( "-" ): # Buggy resize of screen (experimental feature, may break stuff) stats.clear() win.clear() map.clear() stdscr.clear() MAP_HEIGHT -= 5 MAP_WIDTH -= 10 stats.mvwin(stats_y, MAP_WIDTH + 2) stats.refresh() win.refresh() map.refresh() stdscr.refresh() elif c == ord('q') or c == ord('Q'): exit(0) # Draw stats window for position info, etc try: map.clear() stats.clear() stats.addstr(1, 1, 'pos_x:' + str(x)) stats.addstr(2, 1, 'pos_y:' + str(y)) except curses.error: # Passing ncurses errors allows for resizing of windows without crashing pass # Draw main map window, draw visible tiles, draw player for ty in range(y - 1, y + MAP_HEIGHT): for tx in range(x - 1, x + MAP_WIDTH): # Skip tiles that are outside map viewer if ty >= mapsize['y'] or ty < 0 or tx >= mapsize['x'] or tx < 0: continue # key is the index for all tiles key = get_yx_key(ty, tx) # Get relative positions to left corner of screen (x,y) go_y = game_objects[key].y - y go_x = game_objects[key].x - x # Draw tiles try: if (go_y > 0 and go_y < MAP_HEIGHT - 1) and ( go_x > 0 and go_x < MAP_WIDTH - 1): if game_objects[key].ch == WALLCH: map.addstr(game_objects[key].y - y, game_objects[key].x - x, game_objects[key].ch, curses.color_pair(1)) else: map.addstr(game_objects[key].y - y, game_objects[key].x - x, game_objects[key].ch, curses.color_pair(3)) if go_y == midy and go_x == midx: map.addstr(go_y, go_x, 'P', curses.color_pair(2)) except curses.error: # Passing ncurses errors allows for resizing of windows without crashing pass # Window cleanup for screen update and resizing map.border(0) map.resize(MAP_HEIGHT, MAP_WIDTH) stats.resize(5, 15) stats.border(0) # Fake refresh, prepares data structures but does not change screen stats.noutrefresh() map.noutrefresh() time.sleep(0.1) # Doupdate redraws the screen if c != curses.ERR or curses.KEY_RESIZE: curses.doupdate()
########################################## # Begin Client stdscr = cs.initscr() cs.echo() while True: stdscr.erase() cs.flushinp() in_loc = mnu.home_screen(stdscr) stdscr.addstr(in_loc[1],in_loc[0],"Your Choice:") c = stdscr.getch() if c == ord('a'): vquit=False while not vquit: stdscr.erase() cs.flushinp() in_loc = mnu.vis_screen(stdscr) stdscr.addstr(in_loc[1], in_loc[0], "Your Choice:") vc = stdscr.getch() atime = flight.rep_atime figSave = params['svPath'] if vc == ord('a'):
def notify_wait(*args, **keywords): notify(*args, **keywords) curses.napms(3000) curses.flushinp()
def flush_terminal(): """Flushes and terminates curses for a clean exit to the original terminal. """ curses.flushinp() curses.endwin()
def main(): dead = False stdscr = curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.raw() curses.noecho() curses.cbreak() stdscr.nodelay(True) stdscr.keypad(True) curses.curs_set(0) maxyx = stdscr.getmaxyx() rocketxy = [math.trunc(maxyx[0]/2),1] frame = 0 seconds = 0 score = 0 half = 0 clouds = [] enemys = [] stars = [] bullets = [] bullets1 = [] ufos = [] rocketSprite = [ ['0','0','0','|','/','0','0','0','0'], ['|','/','0','|','0','/','0','0','0'], ['=','=','=','=','=','=','=','=','-'], ['|','\\','0','|','0','\\','0','0','0'], ['0','0','0','|','\\','0','0','0','0'] ] ufosSpriteList = [" .---. 0 _/_____\_ 0 (_________) 0 ", " .---. 0 _/_____\_ 0 (_________) 0 / \\ ", " .---. 0 _/_____\_ 0 (_________) 0 / \\ "] enemysSpriteList = [ #format: #[ #"x","y" <---- sprite as two strings, 0 anywhere in the string corresponds to newline (str) #y, <--------- How many characters per line (int) #z <---------- How many lines the sprite takes up (int) #] ["-OK", "-O ", 3, 1], [" /|0-===0 \\|", " /K0-===0 \\K", 4, 3], ["-(O)", "-(X)", 4, 1], ["--=0 O0--=", "--=0 X0--=", 3, 3], [" / 0 -=<=-<0 \\ ", " /- 0 -=<=-K0 \\- ", 6, 3], [" /| 0< | 0 \| ", " /|_0< |_0 \| ", 4, 3] ] spriteNum = int(len(enemysSpriteList)) health = 10 ammo = 30 prevscore = 0 notshootingframe = 0 drawTitle(stdscr, prevscore) drawControls(stdscr) for i in range(125): stars.append([random.randrange(3), random.randrange(maxyx[0]-1), random.randrange(maxyx[1]-1), random.randrange(2, 4)]) nonplayable = True while(nonplayable): drawBG(stdscr, stars) drawRocket(stdscr, rocketxy, rocketSprite) if (rocketxy[1]<math.trunc(maxyx[1]/2)): rocketxy[1] += 2 stdscr.refresh() stdscr.erase() time.sleep(0.016) else: nonplayable = False curses.flushinp() while(dead!=True): if (frame>59): frame = 0 seconds += 1 else: frame += 1 #draw frame drawBG(stdscr, stars) drawClouds(stdscr, clouds) drawBullets(stdscr, bullets, bullets1) for i in enemys: drawEnemy(stdscr, enemysSpriteList, i[0], i[1], i[2], i[3], half) drawUfos(stdscr, ufos, frame, ufosSpriteList) drawRocket(stdscr, rocketxy, rocketSprite) drawUI(stdscr, health, ammo) #keyboard input try: c = stdscr.getkey() except: c = 0 #moving, quitting, shooting, and all that stuff if (c == 'q'): gameover(stdscr, score, rocketxy, rocketSprite) dead = True if (c == 'w'): rocketxy[0] -= 2 if (c == 's'): rocketxy[0] += 2 if (c == 'd'): rocketxy[1] += 2 if (c == 'a'): rocketxy[1] -= 2 if (c == 'j' and frame%1==0 and ammo>0): bullets.append([rocketxy[0]-3, rocketxy[1]+6]) bullets.append([rocketxy[0]-1, rocketxy[1]+6]) stdscr.move(rocketxy[0]+2, rocketxy[1]+1) ammo -= 2 stdscr.addstr("FIRE", curses.COLOR_GREEN) stdscr.refresh() if (c == ' '): while(stdscr.getch()==curses.ERR): stdscr.move(math.trunc(maxyx[0]/2), math.trunc(maxyx[1]/2-3)) stdscr.addstr("PAUSED") time.sleep(0.016) if (c != 'j'): notshootingframe += 1 #keeping rocket in bounds if (rocketxy[0]<5): rocketxy[0] = 5 elif (rocketxy[0]>(maxyx[0]-4)): rocketxy[0] = (maxyx[0]-4) elif (rocketxy[1]<10): rocketxy[1] = 10 elif (rocketxy[1]>(maxyx[1]-12)): rocketxy[1] = (maxyx[1]-12) #make enemies fire if (frame%random.randrange(20, 40)==0): for i in enemys: j = random.randrange(100) if (j%2==0): bullets1.append([i[1]-2, i[2]-3]) j = random.randrange(100) if (j%2==0): bullets1.append([i[1]-2, i[2]-3]) if (frame%18>=9): for i in ufos: bullets1.append([i[0],i[1]]) #move all player bullets to the right once for i in bullets: i[1] += 1 #move all enemy bullets to the left once for i in bullets1: i[1] -= 1 #move clouds if (frame%3==0): for i in clouds: i[1] -= 1 #check for bullets at edge of screen and clear them for i in bullets: if (i[1]>=maxyx[1]-5): bullets.pop(bullets.index(i)) for i in bullets1: if (i[1]<5): bullets1.pop(bullets1.index(i)) #generate new clouds if (seconds%random.randrange(1,5)==0 and frame==0): clouds.append([random.randrange(maxyx[0]-10), maxyx[1]-5]) #delete clouds at edge for i in clouds: if (i[1]-5==0): clouds.pop(clouds.index(i)) #add new enemies if (seconds%random.randrange(1, 5)==0 and frame==0): enemys.append([random.randrange(spriteNum), random.randrange(maxyx[0]), maxyx[1]-10, random.randrange(2, 6)]) if (seconds%15==0 and frame==0): ufos.append([random.randrange(10, maxyx[0]-10), random.randrange(math.trunc(maxyx[1]/2), maxyx[1]), 0, random.randrange(2, 6)]) #move enemies if(frame%3==0): for i in enemys: if (i[1]>=math.trunc(maxyx[0]/2)): i[1] += random.randrange(-2, 1) else: i[1] += random.randrange(-1, 2) i[2] += random.randrange(-1, 0) if (i[1]>maxyx[0]-10): i[1] = maxyx[0]-10 if (i[1]<10): i[1] = 10 if (i[2]>maxyx[1]-10): i[2] = maxyx[1]-10 if (i[2]<20): i[2] = 20 if(frame%54==0): ufocount = len(ufos) for i in range(ufocount): ufos[i] = [random.randrange(10, maxyx[0]-10), random.randrange(math.trunc(maxyx[1]/2), maxyx[1]), ufos[i][2], ufos[i][3]] #detect bullet collisions for num, i in enumerate(bullets): for num2, j in enumerate(ufos): if((i[0]>=j[0] and i[0]<=j[0]+len(ufosSpriteList)) and (i[1]>=j[1] and i[1]<=j[1]+len(ufosSpriteList[0]))): bullets.pop(num) num -= 1 score += 1 health += 1 ammo += 2 if(health>10): health = 10 if(ammo>30): ammo = 30 if(j[2]<1): j[2] += 1 else: ufos.pop(num2) num2 -= 1 for num2, j in enumerate(enemys): if((i[0]>=j[1] and i[0]<=j[1]+enemysSpriteList[j[0]][3]) and (i[1]>=j[2] and i[1]<=j[2]+enemysSpriteList[j[0]][2])): bullets.pop(num) enemys.pop(num2) num2 -= 1 num -= 1 score += 1 health += 1 ammo += 2 if(health>10): health = 10 if(ammo>30): ammo = 30 for num, i in enumerate(bullets1): if((i[0]<=rocketxy[0] and i[0]>=rocketxy[0]-len(rocketSprite)) and (i[1]<=rocketxy[1] and i[1]>=rocketxy[1]-len(rocketSprite[0]))): bullets1.pop(num) num -= 1 health -= 1 curses.flash() continue for num2, j in enumerate(enemys): if((i[0]>=j[1] and i[0]<=j[1]+enemysSpriteList[j[0]][3]) and (i[1]>=j[2] and i[1]<=j[2]+enemysSpriteList[j[0]][2])): bullets1.pop(num) enemys.pop(num2) num2 -= 1 num -= 1 score += 1 health += 1 ammo += 2 if(health>10): health = 10 if(ammo>30): ammo = 30 #add stars if (frame%random.randrange(20, 40)==0): stars.append([random.randrange(3), random.randrange(maxyx[0]-1), maxyx[1]-1, random.randrange(2, 4)]) #move stars if (frame%10==0): for i in stars: i[2] -= 1 #delete stars at edge for i in stars: if (i[2]<=4): stars.pop(stars.index(i)) #replenish ammo if (notshootingframe%180==0): ammo += 2 if ammo>30: ammo = 30 #weird misc stuff if (frame%30<15): half = 0 else: half = 1 #check if dead if (health<1): gameover(stdscr, score, rocketxy, rocketSprite) dead = True stdscr.refresh() stdscr.erase() time.sleep(0.016) curses.endwin()
def keyboard_ctrl(): #HACK HACK HACk. If there's a tf_listener, there's gonna be a non-none trans/rot global trans global rot print("We should be running now") screen = curses.initscr() inc_var = 0.050 try: curses.noecho() curses.cbreak() curses.curs_set(0) screen.keypad(1) screen.nodelay(0) while True: #moved inside while so dynamic updates to inc_var can propigate event = screen.getch() curses.flushinp() #do this so only one keyboard command gets processed at a time! grip = '' trans_mat = [] if event == curses.KEY_RIGHT: trans_mat = [inc_var, 0, 0] elif event == curses.KEY_LEFT: trans_mat = [-inc_var, 0, 0] elif event == curses.KEY_UP: trans_mat = [0, inc_var, 0] elif event == curses.KEY_DOWN: trans_mat = [0, -inc_var, 0] elif event == 122: # Z trans_mat = [0, 0, inc_var] elif event == 120: # X trans_mat = [0, 0, -inc_var] elif event == 103: # G grip = 'True' elif event == 104: grip = 'False' elif event == 100: #D screen.nodelay(0) #temporarily turn off non-blocking getch #set inc_var to a new value print("Enter new value for inc-var, in the form\n\r") print( "XX.XXd. You must terminate with a d since we are bad at using curses\n\r" ) event2 = screen.getch() string = chr(event2) while event2 is not 'd': event2 = chr(screen.getch()) string = string + event2 string = string[:-1] inc_var = float(string) print("New Inc_var is " + str(inc_var) + '\n\r') screen.nodelay(1) #and then turn back on non-blocking getch elif event == -1: #no press on getch, it'll just keep running pass else: print("invalid key: %r \n\r" % event) #so we can only spam keyboard commands so fast. But in general, don't hold down the key. if event is not -1: #do this b/c -1 means i've not put in a keyboard command #setup request. Now, we just need to figure out what to put into it. rospy.wait_for_service('low_level_arm') movement_server = rospy.ServiceProxy('low_level_arm', kinematics_request) if rot is None: #if rot is none, there's no TF listener looking at AR tag transforms. Therefore, i'm moving in baxter base coordinate systems response = movement_server(trans=trans_mat, incrimental='True', grip=grip) else: print("Rot is not none \n\r") response = movement_server(trans=trans_mat, incrimental='True', grip=grip, target_trans=trans, target_rot=rot) print(str(response) + "\n\r") finally: screen.keypad(0) curses.curs_set(1) curses.nocbreak() curses.echo() curses.endwin() rospy.signal_shutdown("Shutdown signal recieved")
def main(args): # Parse the command line config = parseOptions(args) # Grab the list of filenames to look for TLEs in filenames = config['args'] # Read in the TLEs and create a dictionary that helps map the NORAD ID # number to a particular entry. This helps with assigned intrinsic # magnitudes to satellites from the QuickSat qs.mag file. satellites = [] lookup = {} for filename in filenames: fh = open(filename, 'r') data = fh.readlines() fh.close() ## Is this geo.txt? If so, filter out everything but the "bright" ones. If we ## don't do this we end up tracking far too many things at once and the telescope ## command rate drops. if os.path.basename(filename) == 'geo.txt': toKeep = [26038, 26608, 26724, 28626, 28644, 28903, 29520, 32018, 39616] else: toKeep = None ## Convert to EarthSatellitePlus instances for i in xrange(len(data)/3): sat = EarthSatellitePlus() try: sat.fillFromPyEphem( ephem.readtle(data[3*i+0], data[3*i+1], data[3*i+2]) ) except ValueError: print "ERROR: Cannot parse TLE:" print " %s" % data[3*i+0].rstrip() print " %s" % data[3*i+1].rstrip() print " %s" % data[3*i+2].rstrip() print "-> skipping" continue ### Is this in the geo.txt "bright" list? try: if sat.catalog_number not in toKeep: continue except TypeError: pass ### Have we already loaded this satellite from a different file? if sat.catalog_number not in lookup.keys(): satellites.append( sat ) lookup[sat.catalog_number] = len(satellites)-1 # Load in the standard magnitude if we happen to have a qs.mag file to read # and add the information to the various # instances. try: fh = open('qs.mag', 'r') for line in fh: cNum = int(line[:5], 10) if cNum == 1 or cNum == 99999: continue try: mag = float(line[33:37]) except ValueError: pass try: satellites[ lookup[cNum] ].setStdMag( mag ) except KeyError: pass fh.close() except IOError as e: print "ERROR: Error reading 'qs.mag': %s" % str(e) pass # Report on what we found nSats = len(satellites) if nSats == 0: print "ERROR: Found no valid TLEs, exiting" sys.exit(1) print "Loaded %i TLEs from %i file%s" % (nSats, len(filenames), 's' if len(filenames) > 1 else '') # Try and setup the telescope. This not only opens up the port but also # makes sure that the time is right. try: lx200 = LX200(config['port'], baud=config['baud']) ## Make sure that the time is "reasonable" tTime = lx200.getDateTime() cTime = datetime.utcnow() tcOffset = cTime - tTime if abs(tcOffset) > timedelta(seconds=10): lx200.setDateTime(cTime) tTime = lx200.getDateTime() cTime = datetime.utcnow() tcOffset = cTime - tTime print "LX200 set to %s, computer at %s" % (tTime, cTime) print "-> Difference is %s" % tcOffset lx200StatusString = "LX200 set to %s, computer at %s" % (tTime, cTime) # Set the slew rate to maximum lx200.setMaximumSlewRate(8) lx200.setSlewRateMax() # Set high precision coordinates lx200.setHighPrecision() except Exception as e: print "ERROR: %s" % str(e) lx200 = None lx200StatusString = 'Telescope not connected' # Set the observer according to the telescope, if found. Otherwise, use # the default values. try: obs = lx200.getObserver(elevation=config['elev']) except Exception as e: print "ERROR: %s" % str(e) obs = ephem.Observer() obs.lat = config['lat']*_deg2rad obs.lon = config['lon']*_deg2rad obs.elevation = config['elev'] print "Observer set to %.4f %s, %.4f %s @ %.1f m" % (abs(obs.lat)*_rad2deg, 'N' if obs.lat >= 0 else 'S', abs(obs.lon)*_rad2deg, 'E' if obs.lon >= 0 else 'W', obs.elevation) # Select how to run if config['predictorMode']: # Predictor mode # Work with the date and time provided so that we can display # something helpful with the pass predictions d, t = config['predictorDate'], config['predictorTime'] if d is None and t is None: ## Use the current UTC time and convert it to local using ## the provided UTC offset dt = datetime.utcnow() oG = -1 if config['utcOffset'] < 0 else 1 oS = abs(config['utcOffset']*3600.0) oU = int((oS-int(oS))*1e6) oS = int(oS) dt += oG*timedelta(seconds=oS, microseconds=oU) dt = dt.strftime("%Y/%m/%d %H:%M:%S") else: ## Use the provided date and time dt = "%s %s" % (d, t) # Compute the passes - this should return values in local time events = passPredictor(obs, satellites, date=d, time=t, utcOffset=config['utcOffset'], duration=config['predictorInterval'], magnitudeCut=config['predictorMagLimit']) print " " print "Satellite Pass Predictions for %s:" % dt print "%24s %5s %13s %15s %13s" % ('Name', 'Mag.', 'Rise Time', 'Max. Time/El.', 'Set Time') print "-" * (24+2+5+2+13+2+15+2+13) for event in events: mag = event[1] if mag < 15: mag = "%5.1f" % mag else: mag = " --- " rTime = str(event[2])[5:] mTime = str(event[4]).split(None, 1)[1] mEl = event[5]*_rad2deg sTime = str(event[6])[5:] print "%24s %5s %13s %8s @ %4.1f %13s" % (event[0], mag, rTime, mTime, mEl, sTime) else: # Tracking mode # Convert the provided UT offset to a timedelta instance that we # can use to update the clock oG = -1 if config['utcOffset'] < 0 else 1 oS = abs(config['utcOffset']*3600.0) oU = int((oS-int(oS))*1e6) oS = int(oS) utcOffset = oG*timedelta(seconds=oS, microseconds=oU) # Initialize the tracker and run the first full update trkr = SatellitePositionTracker(obs, satellites, telescope=lx200) trkr.update(full=True) # Setup the TUI stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) stdscr.nodelay(1) # Main TUI loop ## State control variables and such act = 0 # Line number of the satellite the selector is on trk = -1 # Line number of the satellite being tracked info = -1 # Whether or not to get info about a satellite magLimit = 6.0 # Magnitude limit for what to display msg = lx200StatusString # Message string oldMsg = '' # Message string - previous value (to help with clearing old messages) msgCount = 0 # Message string display counter (to help with clearing old messages) empty = '' # Empty string (to help with clearing old messages/the window) while len(empty) < (5+2+24+2+12+2+12+2+12+2+5): empty += ' ' while True: ## Current time tNow = datetime.utcnow() tNowLocal = tNow + utcOffset ## Update the tracker tElapsed = trkr.update() ## Figure out how many satellites are currently visible and brighter ## than the current magnitude limit trkChange = False nVis = trkr.getNumberVisible(magnitudeCut=magLimit) ## Interact with the user's key presses - one key at a time c = stdscr.getch() curses.flushinp() if c == ord('Q'): ### 'q' to exit the main loop after stopping the movement if trkr.getTracking() is not None: trkr.stopTracking() if lx200 is not None: lx200.haltCurrentSlew() break elif c == curses.KEY_UP: ### Up arrow to change what is selected act -= 1 act = max([act, 0]) elif c == curses.KEY_DOWN: ### Down array to change what is selected act += 1 act = min([act, nVis-1, 12]) elif c == ord('a'): ### 'a' to adjust the tracking time offset - negative trkr.adjustTimeOffset( -config['trackOffsetStep'] ) off = trkr.getTimeOffset() msg = 'Time offset now %+.1f s' % (off.days*86400+off.seconds+off.microseconds/1e6) elif c == ord('A'): ### 'A' to adjust the tracking time offset - negative x10 trkr.adjustTimeOffset( -10*config['trackOffsetStep'] ) off = trkr.getTimeOffset() msg = 'Time offset now %+.1f s' % (off.days*86400+off.seconds+off.microseconds/1e6) elif c == ord('s'): ### 's' to adjust the tracking time offset - positive trkr.adjustTimeOffset( config['trackOffsetStep'] ) off = trkr.getTimeOffset() msg = 'Time offset now %+.1f s' % (off.days*86400+off.seconds+off.microseconds/1e6) elif c == ord('S'): ### 's' to adjust the tracking time offset - positive x10 trkr.adjustTimeOffset( 10*config['trackOffsetStep'] ) off = trkr.getTimeOffset() msg = 'Time offset now %+.1f s' % (off.days*86400+off.seconds+off.microseconds/1e6) elif c == ord('z'): ### 'z' to adjust the perpendicular track offset - negative trkr.adjustCrossTrackOffset( -config['crossTrackOffsetStep'] ) off = trkr.getCrossTrackOffset() msg = 'Cross track offset now %+.1f degrees' % off elif c == ord('Z'): ### 'Z' to adjust the perpendicular track offset - negative x10 trkr.adjustCrossTrackOffset( -10*config['crossTrackOffsetStep'] ) off = trkr.getCrossTrackOffset() msg = 'Cross track offset now %+.1f degrees' % off elif c == ord('w'): ### 'w' to adjust the perpendicular track offset - positive trkr.adjustCrossTrackOffset( config['crossTrackOffsetStep'] ) off = trkr.getCrossTrackOffset() msg = 'Cross track offset now %+.1f degrees' % off elif c == ord('W'): ### 'W' to adjust the perpendicular track offset - positive x10 trkr.adjustCrossTrackOffset( 10*config['crossTrackOffsetStep'] ) off = trkr.getCrossTrackOffset() msg = 'Cross track offset now %+.1f degrees' % off elif c == ord('p'): off1 = trkr.getTimeOffset() off2 = trkr.getCrossTrackOffset() msg = 'Time offset is %+.1f s; Cross track offset is %+.1f degrees' % (off1.days*86400+off1.seconds+off1.microseconds/1e6, off2) elif c == ord('k'): ### 'k' to adjust the magnitude limit - negative magLimit -= 0.5 magLimit = max([magLimit, -2.0]) msg = 'Magntiude limit now <= %.1f mag' % magLimit elif c == ord('l'): ### 'k' to adjust the magnitude limit - negative magLimit += 0.5 magLimit = min([magLimit, 15.0]) if magLimit == 15.0: msg = 'Magntiude limit now disabled' else: msg = 'Magntiude limit now <= %.1f mag' % magLimit elif c == ord('r'): ### 'r' to reset the telescope target trkr.resetTracking() msg = 'Resetting telescope target' elif c == ord('t'): ### 't' to toggle telesope tracking on/off if trk == -1: trk = act trkChange = True else: trk = -1 trkChange = True elif c == ord('i'): ### 'i' to get information about the currently selected satellite info = act ## Additional state check to make sure that we aren't still trying ## to track a satellite that has set/been eclipsed if not trkChange: if trk != -1 and trkr.getTracking() is None: trk = -1 trkChange = True ## Header for the satellite data output = "%5s %24s %12s %12s %12s %5s\n" % ('ID', 'Name', 'Azimuth', 'Elevation', 'Status', 'Mag.') stdscr.addstr(0, 0, output, curses.A_UNDERLINE) ## Have we stopped a track? If so, let the user know. if trkChange: if trk == -1: trkr.stopTracking() msg = 'Tracking stopped' trkChange = False ## Satellite information k = 0 for j in xrange(nSats): ### Make the satellite easy-to-access sat = trkr.satellites[j] ### Is it visible and bright enough? if sat.alt > 0 and sat.magnitude <= magLimit: #### Create the output line output = "%5i %24s %12s %12s %8s-%3s %5s" % (sat.catalog_number, sat.name, sat.az, sat.alt, 'Eclipsed' if sat.eclipsed else 'In Sun', 'Asc' if sat.rising else 'Dsc', '%5.1f' % sat.magnitude if sat.magnitude < 15 else ' --- ') #### See if we need to enable/disable tracking if trkChange: if k == trk: if sat.catalog_number != trkr.getTracking(): trkr.setTimeOffset( timedelta() ) trkr.setCrossTrackOffset( 0.0 ) trkr.startTracking(sat.catalog_number) msg = 'Now tracking \'%s\' (NORAD ID #%i)' % (sat.name, sat.catalog_number) #### See if we need to poll and print info if k == info: ## Is this one active? isTracked = '' if sat.catalog_number == trkr.getTracking(): isTracked = ' (tracking)' ## Loss of signal information los = sat.los los = '%i:%02i:%04.1f' % (int(los/3600.0), int(los/60.0)%60, los%60) msg = '%s%s: LoS %s, range %.1f km, velocity %.1f km/s' % (sat.name, isTracked, los, sat.range/1e3, sat.range_velocity/1e3) info = -1 #### Add the line to the screen, provided it will fit if k <= 12: ## Standard flag for normal satellites displayFlags = curses.A_DIM ## Make the satellite currently be traced more obvious if trkr.satellites[j].catalog_number == trkr.getTracking(): displayFlags = curses.A_BOLD ## Make the satellite currently selected reversed if k == act: displayFlags |= curses.A_REVERSE ## Underline the last satellite in the list if k == min([nVis-1, 12]): displayFlags |= curses.A_UNDERLINE stdscr.addstr(k+1, 0, output, displayFlags) k += 1 else: break ## Pad out the message stored in 'msg' generated from interaction ## with the user/telescope while len(msg) < (5+2+24+2+12+2+12+2+12+2+5): msg += ' ' ## See if it is time to clear off the message if msg == oldMsg: msgCount += 1 if msgCount == 201: msg = empty msgCount = 0 oldMsg = msg ## Pad out the current UTC time output = "UTC: " output += tNow.strftime("%Y/%m/%d %H:%M:%S") output += ".%01i" % (float(tNow.strftime("%f"))/1e5,) output += " " output += "%5.3f s" % tElapsed output += " " output += "LT: " output += tNowLocal.strftime("%Y/%m/%d %H:%M:%S") output += ".%01i" % (float(tNowLocal.strftime("%f"))/1e5,) while len(output) < (5+2+24+2+12+2+12+2+12+2+5): output += ' ' ## Final time/message/help information stdscr.addstr(k+1, 0, output) stdscr.addstr(k+2, 0, msg, curses.A_UNDERLINE) stdscr.addstr(k+3, 0, 'Keys: ') stdscr.addstr(k+4, 0, ' t - Start/stop tracking of the currently selected satellite ') stdscr.addstr(k+5, 0, ' r - Reset failed telescope slew ') stdscr.addstr(k+6, 0, ' a/s - Decrease/Increase track offset by %.1f second (x10 with shift) ' % ( config['trackOffsetStep'].seconds+config['trackOffsetStep'].microseconds/1e6)) stdscr.addstr(k+7, 0, ' z/w - Decrease/Increase cross track offset by %.1f degrees (x10 with shift) ' % config['crossTrackOffsetStep']) stdscr.addstr(k+8, 0, ' k/l - Decrease/Increase the magnitude limit by 0.5 mag ') stdscr.addstr(k+9, 0, ' p - Print current tracking offsets ') stdscr.addstr(k+10, 0, ' Q - Exit ') ## Pad out the window to deal with satellite setting while k+11 < 23: stdscr.addstr(k+11, 0, empty) k += 1 ## Refresh the display stdscr.refresh() ## Sleep until the next iteration tSleep = config['updateInterval'] - tElapsed time.sleep( max([tSleep, 0.001]) ) # Close out the curses session curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin()
def update(self): garbage_collection = {'b': [], 'e': [], 'ex': []} c = self.screen.getch() curses.flushinp() #spawn enemies if len(self.enemies) < self.level * 2 and random.randint(0, 30) == 2: self.enemies.append(Enemy()) self.enemy_count += 1 if self.enemy_count == self.level * 10: self.level += 1 #handle key input if c == curses.KEY_RIGHT: self.hero.movement = 1 elif c == curses.KEY_LEFT: self.hero.movement = -1 elif c == curses.KEY_UP or c == 32: shot = self.hero.fire( len([x for x in self.bullets if x.type == 'hero'])) if shot: self.bullets.append(shot) elif c == curses.KEY_DOWN: self.hero.movement = 0 elif c == 113 or c == 81: return False #clear the screen and redraw the bounding box self.screen.erase() self.screen.box() #handle player movement self.hero.move() # move bullets, check bullet collision, add explosions, draw bullets for i, b in enumerate(self.bullets): loc = b.move() if loc[0] > 1 and loc[0] < self.height - 1 and loc[1] > 2 and loc[ 1] < self.width - 3: if b.yx[1] < 2: b.yx[1] = self.width - 4 if b.yx[1] > self.width - 3: b.yx[1] = 2 b.yx = loc if self.check_col(b, self.hero): self.hero.health -= 1 # replace 1 with the weapon damage if self.hero.health <= 0: with open(self.filepath, 'a+') as highscores: highscores.write(',' + str(self.score)) self.status = 'death' garbage_collection['b'].append(i) continue for ei, e in enumerate(self.enemies): if self.check_col(b, e) and b.type == 'hero': e.health -= 1 if e.yx[0] > 2: e.yx[0] -= 0.5 garbage_collection['b'].append(i) if e.health <= 0: self.score += e.value self.explosions.append(Explosion( b.yx, self.screen)) garbage_collection['e'].append(ei) continue self.screen.addch(int(b.yx[0]), int(b.yx[1]), b.icon, curses.A_BOLD) else: garbage_collection['b'].append(i) #move enemies, fire, draw enemies for i, e in enumerate(self.enemies): loc = e.move() if int(loc[0]) < curses.LINES - 2: e.yx = loc e.draw(self.screen) if e.movement_pattern == 2 or e.movement_pattern == 3: shot = e.fire(self.get_player_angle(e.yx, self.hero.yx)) if shot: self.bullets.append(shot) elif abs(e.yx[1] - self.hero.yx[1]) < 15: shot = e.fire(self.get_player_angle(e.yx, self.hero.yx)) if shot: self.bullets.append(shot) if self.check_col(e, self.hero): with open(self.filepath, 'a+') as highscores: highscores.write(',' + str(self.score)) self.status = 'death' else: garbage_collection['e'].append(i) #update explosions (includes draw) for i, ex in enumerate(self.explosions): ex.update() if ex.count >= 10: garbage_collection['ex'].append(i) # draw player self.screen.addstr(int(self.hero.yx[0]), int(self.hero.yx[1]), self.hero.icon, curses.A_BOLD) # Add health, title/level, and score health_display = 'HEALTH: ' + '#' * self.hero.health score_add_zeros = 6 - len(str(self.score)) score_string = 'SCORE: ' + '0' * score_add_zeros + str(self.score) title_string = 'COSMONAUT [Level ' + str(self.level) + ']' if self.width > len(health_display) + 6: self.screen.addstr(self.height - 2, 4, health_display, curses.color_pair(1)) if self.width > len(health_display) + len(score_string) + 10: self.screen.addstr(self.height - 2, self.width - len(score_string) - 4, score_string, curses.color_pair(2)) if self.width > len(health_display) + len(score_string) + len( title_string) + 15: self.screen.addstr(self.height - 2, self.width / 2 - len(title_string) / 2, title_string, curses.color_pair(3)) self.screen.refresh() # Remove dead items from lists/garbage collect for i, trash in enumerate(garbage_collection['b']): del self.bullets[trash - i] for i, trash in enumerate(garbage_collection['e']): del self.enemies[trash - i] for i, trash in enumerate(garbage_collection['ex']): del self.explosions[trash - i] return True
def menu(): mapsizey = 100 mapsizex = 100 menu = curses.newwin(MAP_HEIGHT, MAP_WIDTH, 0, 0) menu.clear() menu.nodelay(False) menu.clear() menu.border(0) menu.refresh() while True: curses.curs_set(False) menu.border(0) menu.addstr(1, 1, 'G - generate new map') menu.addstr(2, 1, 'L - load map') menu.addstr(3, 1, 'Q - quit program') menu.refresh() c = menu.getch() curses.flushinp() # clear other things besides getch? game_objects = {} if c == ord('g') or c == ord('G'): # delete map, make new map midy = int(MAP_HEIGHT / 2) midx = int(MAP_WIDTH / 2) menu.clear() menu.refresh() path = get_map_path() size = get_map_size() mapsizey = size mapsizex = size game_objects = gen_map(mapsizey, mapsizex, midy, midx) menu.clear() menu.refresh() save_map(path, game_objects) """ try: save_map(path, game_objects) except: menu.clear() menu.addstr(MAP_HEIGHT-2, 1, 'error: failed to save map file (path or permissions?)') continue """ menu.clear() menu.refresh() #html_map_export(mapsizey, mapsizex, game_objects) elif c == ord('l') or c == ord('L'): # load current map1 game_objects = {} path = load_map_path() game_objects = load_map(path) """ try: game_objects = load_map(path) except: menu.clear() menu.addstr(MAP_HEIGHT-2, 1, 'error: failed to load map file (possible corruption?)') continue """ elif c == ord('q') or c == ord('Q'): exit(0) menu.clear() menu.refresh() del menu return game_objects
def menu(self): c = self.screen.getch() curses.flushinp() if c == 80 or c == 112: self.status = 'play' elif c == 113 or c == 81: return False word_x = self.width / 2 - 41 word_x2 = self.width / 2 - 18 if word_x < 1: word_x = 1 #clear the screen and redraw the bounding box self.screen.erase() self.screen.box() if self.width > 90: self.cover_animation = [self.cover_animation.pop() ] + self.cover_animation self.screen.addstr( 5, word_x, ' _______ _______ _______ __ __ _______ __ _ _______ __ __ _______ ', curses.color_pair(self.cover_animation[0])) self.screen.addstr( 6, word_x, '| || || || |_| || || | | || _ || | | || |', curses.color_pair(self.cover_animation[1])) self.screen.addstr( 7, word_x, '| || _ || _____|| || _ || | | || | | || | | ||_ _|', curses.color_pair(self.cover_animation[2])) self.screen.addstr( 8, word_x, '| _|| | | || |_____ | || | | || \| || |_| || | | | | | ', curses.color_pair(self.cover_animation[3])) self.screen.addstr( 9, word_x, '| | | |_| ||_____ || || |_| || |\ || || |_| | | | ', curses.color_pair(self.cover_animation[4])) self.screen.addstr( 10, word_x, '| |_ | | _____| || ||_|| || || | | || _ || | | | ', curses.color_pair(self.cover_animation[5])) self.screen.addstr( 11, word_x, '|_______||_______||_______||_| |_||_______||_| |__||__| |__||_______| |___| ', curses.color_pair(self.cover_animation[0])) else: self.screen.addstr(8, word_x2, ".-. .-. .-. . . .-. . . .-. . . .-. ", curses.color_pair(1)) self.screen.addstr(9, word_x2, "| | | `-. |\/| | | |\| |-| | | | ", curses.color_pair(2)) self.screen.addstr(10, word_x2, "`-' `-' `-' ' ` `-' ' ` ` ' `-' ' ", curses.color_pair(3)) message1 = '(P)lay (Q)uit' self.screen.addstr(self.height - 5, self.width / 2 - len(message1) / 2, message1, curses.color_pair(2)) self.screen.refresh() return True
def main(args): hostname = socket.gethostname() scr = curses.initscr() curses.noecho() curses.cbreak() scr.keypad(1) scr.nodelay(1) size = scr.getmaxyx() std = curses.A_NORMAL rev = curses.A_REVERSE poll_interval = 1.0 tLastPoll = 0.0 sort_key = 'process' sort_rev = True display_gpu = False try: while True: t = time.time() ## Interact with the user c = scr.getch() curses.flushinp() if c == ord('q'): break elif c == ord('i'): new_key = 'pid' elif c == ord('b'): new_key = 'name' elif c == ord('c'): new_key = 'core' elif c == ord('t'): new_key = 'total' elif c == ord('a'): new_key = 'acquire' elif c == ord('p'): new_key = 'process' elif c == ord('r'): new_key = 'reserve' try: if sort_key == new_key: sort_rev = not sort_rev else: sort_key = new_key sort_rev = True del new_key except NameError: pass ## Do we need to poll the system again? if t - tLastPoll > poll_interval: ## Load in the various bits form /proc that we need load = get_load_average() cpu = get_processor_usage() mem = get_memory_swap_usage() gpu = get_gpu_memory_usage() ## Determine if we have GPU data to display if gpu['devCount'] > 0: display_gpu = True ## Find all running processes pidDirs = glob.glob(os.path.join(BIFROST_STATS_BASE_DIR, '*')) pidDirs.sort() ## Load the data blockList = {} for pidDir in pidDirs: pid = int(os.path.basename(pidDir), 10) contents = load_by_pid(pid) cmd = get_command_line(pid) if cmd == '': continue for block in contents.keys(): try: log = contents[block]['bind'] cr = log['core0'] except KeyError: continue try: log = contents[block]['perf'] ac = max([0.0, log['acquire_time']]) pr = max([0.0, log['process_time']]) re = max([0.0, log['reserve_time']]) except KeyError: ac, pr, re = 0.0, 0.0, 0.0 blockList['%i-%s' % (pid, block)] = { 'pid': pid, 'name': block, 'cmd': cmd, 'core': cr, 'acquire': ac, 'process': pr, 'reserve': re, 'total': ac + pr + re } ## Sort order = sorted(blockList, key=lambda x: blockList[x][sort_key], reverse=sort_rev) ## Mark tLastPoll = time.time() ## Display k = 0 ### General - load average output = '%s - %s - load average: %s, %s, %s\n' % ( os.path.basename(__file__), hostname, load['1min'], load['5min'], load['10min']) k = _add_line(scr, k, 0, output, std) ### General - process counts output = 'Processes: %s total, %s running\n' % ( load['procTotal'], load['procRunning']) k = _add_line(scr, k, 0, output, std) ### General - average processor usage c = cpu['avg'] output = 'CPU(s):%5.1f%%us,%5.1f%%sy,%5.1f%%ni,%5.1f%%id,%5.1f%%wa,%5.1f%%hi,%5.1f%%si,%5.1f%%st\n' % ( 100.0 * c['user'], 100.0 * c['sys'], 100.0 * c['nice'], 100.0 * c['idle'], 100.0 * c['wait'], 100.0 * c['irq'], 100.0 * c['sirq'], 100.0 * c['steal']) k = _add_line(scr, k, 0, output, std) ### General - memory output = 'Mem: %9ik total, %9ik used, %9ik free, %9ik buffers\n' % ( mem['memTotal'], mem['memUsed'], mem['memFree'], mem['buffers']) k = _add_line(scr, k, 0, output, std) ### General - swap output = 'Swap: %9ik total, %9ik used, %9ik free, %9ik cached\n' % ( mem['swapTotal'], mem['swapUsed'], mem['swapFree'], mem['cached']) k = _add_line(scr, k, 0, output, std) ### General - GPU, if avaliable if display_gpu: if gpu['pwrLimit'] != 0.0: if gpu['load'] != 0.0: output = 'GPU(s): %9ik total, %9ik used, %9ik free, %5.1f%%us, %.0f/%.0fW\n' % ( gpu['memTotal'], gpu['memUsed'], gpu['memFree'], gpu['load'], gpu['pwrDraw'], gpu['pwrLimit']) else: output = 'GPU(s): %9ik total, %9ik used, %9ik free, %.0f/%.0fW\n' % ( gpu['memTotal'], gpu['memUsed'], gpu['memFree'], gpu['pwrDraw'], gpu['pwrLimit']) else: output = 'GPU(s): %9ik total, %9ik used, %9ik free, %i device(s)\n' % ( gpu['memTotal'], gpu['memUsed'], gpu['memFree'], gpu['devCount']) k = _add_line(scr, k, 0, output, std) ### Header k = _add_line(scr, k, 0, ' ', std) output = '%6s %15s %4s %5s %7s %7s %7s %7s Cmd' % ( 'PID', 'Block', 'Core', '%CPU', 'Total', 'Acquire', 'Process', 'Reserve') csize = size[1] - len(output) output += ' ' * csize output += '\n' k = _add_line(scr, k, 0, output, rev) ### Data for o in order: d = blockList[o] try: c = 100.0 * cpu[d['core']]['total'] c = '%5.1f' % c except KeyError: c = '%5s' % ' ' output = '%6i %15s %4i %5s %7.3f %7.3f %7.3f %7.3f %s' % ( d['pid'], d['name'][:15], d['core'], c, d['total'], d['acquire'], d['process'], d['reserve'], d['cmd'][:csize + 3]) k = _add_line(scr, k, 0, output, std) if k >= size[0] - 1: break ### Clear to the bottom scr.clrtobot() ### Refresh scr.refresh() ## Sleep time.sleep(_REDRAW_INTERVAL_SEC) except KeyboardInterrupt: pass except Exception as error: exc_type, exc_value, exc_traceback = sys.exc_info() fileObject = StringIO() traceback.print_tb(exc_traceback, file=fileObject) tbString = fileObject.getvalue() fileObject.close() # Save the window contents contents = '' y, x = scr.getmaxyx() for i in range(y - 1): for j in range(x): d = scr.inch(i, j) c = d & 0xFF a = (d >> 8) & 0xFF contents += chr(c) # Tear down curses scr.keypad(0) curses.echo() curses.nocbreak() curses.endwin() # Final reporting try: ## Error print("%s: failed with %s at line %i" % (os.path.basename(__file__), str(error), traceback.tb_lineno(exc_traceback))) for line in tbString.split('\n'): print(line) except NameError: ## Last window contents sans attributes print(contents)
def keyboard_controller(screen): CMDS = { 'roll': 1500, 'pitch': 1500, 'throttle': 900, 'yaw': 1500, 'aux1': 1000, 'aux2': 1000 } # This order is the important bit: it will depend on how your flight controller is configured. # Below it is considering the flight controller is set to use AETR. # The names here don't really matter, they just need to match what is used for the CMDS dictionary. # In the documentation, iNAV uses CH5, CH6, etc while Betaflight goes AUX1, AUX2... CMDS_ORDER = ['roll', 'pitch', 'throttle', 'yaw', 'aux1', 'aux2'] # "print" doesn't work with curses, use addstr instead try: screen.addstr(15, 0, "Connecting to the FC...") with MSPy(device=SERIAL_PORT, loglevel='WARNING', baudrate=115200) as board: if board == 1: # an error occurred... return 1 screen.addstr(15, 0, "Connecting to the FC... connected!") screen.clrtoeol() screen.move(1, 0) average_cycle = deque([0] * NO_OF_CYCLES_AVERAGE_GUI_TIME) # It's necessary to send some messages or the RX failsafe will be activated # and it will not be possible to arm. command_list = [ 'MSP_API_VERSION', 'MSP_FC_VARIANT', 'MSP_FC_VERSION', 'MSP_BUILD_INFO', 'MSP_BOARD_INFO', 'MSP_UID', 'MSP_ACC_TRIM', 'MSP_NAME', 'MSP_STATUS', 'MSP_STATUS_EX', 'MSP_BATTERY_CONFIG', 'MSP_BATTERY_STATE', 'MSP_BOXNAMES' ] if board.INAV: command_list.append('MSPV2_INAV_ANALOG') command_list.append('MSP_VOLTAGE_METER_CONFIG') for msg in command_list: if board.send_RAW_msg(MSPy.MSPCodes[msg], data=[]): dataHandler = board.receive_msg() board.process_recv_data(dataHandler) if board.INAV: cellCount = board.BATTERY_STATE['cellCount'] else: cellCount = 0 # MSPV2_INAV_ANALOG is necessary min_voltage = board.BATTERY_CONFIG['vbatmincellvoltage'] * cellCount warn_voltage = board.BATTERY_CONFIG[ 'vbatwarningcellvoltage'] * cellCount max_voltage = board.BATTERY_CONFIG['vbatmaxcellvoltage'] * cellCount screen.addstr(15, 0, "apiVersion: {}".format(board.CONFIG['apiVersion'])) screen.clrtoeol() screen.addstr( 15, 50, "flightControllerIdentifier: {}".format( board.CONFIG['flightControllerIdentifier'])) screen.addstr( 16, 0, "flightControllerVersion: {}".format( board.CONFIG['flightControllerVersion'])) screen.addstr( 16, 50, "boardIdentifier: {}".format(board.CONFIG['boardIdentifier'])) screen.addstr(17, 0, "boardName: {}".format(board.CONFIG['boardName'])) screen.addstr(17, 50, "name: {}".format(board.CONFIG['name'])) slow_msgs = cycle( ['MSP_ANALOG', 'MSP_STATUS_EX', 'MSP_MOTOR', 'MSP_RC']) cursor_msg = "" last_loop_time = last_slow_msg_time = last_cycleTime = time.time() while True: start_time = time.time() char = screen.getch() # get keypress curses.flushinp() # flushes buffer # # Key input processing # # # KEYS (NO DELAYS) # if char == ord('q') or char == ord('Q'): break elif char == ord('d') or char == ord('D'): cursor_msg = 'Sending Disarm command...' CMDS['aux1'] = 1000 elif char == ord('r') or char == ord('R'): screen.addstr(3, 0, 'Sending Reboot command...') screen.clrtoeol() board.reboot() time.sleep(0.5) break elif char == ord('a') or char == ord('A'): cursor_msg = 'Sending Arm command...' CMDS['aux1'] = 1800 # # The code below is expecting the drone to have the # modes set accordingly since everything is hardcoded. # elif char == ord('m') or char == ord('M'): if CMDS['aux2'] <= 1300: cursor_msg = 'Horizon Mode...' CMDS['aux2'] = 1500 elif 1700 > CMDS['aux2'] > 1300: cursor_msg = 'Flip Mode...' CMDS['aux2'] = 2000 elif CMDS['aux2'] >= 1700: cursor_msg = 'Angle Mode...' CMDS['aux2'] = 1000 elif char == ord('w') or char == ord('W'): CMDS['throttle'] = CMDS['throttle'] + 10 if CMDS[ 'throttle'] + 10 <= 2000 else CMDS['throttle'] cursor_msg = 'W Key - throttle(+):{}'.format( CMDS['throttle']) elif char == ord('e') or char == ord('E'): CMDS['throttle'] = CMDS['throttle'] - 10 if CMDS[ 'throttle'] - 10 >= 1000 else CMDS['throttle'] cursor_msg = 'E Key - throttle(-):{}'.format( CMDS['throttle']) elif char == curses.KEY_RIGHT: CMDS['roll'] = CMDS['roll'] + 10 if CMDS[ 'roll'] + 10 <= 2000 else CMDS['roll'] cursor_msg = 'Right Key - roll(-):{}'.format(CMDS['roll']) elif char == curses.KEY_LEFT: CMDS['roll'] = CMDS['roll'] - 10 if CMDS[ 'roll'] - 10 >= 1000 else CMDS['roll'] cursor_msg = 'Left Key - roll(+):{}'.format(CMDS['roll']) elif char == curses.KEY_UP: CMDS['pitch'] = CMDS['pitch'] + 10 if CMDS[ 'pitch'] + 10 <= 2000 else CMDS['pitch'] cursor_msg = 'Up Key - pitch(+):{}'.format(CMDS['pitch']) elif char == curses.KEY_DOWN: CMDS['pitch'] = CMDS['pitch'] - 10 if CMDS[ 'pitch'] - 10 >= 1000 else CMDS['pitch'] cursor_msg = 'Down Key - pitch(-):{}'.format(CMDS['pitch']) # # IMPORTANT MESSAGES (CTRL_LOOP_TIME based) # if (time.time() - last_loop_time) >= CTRL_LOOP_TIME: last_loop_time = time.time() # Send the RC channel values to the FC if board.send_RAW_RC([CMDS[ki] for ki in CMDS_ORDER]): dataHandler = board.receive_msg() board.process_recv_data(dataHandler) # # SLOW MSG processing (user GUI) # if (time.time() - last_slow_msg_time) >= SLOW_MSGS_LOOP_TIME: last_slow_msg_time = time.time() next_msg = next(slow_msgs) # circular list # Read info from the FC if board.send_RAW_msg(MSPy.MSPCodes[next_msg], data=[]): dataHandler = board.receive_msg() board.process_recv_data(dataHandler) if next_msg == 'MSP_ANALOG': voltage = board.ANALOG['voltage'] voltage_msg = "" if min_voltage < voltage <= warn_voltage: voltage_msg = "LOW BATT WARNING" elif voltage <= min_voltage: voltage_msg = "ULTRA LOW BATT!!!" elif voltage >= max_voltage: voltage_msg = "VOLTAGE TOO HIGH" screen.addstr( 8, 0, "Battery Voltage: {:2.2f}V".format( board.ANALOG['voltage'])) screen.clrtoeol() screen.addstr(8, 24, voltage_msg, curses.A_BOLD + curses.A_BLINK) screen.clrtoeol() elif next_msg == 'MSP_STATUS_EX': ARMED = board.bit_check(board.CONFIG['mode'], 0) screen.addstr(5, 0, "ARMED: {}".format(ARMED), curses.A_BOLD) screen.clrtoeol() screen.addstr( 5, 50, "armingDisableFlags: {}".format( board.process_armingDisableFlags( board.CONFIG['armingDisableFlags']))) screen.clrtoeol() screen.addstr( 6, 0, "cpuload: {}".format(board.CONFIG['cpuload'])) screen.clrtoeol() screen.addstr( 6, 50, "cycleTime: {}".format(board.CONFIG['cycleTime'])) screen.clrtoeol() screen.addstr(7, 0, "mode: {}".format(board.CONFIG['mode'])) screen.clrtoeol() screen.addstr( 7, 50, "Flight Mode: {}".format( board.process_mode(board.CONFIG['mode']))) screen.clrtoeol() elif next_msg == 'MSP_MOTOR': screen.addstr( 9, 0, "Motor Values: {}".format(board.MOTOR_DATA)) screen.clrtoeol() elif next_msg == 'MSP_RC': screen.addstr( 10, 0, "RC Channels Values: {}".format( board.RC['channels'])) screen.clrtoeol() screen.addstr( 11, 0, "GUI cycleTime: {0:2.2f}ms (average {1:2.2f}Hz)". format((last_cycleTime) * 1000, 1 / (sum(average_cycle) / len(average_cycle)))) screen.clrtoeol() screen.addstr(3, 0, cursor_msg) screen.clrtoeol() end_time = time.time() last_cycleTime = end_time - start_time if (end_time - start_time) < CTRL_LOOP_TIME: time.sleep(CTRL_LOOP_TIME - (end_time - start_time)) average_cycle.append(end_time - start_time) average_cycle.popleft() finally: screen.addstr(5, 0, "Disconneced from the FC!") screen.clrtoeol()
def end_screen(self) -> None: self.screen.keypad(False) curses.flushinp() curses.endwin()
print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP #intialize curses module stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) curses.halfdelay(1) lastmessage = "0" while (True): #clear buffer to prevent overwhelming RasPI with UDP messages when directional keys held down curses.flushinp() inputKey = stdscr.getch() if inputKey == ord('x'): #exit on X key and close curses module curses.nocbreak() stdscr.keypad(False) curses.echo() curses.endwin() break #dpad right/left control crane yaw, dpad up/down move rack in and out #q rotates claw up, w rotates claw down, a closes claw, s opens claw elif inputKey == curses.KEY_RIGHT: MESSAGE = "R" elif inputKey == curses.KEY_LEFT: MESSAGE = "L" elif inputKey == curses.KEY_UP: MESSAGE = "F"
def main(stdscr): currentlyCalibrating=placeableNames[0] currentPipette=pipetteNames[0] movementAmount=1 position=list(robot._driver.get_head_position()["current"]) position[0]=0 def chooseWhatToCalibrate(): nonlocal currentlyCalibrating stdscr.clear() stdscr.addstr("What should we calibrate?\n") for i,value in enumerate(placeableNames): stdscr.addstr(str(i+1)+" - " + value+"\n") curses.echo() # Enable echoing of characters s = stdscr.getstr(15,0, 15) stdscr.addstr(s) currentlyCalibrating=placeableNames[int(s)-1] curses.noecho() def chooseWhatPipetteToCalibrate(): nonlocal currentPipette stdscr.clear() stdscr.addstr("What pipette should we calibrate?\n") for i,value in enumerate(pipetteNames): stdscr.addstr(str(i+1)+" - " + value+"\n") curses.echo() # Enable echoing of characters s = stdscr.getstr(10,0, 15) stdscr.addstr(s) currentPipette=pipetteNames[int(s)-1] curses.noecho() # This raises ZeroDivisionError when i == 10. def calibratePlunger(): plungerPos=0 plungerTarget="top" plungerInc=1 while 1: stdscr.clear() stdscr.addstr("PLASMOTRON CALIBRATION MODE - PLUNGER MODE\n\n") stdscr.addstr("Keyboard shortcuts:\n\n") stdscr.addstr("T - start calibrating the 'top' position\n") stdscr.addstr("B - start calibrating the 'bottom' position\n") stdscr.addstr("O - start calibrating the 'blowout' position\n") stdscr.addstr("E - start calibrating the 'eject' position\n\n") stdscr.addstr("Numbers 1-8 - choose how far to move\n") stdscr.addstr("Arrow keys - move plunger up/down\n") stdscr.addstr("S - save this position\n") stdscr.addstr("M - move to this position\n") stdscr.addstr("\n\n") stdscr.addstr("V - switch back to container mode\n\n") stdscr.addstr("Currently calibrating plunger position: ") stdscr.addstr( str(plungerTarget)+"\n",curses.A_STANDOUT) stdscr.addstr("with pipette: ") stdscr.addstr(str(currentPipette)+"\n",curses.A_STANDOUT) stdscr.addstr("Movement increment: ") stdscr.addstr(str(plungerInc)+" mm\n",curses.A_STANDOUT) stdscr.addstr("Current position - X: ") stdscr.addstr(str(plungerPos),curses.A_STANDOUT) key=stdscr.getkey() curses.flushinp() if key=="t": plungerTarget="top" if key=="b": plungerTarget="bottom" if key=="o": plungerTarget="blow_out" if key=="e": plungerTarget="drop_tip" if key=="s": equipment[currentPipette].calibrate(plungerTarget) stdscr.clear() stdscr.addstr("plunger position saved") stdscr.refresh() time.sleep(1) if key=="m": equipment[currentPipette].motor.move(equipment[currentPipette]._get_plunger_position(plungerTarget)) plungerPos=equipment[currentPipette]._get_plunger_position(plungerTarget) if key=="h": equipment[currentPipette].home() plungerPos=0 if key=="v": return() try: if int(key) in movementamounts: plungerInc= movementamounts[int(key)] except ValueError: pass if key == "KEY_UP": plungerPos=plungerPos-plungerInc if key == "KEY_DOWN": plungerPos=plungerPos+plungerInc #stdscr.addstr("Key"+key) equipment[currentPipette].motor.move(plungerPos) stdscr.refresh() while 1: stdscr.clear() stdscr.addstr("PLASMOTRON CALIBRATION MODE\n\n") stdscr.addstr("Keyboard shortcuts:\n") stdscr.addstr("Control+C - exit\n") stdscr.addstr("P - choose what pipette to calibrate with\n") stdscr.addstr("C - choose what container to calibrate\n") stdscr.addstr("S - save this position\n") stdscr.addstr("H - home\n") stdscr.addstr("M - move to the currently saved position\n\n") stdscr.addstr("Numbers 1-8 - choose how far to move\n") stdscr.addstr("Arrow keys - move forwards/back/left/right\n") stdscr.addstr("Control + arrow keys or a and z keys - move up/down\n\n") stdscr.addstr("V - switch to calibrate this pipettes plunger/volume\n\n") stdscr.addstr("Currently pipette: ") stdscr.addstr(str(currentPipette)+"\n",curses.A_STANDOUT) stdscr.addstr("going to: ") stdscr.addstr(str(currentlyCalibrating)+"\n",curses.A_STANDOUT) stdscr.addstr("Movement increment: ") stdscr.addstr( str(movementAmount)+" mm\n",curses.A_STANDOUT) stdscr.addstr("Current position - ") stdscr.addstr("X:"+ str(position[0])+",Y:"+ str(position[1])+",Z:"+ str(position[2]),curses.A_STANDOUT) key=stdscr.getkey() curses.flushinp() if key=="c": chooseWhatToCalibrate() if key=="v": calibratePlunger() if key=="p": chooseWhatPipetteToCalibrate() if key=="s": well = equipment[currentlyCalibrating][0] pos = well.from_center(x=0, y=0, z=-1, reference=equipment[currentlyCalibrating]) location = (equipment[currentlyCalibrating], pos) equipment[currentPipette].calibrate_position(location) stdscr.clear() stdscr.addstr("position saved") stdscr.refresh() time.sleep(1) if key=="m": well = equipment[currentlyCalibrating][0] pos = well.from_center(x=0, y=0, z=-1, reference=equipment[currentlyCalibrating]) location = (equipment[currentlyCalibrating], pos) equipment[currentPipette].move_to(location) position=list(robot._driver.get_head_position()["current"]) if key=="h": robot.home() position=list(robot._driver.get_head_position()["current"]) try: if int(key) in movementamounts: movementAmount= movementamounts[int(key)] except ValueError: pass if key == "kUP5" or key =="a": position[2]=position[2]+movementAmount if key == "kDN5" or key =="z": position[2]=position[2]-movementAmount if key == "KEY_LEFT": position[0]=position[0]-movementAmount if key == "KEY_RIGHT": position[0]=position[0]+movementAmount if key == "KEY_UP": position[1]=position[1]+movementAmount if key == "KEY_DOWN": position[1]=position[1]-movementAmount #stdscr.addstr("Key"+key) robot.move_head(x=position[0],y=position[1],z=position[2]) stdscr.refresh()
def print_eb_passes(stdscreen): """The ncruses window for selecting UniClOGS passes. Parameters ---------- stdscreen : window object A windows object initialized by curses.initscr() from the curses """ stdscreen.nodelay(True) stdscreen.scrollok(True) # Enable window scroll stdscreen.refresh() screen_height, screen_width = stdscreen.getmaxyx() # to turn these from size to index screen_width -= 1 screen_height -= 1 screen_title_heigth = 3 boarder_x = 1 boarder_y = 1 panel_space_width = 5 pads_y0 = screen_title_heigth + boarder_y pads_y1 = screen_height - boarder_y # pass pad location on window (left panel) pass_win_x0 = boarder_x pass_win_x1 = pass_win_x0 + 50 # schedule pad location on window (right panel) schedule_win_x0 = pass_win_x1 + 1 + panel_space_width schedule_win_x1 = screen_width - boarder_x try: eb_passes = EBPassTable() pass_pad_height = len(eb_passes) pass_pad_width = len(str(eb_passes[0])) except Exception: no_tle_window(stdscreen, screen_width) return pass_pad = newpad(pass_pad_height+1, pass_pad_width+1) schedule = RequestTable() schedule_pad_height = len(schedule) schedule_pad_width = 0 if schedule_pad_height > 0: schedule_pad_width = len(str(schedule[0])) schedule_pad = newpad(schedule_pad_height+1, schedule_pad_width+1) focus = 0 pass_index = 0 schedule_index = 0 pass_pad.refresh(pass_index, 0, pads_y0, pass_win_x0, pads_y1, pass_win_x1) schedule_pad.refresh( schedule_index, 0, pads_y0, schedule_win_x0, pads_y1, schedule_win_x1 ) # print headers msg = "EB Pass Scheduler (lat {}, long {}, elev {} meters)".format( PSU_LAT, PSU_LONG, PSU_ELEV ) stdscreen.addstr(0, screen_width//2 - len(msg)//2, msg) command_msg = "Arrow Keys: To Move, a: Accept, d: Deny, c: Exit, s: Save and Exit, f: swap focus" stdscreen.addstr(1, screen_width//2 - len(command_msg)//2, command_msg) stdscreen.addstr(3, boarder_x, eb_passes.header) stdscreen.addstr(3, pass_win_x1+panel_space_width, " "+schedule.header) running = True while running is True: key = stdscreen.getch() flushinp() if key == ord('f'): # swap focus onto other pad focus = (focus + 1) % 2 elif key == ord('c'): # clear and quit running = False elif key == ord('s'): # save and quit running = False eb_passes.save() schedule.save() if focus == 0: if key == KEY_UP and pass_index > 0: pass_index -= 1 elif key == KEY_DOWN and pass_index < pass_pad_height-1: pass_index += 1 elif key == ord('a'): # add new uniclogs pass eb_passes[pass_index].add = True for i in range(schedule_pad_height): if overlap(eb_passes[pass_index], schedule[i].pass_data): schedule[i].deny() elif key == ord('d'): # remove new uniclogs pass eb_passes[pass_index].add = False for i in range(schedule_pad_height): if overlap(eb_passes[pass_index], schedule[i].pass_data): schedule[i].undeny() # rebuild display strings for eb_passes for i in range(pass_index, pass_pad_height): if i == pass_index: # current index pass_pad.addstr(i, 0, str(eb_passes[i]), color_pair(1)) elif eb_passes[i].add is True: # added pass_pad.addstr(i, 0, str(eb_passes[i]), color_pair(3)) else: pass_pad.addstr(i, 0, str(eb_passes[i])) # rebuild display strings for schedule for i in range(schedule_index, schedule_pad_height): if len(eb_passes) == 0: continue if overlap(eb_passes[pass_index], schedule[i].pass_data): schedule_pad.addstr(i, 0, str(schedule[i]), color_pair(5)) elif schedule[i].is_approved is False: # denied schedule_pad.addstr(i, 0, str(schedule[i]), color_pair(2)) else: schedule_pad.addstr(i, 0, str(schedule[i])) else: if key == KEY_UP and schedule_index > 0: schedule_index -= 1 elif key == KEY_DOWN and schedule_index < schedule_pad_height-1: schedule_index += 1 # rebuild display strings for eb_passes for i in range(pass_index, pass_pad_height): if len(schedule) == 0: continue if overlap(schedule[schedule_index].pass_data, eb_passes[i]): pass_pad.addstr(i, 0, str(eb_passes[i]), color_pair(4)) elif eb_passes[i].add is True: # added pass_pad.addstr(i, 0, str(eb_passes[i]), color_pair(3)) else: pass_pad.addstr(i, 0, str(eb_passes[i])) # rebuild display strings for schedule for i in range(schedule_index, schedule_pad_height): if i == schedule_index: # current index schedule_pad.addstr(i, 0, str(schedule[i]), color_pair(1)) elif schedule[i].is_approved is False: # denied schedule_pad.addstr(i, 0, str(schedule[i]), color_pair(2)) else: schedule_pad.addstr(i, 0, str(schedule[i])) pass_pad.refresh( pass_index, 0, pads_y0, pass_win_x0, pads_y1, pass_win_x1 ) schedule_pad.refresh( schedule_index, 0, pads_y0, schedule_win_x0, pads_y1, schedule_win_x1 ) sleep(0.01) stdscreen.refresh() stdscreen.scrollok(False) # Enable window scroll stdscreen.nodelay(False)
def check(stdscr=None): if args.monitor: init_colors() stdscr.nodelay(True) while True: force_refresh = False if args.monitor: c = stdscr.getch() curses.flushinp() if c == ord('q'): return force_refresh = (c == ord('r')) global last_lock, last_check if time() - last_check > 5: if len(glob(lockdir + '/*')) > 0: recent_lock = int(path.getmtime(lockdir)) else: recent_lock = 1 last_check = time() if force_refresh or (recent_lock >= last_lock) or (time() - last_lock > args.monitor): # determine what files have been processed and logged as such processedfiles = [] locks = glob(lockdir + '/*lock') nl = len(locks) il = 1 for lock in locks: il += 1 try: flock = open(lock) for l in flock: processedfiles.append(l.strip()) except IOError: pass # determine what samples from previous resubmissions are still running t2_samples = [] t3_samples = [] idle_samples = [] if path.isfile(workdir + '/submission.pkl'): with open(workdir + '/submission.pkl', 'rb') as fpkl: submissions = pickle.load(fpkl) else: submissions = [] for s in submissions: results = s.query_status() t3_samples += results['T3'] t2_samples += results['T2'] idle_samples += results['idle'] t2_files = list(chain.from_iterable([x.files for x in t2_samples])) t3_files = list(chain.from_iterable([x.files for x in t3_samples])) idle_files = list( chain.from_iterable([x.files for x in idle_samples])) # for fancy display outputs = {} data = Output('Data') mc = Output('MC') all_samples = jm.read_sample_config(incfg) filtered_samples = {} merged_samples = {} outfile = open(outcfg, 'w') for name in sorted(all_samples): sample = all_samples[name] out_sample = jm.DataSample(name, sample.dtype, sample.xsec) base_name = sub('_[0-9]+$', '', name) if base_name not in outputs: outputs[base_name] = Output(base_name) output = outputs[base_name] if base_name not in merged_samples: merged_samples[base_name] = jm.DataSample( base_name, sample.dtype, sample.xsec) merged_sample = merged_samples[base_name] to_resubmit = [] for f in sample.files: state = 'missing' if f in processedfiles: state = 'done' elif f in t3_files: state = 't3' elif f in t2_files: state = 't2' elif f in idle_files: state = 'idle' if state == 'missing' or (args.force and state != 'done'): out_sample.add_file(f) merged_sample.add_file(f) output.add(state) if sample.dtype == 'MC': mc.add(state) else: data.add(state) if len(out_sample.files) > 0: filtered_samples[name] = out_sample if args.nfiles < 0: keys = sorted(filtered_samples) for k in keys: sample = filtered_samples[k] if len(sample.files) == 0: continue configs = sample.get_config(-1) for c in configs: outfile.write(c) else: keys = sorted(merged_samples) counter = 0 for k in keys: sample = merged_samples[k] if len(sample.files) == 0: continue configs = sample.get_config(args.nfiles, suffix='_%i') for c in configs: outfile.write(c % (counter, counter)) counter += 1 msg = ['TASK = ' + submit_name] if args.monitor: msg.append('\n') msg.append(header) if args.monitor: msg.append('\n') if args.monitor and len(outputs) + 10 > rows: args.silent = True msg.append(('Too many samples to show in monitoring mode!\n', curses.color_pair(colors['red']))) if not args.silent: for n in sorted(outputs): if args.monitor: msg.extend(outputs[n].str()) else: msg.append(outputs[n].str().strip()) msg.append('') if args.monitor: msg.extend(data.str()) msg.extend(mc.str()) else: msg.append(data.str().strip()) msg.append(mc.str().strip()) msg.append('') if args.monitor: msg.append('Legend: Done=[') msg.append((' ', curses.color_pair(colors['green']))) msg.append('], T3=[') msg.append((' ', curses.color_pair(colors['blue']))) msg.append('], T2=[') msg.append((' ', curses.color_pair(colors['cyan']))) msg.append('], Idle[') msg.append((' ', curses.color_pair(colors['grey']))) msg.append('], Missing=[') msg.append((' ', curses.color_pair(colors['red']))) msg.append(']\n') else: msg.append( 'Legend: Done=\033[0;%im \033[0m, T3=\033[0;%im \033[0m, T2=\033[0;%im \033[0m, Idle=\033[0;%im \033[0m, Missing=\033[0;%im \033[0m, ' % (colors['green'], colors['blue'], colors['cyan'], colors['grey'], colors['red'])) outfile.close() msg.append(strftime('%Y-%m-%d %H:%M:%S')) if args.monitor: msg.append('\n') msg.append('\nMost recent submission:') if args.monitor: msg.extend([x + '\n' for x in query()]) msg.append('\nPress "r" to refresh or "q" to close') else: msg.extend(query()) msg.append('') if args.monitor: stdscr.clear() for m in msg: if type(m) == str: stdscr.addstr(m) else: stdscr.addstr(*m) stdscr.refresh() else: sys.stdout.write('\n'.join(msg)) last_lock = int(time()) if args.submit_only and (mc.missing + data.missing > 0): submit(silent=(args.monitor is not None)) if args.monitor: sleep(1) else: return
def calibratePlunger(): plungerPos=0 plungerTarget="top" plungerInc=1 while 1: stdscr.clear() stdscr.addstr("PLASMOTRON CALIBRATION MODE - PLUNGER MODE\n\n") stdscr.addstr("Keyboard shortcuts:\n\n") stdscr.addstr("T - start calibrating the 'top' position\n") stdscr.addstr("B - start calibrating the 'bottom' position\n") stdscr.addstr("O - start calibrating the 'blowout' position\n") stdscr.addstr("E - start calibrating the 'eject' position\n\n") stdscr.addstr("Numbers 1-8 - choose how far to move\n") stdscr.addstr("Arrow keys - move plunger up/down\n") stdscr.addstr("S - save this position\n") stdscr.addstr("M - move to this position\n") stdscr.addstr("\n\n") stdscr.addstr("V - switch back to container mode\n\n") stdscr.addstr("Currently calibrating plunger position: ") stdscr.addstr( str(plungerTarget)+"\n",curses.A_STANDOUT) stdscr.addstr("with pipette: ") stdscr.addstr(str(currentPipette)+"\n",curses.A_STANDOUT) stdscr.addstr("Movement increment: ") stdscr.addstr(str(plungerInc)+" mm\n",curses.A_STANDOUT) stdscr.addstr("Current position - X: ") stdscr.addstr(str(plungerPos),curses.A_STANDOUT) key=stdscr.getkey() curses.flushinp() if key=="t": plungerTarget="top" if key=="b": plungerTarget="bottom" if key=="o": plungerTarget="blow_out" if key=="e": plungerTarget="drop_tip" if key=="s": equipment[currentPipette].calibrate(plungerTarget) stdscr.clear() stdscr.addstr("plunger position saved") stdscr.refresh() time.sleep(1) if key=="m": equipment[currentPipette].motor.move(equipment[currentPipette]._get_plunger_position(plungerTarget)) plungerPos=equipment[currentPipette]._get_plunger_position(plungerTarget) if key=="h": equipment[currentPipette].home() plungerPos=0 if key=="v": return() try: if int(key) in movementamounts: plungerInc= movementamounts[int(key)] except ValueError: pass if key == "KEY_UP": plungerPos=plungerPos-plungerInc if key == "KEY_DOWN": plungerPos=plungerPos+plungerInc #stdscr.addstr("Key"+key) equipment[currentPipette].motor.move(plungerPos) stdscr.refresh()
def getCmd(self, f, prefix = "> ", history = True): curses.curs_set(1) self.scr.paint() curses.noecho() cmd = "" force = not self.g.force == "" if force: forceCmd = self.g.force self.prefix = prefix self.inwin.clear() self.inwin.addstr(0,0, self.prefix) self.inwin.refresh() ### """ self.xpos = 0 self.hpos = 0 tbox = Textbox(self.inwin.derwin(0,2)) #game.rend.play(False) tbox.stripspaces = 0 cmd = tbox.edit(self.validateCmd)[:].strip().lower() """ ### curses.flushinp() self.xpos = 0 hpos = 0 cmdTemp = '' while 1: char = self.getNext() if char == 0x0a: break elif char == -1: pass elif char == 127 or char == curses.KEY_BACKSPACE or char == 8: if self.xpos > 0 and not force: cmd = cmd[:-1] elif char == 21: if not force: cmd = '' elif char == curses.KEY_UP and history: if hpos > -len(self.history): hpos -= 1 cmd = self.history[hpos] elif char == curses.KEY_DOWN and history: if hpos < -1: hpos += 1 cmd = self.history[hpos] elif hpos == -1: hpos = 0 cmd = cmdTemp elif char == curses.KEY_NPAGE: self.scr.pageUp() elif char == curses.KEY_PPAGE: self.scr.pageDown() elif char >= 32 and char <= 126: self.scr.home() if not force: cmd += chr(char) elif self.xpos < len(forceCmd): cmd += forceCmd[self.xpos] self.xpos += 1 if force and self.xpos >= len(cmd): self.xpos = len(cmd)-1 cmdTemp = cmd self.xpos = self.refreshCmd(cmd) self.inwin.refresh() ### if force: cmd = forceCmd self.inwin.clear() self.inwin.refresh() self.g.force = "" if history: self.history.append(cmd) curses.curs_set(0) return cmd
def main(stdscr): """ Intializing curses and static menu """ # Clear screen stdscr.clear() # pick curses dimensions max_lines = curses.LINES - 1 max_cols = curses.COLS - 1 begin_menu_x = int(max_cols * 0.5) - 10 begin_menu_y = max([int(max_lines * 0.5) - 15, 2]) stdscr.addstr(begin_menu_y, begin_menu_x, "TV Volumen Control:", curses.A_REVERSE) stdscr.addstr(begin_menu_y + 2, begin_menu_x + 3, "1) <- to set down TV volume") stdscr.addstr(begin_menu_y + 3, begin_menu_x + 3, "2) -> to set up TV volume") stdscr.addstr(begin_menu_y + 4, begin_menu_x + 3, "3) Joystick A button to exit") stdscr.addstr(begin_menu_y + 6, begin_menu_x + 4, " /\_/\\") stdscr.addstr(begin_menu_y + 7, begin_menu_x + 3, " (='_' )") stdscr.addstr(begin_menu_y + 8, begin_menu_x + 3, "o(,(\")(\")") begin_win_x = int(max_cols * 0.5) - 15 begin_win_y = max(int(max_lines * 0.5) - 5, 13) height = 5 width = 30 win = curses.newwin(height, width, begin_win_y, begin_win_x) curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_CYAN) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_WHITE) curses.init_pair(3, curses.COLOR_MAGENTA, curses.COLOR_CYAN) refresh_window(win, stdscr) # Emit a short beep curses.beep() while (True): key_str = stdscr.getkey() refresh_window(win, stdscr) if key_str != "\n": win.addstr(3, 2, key_str, curses.color_pair(1) | curses.A_BLINK) if key_str == "KEY_LEFT": win.addstr(2, 8, "VOLUME DOWN! ", curses.color_pair(2) | curses.A_BLINK) win.addstr(3, 15, "<('-'<)", curses.color_pair(3) | curses.A_BLINK) volume_down() curses.beep() sleep(0.5) curses.flushinp() elif key_str == "KEY_RIGHT": win.addstr(2, 8, "VOLUME UP! ", curses.color_pair(2) | curses.A_BLINK) win.addstr(3, 15, "(>'-')>", curses.color_pair(3) | curses.A_BLINK) volume_up() curses.beep() sleep(0.5) curses.flushinp() elif key_str == "KEY_DOWN" or key_str == "KEY_UP": pass else: break win.refresh()
def getInput(self): curses.flushinp() k = self.windows['main']['window'].getch() return k