def __init__(self, stdscreen, title, debug_console, threadcount):
        self.debug_console = debug_console
        self.threadcount = threadcount
        self.runningthreads = threadcount

        self.title = title

        self.index = []
        self.totalsums = []
        
        self.height = int(terminal.height/2)
        self.width = terminal.width - 2
        
        self.window = stdscreen.subwin(self.height,self.width,1,1)
        self.window.border(0)
        self.window.addstr(0,1,title)
        self.padding = 1 #padding between drawed items
        self.panel = panel.new_panel(self.window)
        self.panel.hide()
        panel.update_panels()
        # Add the Border

        for i in range(0, self.threadcount):
            self.index.append(0)
            self.totalsums.append(0)

        #for the running time
        self.i = 7
        self.start_time = time.time()

        self.debug_console.log("Init of InfoContainer complete")
Пример #2
0
def main(scr):
    h, w = scr.getmaxyx()
    hghts = [h // 3 + (1 if 3 - h % 3 <= i else 0) for i in range(3)]
    pr = 0
    wins = []
    for i in hghts:
        wins.append(newwin(i, w, pr, 0))
        pr += i
    for i in range(3):
        wins[i].box(0, 0)
    panels = [new_panel(i) for i in wins]
    update_panels()
    doupdate()
    x = 0
    while x != ord('q'):
        x = scr.getch()
        wn = wins[0]
        wn.addstr(1, 1, "%x" % x)
        wn.addstr(2, 1, repr([
            i for i in dir(wn) if not i.startswith('__')])[:w-3])
        def_prog_mode()
        endwin()
        print(dir(wn))
        reset_prog_mode()
        wins[0].refresh()
Пример #3
0
    def __init__(self, starty, startx, width, new_win=False):
        self.timer = None
        self.loadding_timer = None
        self.timer_lock = threading.Lock()
        self.loadding_timer_lock = threading.Lock()

        self.loading_interval = 0.4
        self.loading_chars = ['    ', '.   ', '..  ', '... ', '....']
        self.loading_count = 0

        self.width = width - 1

        self.window = curses.newwin(5, width)
        self.window.bkgd(' ', curses.color_pair(2)) #defaultbackground color
        self.progress = 0

        self.new_win = new_win
        self.x=startx
        self.y=starty

        if new_win:
            self.contentwin = curses.newwin(7, width+2)
            self.contentwin.bkgd(' ', curses.color_pair(2)) #Default Window color
            self.contentwin.erase()
            self.contentwin.box()
            self.contentpanel = curses.panel.new_panel(self.contentwin)
            self.contentpanel.move(starty-1, startx-1)
            self.contentpanel.hide()


        self.panel = panel.new_panel(self.window)
        self.panel.move(starty, startx)
        self.panel.hide()
        panel.update_panels()
Пример #4
0
    def __init__(self, screen, title, items, selected, resp):
        self.resp = resp
        self.screen = screen
        self.items = list(items)
        self.position = 0
        if selected:
            for index, item in enumerate(self.items):
                if item.tid == selected.tid:
                    self.position = index
                    break
        self.offset = 0
        self.window = screen.subwin(0, 0)
        self.height = height = self.window.getmaxyx()[0]
        if self.position + 2 >= height:
            self.offset = self.position - 1

        if use_unicode:
            self.title = "┤ {0} (q to cancel) ├".format(title)
        else:
            self.title = "| {0} (q to cancel) |".format(title)

        self.window.keypad(1)
        self.panel = panel.new_panel(self.window)
        self.panel.hide()
        panel.update_panels()
        try:
            curses.curs_set(0)
            curses.use_default_colors()
        except curses.error:
            pass
        self.start()
Пример #5
0
    def display(self):
        self.panel.top()
        self.panel.show()

        self.window.clear()

        self.window.border(0)
        self.window.addstr(0,1,self.title)

        while True:
            self.refresh()
        
            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                if self.position == len(self.items)-1:
                    break
                else:
                    self.items[self.position][1]()
                    break

            elif key == curses.KEY_UP:
                self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

        self.window.clear()
        self.panel.hide()

        panel.update_panels()
        curses.doupdate()
Пример #6
0
    def run (self):
        try:
            curses.curs_set(0)
        except:
            pass

        curses.use_default_colors()        
        self.stdscr.nodelay(1)
        curses.nonl()
        curses.noecho()
     
        self.generate_layout()

        self.update_active = True
        while (True):

            rc = self.wait_for_key_input()
            if not rc:
                break

            self.server_info_panel.draw()
            self.general_info_panel.draw()
            self.control_panel.draw()

            # can be different kinds of panels
            self.stats_panel.panel.top()
            self.stats_panel.draw()

            panel.update_panels(); 
            self.stdscr.refresh()
            sleep(0.01)
Пример #7
0
def draw():
    walls.erase()
    #obj.erase()
    for i in objects:
        if i.objtype=='effect':
            if i.live==0:
                killobj(objects, i)
                continue
            else:
                i.live -= 1
        if inframe(i.y,i.x):
            if i.objtype=='plr':
                walls.addch(i.y,i.x,i.mark, curses.A_REVERSE+curses.color_pair(1))
            elif i.objtype=='bot':
                walls.addch(i.y,i.x,i.mark, curses.A_REVERSE+curses.color_pair(2))
            elif i.objtype=='blt':
                walls.addch(i.y,i.x,i.mark, curses.A_REVERSE+curses.color_pair(3))
            elif i.objtype=='effect':
                walls.addch(i.y,i.x,i.mark, curses.A_REVERSE+curses.color_pair(4))
            else:
                walls.addch(i.y,i.x,i.mark)
    panel.update_panels()
    curses.doupdate()
    if not blast_panel.hidden():
        blast_panel.hide()
Пример #8
0
	def display(self):
		self.panel.top()
		self.panel.show()
		self.window.clear()
		index=0
		while True:
			self.window.refresh()
			panel.update_panels()
			self.window.clear()
			self.panel.hide()
			curses.doupdate()
			self.window.addstr(0, 15, 'é necessário a entrada de um novo valor de pressão', curses.A_NORMAL)
			msg = '%s\t\t<%s> [kPa]' % ( self.items[0],self.values[index])
			self.window.addstr(3, 0, msg, curses.A_REVERSE)
			
			key = self.window.getkey()
			
			if (key == '\n'):
				return self.values[index]
			
			elif key == 'KEY_RIGHT':
				index +=1
				index %= len(self.values)
				
			elif key == 'KEY_LEFT':
				index -=1
				index %= len(self.values)
Пример #9
0
	def __init__(self, text_path, stdscreen, path_flag=True):
		self.window=stdscreen.subwin(0,0)
		self.window.keypad(1)
		self.panel = panel.new_panel(self.window)
		self.panel.hide()
		panel.update_panels()
		self.position = 0
		
		if path_flag:
			# If the flag indicates text_path is a path,
			# the file at that location is read
			with open(text_path,'rb') as txt:
				self.txt = txt.readlines()
		else:
			# Otherwise the text in the text_path parameter
			# is used
			self.txt = text_path
			
		self.txt = '\n'.join(self.txt)
		self.txt+='\nPress any key to return...'
		with open('log.txt','wb') as lg:
			lg.write(self.txt)
		self.window.addstr(self.txt)
		
		self.panel.top()
		self.panel.show()
		self.window.clear()

		key = self.window.getch()
				
		self.window.clear()
		self.panel.hide()
		panel.update_panels()
		curses.doupdate()
Пример #10
0
    def __init__(self, items, stdscreen, IFL):
        if not IFL:
            self.pytify = get_pytify_class_by_platform()()
            self.window = stdscreen.subwin(0, 0)
            self.window.keypad(1)
            self.panel = panel.new_panel(self.window)
            self.panel.hide()
            panel.update_panels()
            self.position = 2
            self.items = items
            self.song_length = len(items) - 1

            self.items.append(' ')
            self.items.append('<UP> and <DOWN> for navigation.')
            self.items.append('<Enter> to select song.')
            self.items.append('<Esc> for search.')
            self.items.append('<LEFT> and <RIGHT> for prev/next song.')
            self.items.append('<SPACEBAR> for play/pause.')
        else:
            self.position = 2
            self.items = items
            self.window = stdscreen.subwin(0, 0)
            self.window.keypad(1)
            self.panel = panel.new_panel(self.window)
            self.panel = panel.new_panel(self.window)
            self.panel.hide()
            panel.update_panels()
            self.pytify = get_pytify_class_by_platform()()
            self.pytify.listen(1)
            self.pytify.play_pause()
            self.panel.hide()
            self.window.clear()
            curses.endwin();
            exit();
Пример #11
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()

        # Play keys.
        play = lambda c: c == ord('p') or c == curses.KEY_ENTER or c == 10 or c == 13

        while True:
            self.window.refresh()
            curses.doupdate()

            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                self.window.addstr(index, 1, str(item), mode)

            key = self.window.getch()

            # Start song
            if play(key):
                self.pytify.listen(int(self.position - 1))

            # Up
            elif key == ord('k') or key == curses.KEY_UP:
                self.navigate(-1)

            # Down
            elif key == ord('j') or key == curses.KEY_DOWN:
                self.navigate(1)

            # Left
            elif key == ord('h') or key == curses.KEY_LEFT:
                self.pytify.prev()

            # Rights
            elif key == ord('l') or key == curses.KEY_RIGHT:
                self.pytify.next()

            # Play/Pause
            elif key == ord(' '):
                self.pytify.play_pause()

            # Search
            elif key == ord('s'):
                break

            # Search
            elif key == ord('q'):
                curses.endwin()
                sys.exit()


        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #12
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()

        while True:
            self.window.refresh()
            curses.doupdate()
            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                msg = '{}'.format(item[0])
                self.window.addstr(index, 2, msg, mode)

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                self.disp_text(ProH.article(self.items[self.position][1]))

            elif key == curses.KEY_UP:
                self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)
            
            elif key == ord('q'):
                break

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #13
0
    def __init__(self, items):
        self.pytify = get_pytify_class_by_platform()()
        self.items = items

        self.position = 2
        self.song_length = len(items) - 1

        # Init curses screen
        self.window = curses.initscr()

        self.window.keypad(1)

        self.panel = panel.new_panel(self.window)
        self.panel.hide()
        panel.update_panels()

        # Show shortcuts
        self.shortcuts()

        # Disable echoing of keys to the screen
        curses.noecho()

        # Disable blinking cursor
        curses.curs_set(False)

        # Use user terminal settings
        curses.endwin()

        # Display window
        self.display()
Пример #14
0
    def run (self):
        try:
            curses.curs_set(0)
        except:
            pass

        curses.use_default_colors()        
        self.stdscr.nodelay(1)
        curses.nonl()
        curses.noecho()
     
        self.generate_layout()

        self.update_active = True
        while (True):

            rc = self.wait_for_key_input()
            if not rc:
                break

            self.update_control()
            self.update_info()

            panel.update_panels(); 
            self.stdscr.refresh()
            sleep(0.1)
Пример #15
0
def handle_form(form, ok_button, cancel_button, ui=None):

    form.add(ok_button, attached=False)
    form.add(cancel_button, attached=False)

    form.render()

    while True:

        panel.update_panels()
        curses.doupdate()

        ret = form.handle_key(form.win.getch())
        form.clean_popup()

        if ret == ok_button.label:

            try:
                return form.validator(form.data, form.config)
            except InvalidOption as e:
                form.show_popup(ErrorPopup(str(e)))
            except NoValidatorError:
                return form.data

        elif ret == cancel_button.label:
            return 'Cancel, nothing to do!'
Пример #16
0
    def display(self):
        """
        Main loop to display the menu. Adds selections from the items variable
        to the list of options, and calls the second parameter of the tuple
        when an item is selected with the enter key.
        """
        self.panel.top()                                                     
        self.panel.show()                                                    
        self.window.clear()                                          
        while 1:
            self.display_items()

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                # Exit selected, so pop current panel off.
                if self.menu_pos == len(self.items)-1:
                    break
                # Perform the action pointed to by the cursor.
                else:
                    self.items[self.menu_pos][1]()
            elif key == ord('w'):
                self.navigate(-1)
            elif key == ord('s'):
                self.navigate(1)
            elif key == curses.KEY_RESIZE:
                pass
            elif key == ord('n'):
                self.scroll_down()
            elif key == ord('p'):
                self.scroll_up()
                
        self.window.clear()                                                  
        self.panel.hide()
        panel.update_panels()
Пример #17
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()

        while True:
            self.window.refresh()
            curses.doupdate()
            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                msg = '%d. %s' % (index, item[0])
                self.window.addstr(1+index, 1, msg, mode)

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                if self.position == len(self.items)-1:
                    break
                else:
                    self.items[self.position][1]()

            elif key == curses.KEY_UP:
                self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #18
0
    def __init__(self, screen):  # {{{
        ## curses options
        curses.curs_set(0)
        cui.color.setColor()
        self.stdscr = screen
        self.stdscr.keypad(1)

        self.settings = settings()
        self.initSrvlst()
        self.initMenus()
        self.focusedWidget = self.srvlst

        panel.update_panels()
        curses.doupdate()

        self.startQuery()

        ## Main Loop -- have to catch all quit events here
        while True:
            key = self.stdscr.getch()

            if key in cui.KEY_QUIT:
                self.quit()
                break

            if key in cui.KEY_LAUNCH and self.focusedWidget == self.srvlst:
                self.launch()
                self.quit()
                break

            else:
                self.handleInput(key)

            curses.doupdate()  # }}}
    def run (self):

        # list of owned ports
        self.owned_ports_list = self.stateless_client.get_acquired_ports()
     
        # data per port
        self.owned_ports = {}

        for port_id in self.owned_ports_list:
            self.owned_ports[str(port_id)] = {}
            self.owned_ports[str(port_id)]['streams'] = {}

            stream_list = self.stateless_client.get_all_streams(port_id)

            self.owned_ports[str(port_id)] = stream_list

        self.update_active = True
        while (True):

            rc = self.wait_for_key_input()
            if not rc:
                break

            self.server_info_panel.draw()
            self.general_info_panel.draw()
            self.control_panel.draw()

            # can be different kinds of panels
            self.stats_panel.panel.top()
            self.stats_panel.draw()

            panel.update_panels()
            self.stdscr.refresh()
            sleep(0.01)
Пример #20
0
	def display(self):
		self.panel.top()
		self.panel.show()
		self.window.clear()

		while True:
			self.window.refresh()
			panel.update_panels()
			self.window.clear()
			self.panel.hide()
			curses.doupdate()
			msg=''
			for index, item in enumerate(self.items):
				if index == self.position:
					mode = curses.A_REVERSE
				else:
					mode = curses.A_NORMAL
				msg = '%d. %s\t' % (index, item)  + str(self.values[index])
				self.window.addstr(1+index, 1, msg, mode)

			#key = self.window.getch()
			key = self.window.getkey()

			if (key == '\n'):
				if(self.position==  len(self.items)-1):
					break;
				else:
					if(self.position == 0): #Estado termodinâmico
						opcoes ={'names':[ 
							['Temperature','Pressure'],
							['Volume','Energy','Enthalpy','Entropy'],
							['exit']
							],
							'unit':[
							['[°C]','[kPa]'],
							['[m³/kg]','[kJ/kg]','[kJ/kg]','[kJ/kg.K]'],
							['']
							]}
						primeira = Termo(opcoes, self.stdscreen)
					else: #ciclo de Rankine
						primeira = Ciclo( self.stdscreen)
					res= primeira.display()
					self.window.refresh()
					panel.update_panels()
					curses.doupdate()

			if key == 'KEY_UP':
				self.navigate(-1)

			elif key == 'KEY_DOWN':
				self.navigate(1)
				
			elif key == 'KEY_RIGHT':
				index +=1
				index %= len(self.values)
				
			elif key == 'KEY_LEFT':
				index -=1
				index %= len(self.values)
Пример #21
0
    def start(self):
        """Initialize the game
        """
        stdscr = self.stdscr
        curses.curs_set(0)

        self.WINHW = (stdscr.getmaxyx()[0] - 1, stdscr.getmaxyx()[1] - 3)
        self.cur = [0, 0]
        self.mapscr = [0, 0]
        self.MAPHW = (99, 99)

        map = curses.newpad(self.MAPHW[0]+1, self.MAPHW[1]+1)

        # curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_CYAN)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_YELLOW)
        curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN)
        # CP_FWHITE_BGRAY = curses.color_pair(1) | curses.A_REVERSE | curses.A_BOLD
        CP1 = curses.color_pair(1)
        CP2 = curses.color_pair(2)
        CP3 = curses.color_pair(3)
        for y in range(0, self.MAPHW[0]):
            for x in range(0, self.MAPHW[1]+1):
                # map.addch(y, x, random.randint(32, 122))
                # if ((x + (y%2) + 2) / 2) % 2:
                #     map.addch(y, x, '.', CP_FWHITE_BGRAY)
                # else: 
                #     map.addch(y, x, '.')
                # grid = ((x + (y%2)*3) / 2) % 3
                grid = (x + (y%2)*2) % 4
                if grid == 3:
                    map.addch(y, x, ' ')
                # elif grid == 0:
                #     map.addch(y, x, '.')
                else:
                    map.addch(y, x, ':')
                # elif grid == 1:
                #     map.addch(y, x, '.')
                # elif grid == 2:
                #     map.addch(y, x, '.')
                self.map = map

        dia = curses.newwin(3, 20, self.WINHW[0]/2, (self.WINHW[1]-20)/2)
        dia.border()
        dia.addstr(1, 4, 'Hello World!')
        dia2 = curses.newwin(5,5,11,40)
        dia2.border()
        self.dia = dia
        self.dia2 = dia2

        self.pdia = cpanel.new_panel(dia)
        self.p2 = cpanel.new_panel(dia2)
        cpanel.update_panels()
        curses.doupdate()

        self._draw_cur()
        # stdscr.refresh()
        self._draw_map()
        self.run()
Пример #22
0
def print_to_input(msg):
	#print ">" + msg to win_input
	if READY:
		win_input.clear()
		print("GUI GOT : {" + msg + "}")
		win_input.addstr(0, 0, msg[:50])
		panel.update_panels()
		curses.doupdate()
Пример #23
0
    def __init__(self, items, stdscreen):
        self.window = stdscreen.subwin(0, 0)
        self.window.keypad(1)
        self.panel = panel.new_panel(self.window)
        self.panel.hide()
        panel.update_panels()

        self.items = items
Пример #24
0
 def hide(self):
     self.__header.clear()
     self.__menu.clear()
     self.__log.clear()
     self.panel_header.hide()
     self.panel_window.hide()
     self.panel_log.hide()
     panel.update_panels()
     curses.doupdate()
Пример #25
0
def print_to_stat(msg):
	#print ">" + msg to win_status
	if READY:
		win_status.clear()
		win_status.addstr(0, 0, msg[:50])
		panel.update_panels()
		curses.doupdate()
	else:
		print_to_scr(msg)
Пример #26
0
	def __init__(self, items, stdscreen):
		self.window = stdscreen.subwin(0,0)
		self.window.keypad(1)
		self.panel = panel.new_panel(self.window)
		self.panel.hide()
		panel.update_panels()
		self.position = 0
		self.items = items
		self.items.append(('exit', 'exit'))
Пример #27
0
 def RunUI(self, stdscr):
     win = curses.newwin(8,8,1,1)
     pan = panel.new_panel(win)
     pan.show()
     while 1:
         stdscr.addstr(0, 0, "Current mode: Typing mode", curses.A_REVERSE)
         panel.update_panels()
         curses.doupdate()
         stdscr.refresh()
Пример #28
0
	def __init__(self, data, stdscreen):
		self.window = stdscreen.subwin(0,0)
		self.window.keypad(1)
		self.panel = panel.new_panel(self.window)
		self.panel.hide()
		panel.update_panels()

		self.position = 0
		self.items = ['Pressure']
		self.values=data
Пример #29
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()
        self.confirmed = False
        self.cancel=False
        self.breakout=False
        self.init_display()

        while True:
            if self.breakout:
                self.confirmed = True
                break
            if self.cancel:
                break
            self.window.refresh()
            curses.doupdate()

            mode = curses.A_NORMAL
            msg = " {} ".format(self.title)
            self.write(1, 1, msg, mode, 1)
            y, x = self.window.getmaxyx()
            self.write(2, 0, "_"*x, curses.A_NORMAL)
            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL
                if self.submenu < 2:
                    msg = " {}. {} ".format(index, item[0])
                else:
                    msg = " {} ".format(item[0])
                self.write(3+index, 1, msg, mode)

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                #if self.position == len(self.items)-1:
                #    break
                #else:
                if len(self.items[self.position])>2:
                    self.items[self.position][1](self.items[self.position][2:])
                else:
                    self.items[self.position][1]()

            elif key == curses.KEY_UP:
                self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #30
0
    def __init__(self, items, stdscreen):
        self.window = stdscreen.subwin(0,0)
        self.window.keypad(1)
        self.panel = panel.new_panel(self.window)
        self.panel.hide()
        panel.update_panels()

        self.position = 0
        self.items = items
        self.items.append(('==== OUTPUT ==== (press "q" for exit)','nothing'))
        self.items.append(('>','nothing'))
Пример #31
0
 def hide(self):
   #self.window.clear() #causes blink
   self.window.erase()
   self.panel.hide()
   panel.update_panels()
   curses.doupdate()
Пример #32
0
 def __exit__(self, _type, value, traceback):
     self.screen.clear()
     self.panel.hide()
     panel.update_panels()
     curses.doupdate()
Пример #33
0
def selectEvent(layer):
    try:
        update_panel.show()
        panel.update_panels()
        curses.doupdate()
    except NameError:
        status("update_panel do not exist")

    global subm_name
    global subm_val
    global selectS
    global info_on
    if layer == 0:  #root
        act = "root"
    elif layer == 1:  #window
        act = window_act[select]
    elif layer == 2:  #menu
        act = menu_act[selectM]
    elif layer == 3 and not info_on:  #submenu
        if selectS == 1:
            act = "save"
        else:
            act = "none"
    elif layer == 3 and info_on:  #info window
        act = "no info"
    else:
        act = "none"

    if act == "none":
        return True, 0
    elif act == "root":
        return True, 1
    elif act == "menu":
        menu_panel.show()
        return True, 1
    elif act == "back":
        menu_panel.hide()
        return True, -1
    elif act == "chng":
        selectS = 0
        subm_name = menu_data[selectM]
        subm_val = params[subm_name]
        subm_panel.show()
        return True, 1
    elif act == "save":
        params[subm_name] = subm_val
        subm_panel.hide()
        status("%s saved to %s" % (str(subm_val), subm_name))
        return True, -1
    elif act == "stop":
        return False, 0
    elif act == "info":
        info_on = True
        info_panel.show()
        return True, 2
    elif act == "no info":
        info_on = False
        info_panel.hide()
        return True, -2
    else:
        return False, 0
Пример #34
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()
        self.update()

        while True:
            self.window.clear()
            self.window.refresh()
            curses.doupdate()
            ### show the list of xpinfo files ###
            for index, item in enumerate(self.xpinfo_file_list):
                if index == self.position:
                    mode = curses.A_STANDOUT
                else:
                    mode = curses.A_NORMAL
                line = "{}".format(item)
                if len(line) >= self.width:
                    line = line[:self.width - 1]
                ### only add lines in the slice ###
                if self.slice_start <= index <= self.slice_end:
                    self.window.addstr(1 + (index - self.slice_start), 2, line,
                                       mode)
            key = self.window.getch()
            if key in [ord("b"), ord("B")]:
                break
            elif key in [curses.KEY_ENTER, ord("\n")]:
                if self.position == len(self.xpinfo_file_list) - 1:
                    break
                else:
                    logger.debug("XPINFO: start processing {}".format(
                        self.xpinfo_file_list[self.position]))
                    serial_nbr_set = set(serialnbr_dict.values())
                    ldev_dict = {}
                    hostgroup_dict = {}
                    for serial_nbr in serial_nbr_set:
                        ldev_dict[serial_nbr] = set()
                    ### process the selected xpinfo file ###
                    with open(
                            "{}/{}".format(
                                self.xpinfo_dir,
                                self.xpinfo_file_list[self.position]),
                            "rt") as f:
                        xpinfo_file_reader = csv.reader(f,
                                                        delimiter=",",
                                                        quotechar="'")
                        for row in xpinfo_file_reader:
                            if len(row) > 8:
                                hostname = row[0]
                                device_name = row[1]
                                ldev_nbr = xp7.standard_format_ldev(row[5])
                                serial_nbr = int(row[8])
                                logger.debug(
                                    "XPINFO: got S/N {} LDEV {} from xpinfo file"
                                    .format(serial_nbr, ldev_nbr))
                                if serial_nbr in ldev_dict:
                                    ldev_dict[serial_nbr].add(ldev_nbr)
                                    logger.debug(
                                        "XPINFO: known S/N, added to ldev_dict, now at {} elements"
                                        .format(len(ldev_dict[serial_nbr])))
                            else:
                                logger.error(
                                    "XPINFO: line too short to be valid, skipping {}"
                                    .format(row))
                    ### translate ldev to hostgroup ###
                    for serial_nbr in ldev_dict:
                        box_name = serial_to_name_dict[serial_nbr]
                        if not box_name in hostgroup_dict:
                            hostgroup_dict[box_name] = set()
                        for ldev_nbr in ldev_dict[serial_nbr]:
                            for hostgroup_name in box_dict[
                                    box_name].get_ldev_hostgroups(ldev_nbr):
                                hostgroup_dict[box_name].add(hostgroup_name)
                    ### add found hostgroups to the selection ###
                    for box_name in hostgroup_dict:
                        for hostgroup_name in hostgroup_dict[box_name]:
                            logger.debug(
                                "XPINFO processing: adding {}-{} to the selection"
                                .format(box_name, hostgroup_name))
                            self.selection.add((box_name, hostgroup_name))
            elif key == curses.KEY_UP:
                self.navigate(-1)
            elif key == curses.KEY_DOWN:
                self.navigate(1)
            elif key == curses.KEY_PPAGE:
                self.navigate(-10)
            elif key == curses.KEY_NPAGE:
                self.navigate(10)

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #35
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()

        while True:
            self.window.refresh()

            if self.title:
                sx = 2
                self.window.addstr(1, 1, self.title, curses.color_pair(1))
            else:
                sx = 1

            curses.doupdate()
            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                if self.type == 'edit' and index < len(self.items) - 1:
                    msg = '%2d. %20s: %-30s' % (
                        index, item['field'], item['value'].replace('\n', ' ')
                        if len(item['value']) <= 30 else
                        item['value'].replace('\n', ' ')[0:25] + '...')
                    self.window.addstr(sx + index, 1, msg, mode)
                else:
                    msg = '%2d. %s' % (index, item['field'])
                    self.window.addstr(sx + index, 1, msg, mode)

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                if self.position == len(
                        self.items) - 1 and self.type != 'edit':
                    break

                elif self.position < len(
                        self.items) - 1 and self.type != 'edit':
                    self.items[self.position]['function'](self)

                else:
                    if self.position == len(self.items) - 1:
                        # save changes
                        if save_changes(self):
                            break
                    else:
                        # enter edit mode
                        self.enter_edit_mode()

            elif key == curses.KEY_UP:
                self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

            elif key == 27:  # escape (cancel)
                break
            else:
                if self.type == 'edit':
                    # edit mode, hightlight the field and replace text
                    if key == 4:  # control + D
                        # ask if user want to delete record
                        self.window.addstr(
                            sx + len(self.items), 1,
                            'Are you sure you want to delete this record?',
                            curses.color_pair(2))
                        key = self.window.getch()
                        if chr(key).upper() == 'Y':
                            # delete record
                            delete_record(self)
                            break
                    else:
                        if key < 256:
                            self.enter_edit_mode(chr(key))

                    self.window.clear()

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #36
0
    def display(self, stdscr):
        self.panel.top()
        self.panel.show()
        stdscr.clear()

        # Temporary solution to warn the user
        self.exit_if_terminal_size_is_to_small()

        # Play keys.
        play = lambda c: c == ord(
            'p') or c == curses.KEY_ENTER or c == 10 or c == 13

        while True:
            stdscr.refresh()
            curses.doupdate()

            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                stdscr.addstr(index, 1, str(item), mode)

            key = stdscr.getch()

            # Start song
            if play(key):
                self.pytify.listen(int(self.position - 1))

            # Up
            elif key == ord('k') or key == curses.KEY_UP:
                self.navigate(-1)

            # Down
            elif key == ord('j') or key == curses.KEY_DOWN:
                self.navigate(1)

            # Left
            elif key == ord('h') or key == curses.KEY_LEFT:
                self.pytify.prev()

            # Rights
            elif key == ord('l') or key == curses.KEY_RIGHT:
                self.pytify.next()

            # Play/Pause
            elif key == ord(' '):
                self.pytify.play_pause()

            # Add song to mellow playlist
            elif key == ord('m'):
                self.pytify.add_mellow()

            # Add song to favorite playlist
            elif key == ord('f'):
                self.pytify.add_favorite()

            # Search
            elif key == ord('s'):
                break

            # Quit
            elif key == ord('q'):
                curses.endwin()
                sys.exit()

        stdscr.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #37
0
 elif tiles[curTile] == 13:
     curLine = 5
 elif tiles[curTile] == 12 or tiles[curTile] == 11 or tiles[curTile] == 10:
     curLine = 4
 #draw dashboard
 log("Spd: %d Gas: %d Mtr:%d/%d iter: %d next: %d dV: %f" %
     (curSpeed, int(curGas), curTile, len(tiles), itr, next_move,
      getDGas()))
 #draw road
 for i in range(0, 15):
     t = 7 + curTile - i
     if t < len(tiles) and t >= 0:
         road.addstr(i + 1, 2, getDrawing(tiles[t], links[t]))
         if t == curTile:
             road.addch(i + 1, 3 + curLine, "A", curses.A_REVERSE)
 panel.update_panels()
 curses.doupdate()
 #change parameters if necessary
 key = road.getch()
 if key == ord('q'):
     run = False
 elif key == 260 or key == 68:  #left
     itr = (itr + 1) % 100
     if curLine > 0:
         curLine -= 1
 elif key == 261 or key == 67:  #right
     itr = (itr + 1) % 100
     if curLine < 6:
         curLine += 1
 elif key == 259 or key == 65:  #up
     if curSpeed < 10 and curGas > 0:
Пример #38
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()
        self.window.addstr(
            "       " +
            os.path.basename(self.get_target()).replace(".csv", ""))
        global current_title

        while True:
            self.window.refresh()
            curses.doupdate()
            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                msg = '%d. %s' % (index + 1, item[0])
                self.window.addstr(2 + index, 1, msg, mode)

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                if self.position == len(
                        self.items) - 1:  #if its the exit button
                    break
                else:
                    #TODO make it call a thing instead

                    #TODO 1st make it print what the cmd is
                    self.target = self.items[self.position]
                    #print(self.target)
                    current_title = self.items[self.position][0]
                    self.items[self.position][1]()

            elif key == curses.KEY_UP:
                self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

            else:
                print("key was", key)
                #print(self.letters_to_listen_to)
                #print(self.numbers_to_listen_to)
                #print(self.items)
                for n in self.numbers_to_listen_to:
                    if key == ord(str(n)):
                        #print("dIng")
                        #print(self.position)
                        #run item at n
                        current_title = self.items[n - 1][0]
                        self.items[n - 1][1]()

                for l in self.letters_to_listen_to:
                    if key == ord(str(l)):
                        # print("dIng")
                        # print(self.position)
                        # run item at n
                        current_title = self.items[
                            self.letters_to_listen_to.index(l)][0]
                        self.items[self.letters_to_listen_to.index(l)][1]()

                #if key in [for n in self.numbers_to_listen_to:ord(n)]

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #39
0
#!/usr/bin/env python
Пример #40
0
    def pflush(self):
        """refresh the panels"""

        panel.update_panels()
        curses.doupdate()
Пример #41
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()

        self.init_term_colors()

        alert = 0
        alert_msg = ""
        devices_state = {}
        global airc_temp

        while True:
            self.window.refresh()
            curses.doupdate()

            json_data = self.server.json_data.copy()
            if "Alert" in json_data:
                alert, alert_msg = self.check_for_alert(json_data, alert)

            self.window.addstr(0, 0, alert_msg, curses.color_pair(1))
            self.window.clrtoeol()

            self.show_devices_info(json_data)
            devices_state = self.get_devices_current_state(
                devices_state, json_data)

            self.window.addstr(1, 0,
                               "Temperatura do Ar Cond.: {}".format(airc_temp))

            for index, item in enumerate(self.items):
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                msg = "%d. %s" % (index, item[0])
                self.window.addstr(1 + index, 40, msg, mode)

            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord("\n")]:
                if self.position == len(
                        self.items) - 2:  # Selecionar Temperatura
                    self.items[self.position][1]()
                elif self.position == len(self.items) - 1:  # Sair
                    break
                else:
                    device = self.items[self.position][1]
                    self.server.send('{{"Device": "{}"}}'.format(device))

                    self.server.save_log(
                        {"Device": (device, 1 - devices_state[device])})

            elif key == curses.KEY_UP:
                self.navigate(-1)

            elif key == curses.KEY_DOWN:
                self.navigate(1)

        self.server.close()
        self.server.run_server = False
        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #42
0
 def show(self):
     self.panel.top()
     self.panel.show()
     self.win.refresh()
     panel.update_panels()
     curses.doupdate()
Пример #43
0
    def display(self):

        self.panel.top()
        self.panel.show()
        self.window.clear()

        while True:

            self.window.refresh()
            curses.doupdate()

            self.max_y, self.max_x = self.window.getmaxyx()

            # Display the menu title.
            if self.title:
                self.addline(1, self.title)
                self.addline(2, '-' * len(self.title))
                offset_top = 3
            else:
                offset_top = 1
            offset_bottom = 1

            window_height = max(self.max_y - offset_top - offset_bottom - 1, 0)

            if self.position < window_height:
                window = (0, window_height)
            else:
                window = (self.position - window_height, self.position)

            row = 0

            for index, item in enumerate(self.items):

                if index < window[0] or index > window[1]:
                    continue

                # Highlight the selected item.
                if index == self.position:
                    mode = curses.A_REVERSE
                else:
                    mode = curses.A_NORMAL

                # Display the item.
                self.addline(
                    offset_top + row,
                    item.label,
                    mode,
                )

                row += 1

            # Blank bottom lines if screen was resized
            for y in range(offset_bottom):
                self.addline(
                    self.max_y - y - 1,
                    '',
                    curses.A_NORMAL,
                )

            # Because window.timeout was called,
            # this returns -1 if nothing was pressed.
            key = self.window.getch()

            if key in [curses.KEY_ENTER, ord('\n')]:
                return self.items[self.position].value
            elif key in (curses.KEY_UP, ord('k')):
                self.navigate(-1)
            elif key in (curses.KEY_DOWN, ord('j')):
                self.navigate(1)
            elif key in (ord('q'), ord('Q')):
                raise KeyboardInterrupt

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
Пример #44
0
 def hide(self):
     self.panel.bottom()
     self.panel.hide()
     panel.update_panels()
     curses.doupdate()
Пример #45
0
 def hide(self):
     self.window.clear()
     self.panel.hide()
     panel.update_panels()
     curses.doupdate()
     self.window.refresh()
Пример #46
0
cs.start_color()
cs.init_pair(1, cs.COLOR_BLACK, cs.COLOR_GREEN)

window = cs.newwin(5, 5, 3, 5)
window.box()
panel = pnl.new_panel(window)

window2 = cs.newwin(15, 15, 2, 4)
window2.box()
window2.addstr(1, 1, 'Back window')
panel2 = pnl.new_panel(window2)

running = True
while running:
    pnl.update_panels()
    cs.doupdate()
    key = scr.getch()
    if key == 27:
        running = False
    if key == ord('w'):
        window.bkgd(' ', cs.color_pair(1))
    if key == ord('s'):
        window.bkgd(' ', cs.color_pair(1) + cs.A_REVERSE)
    if key == ord('1'):
        panel.move(1, 1)
        panel.top()
    if key == ord('2'):
        panel.move(3, 5)
        panel.top()
    if key == ord('3'):
Пример #47
0
 def _panel_init(self):
     self.panel = panel.new_panel(self.window)
     self.panel.hide()
     panel.update_panels()
Пример #48
0
def main():
    """ Entry point for example 17
    """
    # Initialize curses
    screen = curses.initscr()

    curses.start_color()
    curses.cbreak()
    curses.noecho()
    screen.keypad(True)

    # Initialize all the colors
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_BLACK)

    my_wins = init_wins(3)

    # Attach a panel to each window, order is bottom up
    my_panels = (
        panel.new_panel(my_wins[0]),  # Push 0, order: stdscr-0
        panel.new_panel(my_wins[1]),  # Push 1, order: stdscr-0-1
        panel.new_panel(my_wins[2]),  # Push 2, order: stdscr-0-1-2
    )

    # Initialize panel datas saying that nothing is hidden
    panel_datas = (
        PANEL_DATA(False),
        PANEL_DATA(False),
        PANEL_DATA(False),
    )

    for my_panel, panel_data in zip(my_panels, panel_datas):
        my_panel.set_userptr(panel_data)

    # Update the stacking order. 2nd panel will be on top
    panel.update_panels()

    # Show it on the screen
    screen.attron(curses.color_pair(4))

    msg = "Show or Hide a window with 'a' (first window), 'b' (Second Window), 'c' (Third Window)"
    screen.addstr(curses.LINES - 3, 0, msg)
    screen.addstr(curses.LINES - 2, 0, "F2 to Exit")
    screen.attroff(curses.color_pair(4))
    curses.doupdate()

    char = screen.getch()
    while char != curses.KEY_F2:
        if char == ord("a"):
            temp = my_panels[0].userptr()
            if not temp.hide:
                my_panels[0].hide()
                temp.hide = True
            else:
                my_panels[0].show()
                temp.hide = False

        if char == ord("b"):
            temp = my_panels[1].userptr()
            if not temp.hide:
                my_panels[1].hide()
                temp.hide = True
            else:
                my_panels[1].show()
                temp.hide = False

        if char == ord("c"):
            temp = my_panels[2].userptr()
            if not temp.hide:
                my_panels[2].hide()
                temp.hide = True
            else:
                my_panels[2].show()
                temp.hide = False

        panel.update_panels()
        curses.doupdate()
        char = screen.getch()

    curses.endwin()
    sys.exit(0)
Пример #49
0
def tui_main(stdscr, args):
    if args.host:
        client = ModbusTcpClient(args.host, port=args.port)
    else:
        # This prevents arduino autoreset. It does not work on the first call
        # because it doesn't give time to the Arduino program to
        # initialize. After that it is not necessary until the configuration
        # of the port changes again but keeping it here seems like the
        # cleanest and simplest solution.
        os.system('stty -hup -F %s' % SERIAL_PORT)
        client = ModbusSerialClient(method="rtu",
                                    port=SERIAL_PORT,
                                    stopbits=1,
                                    bytesize=8,
                                    parity='E',
                                    baudrate=19200,
                                    dsrdtr=False,
                                    timeout=0.01)
        conn = client.connect()
    _configure_curses(stdscr)
    coil_table = CoilTable()
    counter_table = CounterTable()
    analog_table = AnalogTable()
    ud_table = UserDataTable()
    tables = Circular([coil_table, analog_table, counter_table, ud_table])
    _center(stdscr, tables)
    read_op = 0
    coils = []
    counters = []
    analog_values = []
    user_data_values = []
    while True:
        if read_op == READ_COILS:
            coils = client.read_coils(0x0000, 0xd8, unit=UNIT_ID).bits
        elif read_op == READ_COUNTERS:
            counters = client.read_holding_registers(0x000a, 24,
                                                     unit=UNIT_ID).registers
        elif read_op == READ_ANALOG:
            analog_values = client.read_holding_registers(
                0x0000, 10, unit=UNIT_ID).registers
        elif read_op == READ_USER_DATA:
            user_data_values = client.read_holding_registers(
                0x0022, 14, unit=UNIT_ID).registers
        read_op = (read_op + 1) % READ_OP_COUNT
        coil_table.set_data(coils)
        analog_table.set_data(analog_values)
        counter_table.set_data(counters)
        ud_table.set_data(user_data_values)
        stdscr.touchwin()
        panel.update_panels()
        curses.doupdate()
        ch = stdscr.getch()
        action = None
        if ch == -1:
            continue
        elif ch == ord('q'):
            return
        elif ch == ord('\t'):
            tables.current().hide_selection(True)
            tables.next()
            tables.current().hide_selection(False)
        elif ch == ord('h'):
            show_dialog(stdscr, 'Help', HELP_MSG)
        elif ch == curses.KEY_RESIZE:
            stdscr.clear()
            stdscr.border(0)
            _center(stdscr, tables)
        elif ch == ord('s'):
            action = ('write_coils', 0x0100, [1])
        elif ch == ord('l'):
            action = ('write_coils', 0x0101, [1])
        else:
            action = tables.current().handle_ch(ch)
        tl_attr = curses.A_NORMAL
        if action:
            cmd = action[0]
            if cmd == 'write_coils':
                cmd, addr, bits = action
                result = client.write_coils(addr, bits, unit=UNIT_ID)
                tl_msg = 'write_coils(0x%04x, %s, unit=0x%x) -> %s' % (
                    addr, bits, UNIT_ID, result)
                if result.function_code & 0x80:
                    tl_attr = COLOR_WHITE_ON_RED | curses.A_BOLD
                read_op = READ_COILS
            if cmd == 'write_registers':
                cmd, addr, words = action
                result = client.write_registers(addr, words, unit=UNIT_ID)
                tl_msg = 'write_registers(0x%04x, %s, unit=0x%x) -> %s' % (
                    addr, words, UNIT_ID, result)
                if result.function_code & 0x80:
                    tl_attr = COLOR_WHITE_ON_RED | curses.A_BOLD
                read_op = READ_COUNTERS
            else:
                tl_msg = str(action)
        else:
            tl_msg = curses.keyname(ch).decode('utf-8')
        stdscr.addstr(1, 1, tl_msg, tl_attr)
        stdscr.clrtoeol()
def main(stdscr):

    # Array for holding serial connections.
    ser = []

    # Clear screen
    stdscr.clear()

    # Get screen dimensions
    scr_height, scr_width = stdscr.getmaxyx()

    # Create welcome window and panel
    welcome_win = curses.newwin(scr_height, scr_width, 0, 0)
    welcome_panel = panel.new_panel(welcome_win)

    # Display welcome message.
    display_welcome_msg(welcome_win)

    # Prompt user for the com ports to connect to.

    # Echo characters to user
    curses.echo()

    welcome_win.addstr(8, 1, 'Enter the ports to connect to: ')

    # Show panels
    panel.update_panels()
    curses.doupdate()

    myinput = welcome_win.getstr(9, 1).decode(encoding="utf-8")

    welcome_win.addstr('\n')

    # Try to connect to each of the com ports provided by the user. If the
    # connection was successful then add it to the array of serial connections.
    for port in myinput.split():
        try:
            temp = serial.Serial(port=port, baudrate=BAUDRATE, timeout=TIMEOUT)
            ser.append(temp)
            welcome_win.addstr('Successfully connected to: ' + port + '\n')

        except:
            welcome_win.addstr('Failed to connect to: ' + port + '\n')

    # Show panels
    panel.update_panels()
    curses.doupdate()

    # If no connections are made then tell the user and exit the program.
    if len(ser) == 0:
        welcome_win.addstr('Error: no connections established\n')
        welcome_win.addstr(
            'Check the com port and ensure no other programs are connected to it\n\n'
        )
        welcome_win.addstr('Press <enter> to exit\n')

        # Update panels
        panel.update_panels()
        curses.doupdate()

        discard = stdscr.getch()  # block
        return

    # Try to open the text file with all of the packets to send and exit
    # if it fails to open.
    try:
        infile = open('nff-packets.txt', 'r')

    except:
        welcome_win.addstr('Error: couldn\'t open nff-packets.txt\n')
        welcome_win.addstr(
            'Make sure the file is in the same directory as the .exe\n\n')
        welcome_win.addstr('Press <enter> to exit\n')

        # Update panels
        panel.update_panels()
        curses.doupdate()

        discard = stdscr.getch()  # block
        return

    # Try and open output file
    try:
        timestr = time.strftime("%d-%b-%Y_%H:%M:%S", time.localtime())
        outfile = open("log/" + timestr + "_log.txt", "w+")

    except:
        welcome_win.addstr('Error: couldn\'t open logfile\n\n')
        welcome_win.addstr('Press <enter> to exit\n')

        # Update panels
        panel.update_panels()
        curses.doupdate()

        discard = stdscr.getch()  # block
        return

    # Make sure files are open
    time.sleep(0.1)

    # Wait until user is ready to start the simulation.
    welcome_win.addstr('Press <enter> to start the simulation!\n')

    # Update panels
    panel.update_panels()
    curses.doupdate()

    discard = stdscr.getch()  # block

    # Current speed of the simulation, 1 is normal, 2 is twice as fast, etc.
    speed = 1
    '''
  Main program loop
  
  Loops through every line in packets

  Send line only when time since last packet exceed interval

  Check for response from Arduino (Data received)

  '''

    # Counter variable for number of packets sent.
    packet_counter = 0

    # Read all of the packets and store the total number to keep track of progress.
    all_lines = infile.readlines()
    num_lines = len(all_lines)

    prev_time = datetime.datetime.utcnow().timestamp()
    out_packet = all_lines[0]
    in_packet = ""
    packets_received = 0
    packets_sent = 0

    # Init windows for testing
    '''
  header_win is for storing raw data sent and received

  nff_win is for nff packets received
  flow_win is for flowmeter data
  ada_win is for the data received from adafruit sensor

  foot_win is progress bar and cmd list

  '''
    del welcome_win

    header_win = curses.newwin(13, scr_width, 0, 0)
    nff_win = curses.newwin(27, int(scr_width / 3) - 1, 13, 0)
    flow_win = curses.newwin(27,
                             int(scr_width / 3) - 1, 13, int(scr_width / 3))
    ada_win = curses.newwin(27,
                            int(scr_width / 3) - 1, 13,
                            int(scr_width / 3) * 2)
    foot_win = curses.newwin(10, scr_width, 40, 0)

    header_panel = panel.new_panel(header_win)
    nff_panel = panel.new_panel(nff_win)
    flow_panel = panel.new_panel(flow_win)
    ada_panel = panel.new_panel(ada_win)
    foot_panel = panel.new_panel(foot_win)

    panel.update_panels()
    curses.doupdate()

    # Turn off echo mode and make keypresses nonblocking
    curses.noecho()
    stdscr.nodelay(True)

    # Main Loop

    while True:

        # Clear windows
        header_win.erase()
        nff_win.erase()
        flow_win.erase()
        ada_win.erase()
        foot_win.erase()

        # Borders look organized and cool
        header_win.border()
        nff_win.border()
        flow_win.border()
        ada_win.border()
        foot_win.border()

        # Send packet if time interval is met
        curr_time = datetime.datetime.utcnow().timestamp()
        if curr_time - prev_time > PACKET_INTERVAL and packet_counter < num_lines:

            line = all_lines[packet_counter]
            packet = line.rstrip()

            # Send the packet to each connected device.
            for devs in ser:
                devs.write(packet.encode())

            out_packet = line
            prev_time = curr_time
            packet_counter += speed
            packets_sent += 1

        # Check for keystroke input from user
        c = stdscr.getch()

        if (c == ord('q')):
            # (q)uit
            break
        elif (c == ord('p')):
            # (p)ause
            stdscr.nodelay(False)
            discard = stdscr.getch()  # Wait for p to be pressed again
            stdscr.nodelay(True)
        elif (c == curses.KEY_LEFT and speed != 1):
            # Slow down! Left key pressed
            speed = int(speed / 2)
        elif (c == curses.KEY_RIGHT and speed != 64):
            # Speed up! Right key pressed
            speed = int(speed * 2)

        # Listen for response from Arduino

        # Read in up to the maximum size of data per line.
        # 0 is used because we only have 1 arduinp
        data_in = ser[0].readline(MAXBUFFER).decode()
        # ser[0].reset_input_buffer()

        # Strip newline characters
        data_in = data_in.rstrip('\n')
        data_in = data_in.rstrip('\r')
        data_in = data_in.rstrip('\n')

        # Check that some data was received.
        if (len(data_in) != 0):
            in_packet = data_in

        # Verify size of packet received
        if (len(data_in.split(",")) == NUMDATAFIELDS):
            packets_received += 1

        # Output contents to logfile
        outfile.write(in_packet + "\n")

        # Cool running effect with the dots.
        header_win.addstr(
            1, 1, 'NFF simulation running' + ('.' * (int)(
                (packet_counter % 12) / 3)))

        # Display all of the connected ports.
        ports = ""
        for devs in ser:
            ports += devs.port + ", "

        header_win.addstr(3, 1, 'Connected to: ' + ports[:-2])

        # Display the current packet being sent.
        header_win.addstr(5, 1, 'Sending packet: ' + out_packet)

        # Print packet received from arduino
        header_win.addstr(7, 1, "Packet received: " + in_packet)
        header_win.addstr(8, 1, "Length: {}".format(len(in_packet.split(","))))

        # Companre number of packets received to packets sent
        header_win.addstr(10, 1, "Packets sent: {}".format(packets_sent))
        header_win.addstr(11, 1,
                          "Packets received: {}".format(packets_received))

        # Print contents of packet to console
        print_packet(nff_win, flow_win, ada_win, in_packet)

        # Temp
        ada_win.addstr(1, 1, "Adafruit 9-DOF Sensor")

        # Display how far along the simulation is with a neat loading bar (the magic 20 number is to
        # prevent the simulation from obnoxiously ending while displaying 99%, I'm a little OCD).
        foot_win.addstr(
            1, 1, 'Simulation progress: [' + '#' *
            (int)(packet_counter / (num_lines / PROGRESS_BAR_LENGTH)) + ' ' *
            (int)(PROGRESS_BAR_LENGTH -
                  (packet_counter /
                   (num_lines / PROGRESS_BAR_LENGTH))) + '] ' + str(
                       ((100 * (int)(packet_counter + 20)) / num_lines)) + '%')

        # Display the current speed the simulation is running at.
        foot_win.addstr(3, 1, 'Current speed: x' + str(speed))
        foot_win.addstr(
            4, 1, 'Press left to slow down sim or right to speed up sim')

        # Inform user about option to quit
        foot_win.addstr(6, 1, 'Press <q> at any time to quit or <p> to pause')

        panel.update_panels()
        curses.doupdate()

        time.sleep(0.02)

    # Close all device connections after simulation has finished.
    for devs in ser:
        devs.close()

    # Close files
    infile.close()
    outfile.close()
Пример #51
0
def draw(layer):
    if layer == 0:
        window.bkgd(" ", curses.A_REVERSE)
    else:
        window.bkgd(" ")

    for i in range(0, len(window_data)):
        if select == i and layer == 1:
            window.addstr(i + 1, 1, window_data[i], curses.A_REVERSE)
        else:
            window.addstr(i + 1, 1, window_data[i])

    for i in range(0, len(menu_data)):
        if selectM == i and layer == 2:
            menu.addstr(i + 1, 1, menu_data[i], curses.A_REVERSE)
        else:
            menu.addstr(i + 1, 1, menu_data[i])
    menu.addstr(0, 1, "MENU:")

    info.clear()
    for i in range(0, len(menu_data)):
        if layer == 3 and menu_data[i] != "close":
            try:
                if pa_type[menu_data[i]] == "int":
                    line = "%s = %d" % (menu_data[i], params[menu_data[i]])
                else:
                    line = "%s = %s" % (menu_data[i],
                                        str(params[pa_type[menu_data[i]]][
                                            params[menu_data[i]]]))
            except KeyError:
                line = "no such key (%s) in dict (pa_type)" % menu_data[i]
            except TypeError:
                line = "dict error: data: %s." % menu_data[i]
            info.addstr(i + 1, 1, line)

    submenu.clear()
    submenu.addstr(1, 3, subm_name)
    submenu.addstr(2, 1, "<")
    submenu.addstr(2, SUBMENU_X - 2, ">")
    if selectS == 0:
        try:
            if pa_type[subm_name] == "int":
                submenu.addstr(2, 3, str(subm_val), curses.A_REVERSE)
            else:
                submenu.addstr(2, 3, str(params[pa_type[subm_name]][subm_val]),
                               curses.A_REVERSE)
        except KeyError:
            status("no such key (%s) in dict (pa_type)" % subm_name)
        submenu.addstr(3, 3, "OK")
    elif selectS == 1:
        try:
            if pa_type[subm_name] == "int":
                submenu.addstr(2, 3, str(subm_val))
            else:
                submenu.addstr(2, 3, str(params[pa_type[subm_name]][subm_val]))
        except KeyError:
            status("no such key (%s) in dict (pa_type)" % subm_name)
        submenu.addstr(3, 3, "OK", curses.A_REVERSE)
    window.box()
    menu.box()
    submenu.box()
    info.box()
    time.sleep(0.01)
    if not update_panel.hidden():
        update_panel.hide()
    panel.update_panels()
    curses.doupdate()
Пример #52
0
 def debug(self, pan, message):
     win = pan.window()
     win.move(3, 26)
     win.addstr(message)
     panel.update_panels()
Пример #53
0
def pflush():
    panel.update_panels()
    curses.doupdate()
Пример #54
0
    def __init__(self, stdscreen):

        self.rate = 1
        self.position = 0
        self.is_editing = False
        self.state = State()
        self.markItr = 0
        self.blockItrPrev = -1
        self.current_mark = None
        self.volume = config.volume
        self.applyEditsBoolean = False
        self.cycle_start = True
        self.advance_time = config.jump_time_long

        self.screen = stdscreen

        curses.curs_set(0)

        # self.height, self.width = stdscreen.getmaxyx()
        self.window = stdscreen.subwin(0, 0)
        self.window.keypad(1)
        self.panel = panel.new_panel(self.window)
        self.panel.hide()
        panel.update_panels()

        self.position = 0
        self.panel.top()
        self.panel.show()
        self.window.clear()

        self.original_file = sys.argv[1]
        self.output_file_name = None

        self.file_path = os.path.dirname(os.path.realpath(sys.argv[1]))
        self.file_basename = os.path.basename(sys.argv[1])
        self.file_name = os.path.splitext(self.file_basename)[0]
        self.file_ext = os.path.splitext(self.file_basename)[1]

        # if opening a backup, look for a state file with the original name
        self.state_file_name = ""
        if self.file_name.endswith('-original'):
            self.state_file_name = os.path.join(
                self.file_path,
                self.file_name.replace('-original', '') + ".state")
            self.output_file_name = os.path.join(
                self.file_path,
                self.file_name.replace('-original', '') + self.file_ext)
        else:
            # check to see if its our data input
            if self.file_ext == '.data':
                self.file_ext = ".mp4"
            self.file_name_new = os.path.join(
                self.file_path, self.file_name + "-original" + self.file_ext)
            self.output_file_name = self.original_file
            if self.checkRates(os.path.realpath(sys.argv[1])):
                shutil.move(os.path.realpath(sys.argv[1]),
                            os.path.join(self.file_path, self.file_name_new))
            else:
                self.print_to_screen('converting file')
                cmd = [
                    'ffmpeg', '-y', '-i',
                    os.path.realpath(sys.argv[1]), '-ar', '44100',
                    os.path.join(self.file_path, self.file_name_new)
                ]
                result = subprocess.run(cmd,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.STDOUT)
                lines = result.stdout.decode('utf-8').splitlines()
                for line in lines:
                    for word in line.split():
                        if word.startswith('time='):
                            time_temp = word.split("=")[1].split(":")
                            time = int(time_temp[0]) * 3600 + int(
                                time_temp[1]) * 60 + round(float(time_temp[2]))

                quick_state = State()
                quick_state.marks = []
                quick_state.duration = time * 1000
                self.write_state_information()
                os.remove(os.path.realpath(sys.argv[1]))

            # self.file_path = self.file_name_new
            # self.old_file_name = self.original_file
            self.original_file = self.file_name + "-original" + self.file_ext

            self.state_file_name = os.path.join(self.file_path,
                                                self.file_name + ".state")

        # if no state file is found or read, create the information
        if not self.read_state_information():
            print('loading file')
            self.state = State()
            self.state.marks = []
            self.state.duration = self.get_file_length(self.original_file)
            self.write_state_information()

        # this extra step is to set the verbosity of the log errors so they
        # don't print to the screen
        # libvlc_set_log_verbosity tooltip says its defunct
        self.VLC = vlc
        self.VLC.libvlc_set_log_verbosity(None, 1)
        self.instance = self.VLC.Instance(('--no-video'))
        self.song = self.instance.media_player_new()
        self.media = self.instance.media_new(self.original_file)
        self.log("starting file {}".format(self.original_file))
        self.song.set_media(self.media)

        self.song.play()
        self.media.parse()
        self.poll_thread = WT(self)
        self.poll_thread.start()

        try:
            while True:
                self.position = self.song.get_position()
                self.window.refresh()
                curses.doupdate()

                key = self.window.getch()
                # self.keyStrokeLog(key)

                # Raises the volume
                if key == config.volume_up:
                    self.changeVolume(config.volume_increments)
                # Lowers the volume
                if key == config.volume_down:
                    if self.volume > 0:
                        self.changeVolume(-config.volume_increments)

                # Speeds up the playback
                if key == config.play_speed_up:
                    self.update_rate(config.play_speed_rate)

                # Slows down the playback
                elif key == config.play_speed_down:
                    self.update_rate(-config.play_speed_rate)

                # Jumps back 5 seconds
                elif key == config.jump_back:
                    self.changePositionBySecondOffset_new2(-self.advance_time)
                    # self.changePositionBySecondOffset_new(
                    #     -self.advance_time,
                    #     message=False,
                    #     forward=False
                    # )

                # Jump ahead five seconds
                elif key == config.jump_forward:
                    start = self.song.get_position()
                    self.changePositionBySecondOffset_new2(self.advance_time)
                    end = self.song.get_position()
                    self.keyStrokeLog(
                        "key jump_forward start:{} end:{} diff:{}".format(
                            start, end, end - start))
                    # self.changePositionBySecondOffset_new(
                    #     self.advance_time,
                    #     message=False,
                    #     forward=True
                    # )

                # pauses and plays the media
                elif key == config.play_pause:
                    if self.song.is_playing:
                        self.song.pause()
                    else:
                        self.song.play()

                # # Create a new mark
                # elif key == config.mark_create_new:
                #     # self.createNewMark()
                #     pass

                # Saves a current mark
                elif key == config.change_advance_speed:
                    try:
                        self.toggleAdvanceSpeed()
                    except Exception as ex:
                        self.log(ex)

                # Record the beginning of the mark
                elif key == config.mark_record_start_position:
                    try:
                        self.startMarkPosition()
                    except Exception as ex:
                        self.log(ex)

                # Record the end of the mark
                elif key == config.mark_record_end_position:
                    try:
                        self.endMarkPosition()
                    except Exception as ex:
                        self.log(ex)

                # Starting the current markItr cycle through the saved marks
                # This is only for listening
                elif key == config.cycle_through_marks:
                    try:
                        self.cycleThroughMarks()
                    except Exception as ex:
                        self.log(ex)

                elif key == config.cycle_through_marks_editing:
                    try:
                        self.is_editing = not self.is_editing
                        if self.is_editing:
                            self.print_to_screen('Now editing')
                        else:
                            self.print_to_screen('No longer editing')
                    except Exception as ex:
                        self.log(ex)

                # Stop cycling through marks
                # elif key == config.cycle_through_marks_stop:
                #     try:
                #         self.current_mark = None
                #     except Exception as ex:
                #         self.log(ex)

                # Quit the program
                elif key == config.quit_program:
                    self.poll_thread.join()
                    break

                # Do the actual edits taking the marks and applying them to
                # to the original file
                elif key == config.begin_edits:
                    global final_command
                    final_command = self.applyEdits(self.state.marks)
                    self.poll_thread.join()
                    break

                # Go back to normal speed
                elif key == config.normal_speed:
                    self.normalize_rate()

                # print the current time formatted to the screen
                elif key == config.current_time:
                    self.getCurrentTime()

                # print the lenght of the file to the screen
                elif key == config.file_length:
                    length = self.timeStamp(self.state.duration, 1)
                    self.print_to_screen(length)

                # causes the playback to stop and allows user to enter a spcific
                # amount of time to move forward or backward
                elif key == config.jump_specific:
                    self.jumpSpecificTime()

                # creates a mark that starts at the beginning of the file to the
                # current position
                elif key == config.block_till_begining:
                    self.begining_ending_block(True)

                # creates a mark that starts from the current position to the end
                # fo the file
                elif key == config.block_till_end:
                    self.begining_ending_block(False)

                elif key == config.jump_to_start:
                    self.log('jump_to_start')
                    self.song.set_position(0)

                elif key == config.jump_to_end:
                    self.song.set_position(0.9999999999)

                # deletes the current block
                elif key == config.delete_block:
                    self.delete_block()

                elif key == config.nudge_forward:
                    self.log('nudge forward')
                    self.nudge()

                elif key == config.nudge_back:
                    self.log('nudge back')
                    self.nudge(forward=False)

                elif key == config.export_block_as_new_file:
                    self.exportCurrentBlock()

                elif key == config.cycle_through_marks_stop:
                    self.log('current blocks')
                    for mark in self.state.marks:
                        self.log(mark.get_time(self.state.duration))
        except KeyboardInterrupt:
            pass

        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
        curses.endwin()
Пример #55
0
 def top(self):
     self.panel.top()
     panel.update_panels()
     self.refresh()
Пример #56
0
 def _post_loop(self):
     self.window.clear()
     self.panel.hide()
     panel.update_panels()
     curses.doupdate()
Пример #57
0
def main():
    """ Entry point for example 16
    """
    # Initialize curses
    screen = curses.initscr()

    curses.start_color()
    curses.cbreak()
    curses.noecho()
    screen.keypad(True)

    # Initialize all the colors
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_BLACK)

    my_wins = init_wins(3)

    # Attach a panel to each window, order is bottom up
    my_panels = (
        panel.new_panel(my_wins[0]),  # Push 0, order: stdscr-0
        panel.new_panel(my_wins[1]),  # Push 1, order: stdscr-0-1
        panel.new_panel(my_wins[2]),  # Push 2, order: stdscr-0-1-2
    )

    set_user_ptrs(my_panels, len(my_panels))

    # Update the stacking order. 2nd panel will be on top
    panel.update_panels()

    # Show it on the screen
    screen.attron(curses.color_pair(4))
    screen.addstr(curses.LINES - 3, 0, "Use 'm' for moving, 'r' for resizing")
    screen.addstr(curses.LINES - 2, 0,
                  "Use tab to browse through the windows (F2 to Exit)")
    screen.attroff(curses.color_pair(4))
    curses.doupdate()

    stack_top = my_panels[2]
    top = stack_top.userptr()
    newx = top.x
    newy = top.y
    neww = top.w
    newh = top.h

    char = screen.getch()  # Note this is an integer - the ANSI character code

    size = False
    move = False

    while char != curses.KEY_F2:
        if char == ord("\t"):  # Tab
            top = stack_top.userptr()
            top.next_.top()
            stack_top = top.next_
            top = stack_top.userptr()
            newx = top.x
            newy = top.y
            neww = top.w
            newh = top.h

        elif char == ord("r"):  # Re-size
            size = True
            screen.attron(curses.color_pair(4))
            resize_msg = "Entered Resizing: Use Arrow Keys " \
                "to resize and press <ENTER> to end resizing"
            screen.addstr(curses.LINES - 4, 0, resize_msg)
            screen.refresh()
            screen.attroff(curses.color_pair(4))

        elif char == ord("m"):  # Move
            screen.attron(curses.color_pair(4))
            mv_msg = "Entered Moving: Use Arrow Keys to Move and press <ENTER> to end moving"
            screen.addstr(curses.LINES - 4, 0, mv_msg)
            screen.refresh()
            screen.attroff(curses.color_pair(4))
            move = True

        elif char == curses.KEY_LEFT:
            if size:
                newx = newx - 1
                neww = neww + 1

            if move:
                newx = newx - 1

        elif char == curses.KEY_RIGHT:
            if size:
                newx = newx + 1
                neww = neww - 1

            if move:
                newx = newx + 1

        elif char == curses.KEY_UP:
            if size:
                newy = newy - 1
                newh = newh + 1

            if move:
                newy = newy - 1

        elif char == curses.KEY_DOWN:
            if size:
                newy = newy + 1
                newh = newh - 1

            if move:
                newy = newy + 1

        elif char == ord("\n"):  # Enter
            screen.move(curses.LINES - 4, 0)
            screen.clrtoeol()
            screen.refresh()

            if size:
                old_win = stack_top.window()
                temp_win = curses.newwin(newh, neww, newy, newx)
                stack_top.replace(temp_win)
                win_show(temp_win, top.label, top.label_color)
                del old_win
                size = False

            if move:
                stack_top.move(newy, newx)
                move = False

        screen.attron(curses.color_pair(4))
        screen.addstr(curses.LINES - 3, 0,
                      "Use 'm' for moving, 'r' for resizing")
        screen.addstr(curses.LINES - 2, 0,
                      "Use tab to browse through the windows (F2 to Exit)")
        screen.attroff(curses.color_pair(4))
        screen.refresh()
        panel.update_panels()
        curses.doupdate()

        char = screen.getch()

    curses.endwin()
    sys.exit(0)
Пример #58
0
    def display(self):
        self.panel.top()
        self.panel.show()
        self.window.clear()
        self.update()
        
        while True:
            self.window.clear()
            self.window.refresh()
            curses.doupdate()
            ### show the list of map files ###
            for index,item in enumerate(self.map_file_list):
                if index == self.position:
                    mode = curses.A_STANDOUT
                else:
                    mode = curses.A_NORMAL
                line = "{}".format(item)
                if len(line) >= self.width:
                    line = line[:self.width-1]
                ### only add lines in the slice ###
                if self.slice_start <= index <= self.slice_end:
                    self.window.addstr(1+(index-self.slice_start),2,line,mode)
            key = self.window.getch()
            if key in [ord("b"),ord("B")]:
                break
            elif key in [curses.KEY_ENTER,ord("\n")]:
                if self.position == len(self.map_file_list)-1:
                    break
                else:
                    logger.info("MAP FILE: {} select for processing".format(self.map_file_list[self.position]))
                    self.window.clear()
                    self.window.refresh()
                    ### read & parse the map file ### 
                    map_file = os.path.join(self.map_dir,self.map_file_list[self.position])
                    self.window.addstr(2,2,"Processing {}".format(map_file))
                    map_file_ok = True
                    line_nbr = 0
                    with open(map_file,"rt") as f:
                        map_file_reader = csv.reader(f)
                        for row in map_file_reader:
                            line_nbr += 1
                            if not comment_re.match(row[0]):
                                if len(row) == 6:
                                    mig_tuple = Mig_tuple._make(row)
                                    mig_list.append(mig_tuple)
                                    logger.debug("added {}".format(mig_tuple))
                                else:
                                    map_file_ok = False
                                    logger.error("{} map file contains invalid data, please correct & re-run".format(map_file))
                                    logger.error("{}: {}".format(line_nbr,row))
                                    self.window.addstr(3,2,"Map file contains an invalid line, please correct & re-run")
                                    self.window.addstr(4,2,"{}: {}".format(line_nbr,row))
                                    key = self.window.getch()
                                    break
                    if map_file_ok:
                        self.window.addstr(3,2,"Map file read OK, {} source - target relations discovered".format(len(mig_list)))
                    else:
                        self.window.addstr(3,2,"Map file could not be processed, please correct & re-run")
                        key = self.window.getch()
                        break
                    ### request confirmation to proceed with external storage discovery ###
                    self.window.addstr(4,2,"Are all target volumes mapped to XP7 ? (y/N)")
                    key = self.window.getch()
                    if key in [ord("y"),ord("Y")]:
                        ### proceed with external storage discovery ###
                        self.window.addstr(5,2,"Proceeding with target storage discovery..")
                        ### check which target storage is in scope ###
                        target_sn_set = set([x.target_box_sn for x in mig_list])
                        for target_sn in target_sn_set:
                            if target_sn in name_by_serial_dict:
                                target_name = name_by_serial_dict[target_sn]
                                ### now we're able to find the IO ports to scan
                                if target_name in target_storage_dict:
                                    ext_storage_ports = target_storage_dict[target_name]
                                    for external_storage_port in external_storage_ports:
                                        ### get the wwn ###
                                        self.window.addstr(6,2,"External storage discovery on port {}".format(external_storage_port))

                                    
                                else:
                                    logger.error("No target IO ports defined for target {},skipping..".format(target_name))
                            else:
                                logger.error("Unknown target box S/N {}, skipping".format(target_sn)
                    else:
                        logger.info("MAP FILE: exit processing {}, target storage not mapped..".format(map_file))
                        break
            elif key == curses.KEY_UP:
                self.navigate(-1)
            elif key == curses.KEY_DOWN:
                self.navigate(1)
            elif key == curses.KEY_PPAGE:
                self.navigate(-10)
            elif key == curses.KEY_NPAGE:
                self.navigate(10)
        self.window.clear()
        self.panel.hide()
        panel.update_panels()
        curses.doupdate()
        
class Selection(object):
    
    def __init__(self,window,title,stdscr):
        self.window = window
        self.heigth,self.width = self.window.getmaxyx()
        self.title = title
        self.selection = []
        
    def display(self):
        self.window.clear()
        line = "{} : {}".format(self.title, ",".join(["{}-{}".format(x[0],x[1]) for x in self.selection]))
        if len(line) >= self.width:
            line = line[:self.width-1]
        self.window.addstr(1,2,line)
        self.window.border()
        self.window.refresh()
        curses.doupdate()
        
    def add(self,item):
        current_set = set(self.selection)
        current_set.add(item)
        self.selection = list(sorted(current_set))
        self.display()
        
    def clear(self):
        del self.selection[:]
        self.display()
        
    def get(self):
        return self.selection
        
####################################################################################################
### MAIN 
####################################################################################################
def main(stdscr):
    ### clear screen ###
    stdscr.clear()
    
    ### check window height and width ###
    if curses.COLS < 20 and curses.LINES < 20:
        sys.stderr.write("Window not large enough, exiting..\n")
        sys.exit(1)
        
    ### define title_win ###
    title_win = stdscr.subwin(3,curses.COLS,0,0)
    title_win.addstr(1,2,"HPE P9500 to XP7 MIGRATION PREPARE")
    title_win.border()
    
    ### define selection_win ###
    select_win = stdscr.subwin(3,curses.COLS,curses.LINES-4,0)
    selection = Selection(select_win,"SELECTED HOSTGROUP(s)",stdscr)
    selection.display()
    
    ### define menu_win ###
    menu_win = stdscr.subwin(curses.LINES-7,curses.COLS,3,0)
    main_menu_items = []
    
    map_menu = Map_menu(menu_win,map_file_dir,selection,stdscr)
    main_menu_items.append(("Process MAP file",map_menu.display))
    
    ### define status_win ###
    # status_win = stdscr.subwin(3,curses.COLS,curses.LINES-4,0)
    # status_win.addstr(1,2,"STATUS:")
    # status_win.border()
    
    ### fire up the main menu ###
    main_menu = Menu(menu_win,main_menu_items,stdscr)
    main_menu.display()
    
    ### getting here means we exited the menu ###
    stdscr.refresh()
    
configfile = "xpmig.ini"
cfg = ConfigParser()
cfg.read(configfile)

for mandatory_section in ("dir","target"):
    if not cfg.has_section(mandatory_section):
        sys.stderr.write("{} section missing in the config file {}, exiting..".format(mandatory_section,configfile))
        sys.exit(1)
        
for name,value in cfg.items("target"):
    target_storage_dict[name] = value.split(",")
    
try:
    map_file_dir = cfg.get("dir","map")
except:
    map_file_dir = "/tmp"
    
try:
    loglevel =cfg.getint("log","level")
except:
    loglevel = 30
    
try:
    logdir = cfg.get("dir","log")
except:
    logdir = "/tmp/log"
    
try:
    logsize = cfg.getint("log","size")
except:
    logsize = 100000000
    
try:
    logversions = cfg.getint("log","maxversions")
except:
    logversions = 5
    
for name,value in cfg.items("serialnbr"):
    serial_by_name_dict[name] = value
    name_by_serial_dict[value] = name
    
for name,value in cfg.items("instance"):
    instance_dict[name] = value
    
#####################
### start logging ###
#####################
logger = logging.getLogger("xpmig_prepare")
logger.setLevel(loglevel)
logfile = os.path.join(logdir,"xpmig_prepare.log")
fh = logging.handlers.RotatingFileHandler(logfile,maxBytes=logsize,backupCount=logversions)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s","%Y/%m/%d-%H:%M:%S")
fh.setFormatter(formatter)
logger.addHandler(fh)

logger.info("#" * linelen)
logger.info("XPMIG PREPARE started")
logger.info("#" * linelen)

logger.info("Configuration settings :")
logger.info("MAPPING dir: {}".format(map_file_dir))
    
miglog = miglog.Miglog(logdir,"PREPARE")

#####################
### start menu    ###
#####################
curses.wrapper(main)
#####################
### stop  logging ###
#####################
logger.info("#" * linelen)
logger.info("XPMIG PREPARE ended")
logger.info("#" * linelen)