def initcurse(self): # Check the terminal type. If we fail, then assume that the # terminal has no capabilities. try: curses.setupterm() except: return #self.colors = cursescolors() self.cols = curses.tigetnum('cols') self.lines = curses.tigetnum('lines') self.wfilelines = self.lines-3 self.w = curses.initscr() # fenetre hauteur largeur y x self.wheader = curses.newwin( 1, self.cols, 0, 0) self.wfile = curses.newwin(self.wfilelines, self.cols, 1, 0) self.wfooter = curses.newwin( 1, self.cols, self.lines-2, 0) self.wcmd = curses.newwin( 1, self.cols, self.lines-1, 0) curses.noecho() curses.cbreak() curses.nonl() # permet d'activer la touche enter (code 13) curses.curs_set(0) curses.mousemask(0) curses.mouseinterval(0) self.w.keypad(1) self.w.nodelay(0) self.w.timeout(self.timeout) try: self.initcolors_1() except: self.initcolors_2()
def init_curses(self): self.screen = curses.initscr() curses.noecho() curses.start_color() curses.cbreak() self.screen.keypad(0) curses.curs_set(0)
def init(self): self.window = curses.initscr() self.initted = True self.ymax, self.xmax = self.window.getmaxyx() terminfo = curses.longname() assert '256' in terminfo # your env TERM must be xterm-256color! assert curses.has_colors() curses.start_color() curses.use_default_colors() ctr = 1 for fg in CLRS: for bg in CLRS: if ctr <= curses.COLORS-1 and fg != bg: curses.init_pair(ctr, CLRS[fg], CLRS[bg]) pairs[(fg,bg)] = curses.color_pair(ctr) ctr += 1 curses.meta(1) curses.noecho() curses.cbreak() curses.curs_set(0) curses.delay_output(0) curses.mouseinterval(150) availmask,_ = curses.mousemask(curses.ALL_MOUSE_EVENTS) assert availmask != 0 # mouse must be available! self.window.leaveok(1) self.window.scrollok(0) self.window.keypad(1) if NONBLOCKING: self.window.nodelay(1) self.window.timeout(NONBLOCKING_TIMEOUT) else: self.window.nodelay(0) self.window.timeout(-1) self.window.refresh()
def init_curses(self): """ This initializes the screen for curses useage. It must be called before Curses can be used. """ self.user_marker_pos = 1 # Used with curses self.curses_row_offset = 0 # Used for marking the visible rows on the screen to allow scrolling self.curses_row_offset_store = 0 # Used for storing the row offset when switching from detailed to non-detailed view modes self.curses_detailed = None # Used with curses self.screen = curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_WHITE) size = self.screen.getmaxyx() if size[0] < CURSES_MIN_Y or size[1] < CURSES_MIN_X: curses.endwin() return 1 self.curses_max_rows = size[0] - 2 # Minus 2 for the border on the top and bottom self.curses_max_columns = size[1] - 2 self.screen.border(0) self.screen.addstr(2, TAB_LENGTH, 'EAPeak Capturing Live') self.screen.addstr(3, TAB_LENGTH, 'Found 0 Networks') self.screen.addstr(4, TAB_LENGTH, 'Processed 0 Packets') self.screen.addstr(self.user_marker_pos + USER_MARKER_OFFSET, TAB_LENGTH, USER_MARKER) self.screen.refresh() try: curses.curs_set(1) curses.curs_set(0) except curses.error: # Ignore exceptions from terminals that don't support setting the cursor's visibility pass curses.noecho() curses.cbreak() self.curses_enabled = True self.curses_lower_refresh_counter = 1 return 0
def launch(cmdparser): stdscr = curses.initscr() curses.cbreak() #curses.noecho() curses.echo() stdscr.keypad(1) stdscr.scrollok(True) stdscr.clear() stdscr.refresh() try: # Run your code here io = FakeStdIO(stdscr) sys.stdin = io sys.stdout = io cmdparser.stdout = io cmdparser.stdin = io cmdparser.cmdloop() finally: curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin()
def obtainInput( self, option, cnc ): """ Create a new window to obtain user input. @param String option - Selected option @param CommandAndControl cnc - Command And Control Object @return tuple ( STRING selectedOption, STRING userInput, ) """ screen = curses.newwin( 3, 65, 4, 6 ) screen.box() screen.addstr( 1, 2, " "*59, curses.A_UNDERLINE ) screen.refresh() # Tell curses to allow feedback curses.echo() curses.nocbreak() # Obtain data and assign it for processing data_in = screen.getstr( 1, 2 ) self.process = data_in for optIdentifier, call in self.obj[ 'calls' ].iteritems(): if option == optIdentifier: self.cnc.pushTargets( call ) # Reset curses curses.noecho() curses.cbreak() return ( option, data_in )
def run(self): curses.cbreak() curses.noecho() output.lastline() output.overwriteline() self.prompt() output.scr.refresh() last = None for item in self.data: if item[0] != None: if not self.inahurry: if last != None: curses.napms(600 + len(last)*30) else: curses.napms(1000) self.receive(item[0], item[1]) output.scr.refresh() last = item[1] else: self.send(item[1]) output.openline() self.prompt() output.scr.refresh() last = None output.removelastline()
def __init__(self, tFile): self.tFile = tFile #window setup self.screen = curses.initscr() curses.noecho() curses.cbreak()
def __init__(self, evm): self.evm = evm evm.RegisterListener(self) # first we must create a window object; it will fill the whole screen self.scrn = curses.initscr() # turn off keystroke echo curses.noecho() # keystrokes are honored immediately, rather than waiting for the # user to hit Enter curses.cbreak() self.scrn.keypad(1) self.scrn.nodelay(1) # start color display (if it exists; could check with has_colors()) curses.start_color() curses.mousemask(curses.BUTTON1_PRESSED) curses.curs_set(0) # clear screen self.scrn.clear() i = 1 for color_background in self.list_of_colors: for color_foreground in self.list_of_colors: curses.init_pair(i, color_foreground, color_background) self.mapping[color_foreground, color_background] = i i += 1 # implement the actions done so far (just the clear()) self.scrn.refresh()
def CursesMonitor(dev): stdscr = curses.initscr() curses.cbreak() Console = CursesDisplay(stdscr, dev) Console.monitor() curses.nocbreak() curses.endwin()
def prompt_screen(self, should_prompt): if should_prompt: curses.nocbreak() curses.echo() else: curses.cbreak() curses.noecho()
def setup(): """ sets environment up and creates main window :returns: the main window object """ # setup the console mmask = curses.ALL_MOUSE_EVENTS # for now accept all mouse events main = curses.initscr() # get a window object y,x = main.getmaxyx() # get size if y < 24 or x < 80: # verify minimum size rqmts raise RuntimeError("Terminal must be at least 80 x 24") curses.noecho() # turn off key echoing curses.cbreak() # turn off key buffering curses.mousemask(mmask) # accept mouse events initcolors() # turn on and set color pallet main.keypad(1) # let curses handle multibyte special keys main.clear() # erase everything banner(main) # write the banner mainmenu(main) # then the min and menu main.attron(CPS[RED]) # make the border red main.border(0) # place the border main.attroff(CPS[RED]) # turn off the red curses.curs_set(0) # hide the cursor main.refresh() # and show everything return main
def initializeScreen (self): self.screen = curses.initscr () curses.start_color () curses.noecho () curses.cbreak () (self.screenHeight, self.screenWidth) = self.screen.getmaxyx () pass
def __init__(self): import curses self.key = curses.initscr() curses.cbreak() curses.noecho() self.key.keypad(1) self.key.nodelay(1)
def __init__(self, player_sub): self.player_sub = player_sub # self.sea = sea self.display_screen = '' # setlocale enables UTF chars # see: https://docs.python.org/2/library/curses.html locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') self.strcode = locale.getpreferredencoding() # print(self.strcode) screen = curses.initscr() self.screen = screen # Applications will also commonly need to react to keys instantly, without requiring the Enter key # to be pressed; this is called cbreak mode, as opposed to the usual buffered input mode. curses.cbreak() # Usually curses applications turn off automatic echoing of keys to the screen, in order to be able to read # keys and only display them under certain circumstances. This requires calling the noecho() function. curses.noecho() screen.nodelay(1) curses.curs_set(0) screen.keypad(True) curses.start_color() curses.use_default_colors()
def start_interface(self): # {{{ self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.stdscr.keypad(1) curses.curs_set(0) self.mainloop()
def main(argv): def __call__(self): pass dlog = DebugLog("debug.log") dlog.msg("Logging started\n") stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) curses.start_color() try: wl = WindowLogic(stdscr) wl.start() ci = CommandInterpreter(stdscr, wl) ci.start() except Exception as e: dlog.excpt(e) raise ci.join() dlog.msg("Command Interpreter joined.\n") wl.stop() wl.join() dlog.msg("Thread Fetcher joined.\n") curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() curses.resetty() dlog.msg("Terminal restored.\n")
def initialize(self): """initialize curses, then call setup (at the first time) and resize.""" self.win.leaveok(0) self.win.keypad(1) self.load_mode = False curses.cbreak() curses.noecho() curses.halfdelay(20) try: curses.curs_set(int(bool(self.settings.show_cursor))) except: pass curses.start_color() curses.use_default_colors() self.settings.signal_bind('setopt.mouse_enabled', _setup_mouse) _setup_mouse(dict(value=self.settings.mouse_enabled)) if not self.is_set_up: self.is_set_up = True self.setup() self.win.addstr("loading...") self.win.refresh() self._draw_title = curses.tigetflag('hs') # has_status_line self.update_size() self.is_on = True if self.settings.update_tmux_title: sys.stdout.write("\033kranger\033\\") sys.stdout.flush()
def __enter__(self): # init curses and it's wrapper self.screen = curses.initscr() self.display = Display(self.screen, self.encoding) # create keyhandler self.keyhandler = key.KeyHandler(self.screen) # create view self.view = SelectorView(percol = self) # create command self.command_candidate = SelectorCommand(self.model_candidate, self.view) self.command_action = SelectorCommand(self.model_action, self.view) # suppress SIGINT termination signal.signal(signal.SIGINT, lambda signum, frame: None) # handle special keys like <f1>, <down>, ... self.screen.keypad(True) curses.raw() curses.noecho() curses.cbreak() # Leave newline mode. Make percol distinguish between "C-m" and "C-j". curses.nonl() return self
def __init__(self): self.myscreen = curses.initscr() self.thread = None self.threadName = 'CLI' curses.noecho() curses.cbreak() curses.start_color() self.myscreen.keypad(1) curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) self.myscreen_highlighted = curses.color_pair(1) self.myscreen_normal = curses.A_NORMAL self.menus = { 'title': "Main Menu", 'type': MENU_TYPES.MENU, 'subtitle': "Select an option...", 'options': [ { 'title': "Status", 'type': MENU_TYPES.MENU, 'subtitle': "Select an option..", 'options': [ { 'title': "Media Information", 'type': MENU_TYPES.COMMAND, 'command': 'printMediaInfo' }, { 'title': "Thread Information", 'type': MENU_TYPES.COMMAND, 'command': 'printThreadInfo' } ] } ] } self.commands = { 'printMediaInfo': _printMediaInfo(), 'printThreadInfo': _printThreadInfo() } self.initThread()
def main(): open_message = 'SecLab is open :)' closed_message = 'SecLab is closed :(' authenticate() try: is_open = True stdscr = curses.initscr() curses.cbreak() curses.noecho() stdscr.keypad(1) key = '' stdscr.addstr(5,33,please_wait, curses.A_BLINK) stdscr.refresh() stdscr.addstr(5,33,opened, curses.A_NORMAL) post_status(authenticate(), open_message) while 1: key = stdscr.getch() stdscr.clear() if is_open: stdscr.addstr(5, 33, please_wait, curses.A_BLINK) stdscr.refresh() stdscr.addstr(5, 33, closed, curses.A_NORMAL) post_status(authenticate(), closed_message) else: stdscr.addstr(5,33,please_wait, curses.A_BLINK) stdscr.refresh() stdscr.addstr(5,33,opened, curses.A_NORMAL) post_status(authenticate(), open_message) is_open = not is_open finally: curses.endwin() authenticate().destroy_status(id=LAST_POST_ID)
def main(): stdscr = curses.initscr() curses.nocbreak() mode = NORMAL max_y, max_x = stdscr.getmaxyx() print_before, z = covert("输入一个文件地址:") stdscr.addstr((max_y-1)/2-1, (max_x-1-z)/2-1, print_before) stdscr.move((max_y-1)/2, (max_x-1-z)/2-1) path = "" while True: ch = stdscr.getch() if ch == curses.KEY_ENTER or ch == 10: break else: path += chr(ch) stdscr.addstr(chr(ch)) stdscr.move(0,0) stdscr.clear() stdscr.refresh() with open(path,'r') as f: lines = list(line_resize(f.readlines(), 5)) for line in lines[-20:]: stdscr.addstr(line) curses.cbreak() curses.noecho() while True: ch = stdscr.getch() if ch == 27: break else: string = parse(ch) stdscr.addstr(string)
def __init__(self, wallet, config, app=None): self.stdscr = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN) self.stdscr.keypad(1) self.stdscr.border(0) self.maxy, self.maxx = self.stdscr.getmaxyx() curses.curs_set(0) self.w = curses.newwin(10, 50, 5, 5) self.wallet = wallet self.config = config set_verbosity(False) self.tab = 0 self.pos = 0 self.popup_pos = 0 self.str_recipient = "" self.str_description = "" self.str_amount = "" self.str_fee = "" self.wallet.interface.register_callback('updated', self.refresh) self.wallet.interface.register_callback('connected', self.refresh) self.wallet.interface.register_callback('disconnected', self.refresh) self.wallet.interface.register_callback('disconnecting', self.refresh) self.tab_names = [_("History"), _("Send"), _("Receive"), _("Contacts"), _("Wall")] self.num_tabs = len(self.tab_names)
def init(self): self.screen = curses.initscr() curses.noecho() curses.cbreak() self.screen.keypad(1) try: curses.curs_set(0) except: logging.warning("Cursor hiding is not supported") curses.halfdelay(1) # block for 0.1s if curses.has_colors(): self.colors = True curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK) else: self.colors = False logging.warning("Colors are not supported") logging.info("Console I/O initialized")
def uploadAll(folderSrc, folderDst): global FILESTOUP stdscr = curses.initscr() curses.noecho() curses.cbreak() FILESTOUP = [] dirs = [] createFolder(os.path.dirname(os.path.join(folderDst, folderSrc)), os.path.basename(folderSrc), True) for (dirpath, dirnames, filenames) in os.walk(folderSrc): for dirname in dirnames: dirs.append(os.path.join(dirpath, dirname)) for filename in filenames: FILESTOUP.append(os.path.join(dirpath, filename)) for d in dirs: createFolder(os.path.join(folderDst, os.path.dirname(d)), os.path.basename(d), True) uploadBunch(folderDst, FILESTOUP) return
def __enter__(self): self.stdscr = curses.initscr() curses.cbreak() curses.noecho() self.stdscr.keypad(1) SCREEN_HEIGHT, SCREEN_WIDTH = self.stdscr.getmaxyx() return self.stdscr
def display_playback_progress(): stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) stdscr.nodelay(True) while not done_displaying: stdout.write('\033c\r\n') stdout.write('Ingesting Data :\r\n\n') stdout.write('\tDate Glob : ' + gap_glob + '\r\n') stdout.write('\tMax Playbacks : ' + str(num_playback_threads) + '\r\n\n') stdout.write('\tInstruments:\r\n') list_lock.acquire() for refdes in playback_list.keys(): stdout.write('\t\t' + refdes + ' ' + SPINNER_CHAR[playback_list[refdes]] + '\r\n') playback_list[refdes] += 1 if playback_list[refdes] == SPINNER_CHAR.__len__(): playback_list[refdes] = 0 list_lock.release() if not done_displaying: get_key_input(stdscr) stdscr.refresh() sleep(0.2) stdscr.keypad(False) curses.echo() curses.nocbreak() curses.endwin() stdout.write('\033c\n\r') stdout.write('\tIngest Log File : ' + ingest_log_filename + '\r\n') stdout.write('\tPlayback Log Files : ' + playback_logs_dir + '\r\n\n')
def __init__(self): self.screen = curses.initscr() self.screen.timeout(100) # the screen refresh every 100ms # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # term resize handling size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) self.startcol = int(float(self.x) / 5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() self.lyric = '' self.now_lyric = '' self.tlyric = '' self.storage = Storage() self.config = Config() self.newversion = False
def get_and_use_key_press(self): curses.raw() curses.cbreak() curses.meta(1) self.parent.curses_pad.keypad(1) if self.parent.keypress_timeout: curses.halfdelay(self.parent.keypress_timeout) ch = self._get_ch() if ch == -1: return self.try_while_waiting() else: self.parent.curses_pad.timeout(-1) ch = self._get_ch() # handle escape-prefixed rubbish. if ch == curses.ascii.ESC: #self.parent.curses_pad.timeout(1) self.parent.curses_pad.nodelay(1) ch2 = self.parent.curses_pad.getch() if ch2 != -1: ch = curses.ascii.alt(ch2) self.parent.curses_pad.timeout(-1) # back to blocking mode #curses.flushinp() self.handle_input(ch) if self.check_value_change: self.when_check_value_changed() if self.check_cursor_move: self.when_check_cursor_moved() self.try_adjust_widgets()
def start(self): """Initialize curses. Mostly copied from curses/wrapper.py""" # This might do some good locale.setlocale(locale.LC_ALL, "") # Initialize curses stdscr = curses.initscr() # Turn off echoing of keys, and enter cbreak mode, # where no buffering is performed on keyboard input curses.noecho() curses.cbreak() # In keypad mode, escape sequences for special keys # (like the cursor keys) will be interpreted and # a special value like curses.KEY_LEFT will be returned stdscr.keypad(1) # Start color, too. Harmless if the terminal doesn't have # color; user can test with has_color() later on. The try/catch # works around a minor bit of over-conscientiousness in the curses # module -- the error return from C start_color() is ignorable. try: curses.start_color() curses.use_default_colors() for i in range(1, curses.COLORS): curses.init_pair(i, i, -1) except: LOG.exception("Exception in curses color init") self.stdscr = stdscr
def tradegateLiveData(self): """ This function prints all the textual information about a share. """ try: curses.start_color() curses.use_default_colors() for i in range(0, curses.COLORS): curses.init_pair(i + 1, i, -1) curses.noecho() curses.cbreak() self.stdscr.keypad(True) self.line_counter = 0 share_repository = xsr.xml_share_repository() if len(sys.argv)==1: share_repository.built_up_repository() elif len(sys.argv)==2 and sys.argv[1]=='-w': share_repository.built_up_repository(share_file='watchlist.xml') else: self.my_print('Arguments cannot be processed', colorPair=curses.color_pair(0)) shareCounter = 0 while True: req = urllib2.Request('http://www.tradegate.de/indizes.php?art=aktien&index=DE000A1EXRV0') response = urllib2.urlopen(req) page = response.read() #parse the website for shares tradegateWebsiteShares = re.findall('name_[0-9]*.*isin=.*</td>\s*<td.*bid_[0-9]*.*</td>',page) daxShares = {} #foreach share get the name and current value for tradegateWebsiteShare in tradegateWebsiteShares: tradegateWebsiteShareNameUncout = re.search('">.+<',(re.search('>.+</a></td>', tradegateWebsiteShare).group(0))).group(0) tradegateWebsiteShareName = tradegateWebsiteShareNameUncout[2:len(tradegateWebsiteShareNameUncout)-5] tradegateWebsiteSharePrice = re.search('[0-9]+,[0-9]+', (re.search('>[0-9]+,[0-9]+</td>', tradegateWebsiteShare).group(0))).group(0) daxShares [tradegateWebsiteShareName] = tradegateWebsiteSharePrice.replace(',','.') for xml_share in share_repository.xml_shares: try: shareCounter = shareCounter + 1 currentBid = daxShares.get(xml_share.xml_name.replace('&', '&')) current_win_or_loss = 0 if int(xml_share.xml_units) != 0: if xml_share.xml_buy_price != 'None': current_win_or_loss = (int(xml_share.xml_units) * float(currentBid)) - \ (int(xml_share.xml_units) * float(xml_share.xml_buy_price)) # No stop set at all if xml_share.xml_stop_expiration == 'None': self.my_print('No stop set for ' + xml_share.xml_name, curses.color_pair(4)) else: # Stop is about to expire expirationDate = datetime.date(int(xml_share.xml_stop_expiration.split("-")[0]), int(xml_share.xml_stop_expiration.split("-")[1]), int(xml_share.xml_stop_expiration.split("-")[2])) if expirationDate < (datetime.date.today() + (datetime.timedelta(days=20))): self.my_print('Stop is about to expire for ' + xml_share.xml_name, curses.color_pair(5)) if current_win_or_loss >= 0: self.my_print(str(shareCounter) + ': ' + xml_share.xml_name + ' (' + xml_share.xml_buy_price + ' -> ' + currentBid + ')' + ' => ' + str(current_win_or_loss) + '\n', curses.color_pair(3)) else: self.my_print(str(shareCounter) + ': ' + xml_share.xml_name + ' (' + xml_share.xml_buy_price + ' -> ' + currentBid + ')' + ' => ' + str(current_win_or_loss) + '\n', curses.color_pair(2)) #self.my_print(str(share.get_info()) + '\n') except: with open('error_log.txt', 'a') as error_log: error_log.write(str(traceback.print_exc()) + '\n') error_log.write('xml_share was' + str(xml_share) + '\n') error_log.write('currentBid was ' + str(currentBid) + '\n') self.my_print('xml_share', colorPair=curses.color_pair(0)) self.stdscr.addstr(0, 0, 'Something went terribly wrong => xml_share unknown exception ') self.stdscr.getch() self.my_print(str(datetime.datetime.now()), curses.color_pair(1)) self.stdscr.refresh() time.sleep(15) self.stdscr.clear() shareCounter = 0 self.line_counter = 0 except Exception as e: with open('error_log.txt', 'a') as error_log: error_log.write(str(traceback.print_exc()) + '\n') error_log.write(str(e) + '\n') error_log.write('line_counter was ' + str(self.line_counter) + '\n') self.my_print('unknown exception', colorPair=curses.color_pair(0)) self.my_print(str(e), colorPair=curses.color_pair(0)) self.stdscr.addstr(0, 0, 'Something went terribly wrong => unknown exception ') self.stdscr.getch() finally: #deinit stdscr curses.nocbreak() self.stdscr.keypad(False) curses.echo() curses.endwin()
def light_percentage_callback(value): global wid wid = create_main_menu() pass def create_light_percentage(): return PercentageWidget(light_percentage_callback, "Change brightness") wid = create_main_menu() try: import curses stdscr = curses.initscr() curses.cbreak() stdscr.keypad(1) dial = 0 while True: wid.dial(dial) wid.refresh() key = stdscr.getch() stdscr.addch(20, 25, key) stdscr.refresh() if key == curses.KEY_UP: dial = (dial - 10) % 300 if key == curses.KEY_DOWN: dial = (dial + 10) % 300 if key == curses.KEY_RIGHT: wid.click()
def client(my_color, addr): global lastmove, color #addr = socket.getaddrinfo(addr, 9999) #af, socktype, proto, canonname, sa = res s = socket.socket() s.connect((addr, PORT)) f = s.makefile("rw") to_send = json.dumps(my_color) print("sending", to_send) print(to_send, file=f) f.flush() go = Go(5) l = f.readline() print("history", l) history = json.loads(l) x, y = 0, 0 lastmove = -1, -1 color = "b" stdscr = curses.initscr() curses.noecho() curses.cbreak() curses.nonl() curses.mousemask(curses.BUTTON1_CLICKED) win = curses.newwin(8, 8, 0, 0) win.keypad(True) win.addstr(0, 0, """||||||| | | | | | ' | | | | | |||||||""") win.refresh() for p in history: p[0] += 1 p[1] += 1 lastmove, color, r = play(f, { "b": "black", "w": "white" }[go.current_color], go, win, color, lastmove, *p) win.refresh() color = go.current_color threading.Thread(target=client_file, args=(go, win, f, my_color)).start() while True: win.move(x, y) win.refresh() k = win.getch() if curses.KEY_LEFT == k: y -= 1 elif curses.KEY_RIGHT == k: y += 1 elif curses.KEY_UP == k: x -= 1 elif curses.KEY_DOWN == k: x += 1 elif curses.KEY_ENTER == k or k == 10 or k == 13: lastmove, color, r = play(f, my_color, go, win, color, lastmove, x, y) if r: print(json.dumps([x - 1, y - 1]), file=f) f.flush() elif curses.KEY_MOUSE: o = x, y (id, y, x, z, bstate) = curses.getmouse() lastmove, color, r = play(f, my_color, go, win, color, lastmove, x, y) if r: print(json.dumps([x - 1, y - 1]), file=f) f.flush() if not r: x, y = o else: print("bad key", k) mx, my = win.getmaxyx() x %= 7 y %= 7
def tty_size(debug=False): """ fetches current terminal size Has a few methods under *nix, probably largely redundant. Under windows there is only one, and counts on ctypes returns a dict with keys 'cols' and 'rows'. Values are None when we cannot determine them. You probably want fallback logic around this """ ret = {'cols': None, 'rows': None} if not sys.stdin.isatty( ): # if we don't have a terminal (e.g. running in a service), don't try to run things that will only fail ioctls # There may be better ways to detect this. return ret try: # ioctl (*nix only) import fcntl, termios, struct fd = 1 hw = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) ret['cols'] = hw[1] ret['rows'] = hw[0] except: if debug: raise if ret['rows'] not in (0, None) and ret['cols'] not in (0, None): return ret try: # stty (*nix only) import subprocess p = subprocess.Popen('stty size', stdout=subprocess.PIPE, shell=True) out, _ = p.communicate() out.strip() out = out.split() ret['rows'] = int(out[0], 10) ret['cols'] = int(out[1], 10) except: if debug: raise if ret['rows'] not in (0, None) and ret['cols'] not in (0, None): return ret try: # tput (*nix only) import subprocess p = subprocess.Popen('tput cols', stdout=subprocess.PIPE, shell=True) out, _ = p.communicate() ret['cols'] = int(out.strip(), 10) p = subprocess.Popen('tput lines', stdout=subprocess.PIPE, shell=True) out, _ = p.communicate() ret['rows'] = int(out.strip(), 10) except: if debug: raise if ret['rows'] not in (0, None) and ret['cols'] not in (0, None): return ret try: # piggyback on curses (*nix only, really...) import curses stdscr = curses.initscr() curses.initscr() curses.cbreak() curses.noecho() stdscr.keypad(1) try: height, width = stdscr.getmaxyx() ret['rows'] = height ret['cols'] = width finally: curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() except: if debug: raise if ret['rows'] not in (0, None) and ret['cols'] not in (0, None): return ret try: # from http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/ from ctypes import windll, create_string_buffer # stdin, stdout, stderr handles are -10, -11, -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) ret['cols'] = right - left + 1 ret['rows'] = bottom - top + 1 except: if debug: raise if ret['rows'] not in (0, None) and ret['cols'] not in (0, None): return ret # Last because this won't change on resize (most others will) #shutil.get_terminal_size (py3 only) seems to just do the following try: import os if 'LINES' in os.environ and 'COLUMNS' in os.environ: ret['rows'] = os.environ['LINES'] ret['cols'] = os.environ['COLUMNS'] except: if debug: raise if ret['rows'] not in (0, None) and ret['cols'] not in (0, None): return ret return ret
def main(screen): # Setup of bme280 with SPI spi = busio.SPI(board.SCK, board.MOSI, board.MISO) bme_cs = digitalio.DigitalInOut( board.D5) # Change this according to gpio pin used (cs port on sensor) bme280 = adafruit_bme280.Adafruit_BME280_SPI(spi, bme_cs) # Set pressure at sea level bme280.sea_level_pressure = 1013.25 # Start listening for key press in other thread so ui won't get blocked thread = Thread(target=detect_key_press) thread.start() # Use color for nicer ui curses.start_color() # Screen setup num_rows, num_cols = screen.getmaxyx() # Colors curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK) curses.curs_set(0) # Turn off cursor curses.cbreak() # Turn on cbreak mode (no enter) curses.noecho() # Turn echo off while not key_pressed: # Get current time current_time = time.localtime() current_clock = time.strftime("%H:%M:%S", current_time) # Clean screen screen.erase() # Add data to screen screen.addstr("******* Temp monitor (q to quit) *******\n", curses.color_pair(1)) screen.addstr("Time: ") screen.addstr(current_clock + "\n", curses.color_pair(2)) screen.addstr("Temperature: ") screen.addstr(" %0.1f C\n" % bme280.temperature, curses.color_pair(2)) screen.addstr("Humidity: ") screen.addstr("%0.1f %%\n" % bme280.relative_humidity, curses.color_pair(2)) screen.addstr("Pressure: ") screen.addstr("%0.1f hPa\n" % bme280.pressure, curses.color_pair(2)) screen.addstr("Altitude = ") screen.addstr(" %0.2f meters" % bme280.altitude, curses.color_pair(2)) # Refresh screen to show data screen.refresh() # Check for key press for faster exit if not key_pressed: # Wait for 1 second curses.napms(1000) curses.nocbreak() # Turn off cbreak mode curses.echo() # Turn echo back on curses.curs_set(1) # Turn cursor back on
def main(stdscr): global foc,sqSize,targetFPS #game variables global lab,pos,orient #world variables #init curses screen curses.noecho() #dont echo on getch/str curses.cbreak() #dont wait for \n on getch/str curses.curs_set(0) stdscr.nodelay(True) # dont wait for ch in getch/str stdscr.keypad(True) # map arrow keys to special values bash("xset r rate 50 25") #fasten then keyboard pepeat latency #init sizes depending on lab and window unpackLab(lab) labSize=(len(lab),len(lab[0])) floorSize=(sqSize*labSize[0],sqSize*labSize[1]) screenSize = (scrHei,scrWid) = stdscr.getmaxyx() npos=pos #future pos is pos speed=(0.0,0.0) c=-1 #last ascii read = None cldRad=5.0 #collide radius alphas=calcAlphas(foc,scrWid) #init cam sq=getSquare(pos) map=MMap((9,9),labSize,sq) playLoops=0 while (113!=c): ############# main loop ################# t=time() #start mesure time #read keyboard and change cam data accordingly. c = stdscr.getch() stdscr.getstr() #empty buffer vw=(cos(orient),sin(orient)) accel=False if 260==c: # key left-> turn left orient+=angSpeed elif 261==c: # key right->turn right orient-=angSpeed elif 259==c: #key up -> forward accel=smulV(burst,vw) elif 258==c: #key down -> backward accel=smulV(-burst,vw) stdscr.getstr() #empty buffer bc strangely "backawrd" is not flushed previously. elif 97==c: # "a" to zoom out foc-=0 if foc<=30 else 5 if foc <=100 else 10 alphas=calcAlphas(foc,scrWid) elif 122==c: # "z" to zoom in foc+=5 if foc<=100 else 10 if foc<=250 else 0 alphas=calcAlphas(foc,scrWid) elif 112==c: # "p" to print screen f=open("lab.screenshot.txt","w") f.write(buildScrStr( scrAsClns ,screenSize)) f.close() #acceleration, drag, chk wall collision. pos,speed=move(pos,speed,accel,cldRad) nsq=getSquare(pos) if nsq!=sq: #update mmap according to new square map.setPos(nsq) sq=nsq #calc new screen values and display Lclr,Ldist2=raytraceScene(floorSize,scrWid,alphas,pos,orient,map) scrAsClns=buildScreenAsClns(screenSize,Lclr,Ldist2) #build screen image map.embedClnImage(lab,scrAsClns,(scrHei*2-10,scrWid-10)) #add minimap to image addText(scrAsClns,(1,1),Cl_Wht,printableSpeed(speed)) addText(scrAsClns,(1,scrWid-24),Cl_Wht,printableTime(playLoops/targetFPS)) # will crash after an hour haha! print(buildScrStr( scrAsClns ,screenSize ,stdscr)) stdscr.move(0,0) stdscr.refresh() if not((0<=pos[0]<floorSize[0]) and (0<=pos[1]<floorSize[1])): finalTime=playLoops/targetFPS s="%02i:%5.2f"%divmod(finalTime,60) addText(scrAsClns,(10,3),Cl_Wht,s) addText(scrAsClns,(11,2),Cl_Wht,s) addText(scrAsClns,(11,3),Cl_Wht,s) addText(scrAsClns,(10,2),Cl_Blk,s) print(buildScrStr( scrAsClns ,screenSize ,stdscr)) bash("xset r rate 660 25") #restore default linux keyboard repeat delays 660ms to start repeats at 25 chr per sec c=stdscr.getstr() stdscr.nodelay(False) stdscr.refresh() c=stdscr.getstr() return playLoops+=1 sleep(max(0, (1.0/targetFPS)+t-time() )) stdscr.getstr() stdscr.nodelay(False) bash("xset r rate 660 25") #when exit main loop
current = 'RIGHT' def loop(stdscr): global head,snake_speed randomyx() t1 = threading.Thread(target=listening, args=(head,), name='listenkeyboard') t1.start() while isover(head) is False: draw() head = [ head[0] + pos[current][0] , head[1] + pos[current][1]] snake.append(head) if head[0] == rany and head[1] == ranx: randomyx() snake_speed = snake_speed - 0.01 else: snake.pop(0) time.sleep(snake_speed) stdscr = curses.initscr() curses.noecho() #不输出- - curses.cbreak() #立刻读取:暂不清楚- - curses.start_color() #开启颜色 curses.init_pair(1, curses.COLOR_RED, curses.COLOR_RED)#定义点的颜色 curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLUE) #定义蛇的颜色 #init_pair(n,f,b)修改颜色对n,让f为前景色,b为背景色。颜色对0天生的黑白色,不允许改。 stdscr.keypad(1) #开启keypad stdscr.border() curses.curs_set(0) (y,x) = stdscr.getmaxyx() curses.wrapper(loop) curses.endwin()
def main(stdscr, reading_thread): """Main function displaying the UI.""" # Don't print typed character curses.noecho() curses.cbreak() curses.curs_set(0) # set cursor state to invisible # Set getch() to non-blocking stdscr.nodelay(True) win = init_window(stdscr) while True: # should_redraw is set by the serial thread when new data is available if should_redraw.wait( timeout=0.05 ): # Timeout needed in order to react to user input max_y, max_x = win.getmaxyx() column_width = 100 id_column_start = 2 bytes_column_start = 13 text_column_start = 38 # Compute row/column counts according to the window size and borders row_start = 3 lines_per_column = max_y - (1 + row_start) num_columns = (max_x - 2) // column_width # Setting up column headers for i in range(0, num_columns): win.addstr(1, id_column_start + i * column_width, 'ID') win.addstr(1, 25 + bytes_column_start + i * column_width, 'Bytes') win.addstr(1, 30 + text_column_start + i * column_width, 'Text') win.addstr(3, id_column_start, "Press 'q' to quit") row = row_start + 2 # The first column starts a bit lower to make space for the 'press q to quit message' current_column = 0 # Make sure we don't read the can_messages dict while it's being written to in the reading thread with can_messages_lock: for frame_id in sorted(can_messages.keys()): msg = can_messages[frame_id] msg_bytes = format_data_hex(msg) msg_str = format_data_ascii(msg) # print frame ID in decimal and hex win.addstr(row, id_column_start + current_column * column_width, '%s' % str(frame_id).ljust(5)) win.addstr( row, id_column_start + 18 + current_column * column_width, '%X'.ljust(5) % frame_id) # print frame bytes win.addstr( row, 25 + bytes_column_start + current_column * column_width, msg_bytes.ljust(23)) # print frame text win.addstr( row, 30 + text_column_start + current_column * column_width, msg_str.ljust(8)) row = row + 1 if row >= lines_per_column + row_start: # column full, switch to the next one row = row_start current_column = current_column + 1 if current_column >= num_columns: break win.refresh() should_redraw.clear() c = stdscr.getch() if c == ord('q') or not reading_thread.is_alive(): break elif c == curses.KEY_RESIZE: win = init_window(stdscr) should_redraw.set()
def __init__(self, args=None): # Init args self.args = args # Init windows positions self.term_w = 80 self.term_h = 24 # Space between stats self.space_between_column = 3 self.space_between_line = 2 # Init the curses screen self.screen = curses.initscr() if not self.screen: print(_("Error: Cannot init the curses library.\n")) sys.exit(1) # Set curses options if hasattr(curses, 'start_color'): curses.start_color() if hasattr(curses, 'use_default_colors'): curses.use_default_colors() if hasattr(curses, 'noecho'): curses.noecho() if hasattr(curses, 'cbreak'): curses.cbreak() if hasattr(curses, 'curs_set'): try: curses.curs_set(0) except Exception: pass # Init colors self.hascolors = False if curses.has_colors() and curses.COLOR_PAIRS > 8: self.hascolors = True # FG color, BG color curses.init_pair(1, curses.COLOR_WHITE, -1) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA) curses.init_pair(6, curses.COLOR_RED, -1) curses.init_pair(7, curses.COLOR_GREEN, -1) curses.init_pair(8, curses.COLOR_BLUE, -1) curses.init_pair(9, curses.COLOR_MAGENTA, -1) else: self.hascolors = False if args.disable_bold: A_BOLD = curses.A_BOLD else: A_BOLD = 0 self.title_color = A_BOLD self.title_underline_color = A_BOLD | curses.A_UNDERLINE self.help_color = A_BOLD if self.hascolors: # Colors text styles self.no_color = curses.color_pair(1) self.default_color = curses.color_pair(3) | A_BOLD self.nice_color = curses.color_pair(9) | A_BOLD self.ifCAREFUL_color = curses.color_pair(4) | A_BOLD self.ifWARNING_color = curses.color_pair(5) | A_BOLD self.ifCRITICAL_color = curses.color_pair(2) | A_BOLD self.default_color2 = curses.color_pair(7) | A_BOLD self.ifCAREFUL_color2 = curses.color_pair(8) | A_BOLD self.ifWARNING_color2 = curses.color_pair(9) | A_BOLD self.ifCRITICAL_color2 = curses.color_pair(6) | A_BOLD else: # B&W text styles self.no_color = curses.A_NORMAL self.default_color = curses.A_NORMAL self.nice_color = A_BOLD self.ifCAREFUL_color = curses.A_UNDERLINE self.ifWARNING_color = A_BOLD self.ifCRITICAL_color = curses.A_REVERSE self.default_color2 = curses.A_NORMAL self.ifCAREFUL_color2 = curses.A_UNDERLINE self.ifWARNING_color2 = A_BOLD self.ifCRITICAL_color2 = curses.A_REVERSE # Define the colors list (hash table) for stats self.__colors_list = { 'DEFAULT': self.no_color, 'UNDERLINE': curses.A_UNDERLINE, 'BOLD': A_BOLD, 'SORT': A_BOLD, 'OK': self.default_color2, 'TITLE': self.title_color, 'PROCESS': self.default_color2, 'STATUS': self.default_color2, 'NICE': self.nice_color, 'CAREFUL': self.ifCAREFUL_color2, 'WARNING': self.ifWARNING_color2, 'CRITICAL': self.ifCRITICAL_color2, 'OK_LOG': self.default_color, 'CAREFUL_LOG': self.ifCAREFUL_color, 'WARNING_LOG': self.ifWARNING_color, 'CRITICAL_LOG': self.ifCRITICAL_color } # Init main window self.term_window = self.screen.subwin(0, 0) # Init refresh time if args.time: self.__refresh_time = args.time else: self.__refresh_time = 3 # Init process sort method self.args.process_sorted_by = 'auto' # Catch key pressed with non blocking mode self.term_window.keypad(1) self.term_window.nodelay(1) self.pressedkey = -1
def print_for_all_shares(self): """ This function prints all the textual information about a share. """ try: curses.noecho() curses.cbreak() self.stdscr.keypad(True) self.stdscr.addstr(0, 0, 'pyShares') pretty_print_result = '' share_repository = xsr.xml_share_repository() if len(sys.argv)==1: share_repository.built_up_repository() elif len(sys.argv)==2 and sys.argv[1]=='-w': share_repository.built_up_repository(share_file='watchlist.xml') else: self.my_print('Arguments cannot be processed') shareCounter = 0 for xml_share in share_repository.xml_shares: try: self.stdscr.addstr(0, 0, 'Refreshing - share ' + str(shareCounter)) self.stdscr.refresh() shareCounter = shareCounter + 1 share = Share(xml_share.xml_name) pretty_print_result = pretty_print_result + str(shareCounter) + ': ' + share.get_name() + ': ' self.my_print(str(shareCounter) + ': ' + share.get_name() + '\n') #self.my_print(str(share.get_info()) + '\n') except: with open('error_log.txt', 'a') as error_log: error_log.write(str(traceback.print_exc()) + '\n') error_log.write('xml_share was' + str(xml_share) + '\n') self.my_print('xml_share') self.stdscr.addstr(0, 0, 'Something went terribly wrong => xml_share unknown exception ') self.stdscr.getch() self.my_print('Select a share or press \'e\' to exit') self.stdscr.refresh() next_action = self.wait_for_next_action() while next_action.quit_pyShares == False: xml_share = share_repository.xml_shares[int(next_action.next_share)-1] share = Share(xml_share.xml_name) # user selections start with 1 today = datetime.datetime.now() if (xml_share.xml_trailing_stop_date != 'None') and (xml_share.xml_trailing_stop_date != today.strftime('%Y-%m-%d')): historical_data_maximum = 0.0 historical_data = share.get_historical(xml_share.xml_trailing_stop_date, today.strftime('%Y-%m-%d')) for historical_date in historical_data: if historical_data_maximum < float(historical_date['High']): historical_data_maximum = float(historical_date['High']) #self.my_print('historical_data_maximum: {}\n'\ # .format(historical_data_maximum)) self.stdscr.refresh() if xml_share.xml_trailing_stop_percentage != 'None': possible_trailing_stop = historical_data_maximum - \ (historical_data_maximum * (float(xml_share.xml_trailing_stop_percentage) / 100)) if float(xml_share.xml_trailing_stop_init) < possible_trailing_stop: pretty_print_result = pretty_print_result + \ str(possible_trailing_stop) + '\n' #self.my_print('trailingStop {}\n'\ # .format(possible_trailing_stop)) self.stdscr.refresh() else: pretty_print_result = pretty_print_result + xml_share.xml_trailing_stop_init + '\n' #self.my_print('trailingStop {} - still on init value\n'\ #.format(xml_share.xml_trailing_stop_init), curses.A_BOLD) if xml_share.xml_trailing_stop_absolute != 'None': possible_trailing_stop = historical_data_maximum - \ float(xml_share.xml_trailing_stop_absolute) if float(xml_share.xml_trailing_stop_init) < possible_trailing_stop: pretty_print_result = pretty_print_result + str(possible_trailing_stop) + '\n' else: pretty_print_result = pretty_print_result + xml_share.xml_trailing_stop_init + '\n' if (xml_share.xml_trailing_stop_percentage == 'None') and\ (xml_share.xml_trailing_stop_absolute == 'None'): pretty_print_result = pretty_print_result + 'No stop set\n' else: pretty_print_result = pretty_print_result + \ 'Trailing stop set today => no historical data available yet\n' self.line_counter = self.line_counter + 1 current_win_or_loss = 0 if xml_share.xml_buy_price != 'None': current_win_or_loss = (int(xml_share.xml_units) * float(share.get_price())) - \ (int(xml_share.xml_units) * float(xml_share.xml_buy_price)) self.stdscr.refresh() try: self.plot_candle_stick_diagram(xml_share=xml_share, share=share, current_price=share.get_price(), today_open=share.get_open(), win_or_loss=current_win_or_loss) except: with open('error_log.txt', 'a') as error_log: error_log.write(str(traceback.print_exc()) + '\n') error_log.write('line_counter was ' + str(self.line_counter) + '\n') error_log.write(str(xml_share) + '\n') error_log.write(str(share) + '\n') error_log.write(str(share.get_price) + '\n') error_log.write(str(share.get_open) + '\n') error_log.write(str(current_win_or_loss) + '\n') self.my_print('unknown exception') self.stdscr.addstr(0, 0, 'Something went terribly wrong => unknown exception ') self.stdscr.getch() next_action = self.wait_for_next_action() self.my_print(pretty_print_result, curses.A_BOLD) self.line_counter = self.line_counter + pretty_print_result.count('\n') self.my_print('Press ENTER to exit') self.stdscr.refresh() self.stdscr.getch() except BaseException as base_exception: with open('error_log.txt', 'a') as error_log: error_log.write(str(base_exception) + '\n') error_log.write(str(traceback.print_exc()) + '\n') error_log.write('line_counter was ' + str(self.line_counter) + '\n') self.stdscr.addstr(0, 0, 'Something went terribly wrong ') self.stdscr.getch() except YQLQueryError as yql_err: with open('error_log.txt', 'a') as error_log: error_log.write(str(yql_err) + '\n') error_log.write(str(traceback.print_exc()) + '\n') error_log.write('line_counter was ' + str(self.line_counter) + '\n') self.stdscr.addstr(0, 0, 'Something went terribly wrong => could not receive data from server ') self.stdscr.getch() except YQLResponseMalformedError as yql_err: with open('error_log.txt', 'a') as error_log: error_log.write(str(yql_err) + '\n') error_log.write(str(traceback.print_exc()) + '\n') error_log.write('line_counter was ' + str(self.line_counter) + '\n') self.stdscr.addstr(0, 0, 'Something went terribly wrong => could not receive data from server ') self.stdscr.getch() except: with open('error_log.txt', 'a') as error_log: error_log.write(str(traceback.print_exc()) + '\n') error_log.write('line_counter was ' + str(self.line_counter) + '\n') self.my_print('unknown exception') self.stdscr.addstr(0, 0, 'Something went terribly wrong => unknown exception ') self.stdscr.getch() finally: #deinit stdscr curses.nocbreak() self.stdscr.keypad(False) curses.echo() curses.endwin()
def input(self): curses.cbreak() try: return self._input() finally: curses.halfdelay(50)
def __init__(self, powersupplyclass, calculator, pullsocket): threading.Thread.__init__(self) self.psc = powersupplyclass self.calc = calculator self.pullsocket = pullsocket # Setting parameters self.settings = {} self.settings['halfdelay'] = 1 # Value parameters self.values = {} self.values['status'] = 'Starting' self.values['voltage_mon'] = 0 self.values['voltage_set'] = 0 self.values['current_mon'] = 0 self.values['current_set'] = 0 self.values['power_mon'] = 0 self.values['power_set'] = 0 self.values['temperature_set'] = None self.values['P_error'] = 0 self.values['I_error'] = 0 # Ramp parameters self.ramp = {} # - Instument specific functions: (not used right now) self.ramp['current'] = [0, 0] # [ramp restriction value, slow_start?] self.ramp['voltage'] = [0, 0] # - Ramp control inputs: self.ramp['value'] = 1 # Kelvin per second self.ramp['stop current'] = 6.0 self.ramp['stop temperature'] = 50 self.calc.pid.pid_p = 0.06 # PID proportional term self.calc.pid.pid_i = 0.00001 # PID integration term self.calc.pid.p_min = -1.0 self.ramp[ 'start current'] = 0.0 # Adopt starting current as PID minimum current self.ramp['standby current'] = 1.0 self.ramp['wait'] = 0.1 self.ramp['track'] = 1 # Initialize screens and draw boxes self.screen = curses.initscr() self.win1 = curses.newwin(7, 77, 1, 1) self.win2 = curses.newwin(7, 28, 10, 1) self.win3 = curses.newwin(15, 44, 10, 33) curses.textpad.rectangle(self.screen, 0, 0, 8, 79) curses.textpad.rectangle(self.screen, 9, 0, 19, 30) curses.textpad.rectangle(self.screen, 9, 32, 27, 79) self.screen.refresh() curses.cbreak() curses.noecho() curses.halfdelay(self.settings['halfdelay']) self.quit = False self.menu = { 1: 'Set voltage', 2: 'Set current', 3: 'Run ramp', 4: 'Reset', 5: 'Ramp settings', 6: 'Fitted ramp', 0: 'Quit (Q)' } self.cursor = 0 self.lst = [1, 2, 3, 4, 5, 6, 0] self.update_display() self.update_menu() self.update_values() self.update_socket()
def main(): global screen, config config = ConfigParser.ConfigParser() config.add_section('Camera') for k, v in { '0x00980900': '205', #Brightness '0x00980901': '0', #Contrast '0x00980902': '60', #Saturation '0x0098091b': '25', #Sharpness '0x009a0901': '1', #Disable Auto Exposure '0x009a0902': '20', #Exposure '0x009a090a': '0', #Focus '0x009a090c': '0', #Disable Auto Focus }.items(): config.set('Camera', k, v) config.read([os.path.expanduser('~/.zsl/camera.cfg')]) for k, v in config.items('Camera'): set(k, v) screen = curses.initscr() try: curses.noecho() curses.cbreak() curses.start_color() screen.keypad(1) curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) Menu({ 'TITLE': 'ZSL Stereo v0.1', 'ITEMS': [{ 'TITLE': 'Camera Settings', 'HELP': 'Set the exposure as low as posible to avoid motion-blur. Auto settings not recomended.', 'ITEMS': [{ 'TITLE': 'Brightness', 'SELECTED': config.getint('Camera', '0x00980900'), 'STEPS': range(30, 256, 25), 'ACTION': lambda x: set('0x00980900', x) }, { 'TITLE': 'Contrast', 'SELECTED': config.getint('Camera', '0x00980901'), 'STEPS': range(0, 11), 'ACTION': lambda x: set('0x00980901', x) }, { 'TITLE': 'Saturation', 'SELECTED': config.getint('Camera', '0x00980902'), 'STEPS': range(0, 201, 20), 'ACTION': lambda x: set('0x00980902', x) }, { 'TITLE': 'Sharpness', 'SELECTED': config.getint('Camera', '0x0098091b'), 'STEPS': range(0, 51, 5), 'ACTION': lambda x: set('0x0098091b', x) }, { 'TITLE': 'Exposure', 'SELECTED': config.getint('Camera', '0x009a0902'), 'STEPS': [ -1, 5, 10, 20, 39, 78, 156, 312, 625, 1250, 2500, 5000, 10000, 20000 ], 'ACTION': lambda x: set('0x009a0902', x) }, { 'TITLE': 'Focus\t', 'SELECTED': config.getint('Camera', '0x009a090a'), 'STEPS': [-1] + range(0, 41, 4), 'ACTION': lambda x: set('0x009a090a', x) }] }] }).draw() finally: curses.endwin() if not (os.path.exists(os.path.expanduser('~/.zsl/'))): os.mkdir(os.path.expanduser('~/.zsl/')) with open(os.path.expanduser('~/.zsl/camera.cfg'), 'wb') as configfile: config.write(configfile)
def init_scene(): curses.noecho() curses.curs_set(0) curses.cbreak()
def run(self): """Runs the curses window that captures keypresses. """ curses.cbreak() self.stdscr.keypad(1) self.stdscr.refresh() self.stdscr.addstr(0, 10, 'Arrow keys or WASD to move vehicle. ') self.stdscr.addstr(1, 10, 'PGUP/PGDN to change gear. ') self.stdscr.addstr(2, 10, 'E to stop vehicle. Q to quit program.') self.stdscr.addstr(3, 10, 'Sending to vehicle {}.'.format(self.vehicle_id)) self.stdscr.addstr(self.h + 6, 20, ' ') self.set_velocity() self.set_angle() self.set_gear() key = '' while key != ord('q'): key = self.stdscr.getch() self.stdscr.refresh() if key == ord('e'): self.reset() self.publish_values() elif key == curses.KEY_UP or key == ord('w'): self.velocity = self.velocity + self.velocity_step self.set_velocity() self.publish_values() elif key == curses.KEY_DOWN or key == ord('s'): self.velocity = self.velocity - self.velocity_step self.set_velocity() self.publish_values() elif key == curses.KEY_LEFT or key == ord('a'): self.angle = self.angle - self.angle_step self.set_angle() self.publish_values() elif key == curses.KEY_RIGHT or key == ord('d'): self.angle = self.angle + self.angle_step self.set_angle() self.publish_values() elif key == curses.KEY_NPAGE: self.gear = 1 self.set_gear() self.publish_values() elif key == curses.KEY_PPAGE: self.gear = 2 self.set_gear() self.publish_values() curses.endwin() self.velocity = self.velocity_zero self.angle = self.angle_zero self.gear_command = self.init_gear_command self.publish_values()
""" Move a man through a maze """ import curses STDSCR = curses.initscr() # Initialize curses screen STDSCR.keypad( True) # Enable keypad mode to return special keys, such as the cursor keys curses.noecho() # Turn off automatic echoing of keys to the screen curses.cbreak( ) # React to keys instantly, without requiring the Enter key to be pressed X_CORD = 0 Y_CORD = 0 CHARACTER = '+' def move(direction): """ Update X/Y coordinates to move the character """ global X_CORD global Y_CORD if direction == 'KEY_LEFT': X_CORD -= 1 elif direction == 'KEY_RIGHT': X_CORD += 1 elif direction == 'KEY_UP': Y_CORD -= 1 elif direction == 'KEY_DOWN': Y_CORD += 1
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 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), exc_traceback.tb_lineno)) for line in tbString.split('\n'): print(line) except NameError: ## Last window contents sans attributes print(contents)
def main(stdscr): # see 2/howto/curses.html for info. # look into curses.textpad, which turns a window into a textbox with bindings # look into curses.ascii for easier char handing # the curses magical setup stdscr = curses.initscr() # setup intial window curses.noecho() # dont echo keystrokes curses.cbreak() # dont wait for enter, handle keys immediately stdscr.keypad(1) # use aliases for special keys curses.start_color() #curses.curs_set(0) # supress the blinking cursor # ---------------------- # useful functions # ---------------------- # window.move(y,x) # window.addstr(...) # window.addch(str/int) # window.refresh() # getch([y,x]) - blocks for input, returns keypress as int, with cursor at (y,x) # getstr([y,x], [n]) - get a string of len(n) if specified, with cursor at (y,x) # nodelay(bool) - makes getch() non blocking (ch ? int(ch) : curses.ERR(int(-1))) # notes # ------------ # getstr() only captures ascii printable chars. # # ---------------------- # example input loop # ---------------------- # if python supported switch-case # this would be that! but, elif chain! # # while True: # c = stdscr.getch() # if c == ord('p'): PrintDocument() # elif c == ord('q'): break # Exit the while() # elif c == curses.KEY_HOME: x = y = 0 # elif c > 255: pass # special key. nonprintable char. handle accordingly. # ----------------------- # the forms of addstr # no more mvwaddch(wtf, ...)!!! #------------------------ #addstr(str) # Display str at current location #addstr(str, attr) # Display str at current location with attribute (attr) set #addstr(y, x, str) # Display str at location (y,x) #addstr(y, x, str, attr) # Display str at location (y,x) with attribute (attr) set # ----------------------- # color # ----------------------- # set color pair 1 to be red text, white bg # Note: anything currently printed with that pair will change color as well! # curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) # print something using color pair 1 # stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1)) # ---------------------- # attributes # ---------------------- # curses.A_BLINK # curses.A_BOLD # curses.A_DIM # curses.A_REVERSE # curses.A_STANDOUT # curses.A_UNDERLINE # curses.color_pair(int) # atrributes can be OR'd # ------------------------ # statusbar = (curses.A_REVERSE | curses.color_pair(2)) # window.addstr("woot!", statusbar) # window.refresh() pad = curses.newpad(100, 100) pad.addstr('A' * 10000) pad.refresh(0, 0, 5, 5, 20, 75) x = y = 0 while True: c = stdscr.getch(y, x) if c == ord('q'): break # Exit the while() elif c == curses.KEY_DOWN: y += 1 elif c == curses.KEY_UP and y > 0: y -= 1 elif c == curses.KEY_HOME: x = y = 0 elif c > 255: pass # special key. nonprintable char. handle accordingly. # undo special stuff and close curses curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin()
def curses_start(self): self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.win = curses.newwin(5 + self.window_height, self.window_width, 2, 4)
def do_setup(self): objective = \ """ Objctive: Move disks from first pole to last (stacked smallest on top) one disk at a time. Controls: 'up' key - lift a disk 'down' key - drop a disk 'left' key - switch to left pole 'right' key - switch to right pole || || || || || || || || || ┌--------------------┐ || || | ┌--------┐ | || || | | | | || || | ┌------------┐ |---------------------------------------> || | | | | || || | ┌----------------┐ | || || | | | | || || ┌|--------------------|--------------------------------------------------┐ └------------------------------------------------------------------------┘""" curses.nocbreak() curses.echo() curses.curs_set(2) self.stdscr.clear() self.stdscr.addstr(2, 0, objective) self.stdscr.addstr(2, 0, "-" * 75) self.stdscr.addstr( 0, 6, "toggle machine player (ai)? (type y/n, press enter) ") c = self.stdscr.getch() while c not in (ord('y'), ord('n')): self.stdscr.clear() self.stdscr.addstr(2, 0, objective) self.stdscr.addstr(2, 0, "-" * 75) self.stdscr.addstr( 0, 6, "toggle machine player (ai)? (type y/n, press enter) ") self.stdscr.refresh() c = self.stdscr.getch() self.ai = True if c == ord('y') else False self.stdscr.clear() self.stdscr.addstr(2, 0, objective) self.stdscr.addstr(2, 0, "-" * 75) self.stdscr.addstr( 0, 6, " How many disks? (enter a number from 2 to 9) ") self.stdscr.refresh() c = self.stdscr.getch() while c not in [ord(str(i)) for i in range(2, 10)]: self.stdscr.clear() self.stdscr.addstr(2, 0, objective) self.stdscr.addstr(2, 0, "-" * 75) self.stdscr.addstr( 0, 6, " How many disks? (enter a number from 2 to 9) ") self.stdscr.refresh() c = self.stdscr.getch() for j in range(2, 10): if c == ord(str(j)): break width, height = \ [int(x) for x in os.popen('stty size', 'r').read().split()] self.g = Game(height, width, j) self.num_moves = 0 curses.cbreak() curses.curs_set(0) curses.noecho()
import curses #Terminal display import math #Math Operations ############################# ## ~ START SUDO - DO NOT TOUCH ~ ## sudo_password = '******' command = 'sudo -i'.split() p = Popen(['sudo', '-S'] + command, stdin=PIPE, stderr=PIPE, universal_newlines=True) sudo_prompt = p.communicate(sudo_password + '\n')[1] #################################### ## ~ START CURSES ~ ## stdscr = curses.initscr() #Standard Screen curses.noecho() #Avoids printing input curses.cbreak() #Character broken input curses.curs_set(2) #Set cursor to block stdscr.keypad(1) #Return characters value height = 22 #Terminal window height width = 79 #Terminal window width pad = curses.newpad(10000, 129) #Main Screen ~ Allows scrolling ###################### ## ~ GLOBAL VARIABLES ~ ## prints = 0 ########################## ## ~ FUNCTIONS ~ ## def start(welcome): presentUSB = findUSB() if welcome:
def int10(self): # BIOS video support # https://en.wikipedia.org/wiki/INT_10H # https://stanislavs.org/helppc/idx_interrupt.html # implemented by curses ah = self.ql.reg.ah al = self.ql.reg.al if ah == 0: # time to set up curses # copied from curses.wrapper self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.stdscr.keypad(1) try: curses.start_color() except: pass if al == 0 or al == 1: curses.resizeterm(25, 40) elif al == 2 or al == 3: curses.resizeterm(25, 80) elif al == 4 or al == 5 or al == 9 or al == 0xD or al == 0x13: curses.resizeterm(200, 320) elif al == 6: curses.resizeterm(200, 640) elif al == 8: curses.resizeterm(200, 160) elif al == 0xA or al == 0xE: curses.resizeterm(200, 640) elif al == 0xF: curses.resizeterm(350, 640) elif al == 0x10: curses.resizeterm(350, 640) elif al == 0x11 or al == 0x12: curses.resizeterm(480, 640) else: self.ql.nprint("Exception: int 10h syscall Not Found, al: %s" % hex(al)) raise NotImplementedError() # Quoted from https://linux.die.net/man/3/resizeterm # # If ncurses is configured to supply its own SIGWINCH handler, # the resizeterm function ungetch's a KEY_RESIZE which will be # read on the next call to getch. ch = self._get_ch_non_blocking() if ch == curses.KEY_RESIZE: self.ql.nprint(f"[!] You term has been resized!") elif ch != -1: curses.ungetch(ch) self.stdscr.scrollok(True) if not curses.has_colors(): self.ql.nprint( f"[!] Warning: your terminal doesn't support colors, content might not be displayed correctly." ) # https://en.wikipedia.org/wiki/BIOS_color_attributes # blink support? if curses.has_colors(): for fg in range(16): for bg in range(16): color_pair_index = 16 * fg + bg + 1 if fg not in self.color_pairs: self.color_pairs[fg] = {} curses.init_pair(color_pair_index, COLORS_MAPPING[fg], COLORS_MAPPING[bg]) color_pair = curses.color_pair(color_pair_index) self.color_pairs[fg][bg] = color_pair self.revese_color_pairs[color_pair] = (fg, bg) elif ah == 1: # limited support ch = self.ql.reg.ch if (ch & 0x20) != 0: curses.curs_set(0) elif ah == 2: # page number ignored dh = self.ql.reg.dh # row dl = self.ql.reg.dl # column self.stdscr.move(dh, dl) elif ah == 5: # No idea how to implement, do nothing here. self.ql.reg.al = 0 pass elif ah == 6: al = self.ql.reg.al # lines to scroll ch = self.ql.reg.ch # row of upper-left cornner cl = self.ql.reg.cl # column of upper-left corner dh = self.ql.reg.dh # row of lower right corner dl = self.ql.reg.dl # column of lower righ corner bh = self.ql.reg.bh fg = bh & 0xF bg = (bh & 0xF0) >> 4 y, x = self.stdscr.getmaxyx() cy, cx = self.stdscr.getyx() attr = self._get_attr(fg, bg) if ch != 0 or cl != 0 or dh != y - 1 or dl != x - 1: self.ql.nprint( f"[!] Warning: Partial scroll is unsupported. Will scroll the whole page." ) self.ql.nprint( f"[!] Resolution: {y}x{x} but asked to scroll [({ch},{cl}),({dh}, {dl})]" ) if al != 0: self.stdscr.scroll(al) ny = 0 if cy - al < 0: ny = 0 else: ny = cy - al + 1 if al > y: al = y for ln in range(al): self.stdscr.addstr(ny + ln, 0, " " * x, attr) self.stdscr.move(cy, cx) else: self.stdscr.clear() # Alternate way? #for ln in range(y): # self.stdscr.addstr(ln, 0, " "*x, attr) self.stdscr.bkgd(" ", attr) self.stdscr.move(0, 0) elif ah == 8: if self.stdscr is None: self.ql.reg.ax = 0x0720 else: cy, cx = self.stdscr.getyx() inch = self.stdscr.inch(cy, cx) attr = inch & curses.A_COLOR ch = inch & 0xFF self.ql.reg.al = ch pair_number = curses.pair_number(attr) fg, bg = curses.pair_content(pair_number) orig_fg = REVERSE_COLORS_MAPPING[fg] orig_bg = REVERSE_COLORS_MAPPING[bg] if attr & curses.A_BLINK != 0: orig_bg |= 0b1000 self.ql.reg.ah = ((orig_bg << 4) & orig_fg) elif ah == 0xE: self.ql.dprint(0, f"Echo: {hex(al)} -> {curses.ascii.unctrl(al)}") y, x = self.stdscr.getmaxyx() cy, cx = self.stdscr.getyx() fg = self.ql.reg.bl # https://stackoverflow.com/questions/27674158/how-to-get-color-information-with-mvinch # https://linux.die.net/man/3/inch # https://github.com/mirror/ncurses/blob/master/include/curses.h.in#L1197 # wtf curses... attr = self.stdscr.inch(cy, cx) & curses.A_COLOR if al == 0xa: # \n will erase current line with echochar, so we have to handle it carefully. self.ql.nprint( f"Resolution: {x}x{y}, Cursor position: {cx},{cy}, Going to get a new line." ) if y - 1 == cy: # scroll doesn't affect our cursor self.stdscr.scroll(1) self.stdscr.move(cy, 0) else: self.stdscr.move(cy + 1, 0) else: self.stdscr.echochar(al, attr) else: self.ql.nprint("Exception: int 10h syscall Not Found, ah: %s" % hex(ah)) raise NotImplementedError() if self.stdscr is not None: self.stdscr.refresh()
def init_screen(self): """Initialize Display class.""" self.screen = curses.initscr() # curses.start_color() # curses.use_default_colors() curses.curs_set(2) self.scr_height = curses.LINES #- 1 self.scr_width = curses.COLS #- 1 # # create time window # self.time_win_y_origin = 0 self.time_win_x_origin = 0 self.time_win_height = config.CONSOLE_WIN_TIME_HEIGHT self.time_win_width = self.scr_width # wrapper with lines self.time_win_wrap = curses.newwin(self.time_win_height, self.time_win_width, self.time_win_y_origin, self.time_win_x_origin) self.time_win_wrap.border() # self.time_win_wrap.clear() self.time_win_wrap.refresh() # left panel self.time_win_lt = curses.newwin(self.time_win_height - 2, (self.time_win_width - 2) // 2, self.time_win_y_origin + 1, self.time_win_x_origin + 1) # right panel self.time_win_rt = curses.newwin( self.time_win_height - 2, (self.time_win_width - 3) // 2, self.time_win_y_origin + 1, self.time_win_x_origin + self.time_win_width // 2) # # create status window # self.status_win_y_origin = self.scr_height - config.CONSOLE_WIN_STATUS_HEIGHT self.status_win_x_origin = 0 self.status_win_height = config.CONSOLE_WIN_STATUS_HEIGHT self.status_win_width = self.scr_width #+ 1 # wrapper with lines self.status_win_wrap = curses.newwin(self.status_win_height, self.status_win_width, self.status_win_y_origin, self.status_win_x_origin) self.status_win_wrap.border() # self.status_win_wrap.clear() self.status_win_wrap.refresh() # inner panel self.status_win = curses.newwin(self.status_win_height - 2, self.status_win_width - 2, self.status_win_y_origin + 1, self.status_win_x_origin + 1) self.status_win.scrollok(True) # # create schedule window # self.sched_win_y_origin = self.time_win_height - 1 self.sched_win_x_origin = 0 self.sched_win_height = self.scr_height - self.time_win_height - self.status_win_height + 2 self.sched_win_width = self.scr_width #+ 1 # wrapper with lines self.sched_win_wrap = curses.newwin(self.sched_win_height, self.sched_win_width, self.sched_win_y_origin, self.sched_win_x_origin) self.sched_win_wrap.border() # self.sched_win_wrap.clear() self.sched_win_wrap.refresh() # inner panel self.sched_win = curses.newwin(self.sched_win_height - 2, self.sched_win_width - 4, self.sched_win_y_origin + 1, self.sched_win_x_origin + 2) # self.fix1_vert = self.time_win_y_origin + self.time_win_height self.fix2_vert = self.status_win_y_origin self.corner_fix() # keyboard init # read keys and only display them under certain circumstances curses.noecho() # read keys and only display them under certain circumstances curses.cbreak() # instead of returning special keys as multibyte escape sequences, # return a special values, e.g., curses.KEY_LEFT self.screen.keypad(True) # Make getch() and getkey() non-blocking, i.e, not wait for input self.time_win_rt.nodelay(True)
def main(): GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) GPIO.setup(11, GPIO.OUT) GPIO.setup(13, GPIO.OUT) GPIO.setup(15, GPIO.OUT) screen = curses.initscr() curses.noecho() curses.cbreak() screen.keypad(True) screen.nodelay(True) action_timestamp = time.time() try: while True: char = screen.getch() if char == ord('q'): break elif char == curses.KEY_UP: print('up') GPIO.output(7, False) GPIO.output(11, True) GPIO.output(13, False) GPIO.output(15, True) action_timestamp = time.time() elif char == curses.KEY_DOWN: print('down') GPIO.output(7, True) GPIO.output(11, False) GPIO.output(13, True) GPIO.output(15, False) action_timestamp = time.time() elif char == curses.KEY_RIGHT: print('right') GPIO.output(7, True) GPIO.output(11, False) GPIO.output(13, False) GPIO.output(15, True) action_timestamp = time.time() elif char == curses.KEY_LEFT: print('left') GPIO.output(7, False) GPIO.output(11, True) GPIO.output(13, True) GPIO.output(15, False) action_timestamp = time.time() elif char == 10: print('stop') GPIO.output(7, False) GPIO.output(11, False) GPIO.output(13, False) GPIO.output(15, False) else: if time.time() - action_timestamp > 0.5: print('release') GPIO.output(7, False) GPIO.output(11, False) GPIO.output(13, False) GPIO.output(15, False) action_timestamp = time.time() finally: curses.nocbreak() screen.keypad(0) curses.echo() curses.endwin()
def main(win): global stdscr stdscr = win global my_bg, y_pos, x_pos global treescrn, treescrn2, treescrn3, treescrn4 global treescrn5, treescrn6, treescrn7, treescrn8 global dotdeer0, stardeer0 global lildeer0, lildeer1, lildeer2, lildeer3 global middeer0, middeer1, middeer2, middeer3 global bigdeer0, bigdeer1, bigdeer2, bigdeer3, bigdeer4 global lookdeer0, lookdeer1, lookdeer2, lookdeer3, lookdeer4 global w_holiday, w_del_msg my_bg = curses.COLOR_BLACK # curses.curs_set(0) treescrn = curses.newwin(16, 27, 3, 53) treescrn2 = curses.newwin(16, 27, 3, 53) treescrn3 = curses.newwin(16, 27, 3, 53) treescrn4 = curses.newwin(16, 27, 3, 53) treescrn5 = curses.newwin(16, 27, 3, 53) treescrn6 = curses.newwin(16, 27, 3, 53) treescrn7 = curses.newwin(16, 27, 3, 53) treescrn8 = curses.newwin(16, 27, 3, 53) dotdeer0 = curses.newwin(3, 71, 0, 8) stardeer0 = curses.newwin(4, 56, 0, 8) lildeer0 = curses.newwin(7, 53, 0, 8) lildeer1 = curses.newwin(2, 4, 0, 0) lildeer2 = curses.newwin(2, 4, 0, 0) lildeer3 = curses.newwin(2, 4, 0, 0) middeer0 = curses.newwin(15, 42, 0, 8) middeer1 = curses.newwin(3, 7, 0, 0) middeer2 = curses.newwin(3, 7, 0, 0) middeer3 = curses.newwin(3, 7, 0, 0) bigdeer0 = curses.newwin(10, 23, 0, 0) bigdeer1 = curses.newwin(10, 23, 0, 0) bigdeer2 = curses.newwin(10, 23, 0, 0) bigdeer3 = curses.newwin(10, 23, 0, 0) bigdeer4 = curses.newwin(10, 23, 0, 0) lookdeer0 = curses.newwin(10, 25, 0, 0) lookdeer1 = curses.newwin(10, 25, 0, 0) lookdeer2 = curses.newwin(10, 25, 0, 0) lookdeer3 = curses.newwin(10, 25, 0, 0) lookdeer4 = curses.newwin(10, 25, 0, 0) w_holiday = curses.newwin(1, 27, 3, 27) w_del_msg = curses.newwin(1, 20, 23, 60) try: w_del_msg.addstr(0, 0, "Hit any key to quit") except curses.error: pass try: w_holiday.addstr(0, 0, "H A P P Y H O L I D A Y S") except curses.error: pass # set up the windows for our various reindeer lildeer1.addch(0, 0, ord('V')) lildeer1.addch(1, 0, ord('@')) lildeer1.addch(1, 1, ord('<')) lildeer1.addch(1, 2, ord('>')) try: lildeer1.addch(1, 3, ord('~')) except curses.error: pass lildeer2.addch(0, 0, ord('V')) lildeer2.addch(1, 0, ord('@')) lildeer2.addch(1, 1, ord('|')) lildeer2.addch(1, 2, ord('|')) try: lildeer2.addch(1, 3, ord('~')) except curses.error: pass lildeer3.addch(0, 0, ord('V')) lildeer3.addch(1, 0, ord('@')) lildeer3.addch(1, 1, ord('>')) lildeer3.addch(1, 2, ord('<')) try: lildeer2.addch(1, 3, ord('~')) # XXX except curses.error: pass middeer1.addch(0, 2, ord('y')) middeer1.addch(0, 3, ord('y')) middeer1.addch(1, 2, ord('0')) middeer1.addch(1, 3, ord('(')) middeer1.addch(1, 4, ord('=')) middeer1.addch(1, 5, ord(')')) middeer1.addch(1, 6, ord('~')) middeer1.addch(2, 3, ord('\\')) middeer1.addch(2, 5, ord('/')) middeer2.addch(0, 2, ord('y')) middeer2.addch(0, 3, ord('y')) middeer2.addch(1, 2, ord('0')) middeer2.addch(1, 3, ord('(')) middeer2.addch(1, 4, ord('=')) middeer2.addch(1, 5, ord(')')) middeer2.addch(1, 6, ord('~')) middeer2.addch(2, 3, ord('|')) middeer2.addch(2, 5, ord('|')) middeer3.addch(0, 2, ord('y')) middeer3.addch(0, 3, ord('y')) middeer3.addch(1, 2, ord('0')) middeer3.addch(1, 3, ord('(')) middeer3.addch(1, 4, ord('=')) middeer3.addch(1, 5, ord(')')) middeer3.addch(1, 6, ord('~')) middeer3.addch(2, 3, ord('/')) middeer3.addch(2, 5, ord('\\')) bigdeer1.addch(0, 17, ord('\\')) bigdeer1.addch(0, 18, ord('/')) bigdeer1.addch(0, 19, ord('\\')) bigdeer1.addch(0, 20, ord('/')) bigdeer1.addch(1, 18, ord('\\')) bigdeer1.addch(1, 20, ord('/')) bigdeer1.addch(2, 19, ord('|')) bigdeer1.addch(2, 20, ord('_')) bigdeer1.addch(3, 18, ord('/')) bigdeer1.addch(3, 19, ord('^')) bigdeer1.addch(3, 20, ord('0')) bigdeer1.addch(3, 21, ord('\\')) bigdeer1.addch(4, 17, ord('/')) bigdeer1.addch(4, 18, ord('/')) bigdeer1.addch(4, 19, ord('\\')) bigdeer1.addch(4, 22, ord('\\')) bigdeer1.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer1.addstr(6, 7, "( \\_____( /") # )) bigdeer1.addstr(7, 8, "( ) /") bigdeer1.addstr(8, 9, "\\\\ /") bigdeer1.addstr(9, 11, "\\>/>") bigdeer2.addch(0, 17, ord('\\')) bigdeer2.addch(0, 18, ord('/')) bigdeer2.addch(0, 19, ord('\\')) bigdeer2.addch(0, 20, ord('/')) bigdeer2.addch(1, 18, ord('\\')) bigdeer2.addch(1, 20, ord('/')) bigdeer2.addch(2, 19, ord('|')) bigdeer2.addch(2, 20, ord('_')) bigdeer2.addch(3, 18, ord('/')) bigdeer2.addch(3, 19, ord('^')) bigdeer2.addch(3, 20, ord('0')) bigdeer2.addch(3, 21, ord('\\')) bigdeer2.addch(4, 17, ord('/')) bigdeer2.addch(4, 18, ord('/')) bigdeer2.addch(4, 19, ord('\\')) bigdeer2.addch(4, 22, ord('\\')) bigdeer2.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer2.addstr(6, 7, "(( )____( /") # )) bigdeer2.addstr(7, 7, "( / |") bigdeer2.addstr(8, 8, "\\/ |") bigdeer2.addstr(9, 9, "|> |>") bigdeer3.addch(0, 17, ord('\\')) bigdeer3.addch(0, 18, ord('/')) bigdeer3.addch(0, 19, ord('\\')) bigdeer3.addch(0, 20, ord('/')) bigdeer3.addch(1, 18, ord('\\')) bigdeer3.addch(1, 20, ord('/')) bigdeer3.addch(2, 19, ord('|')) bigdeer3.addch(2, 20, ord('_')) bigdeer3.addch(3, 18, ord('/')) bigdeer3.addch(3, 19, ord('^')) bigdeer3.addch(3, 20, ord('0')) bigdeer3.addch(3, 21, ord('\\')) bigdeer3.addch(4, 17, ord('/')) bigdeer3.addch(4, 18, ord('/')) bigdeer3.addch(4, 19, ord('\\')) bigdeer3.addch(4, 22, ord('\\')) bigdeer3.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer3.addstr(6, 6, "( ()_____( /") # )) bigdeer3.addstr(7, 6, "/ / /") bigdeer3.addstr(8, 5, "|/ \\") bigdeer3.addstr(9, 5, "/> \\>") bigdeer4.addch(0, 17, ord('\\')) bigdeer4.addch(0, 18, ord('/')) bigdeer4.addch(0, 19, ord('\\')) bigdeer4.addch(0, 20, ord('/')) bigdeer4.addch(1, 18, ord('\\')) bigdeer4.addch(1, 20, ord('/')) bigdeer4.addch(2, 19, ord('|')) bigdeer4.addch(2, 20, ord('_')) bigdeer4.addch(3, 18, ord('/')) bigdeer4.addch(3, 19, ord('^')) bigdeer4.addch(3, 20, ord('0')) bigdeer4.addch(3, 21, ord('\\')) bigdeer4.addch(4, 17, ord('/')) bigdeer4.addch(4, 18, ord('/')) bigdeer4.addch(4, 19, ord('\\')) bigdeer4.addch(4, 22, ord('\\')) bigdeer4.addstr(5, 7, "^~~~~~~~~// ~~U") bigdeer4.addstr(6, 6, "( )______( /") # ) bigdeer4.addstr(7, 5, "(/ \\") # ) bigdeer4.addstr(8, 0, "v___= ----^") lookdeer1.addstr(0, 16, "\\/ \\/") lookdeer1.addstr(1, 17, "\\Y/ \\Y/") lookdeer1.addstr(2, 19, "\\=/") lookdeer1.addstr(3, 17, "^\\o o/^") lookdeer1.addstr(4, 17, "//( )") lookdeer1.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer1.addstr(6, 7, "( \\_____( /") # )) lookdeer1.addstr(7, 8, "( ) /") lookdeer1.addstr(8, 9, "\\\\ /") lookdeer1.addstr(9, 11, "\\>/>") lookdeer2.addstr(0, 16, "\\/ \\/") lookdeer2.addstr(1, 17, "\\Y/ \\Y/") lookdeer2.addstr(2, 19, "\\=/") lookdeer2.addstr(3, 17, "^\\o o/^") lookdeer2.addstr(4, 17, "//( )") lookdeer2.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer2.addstr(6, 7, "(( )____( /") # )) lookdeer2.addstr(7, 7, "( / |") lookdeer2.addstr(8, 8, "\\/ |") lookdeer2.addstr(9, 9, "|> |>") lookdeer3.addstr(0, 16, "\\/ \\/") lookdeer3.addstr(1, 17, "\\Y/ \\Y/") lookdeer3.addstr(2, 19, "\\=/") lookdeer3.addstr(3, 17, "^\\o o/^") lookdeer3.addstr(4, 17, "//( )") lookdeer3.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer3.addstr(6, 6, "( ()_____( /") # )) lookdeer3.addstr(7, 6, "/ / /") lookdeer3.addstr(8, 5, "|/ \\") lookdeer3.addstr(9, 5, "/> \\>") lookdeer4.addstr(0, 16, "\\/ \\/") lookdeer4.addstr(1, 17, "\\Y/ \\Y/") lookdeer4.addstr(2, 19, "\\=/") lookdeer4.addstr(3, 17, "^\\o o/^") lookdeer4.addstr(4, 17, "//( )") lookdeer4.addstr(5, 7, "^~~~~~~~~// \\O/") lookdeer4.addstr(6, 6, "( )______( /") # ) lookdeer4.addstr(7, 5, "(/ \\") # ) lookdeer4.addstr(8, 0, "v___= ----^") ############################################### curses.cbreak() stdscr.nodelay(1) while 1: stdscr.clear() treescrn.erase() w_del_msg.touchwin() treescrn.touchwin() treescrn2.erase() treescrn2.touchwin() treescrn8.erase() treescrn8.touchwin() stdscr.refresh() look_out(150) boxit() stdscr.refresh() look_out(150) seas() stdscr.refresh() greet() stdscr.refresh() look_out(150) fromwho() stdscr.refresh() look_out(150) tree() look_out(150) balls() look_out(150) star() look_out(150) strng1() strng2() strng3() strng4() strng5() # set up the windows for our blinking trees # # treescrn3 treescrn.overlay(treescrn3) # balls treescrn3.addch(4, 18, ord(' ')) treescrn3.addch(7, 6, ord(' ')) treescrn3.addch(8, 19, ord(' ')) treescrn3.addch(11, 22, ord(' ')) # star treescrn3.addch(0, 12, ord('*')) # strng1 treescrn3.addch(3, 11, ord(' ')) # strng2 treescrn3.addch(5, 13, ord(' ')) treescrn3.addch(6, 10, ord(' ')) # strng3 treescrn3.addch(7, 16, ord(' ')) treescrn3.addch(7, 14, ord(' ')) # strng4 treescrn3.addch(10, 13, ord(' ')) treescrn3.addch(10, 10, ord(' ')) treescrn3.addch(11, 8, ord(' ')) # strng5 treescrn3.addch(11, 18, ord(' ')) treescrn3.addch(12, 13, ord(' ')) # treescrn4 treescrn.overlay(treescrn4) # balls treescrn4.addch(3, 9, ord(' ')) treescrn4.addch(4, 16, ord(' ')) treescrn4.addch(7, 6, ord(' ')) treescrn4.addch(8, 19, ord(' ')) treescrn4.addch(11, 2, ord(' ')) treescrn4.addch(12, 23, ord(' ')) # star treescrn4.standout() treescrn4.addch(0, 12, ord('*')) treescrn4.standend() # strng1 treescrn4.addch(3, 13, ord(' ')) # strng2 # strng3 treescrn4.addch(7, 15, ord(' ')) treescrn4.addch(8, 11, ord(' ')) # strng4 treescrn4.addch(9, 16, ord(' ')) treescrn4.addch(10, 12, ord(' ')) treescrn4.addch(11, 8, ord(' ')) # strng5 treescrn4.addch(11, 18, ord(' ')) treescrn4.addch(12, 14, ord(' ')) # treescrn5 treescrn.overlay(treescrn5) # balls treescrn5.addch(3, 15, ord(' ')) treescrn5.addch(10, 20, ord(' ')) treescrn5.addch(12, 1, ord(' ')) # star treescrn5.addch(0, 12, ord(' ')) # strng1 treescrn5.addch(3, 11, ord(' ')) # strng2 treescrn5.addch(5, 12, ord(' ')) # strng3 treescrn5.addch(7, 14, ord(' ')) treescrn5.addch(8, 10, ord(' ')) # strng4 treescrn5.addch(9, 15, ord(' ')) treescrn5.addch(10, 11, ord(' ')) treescrn5.addch(11, 7, ord(' ')) # strng5 treescrn5.addch(11, 17, ord(' ')) treescrn5.addch(12, 13, ord(' ')) # treescrn6 treescrn.overlay(treescrn6) # balls treescrn6.addch(6, 7, ord(' ')) treescrn6.addch(7, 18, ord(' ')) treescrn6.addch(10, 4, ord(' ')) treescrn6.addch(11, 23, ord(' ')) # star treescrn6.standout() treescrn6.addch(0, 12, ord('*')) treescrn6.standend() # strng1 # strng2 treescrn6.addch(5, 11, ord(' ')) # strng3 treescrn6.addch(7, 13, ord(' ')) treescrn6.addch(8, 9, ord(' ')) # strng4 treescrn6.addch(9, 14, ord(' ')) treescrn6.addch(10, 10, ord(' ')) treescrn6.addch(11, 6, ord(' ')) # strng5 treescrn6.addch(11, 16, ord(' ')) treescrn6.addch(12, 12, ord(' ')) # treescrn7 treescrn.overlay(treescrn7) # balls treescrn7.addch(3, 15, ord(' ')) treescrn7.addch(6, 7, ord(' ')) treescrn7.addch(7, 18, ord(' ')) treescrn7.addch(10, 4, ord(' ')) treescrn7.addch(11, 22, ord(' ')) # star treescrn7.addch(0, 12, ord('*')) # strng1 treescrn7.addch(3, 12, ord(' ')) # strng2 treescrn7.addch(5, 13, ord(' ')) treescrn7.addch(6, 9, ord(' ')) # strng3 treescrn7.addch(7, 15, ord(' ')) treescrn7.addch(8, 11, ord(' ')) # strng4 treescrn7.addch(9, 16, ord(' ')) treescrn7.addch(10, 12, ord(' ')) treescrn7.addch(11, 8, ord(' ')) # strng5 treescrn7.addch(11, 18, ord(' ')) treescrn7.addch(12, 14, ord(' ')) look_out(150) reindeer() w_holiday.touchwin() w_holiday.refresh() w_del_msg.refresh() look_out(500) for i in range(0, 20): blinkit()
def main(stdscr): global fe global pch global pcl global iph global ipl global rh global rl global flags global i global d global a global b global out_IO global out_IO2 global out_IO3 global out_IO4 global out_IO5 curses.cbreak() #stdscr.keypad(True) stdscr.nodelay(True) #curses.noecho() lcdMem = [] for n in range(0x80): lcdMem.append('\0') lcdData = 0 lcdCycle = 1 lcdCurs = 0 lastLCDE = 0 lastKey = -1 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LSHIFT: send_scancode(0x12) else: letter = pygame.key.name(event.key) if event.key == pygame.K_RETURN: letter = '\n' if event.key == pygame.K_SPACE: letter = ' ' if len(letter) == 1: letter = ord(letter) scancode = 0 for i in range(len(scancodes_lc)): if scancodes_lc[i] == letter: send_scancode(i) break elif event.type == pygame.KEYUP: if event.key == pygame.K_LSHIFT: send_scancode(0xF0) send_scancode(0x12) else: letter = pygame.key.name(event.key) if event.key == pygame.K_RETURN: letter = '\n' if event.key == pygame.K_SPACE: letter = ' ' if len(letter) == 1: letter = ord(letter) scancode = 0 for i in range(len(scancodes_lc)): if scancodes_lc[i] == letter: send_scancode(0xF0) send_scancode(i) break #---MAIN SIM--- #fetch setup fe = 0 #fetch latch i = (ramData() >> 8) & 255 d = ramData() & 255 pcl += 1 if pcl >= 256: pch += 1 pcl = 0 if pch >= 256: pch = 0 #execute setup fe = 1 #execute latch if il() == 0: a = bus() elif il() == 1: b = bus() elif il() == 2: rh = bus() elif il() == 3: if ramWE(): ram[ramAddr() % (2**16)] = (ramData() & 0xFF00) | (bus() & 255) elif il() == 4: if ramWE(): ram[ramAddr() % (2**16)] = (ramData() & 0xFF00) | (bus() & 255) elif il() == 5: rl = bus() elif il() == 6: out_IO = bus() elif il() == 7: flags = bus() elif il() == 8: if bus() & 1: pch = iph pcl = ipl elif il() == 9: ipl = bus() elif il() == 10: iph = bus() elif il() == 11: pass elif il() == 12: out_IO2 = bus() elif il() == 13: out_IO3 = bus() elif il() == 14: out_IO4 = bus() elif il() == 15: out_IO5 = bus() #lcd data = out_IO lcdE = (data >> 1) & 1 lcdRS = data & 1 if not lastLCDE and lcdE: if lcdCycle == 0: lcdData = data & 0xF0 lcdCycle = 1 elif lcdCycle == 1: lcdData |= (data >> 4) & 0x0F if lcdRS: lcdMem[lcdCurs] = chr(lcdData) lcdCurs += 1 #FIXME if lcdCurs == 28: lcdCurs = 40 elif lcdCurs == 68: lcdCurs = 0 elif lcdCurs == 0x80: lcdCurs = 0 else: if lcdData & 0x80 == 0x80: lcdCurs = lcdData & 0x7F elif lcdData == 0x01: for n in range(len(lcdMem)): lcdMem[n] = '\0' lcdCurs = 0 elif lcdData == 0x02 or lcdData == 0x03: lcdCurs = 0 #TODO: other commands lcdCycle = 0 lastLCDE = lcdE #---RENDER--- stdscr.clear() #---KEYBOARD--- #key = stdscr.getch() #if key != -1: # lastKey = key stdscr.addstr(0, 0, str(lastKey)) #---LCD--- lcdX = 40 lcdY = 1 lcdW = 20 lcdH = 4 stdscr.addstr(lcdY, lcdX, "-" * (lcdW + 2)) for n in range(lcdH): stdscr.addstr(lcdY + 1 + n, lcdX, "|" + " " * lcdW + "|") stdscr.addstr(lcdY + 1 + lcdH, lcdX, "-" * (lcdW + 2)) lcdMemAddr = [0x00, 0x40, 0x14, 0x54] for y in range(lcdH): for x in range(lcdW): val = lcdMem[lcdMemAddr[y] + x] if val == 0: val = ' ' stdscr.addstr(lcdY + 1 + y, lcdX + 1 + x, val) #---DEBUG--- debugX = 1 debugY = 1 debugN = -1 if ((pch << 8) | pcl) < len(debugLN): debugN = int(debugLN[((pch << 8) | pcl)]) if debugN in breakpoints: time.sleep(1) stdscr.addstr(debugY, debugX, "pch: %3d pcl: %3d line: %5d" % (pch, pcl, debugN)) stdscr.addstr(debugY + 1, debugX, "iph: %3d ipl: %3d" % (iph, ipl)) stdscr.addstr(debugY + 3, debugX, "rh: %3d rl: %3d" % (rh, rl)) stdscr.addstr( debugY + 5, debugX, "addr: %3d %3d" % ((ramAddr() >> 8) & 255, ramAddr() & 255)) stdscr.addstr( debugY + 6, debugX, "data: %3d %3d" % ((ramData() >> 8) & 255, ramData() & 255)) stdscr.addstr(debugY + 8, debugX, "i: %3d d: %3d" % (i, d)) stdscr.addstr(debugY + 10, debugX, "a: %3d b: %3d flags: %3d" % (a, b, flags)) stdscr.refresh() time.sleep(0.0001)
# This script controls a picar with keyboard input via ssh console. # # version: 1.0 (31.12.2019) import curses # keyboard input import Adafruit_PCA9685 # PCA9685-module from time import sleep import threading import RPi.GPIO as GPIO # GPIO-pin control screen = curses.initscr() # create new screen curses.noecho() # do not echo keyboard input curses.cbreak() # disable return-press for input screen.keypad(True) # enable special-keys GPIO.setwarnings(False) # disable GPIO warnings for console convenience GPIO.setmode(GPIO.BCM) # GPIO instance works in broadcom-memory mode GPIO.setup(21, GPIO.OUT) # step pin is an output pwm = Adafruit_PCA9685.PCA9685(address=0x40, busnum=1) # create PCA9685-object at I2C-port steering_left = 35 # steer to maximum left steering_neutral = 0 # steer to neutral position steering_right = -35 # steer to maximum right pulse_freq = 50 # I2C communication frequency pwm.set_pwm_freq(pulse_freq) # set frequency # make sure the car does not run away on start current_rps = 0 # start without stepper movement current_steering = steering_neutral
def __init__(self): # # Define Constants # attributes self.BOLD = curses.A_BOLD self.UNDERLINE = curses.A_UNDERLINE self.REVERSE = curses.A_REVERSE self.BLINK = curses.A_BLINK # colors self.BLACK = curses.COLOR_BLACK self.RED = curses.COLOR_RED self.GREEN = curses.COLOR_GREEN self.YELLOW = curses.COLOR_YELLOW self.BLUE = curses.COLOR_BLUE self.MAGENTA = curses.COLOR_MAGENTA self.CYAN = curses.COLOR_CYAN self.WHITE = curses.COLOR_WHITE # # Inititalize screen and keyboard self.scr = curses.initscr() # Initializes the 'curses' screen curses.noecho() # Disables echoing of keystrokes curses.cbreak() # Sets keyboard input mode to single character self.scr.nodelay( 1 ) # No wait for getch(). If no input available, returns curses.ERR self.scr.keypad( True ) # Capture non-ASCII keystrokes as cursor KEY values (ex: KEY_BACKSPACE) # # Establish color pairs - init all 64 possible combinations curses.start_color() # Enable colors for fgcolor in range(0, 8): for bgcolor in range(0, 8): pairnum = fgcolor * 8 + bgcolor + 1 curses.init_pair(pairnum, fgcolor, bgcolor) # # Window constants self.SETCOLOR = curses.color_pair(0) self.HEIGHT = self.scr.getmaxyx()[0] - self.scr.getbegyx()[ 0] #Last row of terminal reserved self.WIDTH = self.scr.getmaxyx()[1] - self.scr.getbegyx()[1] - 1 # # Special purpose Key values used by inkey() function self.KEYS = { 9: 'TAB', 10: 'ENTER', 258: 'DOWN', 259: 'UP', 260: 'LEFT', 261: 'RIGHT', 263: 'BACKSPACE', 265: 'NUMLOCK', 266: 'KP/', 267: 'KP*', 268: 'KP-', 269: 'F5', 270: 'F6', 271: 'F7', 272: 'F8', 273: 'F9', 274: 'F10', 275: 'F11', 276: 'F12', 330: 'DELETE', 331: 'INSERT', 338: 'PGDN', 339: 'PGUP', 343: 'KPENTER', 353: 'BACKTAB' }
def main(stdscr): curses.cbreak() curses.noecho() stdscr.keypad(True) _data_manager = DataManager() criteria = show_search_screen(stdscr) height, width = stdscr.getmaxyx() print(f'{height}, {width}') albums_panel = Menu('List of albums', (height, width, 0, 0)) tracks_panel = Menu('List of tracks for the selected album', (height, width, 0, 0)) artist = _data_manager.search_artist(criteria) albums = _data_manager.get_artist_albums(artist['id']) print(f'artist record: {artist}') albums_panel.items = albums albums_panel.init() albums_panel.update() current_panel = albums_panel is_running = True print('start main cycle') key = 0 while is_running: key = stdscr.getch() action = current_panel.handle_events(key) if action is not None: action_result = action() if current_panel == albums_panel and action_result is not None: # switch to track panel _id, uri = action_result tracks = _data_manager.get_album_tracklist(_id) current_panel.hide() current_panel = tracks_panel current_panel.items = tracks current_panel.init() current_panel.show() elif current_panel == tracks_panel and action_result is not None: _id, uri = action_result print(f'selected track {uri}') clear_screen(stdscr) current_panel = albums_panel current_panel.items = albums current_panel.init() current_panel.show() if key == curses.KEY_F2: current_panel.hide() criteria = show_search_screen(stdscr) artist = _data_manager.search_artist(criteria) albums = _data_manager.get_artist_albums(artist['id']) clear_screen(stdscr) current_panel = albums_panel current_panel.items = albums current_panel.init() current_panel.show() if key == 27: is_running = False current_panel.update()
THREAD_LOCK.release() for j in SRAJoints: joint_pubs[j].publish(joint_vals[j]) sleep(NODE_SLEEP_S) finally: SHUTDOWN_REQUESTED = True if __name__ == "__main__": PREVIOUS_SIGTERM_CALLBACK = signal(SIGTERM, exit_gracefully) THREAD_LOCK = Lock() ACTIVE_KEYS = dict() key_listener = keyboard.Listener(on_press=handle_key_press, on_release=handle_key_release) print HELP_MSG scr = initscr() cbreak() noecho() key_listener.start() update_commanded_joint_efforts() key_listener.join() endwin()