class TkJoystickManager(TkPage):
    def __init__(self, parent, gui, **options):
        """ Initializes the TkJoystickManager object
		
		@param parent
		@param gui
		@param options
		"""
        super(TkJoystickManager, self).__init__(parent, gui, **options)
        self.initDependencyManager()
        if (not self.pm.installRequired()):
            if (hasattr(self.gui, 'scheduler')):
                self.scheduler = self.gui.scheduler
            else:
                self.scheduler = Scheduler.GetInstance()
                self.gui.scheduler = self.scheduler
            self.__joystickModule = self.gui.getModule('Joystick')
            self.jr = self.__joystickModule.JoystickRegistry.GetInstance(
                self.scheduler)
            self.gui.joystickRegistry = self.jr

    def initDependencyManager(self):
        """ setup dependency checks
		"""
        dependencies = [{'package': 'joystick', 'installer': 'apt-get'}]
        self.pm = TkDependencyManager(self.widget, dependencies,
                                      'Joystick Manager', self.gui)

    def setup(self):
        """ setup gui menu
		"""
        try:
            self.gui.menus['joystick']
        except:
            self.gui.menus['joystick'] = Tkinter.Menu(
                self.gui.menubar,
                tearoff=0,
                bg=self.colours['menubg'],
                fg=self.colours['menufg'],
                activeforeground=self.colours['menuactivefg'],
                activebackground=self.colours['menuactivebg'])
            self.addMenu(label="Joystick", menu=self.gui.menus['joystick'])
        self.gui.menus['joystick'].insert_command(
            2, label="Configure", command=self.OnConfigureClick)

    #=== VIEWS ===#
    def showConfig(self):
        """ view - show available joysticks with previews
		"""
        self.open()

        self.widgets['frameLabel'] = Tkinter.Label(
            self.widgets['tframe'],
            text='Joystick / Configure',
            anchor=NW,
            bg=self.colours['bg'],
            fg=self.colours['headingfg'],
            font=self.fonts['heading'])
        self.widgets['frameLabel'].grid(column=0, row=self.gridrow, sticky='W')

        self.gridrow += 1

        self.widgets['jframe'] = Tkinter.Frame(self.widgets['tframe'],
                                               bg=self.colours['bg'])
        self.widgets['jframe'].grid(column=0, row=self.gridrow, sticky='EW')

        self.widgets['joysticks'] = {}

        self.scheduler.addTask('joystick_config_ui', self.updateConfig, 2)

    def updateConfig(self):
        """ util - manage config ui
		"""
        if (any(self.jr.joysticks)):
            # remove no joysticks message
            if ('nojoysticks' in self.widgets.keys()):
                self.widgets['nojoysticks'].grid_forget()
                del (self.widgets['nojoysticks'])
            # disconnected
            for k in self.widgets['joysticks'].keys():
                if (not k in self.jr.joysticks.keys()):
                    self.widgets['joysticks'][k].widget.grid_forget()
                    del (self.widgets['joysticks'][k])
            # connected
            for k, v in self.jr.joysticks.items():
                if (not k in self.widgets['joysticks'].keys()):
                    self.widgets['joysticks'][k] = TkJoystick(
                        self.widgets['jframe'], k, v, self.colours,
                        self.images)
                    self.widgets['joysticks'][k].widget.grid(column=0,
                                                             row=self.gridrow,
                                                             padx=10,
                                                             pady=10,
                                                             sticky='EW')
                    self.gridrow += 1
        else:
            #remove all joysticks
            if (any(self.widgets['joysticks'])):
                for k in self.widgets['joysticks'].keys():
                    self.widgets['joysticks'][k].widget.grid_forget()
                    del (self.widgets['joysticks'][k])
            # add no joysticks message
            if (not 'nojoysticks' in self.widgets.keys()):
                self.widgets['nojoysticks'] = Tkinter.Label(
                    self.widgets['jframe'],
                    text='Connect a USB or Bluetooth Joystick or Gamepad.',
                    anchor=NW,
                    bg=self.colours['bg'],
                    fg=self.colours['fg'],
                    font=self.fonts['heading2'])
                self.widgets['nojoysticks'].grid(column=0,
                                                 row=0,
                                                 padx=10,
                                                 pady=10,
                                                 sticky='EW')

    #=== ACTIONS ===#
    def OnConfigureClick(self):
        """ action - displays the configure page
		"""
        if (not self.pm.installRequired()):
            self.showConfig()
            self.jr.addCallback('TkJoystick', self.tkJoystickCallback)
        else:
            self.open()
            self.pm.addManager()

    def close(self):
        """ override of TkPage.close()
		hides the viewfinder
		"""
        if (hasattr(self, 'jr')):
            self.jr.removeCallback('TkJoystick')
        super(TkJoystickManager, self).close()

    def tkJoystickCallback(self, dev_num, signal, number, name, value, init):
        device = 'js%s' % dev_num
        if (device in self.widgets['joysticks'].keys()):
            self.widgets['joysticks'][device].update(signal, number, name,
                                                     value, init)
Esempio n. 2
0
class TkOrthoManager(TkPage):
	def __init__(self, parent, gui, **options):
		""" Initializes TkOrthoManager object
		
		@param parent
		@param gui
		@param options
		"""
		super(TkOrthoManager,self).__init__(parent, gui, **options)
		self.specification = gui.specification
		self.initDependencyManager()
		if(hasattr(self.gui, 'scheduler')):
			self.scheduler = self.gui.scheduler
		else:
			self.scheduler = Scheduler.GetInstance()
		if(not self.dm.installRequired()):
			self.pimg = self.gui.getModule('PIL.Image')
			self.tkimg = self.gui.getModule('PIL.ImageTk')
			if(hasattr(self.gui, 'imu')):
				self.imu = self.gui.imu
			else:
				self.imu = self.gui.imu = IMU(self.specification, self.scheduler, (not Setting.get('imu_autostart', False)))
			self.shapes = {}
			self.cache = { 'roll': {}, 'pitch': {}, 'yaw': {} }
			self.basepath = AmsEnvironment.AppPath()
			self.initImages()
			self.scheduler.addTask('ortho', self.updateOrtho, 0.2, True)
	def initDependencyManager(self):
		""" setup dependency checks
		"""
		dependencies = [
			{'package':'python-imaging', 'installer': 'apt-get'},
			{'package':'python-imaging-tk', 'installer': 'apt-get'},
			{'package':'tk8.5', 'installer': 'apt-get'},
			{'package':'tcl8.5', 'installer': 'apt-get'},
			{'package':'pillow', 'installer': 'pip', 'version': '2.6.1'}
		]
		self.dm = TkDependencyManager(self.widget, dependencies, 'Orthographic Manager', self.gui)
	def setup(self):
		""" setup gui menu
		"""
		try:
			self.gui.menus['imu']
		except:
			self.gui.menus['imu'] = Tkinter.Menu(self.gui.menubar, tearoff=0, bg=self.colours['menubg'], fg=self.colours['menufg'], activeforeground=self.colours['menuactivefg'], activebackground=self.colours['menuactivebg'])
			self.addMenu(label="IMU", menu=self.gui.menus['imu'])
		self.gui.menus['imu'].insert_command(3, label="Orthographic", command=self.OnShowOrthographicClick)
	def initImages(self):
		""" setup required images
		"""
		self.oimages = {}
		self.oimages['roll'] = self.pimg.Image.open(os.path.join(self.basepath, 'images/orthographic/front.png')).convert('RGBA')
		self.oimages['pitch'] = self.pimg.Image.open(os.path.join(self.basepath, 'images/orthographic/right.png')).convert('RGBA')
		self.oimages['yaw'] = self.pimg.Image.open(os.path.join(self.basepath, 'images/orthographic/top.png')).convert('RGBA')
	def buildCache(self):
		""" setup cache (first 60 degs)
		"""
		if(not any(self.cache['roll'])):
			for i in range(-30,30):
				self.cache['roll'][i] = self.tkimg.ImageTk.PhotoImage(self.oimages['roll'].rotate(i))
				self.cache['pitch'][i] = self.tkimg.ImageTk.PhotoImage(self.oimages['pitch'].rotate(i))
				self.cache['yaw'][i] = self.tkimg.ImageTk.PhotoImage(self.oimages['yaw'].rotate(i))
	def getImage(self, axis, angle):
		""" gets an image from cache or caches it
		
		@param axis
		@param angle
		"""
		try:
			self.cache[axis][angle]
		except:
			self.cache[axis][angle] = self.tkimg.ImageTk.PhotoImage(self.oimages[axis].rotate(angle))
		return self.cache[axis][angle]
	
	#=== VIEWS ===#
	def serviceManager(self):
		""" view - service manager
		"""
		self.widgets['servicelabel'] = Tkinter.Label(self.widgets['tframe'],text='IMU / IMU Service', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['servicelabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['sframe'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['sframe'].grid(column=0,row=self.gridrow, sticky='W')
		
		self.widgets['statusLabel'] = Tkinter.Label(self.widgets['sframe'],text='Status', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['statusLabel'].grid(column=0,row=0,sticky='EW')
		
		self.variables['status'] = Tkinter.StringVar()
		self.widgets['statusdata'] = Tkinter.Label(self.widgets['sframe'],textvariable=self.variables['status'], bg=self.colours['bg'], fg=self.colours['fg'], font=self.fonts['heading2'])
		self.widgets['statusdata'].grid(column=0,row=1,padx=50, sticky='EW')
		
		self.widgets['start'] = Tkinter.Button(self.widgets['sframe'],text=u"Start", image=self.images['play'], command=self.OnStartClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['start'].grid(column=1,row=1,sticky='W')
		
		self.widgets['stop'] = Tkinter.Button(self.widgets['sframe'],text=u"Stop", image=self.images['stop'], command=self.OnStopClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['stop'].grid(column=2,row=1,sticky='W')
		
		if(self.scheduler.tasks['imu_watcher'].stopped == False):
			self.variables['status'].set('Running')
			self.widgets['start'].configure(state='disabled')
		else:
			self.variables['status'].set('Stopped')
			self.widgets['stop'].configure(state='disabled')
			
		self.gridrow += 1
		
		self.widgets['orientframe'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['orientframe'].grid(column=0,row=self.gridrow, sticky='W')
		
		self.widgets['orientLabel'] = Tkinter.Label(self.widgets['orientframe'],text='Mounted', bg=self.colours['bg'], fg=self.colours['headingfg'], height=3)
		self.widgets['orientLabel'].grid(column=0,row=0, padx=10,sticky='EW')
		
		self.widgets['orientLabel'] = Tkinter.Label(self.widgets['orientframe'],text='Facing', bg=self.colours['bg'], fg=self.colours['headingfg'], height=3)
		self.widgets['orientLabel'].grid(column=1,row=0, padx=10,sticky='EW')
		
		self.widgets['orientLabel'] = Tkinter.Label(self.widgets['orientframe'],text=self.specification.imu['facing'], bg=self.colours['bg'], fg=self.colours['valuefg'], height=3)
		self.widgets['orientLabel'].grid(column=2,row=0, padx=10,sticky='EW')
		
		self.widgets['orientLabel'] = Tkinter.Label(self.widgets['orientframe'],text='Offset', bg=self.colours['bg'], fg=self.colours['headingfg'], height=3)
		self.widgets['orientLabel'].grid(column=3,row=0, padx=10,sticky='EW')
		
		self.widgets['orientLabel'] = Tkinter.Label(self.widgets['orientframe'],text=self.specification.imu['offset'], bg=self.colours['bg'], fg=self.colours['valuefg'], height=3)
		self.widgets['orientLabel'].grid(column=4,row=0, padx=10,sticky='EW')
	def showOrthographic(self):
		""" view - displays orthographic ui
		"""
		if (not IMU.isAvailable()):
			return self.unavailable()
		
		self.open()
		
		self.serviceManager()
		
		self.gridrow += 1
		
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='IMU / Orthographic', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='W')
		
		self.gridrow += 1
		
		self.widgets['oframe'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['oframe'].grid(column=0,row=self.gridrow, columnspan = 3, sticky='EW')
		
		self.widgets['rollLabel'] = Tkinter.Label(self.widgets['oframe'],text='Roll', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['rollLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['pitchLabel'] = Tkinter.Label(self.widgets['oframe'],text='Pitch', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['pitchLabel'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.widgets['yawLabel'] = Tkinter.Label(self.widgets['oframe'],text='Yaw', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['yawLabel'].grid(column=2,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['rollCanvas'] = Tkinter.Canvas(self.widgets['oframe'], borderwidth=0, bg=self.colours['bg'], highlightthickness=0, width=280, height=280)
		self.widgets['rollCanvas'].grid(column=0,row=self.gridrow, padx= 10,sticky='NE')
		self.shapes['rollImage'] = self.widgets['rollCanvas'].create_image(150,150, image=self.getImage('roll',0))
		
		self.widgets['pitchCanvas'] = Tkinter.Canvas(self.widgets['oframe'], borderwidth=0, bg=self.colours['bg'], highlightthickness=0, width=280, height=280)
		self.widgets['pitchCanvas'].grid(column=1,row=self.gridrow, padx= 10,sticky='NE')
		self.shapes['pitchImage'] = self.widgets['pitchCanvas'].create_image(150,150, image=self.getImage('pitch',0))
		
		self.widgets['yawCanvas'] = Tkinter.Canvas(self.widgets['oframe'], borderwidth=0, bg=self.colours['bg'], highlightthickness=0, width=280, height=280)
		self.widgets['yawCanvas'].grid(column=2,row=self.gridrow, padx= 10,sticky='NE')
		self.shapes['yawImage'] = self.widgets['yawCanvas'].create_image(150,150, image=self.getImage('yaw',0))
	def updateOrtho(self):
		""" util - updates ortho ui
		"""
		try:
			self.last
		except:
			self.last = { 'roll': 0, 'pitch': 0, 'yaw': 0 }
		try:
			metric = self.imu.metrics['complement'].value
			if(self.last['roll'] != metric['r']):
				self.last['roll'] = metric['r']
				self.widgets['rollCanvas'].itemconfigure(self.shapes['rollImage'], image=self.getImage('roll',int(-metric['r'])))
			if(self.last['pitch'] != metric['p']):
				self.last['pitch'] = metric['p']
				self.widgets['pitchCanvas'].itemconfigure(self.shapes['pitchImage'], image=self.getImage('pitch',int(-metric['p'])))
			if(self.last['yaw'] != metric['y']):
				self.last['yaw'] = metric['y']
				self.widgets['yawCanvas'].itemconfigure(self.shapes['yawImage'], image=self.getImage('yaw',int(metric['y'])))
		except:
			pass
	def unavailable(self):
		""" view - fallback for missing imu
		"""
		self.open()
		
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='IMU / Unavailable', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='The MPU6050 has not been detected.', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
	
	#=== ACTIONS ===#
	def OnStartClick(self):
		""" action - starts the imu service
		"""
		self.widgets['start'].configure(state='disabled')
		self.widgets['stop'].configure(state='normal')
		self.variables['status'].set('Running')
		Setting.set('imu_watch_raw', True)
		Setting.set('imu_watch_norm', True)
		Setting.set('imu_watch_low', True)
		Setting.set('imu_watch_com', True)
		self.imu.start()
		self.scheduler.startTask('ortho')
	def OnStopClick(self):
		""" action - stops the imu service
		"""
		self.widgets['start'].configure(state='normal')
		self.widgets['stop'].configure(state='disabled')
		self.variables['status'].set('Stopped')
		self.scheduler.stopTask('ortho')
		self.imu.stop()
	def OnShowOrthographicClick(self):
		""" action - dsplays the ortho page
		"""
		if(not self.dm.installRequired()):
			self.buildCache()
			self.showOrthographic()
		else:
			self.open()
			self.dm.addManager()
Esempio n. 3
0
class TkResourceManager(TkBlock):
	def __init__(self, parent, gui, **options):
		super(TkResourceManager,self).__init__(parent, gui, **options)
		self.dm = TkDependencyManager(self.widget, {'package':'psutil', 'installer': 'pip', 'version': '3.3.0'}, 'Resource Manager', self.gui)
		if(not self.dm.installRequired()):
			self.gridrows = {}
			if(self.gui.scheduler != None):
				self.scheduler = self.gui.scheduler
			else:
				self.scheduler = Scheduler()
			self.resources = self.gui.getClass('Resource.Resources')(self.scheduler)
			self.tasksheight = 200 # sets the height of the tasks notebook
			self.last = { 'memory':0, 'disks':0, 'threads':0, 'processes':0, 'network':0 }
			if(Setting.get('resman_show_cpu',True)):
				self.addCpuManager()
			if(Setting.get('resman_show_tasks',True)):
				self.addTaskManager()
			if(Setting.get('resman_show_memory',True)):
				self.addMemoryManager()
			if(Setting.get('resman_show_temperature',True)):
				self.addTemperatureManager()
			if(Setting.get('resman_show_disk',True)):
				self.addDiskManager()
			self.addOptionManager()
		else:
			self.open()
			self.dm.addManager()
	
	#=== VIEWS ===#
	def addCpuManager(self):
		row = 0
		self.cpuwidgets = {}
		self.gridrows['cpu'] = 0
		self.widgets['cpuframe'] = Frame(self.widget,bg=self.colours['bg'])
		self.widgets['cpuframe'].grid(column=0,row=row,sticky='EW')
		self.variables['cpupercentage'] = StringVar()
		self.variables['cpupercentage'].set(self.resources.metrics['cpu_percent'].value)
		self.cpuwidgets['cpulabel'] = Tkinter.Label(self.widgets['cpuframe'],text='CPU Usage', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.cpuwidgets['cpulabel'].grid(column=0,row=self.gridrows['cpu'],sticky='EW')
		self.gridrows['cpu'] += 1
		self.cpuwidgets['graph'] = TkLineGraph(self.widgets['cpuframe'], { }, {'bg': self.colours['bg'], 'fg': self.colours['fg'], 'line': self.colours['consolefg']}, height = 50, width = 150, yrange = { 'min': 0, 'max': 100}, pointlimit=20)
		self.cpuwidgets['graph'].widget.grid(column=0,row=self.gridrows['cpu'], sticky='EW')
		self.cpuwidgets['cpudata'] = Tkinter.Label(self.widgets['cpuframe'],textvariable=self.variables['cpupercentage'], bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'], width=4)
		self.cpuwidgets['cpudata'].grid(column=1,row=self.gridrows['cpu'],sticky='EW')
		self.cpuwidgets['cpupercent'] = Tkinter.Label(self.widgets['cpuframe'],text='%', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.cpuwidgets['cpupercent'].grid(column=2,row=self.gridrows['cpu'],sticky='EW')
		self.scheduler.addTask('resman_cpu_pc', self.updateCpuPc, interval = 1)
		self.scheduler.addTask('resman_cpu_graph', self.updateCpuGraph, interval = 1)
	def updateCpuPc(self):
		try:
			history = self.resources.metrics['cpu_percent'].hotValues()
			if(len(history) > 1):
				if(history[-1].datavalue != history[-2].datavalue):
					self.variables['cpupercentage'].set(self.resources.metrics['cpu_percent'].value)
			else:
				self.variables['cpupercentage'].set(self.resources.metrics['cpu_percent'].value)
		except:
			pass
	def updateCpuGraph(self):
		try:
			self.cpuwidgets['graph'].data = { x.timestamp : x.datavalue for x in self.resources.metrics['cpu_percent'].hotValues() }
			self.cpuwidgets['graph'].update()
		except:
			pass
	def addMemoryManager(self):
		row = 0
		self.gridrows['mem'] = 0
		self.widgets['memoryframe'] = Frame(self.widget,bg=self.colours['bg'])
		self.widgets['memoryframe'].grid(column=1,row=row,sticky='EW')
		self.widgets['memlabel'] = Tkinter.Label(self.widgets['memoryframe'],text='Memory', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['memlabel'].grid(column=0,row=self.gridrows['mem'],sticky='EW')
		self.gridrows['mem'] += 1
		self.widgets['vmemlabel'] = Tkinter.Label(self.widgets['memoryframe'],text="VMem", bg=self.colours['bg'], fg=self.colours['fg'])
		self.widgets['vmemlabel'].grid(column=0,row=self.gridrows['mem'],sticky='EW')
		self.widgets['vmemdata'] = Tkinter.Label(self.widgets['memoryframe'],text=0, bg=self.colours['bg'], fg=self.colours['fg'])
		self.widgets['vmemdata'].grid(column=1,row=self.gridrows['mem'],sticky='EW')
		self.widgets['vmemgraph'] = TkBarGraph(self.widgets['memoryframe'], self.colours)
		self.widgets['vmemgraph'].widget.grid(column=2,row=self.gridrows['mem'],sticky='EW')
		self.gridrows['mem'] += 1
		self.widgets['swaplabel'] = Tkinter.Label(self.widgets['memoryframe'],text="Swap", bg=self.colours['bg'], fg=self.colours['fg'])
		self.widgets['swaplabel'].grid(column=0,row=self.gridrows['mem'],sticky='EW')
		self.widgets['swapdata'] = Tkinter.Label(self.widgets['memoryframe'],text=0, bg=self.colours['bg'], fg=self.colours['fg'])
		self.widgets['swapdata'].grid(column=1,row=self.gridrows['mem'],sticky='EW')
		self.widgets['swapgraph'] = TkBarGraph(self.widgets['memoryframe'], self.colours)
		self.widgets['swapgraph'].widget.grid(column=2,row=self.gridrows['mem'],sticky='EW')
		self.scheduler.addTask('resman_memory', self.updateMemory, interval = 10)
	def updateMemory(self):
		try:
			history = self.resources.metrics['memory'].hotValues()
			mem = self.resources.metrics['memory'].value
			if(len(history) > 1):
				if(history[-1].timestamp != self.last['memory']):
					self.last['memory'] = history[-1].timestamp
					self.widgets['vmemdata'].configure(text=mem['vmem'])
					self.widgets['vmemgraph'].update(mem['vmem'])
					self.widgets['swapdata'].configure(text=mem['smem'])
					self.widgets['swapgraph'].update(mem['smem'])
			else:
				self.widgets['vmemdata'].configure(text=mem['vmem'])
				self.widgets['vmemgraph'].update(mem['vmem'])
				self.widgets['swapdata'].configure(text=mem['smem'])
				self.widgets['swapgraph'].update(mem['smem'])
		except:
			pass
	def addTemperatureManager(self):
		row = 1
		self.gridrows['temp'] = 0
		self.widgets['tempframe'] = Frame(self.widget,bg=self.colours['bg'])
		self.widgets['tempframe'].grid(column=0,row=row, columnspan=2, sticky='EW')
		self.widgets['cpuTemplabel'] = Tkinter.Label(self.widgets['tempframe'],text='CPU Temp', anchor=E, bg=self.colours['bg'], fg=self.colours['headingfg'], height=2)
		self.widgets['cpuTemplabel'].grid(column=0,row=self.gridrows['temp'], ipadx=30,sticky='EW')
		self.widgets['cpuTempData'] = Tkinter.Label(self.widgets['tempframe'],text='TBD', anchor=W, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['cpuTempData'].grid(column=1,row=self.gridrows['temp'], ipadx=10, padx=10, sticky='EW')
		
		self.widgets['gpuTemplabel'] = Tkinter.Label(self.widgets['tempframe'],text='GPU Temp', anchor=E, bg=self.colours['bg'], fg=self.colours['headingfg'], height=2)
		self.widgets['gpuTemplabel'].grid(column=2,row=self.gridrows['temp'], ipadx=30,sticky='EW')
		self.widgets['gpuTempData'] = Tkinter.Label(self.widgets['tempframe'],text='TBD', anchor=W, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['gpuTempData'].grid(column=3,row=self.gridrows['temp'], ipadx=10, padx=10,sticky='EW')
		
		self.scheduler.addTask('resman_temp', self.updateTemps, interval = 30)
	def updateTemps(self):
		temps = self.resources.metrics['temperature'].value
		if(temps != None):
			try:
				self.widgets['cpuTempData'].configure(text=round(temps['cpu'], 1), fg=self.colours['valuefg'] )
				self.widgets['gpuTempData'].configure(text=round(temps['gpu'], 1), fg=self.colours['valuefg'] )
			except:
				pass
	def addDiskManager(self):
		row = 2	
		self.gridrows['disk'] = 0
		self.widgets['diskframe'] = Frame(self.widget,bg=self.colours['bg'])
		self.widgets['diskframe'].grid(column=0,row=row, columnspan=2, sticky='EW')
		self.widgets['disklabel'] = Tkinter.Label(self.widgets['diskframe'],text='Disk Usage', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['disklabel'].grid(column=0,row=self.gridrows['disk'],sticky='EW')
		
		self.gridrows['disk'] += 1
		
		self.widgets['diskCanvas'] = Tkinter.Canvas(self.widgets['diskframe'], borderwidth=0, highlightthickness=0, width=420, height=220)
		self.widgets['diskCanvas'].grid(column=0,row=self.gridrows['disk'], sticky='EW')
		self.widgets['diskdataframe'] = Frame(self.widgets['diskCanvas'],bg=self.colours['bg'])
		self.widgets['diskdataframe'].grid(column=0,row=0,sticky='EW')
		self.widgets['diskScroller'] = Tkinter.Scrollbar(self.widgets['diskframe'], orient=VERTICAL, command=self.widgets['diskCanvas'].yview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
		self.widgets['diskScroller'].grid(column=1, row=self.gridrows['disk'], sticky="NS")
		self.widgets['diskCanvas'].configure(yscrollcommand=self.widgets['diskScroller'].set, bg=self.colours['bg'])
		self.widgets['diskCanvas'].create_window((0,0),window=self.widgets['diskdataframe'],anchor='nw')
		self.widgets['diskdataframe'].bind("<Configure>", self.diskInfoScroll)
		
		self.scheduler.addTask('resman_disks', self.updateDisks, interval = 30)
	def diskInfoScroll(self, event):
		self.widgets['diskCanvas'].configure(scrollregion=self.widgets['diskCanvas'].bbox(ALL), width=420, height=220)
	def updateDisks(self):
		history = self.resources.metrics['disks'].hotValues()
		if(len(history) > 1):
				if(history[-1].timestamp != self.last['disks']):
					self.last['disks'] = history[-1].timestamp
					self.__applyDiskData(history[1].datavalue)
		else:
			if(self.resources.metrics['disks'].value != None):
				try:
					self.__applyDiskData(self.resources.metrics['disks'].value)
				except:
					pass
	def __applyDiskData(self, disks):
		col = 0
		for k, v in disks.iteritems():
			try:
				self.widgets[k]['diskchart'].update({self.colours['unitblue1']: v['percent'], self.colours['unitblue2']: 100-v['percent']})
				self.widgets[k]['useddata'].configure(text=self.sizeof_fmt(v['used']))
				self.widgets[k]['freedata'].configure(text=self.sizeof_fmt(v['free']))
				self.widgets[k]['disktotaldata'].configure(text=self.sizeof_fmt(v['total']))
			except:
				self.widgets[k] = {}
				mp = v['mountpoint'].split('/')
				if(len(mp) > 2):
					mp = mp[-1]
				else:
					mp = v['mountpoint']
				self.widgets[k]['diskchart'] = TkPiChart(self.widgets['diskdataframe'], {self.colours['unitblue1']: v['percent'], self.colours['unitblue2']: 100-v['percent']}, colours=self.colours, label=mp)
				self.widgets[k]['diskchart'].widget.grid(column=col,row=self.gridrows['disk'],sticky='EW', padx=5, pady=5)
				col += 1
				self.widgets[k]['diskdata'] = Frame(self.widgets['diskdataframe'],bg=self.colours['bg'])
				self.widgets[k]['diskdata'].grid(column=col,row=self.gridrows['disk'], sticky='EW')
				
				dd = self.widgets[k]['diskdata']
				
				self.gridrows['diskdata'] = 1
				
				self.widgets[k]['devicelabel'] = Tkinter.Label(dd,text='Device', anchor=NE, bg=self.colours['bg'], fg=self.colours['fg'])
				self.widgets[k]['devicelabel'].grid(column=0,row=self.gridrows['diskdata'],sticky='EW')
				self.widgets[k]['devicedata'] = Tkinter.Label(dd,text=k, anchor=NW, bg=self.colours['bg'], fg=self.colours['lightfg'])
				self.widgets[k]['devicedata'].grid(column=1,row=self.gridrows['diskdata'],sticky='EW')
				
				self.gridrows['diskdata'] += 1
				
				self.widgets[k]['fslabel'] = Tkinter.Label(dd,text='File System', anchor=NE, bg=self.colours['bg'], fg=self.colours['fg'])
				self.widgets[k]['fslabel'].grid(column=0,row=self.gridrows['diskdata'],sticky='EW')
				self.widgets[k]['fsdata'] = Tkinter.Label(dd,text=v['fstype'], anchor=NW, bg=self.colours['bg'], fg=self.colours['lightfg'])
				self.widgets[k]['fsdata'].grid(column=1,row=self.gridrows['diskdata'],sticky='EW')
				
				self.gridrows['diskdata'] += 1
				
				self.widgets[k]['usedlabel'] = Tkinter.Label(dd,text='Used', anchor=NE, bg=self.colours['bg'], fg=self.colours['fg'])
				self.widgets[k]['usedlabel'].grid(column=0,row=self.gridrows['diskdata'],sticky='EW')
				self.widgets[k]['useddata'] = Tkinter.Label(dd,text=self.sizeof_fmt(v['used']), anchor=NW, bg=self.colours['bg'], fg=self.colours['lightfg'])
				self.widgets[k]['useddata'].grid(column=1,row=self.gridrows['diskdata'],sticky='EW')
				
				self.gridrows['diskdata'] += 1
				
				self.widgets[k]['freelabel'] = Tkinter.Label(dd,text='Free', anchor=NE, bg=self.colours['bg'], fg=self.colours['fg'])
				self.widgets[k]['freelabel'].grid(column=0,row=self.gridrows['diskdata'],sticky='EW')
				self.widgets[k]['freedata'] = Tkinter.Label(dd,text=self.sizeof_fmt(v['free']), anchor=NW, bg=self.colours['bg'], fg=self.colours['lightfg'])
				self.widgets[k]['freedata'].grid(column=1,row=self.gridrows['diskdata'],sticky='EW')
				
				self.gridrows['diskdata'] += 1
				
				self.widgets[k]['disktotallabel'] = Tkinter.Label(dd,text='Total', anchor=NE, bg=self.colours['bg'], fg=self.colours['fg'])
				self.widgets[k]['disktotallabel'].grid(column=0,row=self.gridrows['diskdata'],sticky='EW')
				self.widgets[k]['disktotaldata'] = Tkinter.Label(dd,text=self.sizeof_fmt(v['total']), anchor=NW, bg=self.colours['bg'], fg=self.colours['lightfg'])
				self.widgets[k]['disktotaldata'].grid(column=1,row=self.gridrows['diskdata'],sticky='EW')
				
				col = 0
				self.gridrows['disk'] += 1
	def addTaskManager(self):
		row = 4
		self.widgets['taskframe'] = Frame(self.widget,bg=self.colours['bg'])
		self.widgets['taskframe'].grid(column=0,row=row,columnspan=2, sticky='EW')
		self.taskwidgets = {}
		self.notestyle = ttk.Style()
		self.notestyle.configure("TNotebook", background=self.colours['bg'], borderwidth=0)
		self.notestyle.configure("TNotebook.Tab", background=self.colours['buttonbg'], foreground='#000000', borderwidth=0)
		self.gridrows['tasks'] = 0
		self.taskwidgets['frameLabel'] = Tkinter.Label(self.widgets['taskframe'],text='Tasks / Network', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.taskwidgets['frameLabel'].grid(column=0,row=self.gridrows['tasks'], columnspan=1,sticky='EW')
		self.gridrows['tasks'] += 1
		self.taskwidgets['tasksnotebook'] = ttk.Notebook(self.widgets['taskframe'], style="TNotebook")
		self.taskwidgets['tasksnotebook'].grid(column=0,row=self.gridrows['tasks'],sticky='EW')
		self.addThreadManager()
		self.addProcessManager()
		self.addTrafficManager()
		self.addConnectionManager()
		self.taskwidgets['tasksnotebook'].add(self.widgets['processframe'], text="Processes")
		self.taskwidgets['tasksnotebook'].add(self.widgets['threadframe'], text="Threads")
		self.taskwidgets['tasksnotebook'].add(self.netwidgets['trafficwrap'], text="Traffic")
		self.taskwidgets['tasksnotebook'].add(self.netwidgets['connectionwrap'], text="Connections")
	def addThreadManager(self):
		row = 0
		self.threadwidgets = {}
		self.gridrows['thread'] = 0
		self.widgets['threadframe'] = Frame(self.taskwidgets['tasksnotebook'],bg=self.colours['bg'])
		self.widgets['threadframe'].grid(column=0,row=row,sticky='EW')

		self.threadwidgets['infoCanvas'] = Tkinter.Canvas(self.widgets['threadframe'], borderwidth=0, highlightthickness=0, width=420, height=self.tasksheight)
		self.threadwidgets['infoCanvas'].grid(column=0,row=self.gridrows['thread'], sticky='EW')
		self.threadwidgets['dataframe'] = Frame(self.threadwidgets['infoCanvas'],bg=self.colours['bg'])
		self.threadwidgets['dataframe'].grid(column=0,row=0,sticky='EW')
		self.threadwidgets['infoScroller'] = Tkinter.Scrollbar(self.widgets['threadframe'], orient=VERTICAL, command=self.threadwidgets['infoCanvas'].yview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
		self.threadwidgets['infoScroller'].grid(column=1, row=self.gridrows['thread'], sticky="NS")
		self.threadwidgets['infoCanvas'].configure(yscrollcommand=self.threadwidgets['infoScroller'].set, bg=self.colours['bg'])
		self.threadwidgets['infoCanvas'].create_window((0,0),window=self.threadwidgets['dataframe'],anchor='nw')
		self.threadwidgets['dataframe'].bind("<Configure>", self.threadInfoScroll)
		
		self.threadwidgets['subframe'] = Frame(self.threadwidgets['dataframe'],bg=self.colours['bg'])
		self.threadwidgets['subframe'].grid(column=0,row=0,columnspan=2, sticky='EW')
		
		self.threadwidgets['stretchframe'] = Frame(self.threadwidgets['subframe'],bg=self.colours['bg'], borderwidth=0, width=420)
		self.threadwidgets['stretchframe'].grid(column=0,row=0, columnspan=4, sticky='EW')
		self.threadwidgets['stretchframe'].columnconfigure(0, weight=1)
		
		self.threadwidgets['namelabel'] = Tkinter.Label(self.threadwidgets['subframe'],text='Name', bg=self.colours['bg'], fg=self.colours['fg'])
		self.threadwidgets['namelabel'].grid(column=0,row=1,sticky='EW')
		self.threadwidgets['identlabel'] = Tkinter.Label(self.threadwidgets['subframe'],text='Ident', bg=self.colours['bg'], fg=self.colours['fg'])
		self.threadwidgets['identlabel'].grid(column=1,row=1,sticky='EW')
		self.threadwidgets['daemonlabel'] = Tkinter.Label(self.threadwidgets['subframe'],text='Daemon', bg=self.colours['bg'], fg=self.colours['fg'])
		self.threadwidgets['daemonlabel'].grid(column=2,row=1,sticky='EW')
		self.threadwidgets['alivelabel'] = Tkinter.Label(self.threadwidgets['subframe'],text='Alive', bg=self.colours['bg'], fg=self.colours['fg'])
		self.threadwidgets['alivelabel'].grid(column=3,row=1,sticky='EW')

		self.threadwidgets['activelabel'] = Tkinter.Label(self.threadwidgets['dataframe'],text='Total', bg=self.colours['bg'], fg=self.colours['fg'])
		self.threadwidgets['activelabel'].grid(column=0,row=1,sticky='EW')
		self.threadwidgets['activedata'] = Tkinter.Label(self.threadwidgets['dataframe'],text='TBD', bg=self.colours['bg'], fg=self.colours['fg'])
		self.threadwidgets['activedata'].grid(column=1,row=1,sticky='EW')

		self.scheduler.addTask('resman_threads', self.updateThreads, interval = 20)
	def threadInfoScroll(self, event):
		self.threadwidgets['infoCanvas'].configure(scrollregion=self.threadwidgets['infoCanvas'].bbox(ALL), width=420, height=self.tasksheight)
	def updateThreads(self):
		history = self.resources.metrics['threads'].hotValues()
		if(len(history) > 0):
			if(history[-1].timestamp != self.last['threads']):
				try:
					self.__applyThreadData(history[-1].datavalue)
					self.last['threads'] = history[-1].timestamp
				except:
					pass
		else:
			try:
				self.__applyThreadData(self.resources.metrics['threads'].value)
			except:
				pass
	def __applyThreadData(self, threads):
		if(threads != None):
			self.gridrows['thread'] = 2
			for k, v in threads.iteritems():
				rowcolour = self.colours['rowbg']
				if(self.gridrows['thread'] % 2 == 0):
					rowcolour = self.colours['rowaltbg']
				try:
					self.threadwidgets[k]['talive'].configure(text=v['isalive'])
				except:
					self.threadwidgets[k] = {}
					self.threadwidgets[k]['name'] = Tkinter.Label(self.threadwidgets['subframe'],text=v['name'], bg=rowcolour, fg=self.colours['fg'])
					self.threadwidgets[k]['name'].grid(column=0,row=self.gridrows['thread'],sticky='EW')
					self.threadwidgets[k]['ident'] = Tkinter.Label(self.threadwidgets['subframe'],text=string.replace(k,'i',''), bg=rowcolour, fg=self.colours['fg'])
					self.threadwidgets[k]['ident'].grid(column=1,row=self.gridrows['thread'],sticky='EW')
					self.threadwidgets[k]['daemon'] = Tkinter.Label(self.threadwidgets['subframe'],text=v['isdaemon'], bg=rowcolour, fg=self.colours['fg'])
					self.threadwidgets[k]['daemon'].grid(column=2,row=self.gridrows['thread'],sticky='EW')
					self.threadwidgets[k]['talive'] = Tkinter.Label(self.threadwidgets['subframe'],text=v['isalive'], bg=rowcolour, fg=self.colours['fg'])
					self.threadwidgets[k]['talive'].grid(column=3,row=self.gridrows['thread'],sticky='EW')
				self.gridrows['thread'] += 1
			self.threadwidgets['activedata'].configure(text = str(self.resources.metrics['threadcount'].value))
	def addProcessManager(self):
		row = 1
		self.processwidgets = {}
		self.gridrows['process'] = 0
		self.widgets['processframe'] = Frame(self.taskwidgets['tasksnotebook'],bg=self.colours['bg'])
		self.widgets['processframe'].grid(column=0,row=row,sticky='EW')
		self.processwidgets['infoCanvas'] = Tkinter.Canvas(self.widgets['processframe'], borderwidth=0, highlightthickness=0, width=420, height=self.tasksheight)
		self.processwidgets['infoCanvas'].grid(column=0,row=self.gridrows['process'],sticky='EW')
		self.processwidgets['dataframe'] = Frame(self.processwidgets['infoCanvas'],bg=self.colours['bg'])
		self.processwidgets['dataframe'].grid(column=0,row=0,sticky='EW')
		self.processwidgets['infoScroller'] = Tkinter.Scrollbar(self.widgets['processframe'], orient=VERTICAL, command=self.processwidgets['infoCanvas'].yview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
		self.processwidgets['infoScroller'].grid(column=1, row=self.gridrows['process'], sticky="NS")
		self.processwidgets['infoCanvas'].configure(yscrollcommand=self.processwidgets['infoScroller'].set, bg=self.colours['bg'])
		self.processwidgets['infoCanvas'].create_window((0,0),window=self.processwidgets['dataframe'],anchor='nw')
		self.processwidgets['dataframe'].bind("<Configure>", self.processInfoScroll)
		
		self.processwidgets['stretchframe'] = Frame(self.processwidgets['dataframe'],bg=self.colours['bg'], borderwidth=0, width=420)
		self.processwidgets['stretchframe'].grid(column=0,row=0, columnspan=2, sticky='EW')
		self.processwidgets['stretchframe'].columnconfigure(0, weight=1)
		
		self.processwidgets['namelabel'] = Tkinter.Label(self.processwidgets['dataframe'],text='Name', bg=self.colours['bg'], fg=self.colours['fg'])
		self.processwidgets['namelabel'].grid(column=0,row=1,sticky='EW')
		self.processwidgets['userlabel'] = Tkinter.Label(self.processwidgets['dataframe'],text='User', bg=self.colours['bg'], fg=self.colours['fg'])
		self.processwidgets['userlabel'].grid(column=1,row=1,sticky='EW')
		self.widgets['processframe'].grid_columnconfigure(0, weight=1)
		self.processwidgets['infoCanvas'].grid_columnconfigure(0, weight=1)
		self.processwidgets['dataframe'].grid_columnconfigure(0, weight=4)
		
		self.scheduler.addTask('resman_processes', self.updateProcesses, interval = 30)
	def processInfoScroll(self, event):
		self.processwidgets['infoCanvas'].configure(scrollregion=self.processwidgets['infoCanvas'].bbox(ALL), width=420, height=self.tasksheight)
	def updateProcesses(self):
		history = self.resources.metrics['processes'].hotValues()
		if(history):
				if(history[-1].timestamp != self.last['processes']):
					self.last['processes'] = history[-1].timestamp
					self.__applyProcessData(history[-1].datavalue)
		else:
			try:
				self.__applyProcessData(self.resources.metrics['processes'].value)
			except:
				pass
	def __applyProcessData(self, processes):
		if(processes != None):
			self.gridrows['process'] = 2
			for k, v in processes.iteritems():
				rowcolour = self.colours['rowbg']
				if(self.gridrows['process'] % 2 == 0):
					rowcolour = self.colours['rowaltbg']
				try:
						self.processwidgets[k]
				except:
					self.processwidgets[k] = {}
					self.processwidgets[k]['name'] = Tkinter.Label(self.processwidgets['dataframe'],text=v['name'], bg=rowcolour, fg=self.colours['fg'])
					self.processwidgets[k]['name'].grid(column=0,row=self.gridrows['process'],sticky='EW')
					self.processwidgets[k]['user'] = Tkinter.Label(self.processwidgets['dataframe'],text=v['username'], bg=rowcolour, fg=self.colours['fg'])
					self.processwidgets[k]['user'].grid(column=1,row=self.gridrows['process'],sticky='EW')
				self.gridrows['process'] += 1
	def addTrafficManager(self):
		self.netwidgets = {}
		self.gridrows['traffic'] = 0
		
		self.netwidgets['trafficwrap'] = Frame(self.taskwidgets['tasksnotebook'],bg=self.colours['bg'])
		self.netwidgets['trafficwrap'].grid(column=0,row=2,sticky='EW')
		
		self.netwidgets['trafficCanvas'] = Tkinter.Canvas(self.netwidgets['trafficwrap'], borderwidth=0, highlightthickness=0, width=420, height=self.tasksheight)
		self.netwidgets['trafficCanvas'].grid(column=0,row=self.gridrows['traffic'],sticky='EW')
		self.netwidgets['trafficdata'] = Frame(self.netwidgets['trafficCanvas'],bg=self.colours['bg'])
		self.netwidgets['trafficdata'].grid(column=0,row=0,sticky='EW')
		self.netwidgets['trafficScroller'] = Tkinter.Scrollbar(self.netwidgets['trafficwrap'], orient=VERTICAL, command=self.netwidgets['trafficCanvas'].yview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
		self.netwidgets['trafficScroller'].grid(column=1, row=self.gridrows['traffic'], sticky="NS")
		self.netwidgets['trafficCanvas'].configure(yscrollcommand=self.netwidgets['trafficScroller'].set, bg=self.colours['bg'])
		self.netwidgets['trafficCanvas'].create_window((0,0),window=self.netwidgets['trafficdata'],anchor='nw')
		self.netwidgets['trafficdata'].bind("<Configure>", self.trafficInfoScroll)
		
		self.netwidgets['tstretchframe'] = Frame(self.netwidgets['trafficdata'],bg=self.colours['bg'], borderwidth=0, width=420)
		self.netwidgets['tstretchframe'].grid(column=0,row=self.gridrows['traffic'], columnspan=3, sticky='EW')
		self.netwidgets['tstretchframe'].columnconfigure(0, weight=1)
		
		self.gridrows['traffic'] += 1
		
		self.netwidgets['namelabel'] = Tkinter.Label(self.netwidgets['trafficdata'],text='Name', bg=self.colours['bg'], fg=self.colours['fg'])
		self.netwidgets['namelabel'].grid(column=0,row=self.gridrows['traffic'],sticky='EW')
		self.netwidgets['bsentlabel'] = Tkinter.Label(self.netwidgets['trafficdata'],text='Sent', bg=self.colours['bg'], fg=self.colours['fg'])
		self.netwidgets['bsentlabel'].grid(column=1,row=self.gridrows['traffic'],sticky='EW')
		self.netwidgets['breceivedlabel'] = Tkinter.Label(self.netwidgets['trafficdata'],text='Received', bg=self.colours['bg'], fg=self.colours['fg'])
		self.netwidgets['breceivedlabel'].grid(column=2,row=self.gridrows['traffic'],sticky='EW')
		self.gridrows['traffic'] += 1
		
		self.netwidgets['trafficdata'].grid_columnconfigure(0, weight=1)
	def addConnectionManager(self):
		self.connwidgets = {}
		self.gridrows['connections'] = 0
		
		self.netwidgets['connectionwrap'] = Frame(self.taskwidgets['tasksnotebook'],bg=self.colours['bg'])
		self.netwidgets['connectionwrap'].grid(column=0,row=3,sticky='EW')
		
		self.netwidgets['connectionCanvas'] = Tkinter.Canvas(self.netwidgets['connectionwrap'], borderwidth=0, highlightthickness=0, width=420, height=self.tasksheight)
		self.netwidgets['connectionCanvas'].grid(column=0,row=self.gridrows['process'],sticky='EW')
		self.netwidgets['connectiondata'] = Frame(self.netwidgets['connectionCanvas'],bg=self.colours['bg'])
		self.netwidgets['connectiondata'].grid(column=0,row=0,sticky='EW')
		self.netwidgets['connectionScroller'] = Tkinter.Scrollbar(self.netwidgets['connectionwrap'], orient=VERTICAL, command=self.netwidgets['connectionCanvas'].yview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
		self.netwidgets['connectionScroller'].grid(column=1, row=self.gridrows['process'], sticky="NS")
		self.netwidgets['connectionCanvas'].configure(yscrollcommand=self.netwidgets['connectionScroller'].set, bg=self.colours['bg'])
		self.netwidgets['connectionCanvas'].create_window((0,0),window=self.netwidgets['connectiondata'],anchor='nw')
		self.netwidgets['connectiondata'].bind("<Configure>", self.connectionInfoScroll)
		
		self.netwidgets['cstretchframe'] = Frame(self.netwidgets['connectiondata'],bg=self.colours['bg'], borderwidth=0, width=400)
		self.netwidgets['cstretchframe'].grid(column=0,row=self.gridrows['connections'], columnspan=5, sticky='EW')
		self.netwidgets['cstretchframe'].columnconfigure(0, weight=1)
		
		self.gridrows['connections'] += 1
		
		self.netwidgets['laddlabel'] = Tkinter.Label(self.netwidgets['connectiondata'],text='Local Address', bg=self.colours['bg'], fg=self.colours['fg'])
		self.netwidgets['laddlabel'].grid(column=0,row=self.gridrows['connections'],sticky='EW')
		self.netwidgets['lportlabel'] = Tkinter.Label(self.netwidgets['connectiondata'],text='Local Port', bg=self.colours['bg'], fg=self.colours['fg'])
		self.netwidgets['lportlabel'].grid(column=1,row=self.gridrows['connections'],sticky='EW')
		self.netwidgets['raddlabel'] = Tkinter.Label(self.netwidgets['connectiondata'],text='Remote Address', bg=self.colours['bg'], fg=self.colours['fg'])
		self.netwidgets['raddlabel'].grid(column=2,row=self.gridrows['connections'],sticky='EW')
		self.netwidgets['rportlabel'] = Tkinter.Label(self.netwidgets['connectiondata'],text='Remote Port', bg=self.colours['bg'], fg=self.colours['fg'])
		self.netwidgets['rportlabel'].grid(column=3,row=self.gridrows['connections'],sticky='EW')
		self.netwidgets['statuslabel'] = Tkinter.Label(self.netwidgets['connectiondata'],text='Status', bg=self.colours['bg'], fg=self.colours['fg'])
		self.netwidgets['statuslabel'].grid(column=4,row=self.gridrows['connections'],sticky='EW')

		self.netwidgets['connectiondata'].grid_columnconfigure(0, weight=1)
		
		self.scheduler.addTask('resman_network', self.updateNetwork, interval = 30)
	def addOptionManager(self):
		self.gridrows['option'] = 0
		self.widgets['oframe'] = Frame(self.widget,bg=self.colours['bg'])
		self.widgets['oframe'].grid(column=0,row=5,columnspan=2, padx=10, pady=5, sticky='EW')
		self.netwidgets['olabel'] = Tkinter.Label(self.widgets['oframe'],text='Archive', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.netwidgets['olabel'].grid(column=0,row=self.gridrows['option'], pady=5,sticky='EW')
		self.gridrows['option'] += 1
		self.variables['archiveCpu'] = Tkinter.BooleanVar()
		self.variables['archiveCpu'].set(Setting.get('resource_archive_cpu',False))
		self.netwidgets['aCpuEntry'] = Tkinter.Checkbutton(self.widgets['oframe'], variable=self.variables['archiveCpu'], text='CPU Usage', command=self.OnToggleCpuClick, anchor=W, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.netwidgets['aCpuEntry'].grid(column=0,row=self.gridrows['option'], padx=0, pady=0, ipadx=10, sticky='EW')
		
		self.variables['archiveMem'] = Tkinter.BooleanVar()
		self.variables['archiveMem'].set(Setting.get('resource_archive_mem',False))
		self.netwidgets['aMemEntry'] = Tkinter.Checkbutton(self.widgets['oframe'], variable=self.variables['archiveMem'], text='Memory', command=self.OnToggleMemoryClick, anchor=W, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.netwidgets['aMemEntry'].grid(column=1,row=self.gridrows['option'], padx=0, pady=0, ipadx=10, sticky='EW')
		
		self.variables['archiveTemp'] = Tkinter.BooleanVar()
		self.variables['archiveTemp'].set(Setting.get('resource_archive_temp',False))
		self.netwidgets['aTempEntry'] = Tkinter.Checkbutton(self.widgets['oframe'], variable=self.variables['archiveTemp'], text='Temperature', command=self.OnToggleTempClick, anchor=W, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.netwidgets['aTempEntry'].grid(column=2,row=self.gridrows['option'], padx=0, pady=0, ipadx=10, sticky='EW')
		
		self.variables['archiveDisks'] = Tkinter.BooleanVar()
		self.variables['archiveDisks'].set(Setting.get('resource_archive_disks',False))
		self.netwidgets['aDisksEntry'] = Tkinter.Checkbutton(self.widgets['oframe'], variable=self.variables['archiveDisks'], text='Disks', command=self.OnToggleDisksClick, anchor=W, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.netwidgets['aDisksEntry'].grid(column=3,row=self.gridrows['option'],padx=0, pady=0, ipadx=10, sticky='EW')
		
		self.gridrows['option'] += 1
		self.variables['archiveProcess'] = Tkinter.BooleanVar()
		self.variables['archiveProcess'].set(Setting.get('resource_archive_processes',False))
		self.netwidgets['aProcessEntry'] = Tkinter.Checkbutton(self.widgets['oframe'], variable=self.variables['archiveProcess'], text='Processes', command=self.OnToggleProcessesClick, anchor=W, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.netwidgets['aProcessEntry'].grid(column=0,row=self.gridrows['option'],padx=0, pady=0, ipadx=10, sticky='EW')
		
		self.variables['archiveThread'] = Tkinter.BooleanVar()
		self.variables['archiveThread'].set(Setting.get('resource_archive_threads',False))
		self.netwidgets['aThreadEntry'] = Tkinter.Checkbutton(self.widgets['oframe'], variable=self.variables['archiveThread'], text='Threads', command=self.OnToggleThreadsClick, anchor=W, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.netwidgets['aThreadEntry'].grid(column=1,row=self.gridrows['option'],padx=0, pady=0, ipadx=10, sticky='EW')
		
		self.variables['archiveNet'] = Tkinter.BooleanVar()
		self.variables['archiveNet'].set(Setting.get('resource_archive_net',False))
		self.netwidgets['aNetEntry'] = Tkinter.Checkbutton(self.widgets['oframe'], variable=self.variables['archiveNet'], text='Network', command=self.OnToggleNetworkClick, anchor=W, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.netwidgets['aNetEntry'].grid(column=2,row=self.gridrows['option'],padx=0, pady=0, ipadx=10, sticky='EW')
	
	def trafficInfoScroll(self, event):
		self.netwidgets['trafficCanvas'].configure(scrollregion=self.netwidgets['trafficCanvas'].bbox(ALL), width=420, height=self.tasksheight)
	def connectionInfoScroll(self, event):
		self.netwidgets['connectionCanvas'].configure(scrollregion=self.netwidgets['connectionCanvas'].bbox(ALL), width=420, height=self.tasksheight)
	def updateNetwork(self):
		history = self.resources.metrics['network'].hotValues()
		if(len(history) > 1):
				if(history[-1].timestamp != self.last['network']):
					self.last['network'] = history[-1].timestamp
					self.__applyNetworkData(history[-1].datavalue)
		else:
			try:
				self.__applyNetworkData(self.resources.metrics['network'].value)
			except:
				pass
	def __applyNetworkData(self, network):
		self.gridrows['traffic'] = 2
		rowcount = 0
		for k,v in network['nics'].iteritems():
			rowcolour = self.colours['rowbg']
			if(rowcount % 2 == 0):
				rowcolour = self.colours['rowaltbg']
			rowcount += 1
			try:

				self.netwidgets[k]['bsent'].configure(text = self.sizeof_fmt(v['bytes_sent']))
				self.netwidgets[k]['breceived'].configure(text = self.sizeof_fmt(v['bytes_recv']))
			except:
				self.netwidgets[k] = {}
				self.netwidgets[k]['name'] = Tkinter.Label(self.netwidgets['trafficdata'],text=k, bg=rowcolour, fg=self.colours['fg'])
				self.netwidgets[k]['name'].grid(column=0,row=self.gridrows['traffic'],sticky='EW')
				self.netwidgets[k]['bsent'] = Tkinter.Label(self.netwidgets['trafficdata'],text=self.sizeof_fmt(v['bytes_sent']), bg=rowcolour, fg=self.colours['fg'])
				self.netwidgets[k]['bsent'].grid(column=1,row=self.gridrows['traffic'],sticky='EW')
				self.netwidgets[k]['breceived'] = Tkinter.Label(self.netwidgets['trafficdata'],text=self.sizeof_fmt(v['bytes_recv']), bg=rowcolour, fg=self.colours['fg'])
				self.netwidgets[k]['breceived'].grid(column=2,row=self.gridrows['traffic'],sticky='EW')
			self.gridrows['traffic'] += 1
		self.gridrows['connections'] = 2
		for k,v in network['conns'].iteritems():
			rowcolour = self.colours['rowbg']
			if(rowcount % 2 == 0):
				rowcolour = self.colours['rowaltbg']
			rowcount += 1
			try:
				self.connwidgets[k]['bstatus'].configure(text = v['status'])
				self.connwidgets[k]['status'] = v['status']
			except:
				self.connwidgets[k] = {}
				self.connwidgets[k]['ladd'] = Tkinter.Label(self.netwidgets['connectiondata'],text=v['laddr'][0] if len(v['laddr']) > 0 else '', bg=rowcolour, fg=self.colours['fg'])
				self.connwidgets[k]['ladd'].grid(column=0,row=self.gridrows['connections'],sticky='EW')
				self.connwidgets[k]['lport'] = Tkinter.Label(self.netwidgets['connectiondata'],text=v['laddr'][1] if len(v['laddr']) > 0 else '', bg=rowcolour, fg=self.colours['fg'])
				self.connwidgets[k]['lport'].grid(column=1,row=self.gridrows['connections'],sticky='EW')
				self.connwidgets[k]['radd'] = Tkinter.Label(self.netwidgets['connectiondata'],text=v['raddr'][0] if len(v['raddr']) > 0 else '', bg=rowcolour, fg=self.colours['fg'])
				self.connwidgets[k]['radd'].grid(column=2,row=self.gridrows['connections'],sticky='EW')
				self.connwidgets[k]['rport'] = Tkinter.Label(self.netwidgets['connectiondata'],text=v['laddr'][1] if len(v['raddr']) > 0 else '', bg=rowcolour, fg=self.colours['fg'])
				self.connwidgets[k]['rport'].grid(column=3,row=self.gridrows['connections'],sticky='EW')
				self.connwidgets[k]['bstatus'] = Tkinter.Label(self.netwidgets['connectiondata'],text=v['status'], bg=rowcolour, fg=self.colours['fg'])
				self.connwidgets[k]['bstatus'].grid(column=4,row=self.gridrows['connections'],sticky='EW')
			self.gridrows['connections'] += 1
	
	#=== ACTIONS ===#
	##== Archive ==##
	def OnToggleCpuClick(self):
		Setting.set('resource_archive_cpu', self.variables['archiveCpu'].get())
	def OnToggleMemoryClick(self):
		Setting.set('resource_archive_mem', self.variables['archiveMem'].get())
	def OnToggleTempClick(self):
		Setting.set('resource_archive_temp', self.variables['archiveTemp'].get())
	def OnToggleDisksClick(self):
		Setting.set('resource_archive_disks', self.variables['archiveDisks'].get())
	def OnToggleProcessesClick(self):
		Setting.set('resource_archive_processes', self.variables['archiveProcess'].get())
	def OnToggleThreadsClick(self):
		Setting.set('resource_archive_threads', self.variables['archiveThread'].get())
	def OnToggleNetworkClick(self):
		Setting.set('resource_archive_net', self.variables['archiveNet'].get())
	
	#=== UTILS ===#
	def sizeof_fmt(self, num):
		for x in ['bytes','KB','MB','GB','TB']:
			if num < 1024.0:
				return "%3.1f %s" % (num, x)
			num /= 1024.0
Esempio n. 4
0
class TkGravityManager(TkPage):
    def __init__(self, parent, gui, **options):
        """ Initializes TkGravityManager object
		
		@param parent
		@param gui
		@param options
		"""
        super(TkGravityManager, self).__init__(parent, gui, **options)
        self.initDependencyManager()
        if (hasattr(self.gui, 'scheduler')):
            self.scheduler = self.gui.scheduler
        else:
            self.scheduler = Scheduler.GetInstance()
        if (not self.pm.installRequired()):
            if (hasattr(self.gui, 'imu')):
                self.imu = self.gui.imu
            else:
                self.imu = self.gui.imu = IMU(
                    self.scheduler, (not Setting.get('imu_autostart', False)))
            self.groundcoords = [[0, 237], [800, 237], [800, 800], [0, 800]]
            self.centre = complex(237, 237)
            self.shapes = {}
            self.cache = {}
            self.basepath = AmsEnvironment.AppPath()
            self.pimg = self.gui.getModule('PIL.Image')
            self.tkimg = self.gui.getModule('PIL.ImageTk')
            self.initImages()
            self.scheduler.addTask('gravity_display', self.updateGravity, 0.2,
                                   True)

    def initDependencyManager(self):
        """ setup dependency checks
		"""
        dependencies = [{
            'package': 'python-imaging',
            'installer': 'apt-get'
        }, {
            'package': 'python-imaging-tk',
            'installer': 'apt-get'
        }, {
            'package': 'tk8.5',
            'installer': 'apt-get'
        }, {
            'package': 'tcl8.5',
            'installer': 'apt-get'
        }, {
            'package': 'pillow',
            'installer': 'pip',
            'version': '2.6.1'
        }]
        self.pm = TkDependencyManager(self.widget, dependencies,
                                      'Gravity Manager', self.gui)

    def initImages(self):
        """ setup required images
		"""
        self.oimages = {}
        self.oimages['reticle'] = self.pimg.Image.open(
            os.path.join(self.basepath,
                         'images/horizon/reticle.png')).convert('RGBA')
        self.oimages['mask'] = self.pimg.Image.open(
            os.path.join(self.basepath,
                         'images/horizon/mask.png')).convert('RGBA')

    def getImage(self, name, angle):
        """ gets an image from cache or caches it
		
		@param name
		@param angle
		"""
        try:
            self.cache[name]
        except:
            self.cache[name] = {}
        try:
            self.cache[name][angle]
        except:
            self.cache[name][angle] = self.tkimg.ImageTk.PhotoImage(
                self.oimages[name].rotate(angle))
        return self.cache[name][angle]

    def setup(self):
        """ setup gui menu
		"""
        try:
            self.gui.menus['imu']
        except:
            self.gui.menus['imu'] = Tkinter.Menu(
                self.gui.menubar,
                tearoff=0,
                bg=self.colours['menubg'],
                fg=self.colours['menufg'],
                activeforeground=self.colours['menuactivefg'],
                activebackground=self.colours['menuactivebg'])
            self.addMenu(label="IMU", menu=self.gui.menus['imu'])
        self.gui.menus['imu'].insert_command(2,
                                             label="Gravity",
                                             command=self.OnGravityClick)

    #=== VIEWS ===#
    def serviceManager(self):
        """ view - imu service manager
		"""
        self.widgets['servicelabel'] = Tkinter.Label(
            self.widgets['tframe'],
            text='IMU / IMU Service',
            anchor=NW,
            bg=self.colours['bg'],
            fg=self.colours['headingfg'],
            font=self.fonts['heading'])
        self.widgets['servicelabel'].grid(column=0,
                                          row=self.gridrow,
                                          sticky='EW')

        self.gridrow += 1

        self.widgets['sframe'] = Tkinter.Frame(self.widgets['tframe'],
                                               bg=self.colours['bg'])
        self.widgets['sframe'].grid(column=0, row=self.gridrow, sticky='W')

        self.widgets['statusLabel'] = Tkinter.Label(
            self.widgets['sframe'],
            text='Status',
            bg=self.colours['bg'],
            fg=self.colours['headingfg'],
            font=self.fonts['heading2'])
        self.widgets['statusLabel'].grid(column=0, row=0, sticky='EW')

        self.variables['status'] = Tkinter.StringVar()
        self.widgets['statusdata'] = Tkinter.Label(
            self.widgets['sframe'],
            textvariable=self.variables['status'],
            bg=self.colours['bg'],
            fg=self.colours['fg'],
            font=self.fonts['heading2'])
        self.widgets['statusdata'].grid(column=0, row=1, padx=50, sticky='EW')

        self.widgets['start'] = Tkinter.Button(
            self.widgets['sframe'],
            text=u"Start",
            image=self.images['play'],
            command=self.OnStartClick,
            bg=self.colours['buttonbg'],
            activebackground=self.colours['buttonhighlightbg'],
            highlightbackground=self.colours['buttonborder'])
        self.widgets['start'].grid(column=1, row=1, sticky='W')

        self.widgets['stop'] = Tkinter.Button(
            self.widgets['sframe'],
            text=u"Stop",
            image=self.images['stop'],
            command=self.OnStopClick,
            bg=self.colours['buttonbg'],
            activebackground=self.colours['buttonhighlightbg'],
            highlightbackground=self.colours['buttonborder'])
        self.widgets['stop'].grid(column=2, row=1, sticky='W')

        if (self.scheduler.tasks['imu_watcher'].stopped == False):
            self.variables['status'].set('Running')
            self.widgets['start'].configure(state='disabled')
        else:
            self.variables['status'].set('Stopped')
            self.widgets['stop'].configure(state='disabled')

    def showGravity(self):
        """ view - displays graviry ui
		"""
        if (not IMU.isAvailable()):
            return self.unavailable()

        self.open()

        self.serviceManager()

        self.gridrow += 1

        self.widgets['frameLabel'] = Tkinter.Label(
            self.widgets['tframe'],
            text='IMU / Gravity',
            anchor=NW,
            bg=self.colours['bg'],
            fg=self.colours['headingfg'],
            font=self.fonts['heading'])
        self.widgets['frameLabel'].grid(column=0, row=self.gridrow, sticky='W')

        self.gridrow += 1

        self.widgets['gframe'] = Tkinter.Frame(self.widgets['tframe'],
                                               bg=self.colours['bg'])
        self.widgets['gframe'].grid(column=0,
                                    row=self.gridrow,
                                    columnspan=3,
                                    sticky='EW')
        self.widgets['gframe'].columnconfigure(0, weight=1)
        self.widgets['tframe'].columnconfigure(0, weight=1)

        self.widgets['rollLabel'] = Tkinter.Label(self.widgets['gframe'],
                                                  text='TBD',
                                                  bg=self.colours['bg'],
                                                  fg=self.colours['fg'],
                                                  font=self.fonts['heading2'])
        self.widgets['rollLabel'].grid(column=0, row=self.gridrow, sticky='EW')

        self.gridrow += 1

        self.widgets['hCanvas'] = Tkinter.Canvas(self.widgets['gframe'],
                                                 borderwidth=0,
                                                 bg=self.colours['bg'],
                                                 highlightthickness=0,
                                                 width=474,
                                                 height=474)
        self.widgets['hCanvas'].grid(column=0,
                                     row=self.gridrow,
                                     padx=10,
                                     sticky='EW')
        self.shapes['skyplane'] = self.widgets['hCanvas'].create_polygon(
            [(0, 0), (474, 0), (474, 474), (0, 474)], fill='#fff')
        self.shapes['groundplane'] = self.widgets['hCanvas'].create_polygon(
            self.groundcoords, fill='#828282')
        self.shapes['mask'] = self.widgets['hCanvas'].create_image(
            self.centre.real, self.centre.imag, image=self.getImage('mask', 0))
        self.shapes['reticle'] = self.widgets['hCanvas'].create_image(
            self.centre.real,
            self.centre.imag,
            image=self.getImage('reticle', 0))

        self.widgets['pitchLabel'] = Tkinter.Label(self.widgets['gframe'],
                                                   text='TBD',
                                                   anchor=W,
                                                   bg=self.colours['bg'],
                                                   fg=self.colours['fg'],
                                                   font=self.fonts['heading2'])
        self.widgets['pitchLabel'].grid(column=1,
                                        row=self.gridrow,
                                        sticky='NS')

    def updateGravity(self):
        """ util - updates gravity ui
		"""
        try:
            self.last
        except:
            self.last = {'roll': 0, 'pitch': 0, 'yaw': 0}
        metric = self.imu.metrics['acc_ang'].value
        if (metric != None):
            p = int(metric['p'])
            r = int(metric['r'])
            if (self.last['pitch'] != p or self.last['roll'] != r):
                newcoords = [x[:] for x in self.groundcoords]
                if (self.last['pitch'] != p):
                    self.last['pitch'] = p
                    self.widgets['pitchLabel'].configure(
                        text=str(p), fg=self.colours['valuefg'])
                for c in newcoords:
                    c[1] += 4.444 * -p
                if (self.last['roll'] != r):
                    self.last['roll'] = r
                    self.widgets['rollLabel'].configure(
                        text=str(r), fg=self.colours['valuefg'])
                cangle = cmath.exp(math.radians(r) * 1j)
                newpoly = []
                for x, y in newcoords:
                    new = cangle * (complex(x, y) - self.centre) + self.centre
                    newpoly.append(int(new.real))
                    newpoly.append(int(new.imag))
                self.widgets['hCanvas'].coords(self.shapes['groundplane'],
                                               *newpoly)

    def unavailable(self):
        """ view - fallback for missing imu
		"""
        self.open()

        self.widgets['frameLabel'] = Tkinter.Label(
            self.widgets['tframe'],
            text='IMU / Unavailable',
            anchor=NW,
            bg=self.colours['bg'],
            fg=self.colours['headingfg'],
            font=self.fonts['heading'])
        self.widgets['frameLabel'].grid(column=0,
                                        row=self.gridrow,
                                        sticky='EW')

        self.gridrow += 1

        self.widgets['frameLabel'] = Tkinter.Label(
            self.widgets['tframe'],
            text='The MPU6050 has not been detected.',
            anchor=NW,
            bg=self.colours['bg'],
            fg=self.colours['headingfg'])
        self.widgets['frameLabel'].grid(column=0,
                                        row=self.gridrow,
                                        sticky='EW')

    #=== ACTIONS ===#
    def OnStartClick(self):
        """ action - starts the imu service
		"""
        self.widgets['start'].configure(state='disabled')
        self.widgets['stop'].configure(state='normal')
        self.variables['status'].set('Running')
        Setting.set('imu_watch_norm', True)
        Setting.set('imu_watch_low', True)
        Setting.set('imu_watch_ang', True)
        self.imu.start()
        self.scheduler.startTask('gravity_display')

    def OnStopClick(self):
        """ action - stops the imu service
		"""
        self.widgets['start'].configure(state='normal')
        self.widgets['stop'].configure(state='disabled')
        self.variables['status'].set('Stopped')
        self.scheduler.stopTask('gravity_display')
        self.imu.stop()

    def OnToggleAutostartClick(self):
        """ action - toggles imu service autostart
		"""
        self.autostart = Setting.set('imu_autostart',
                                     self.variables['autostart'].get())

    def OnGravityClick(self):
        """ action - displays the gravity page
		"""
        if (not self.pm.installRequired()):
            self.showGravity()
        else:
            self.open()
            self.pm.addManager()
Esempio n. 5
0
class TkOrthoManager(TkPage):
    def __init__(self, parent, gui, **options):
        super(TkOrthoManager, self).__init__(parent, gui, **options)
        self.specification = gui.specification
        self.initDependencyManager()
        if hasattr(self.gui, "scheduler"):
            self.scheduler = self.gui.scheduler
        else:
            self.scheduler = Scheduler()
        if not self.dm.installRequired():
            self.pimg = self.gui.getModule("PIL.Image")
            self.tkimg = self.gui.getModule("PIL.ImageTk")
            if hasattr(self.gui, "imu"):
                self.imu = self.gui.imu
            else:
                self.imu = self.gui.imu = IMU(
                    self.specification, self.scheduler, (not Setting.get("imu_autostart", False))
                )
            self.shapes = {}
            self.cache = {"roll": {}, "pitch": {}, "yaw": {}}
            self.basepath = os.getcwd()
            self.initImages()
            self.scheduler.addTask("ortho", self.updateOrtho, 0.2, True)

    def initDependencyManager(self):
        dependencies = [
            {"package": "python-imaging", "installer": "apt-get"},
            {"package": "python-imaging-tk", "installer": "apt-get"},
            {"package": "tk8.5-dev", "installer": "apt-get"},
            {"package": "tcl8.5-dev", "installer": "apt-get"},
            {"package": "pillow", "installer": "pip", "version": "2.6.1"},
        ]
        self.dm = TkDependencyManager(self.widget, dependencies, "Orthographic Manager", self.gui)

    def setup(self):
        try:
            self.gui.menus["imu"]
        except:
            self.gui.menus["imu"] = Tkinter.Menu(
                self.gui.menubar,
                tearoff=0,
                bg=self.colours["menubg"],
                fg=self.colours["menufg"],
                activeforeground=self.colours["menuactivefg"],
                activebackground=self.colours["menuactivebg"],
            )
            self.addMenu(label="IMU", menu=self.gui.menus["imu"])
        self.gui.menus["imu"].insert_command(3, label="Orthographic", command=self.OnShowOrthographicClick)

    def initImages(self):
        self.oimages = {}
        self.oimages["roll"] = self.pimg.Image.open(
            os.path.join(self.basepath, "images/orthographic/front.png")
        ).convert("RGBA")
        self.oimages["pitch"] = self.pimg.Image.open(
            os.path.join(self.basepath, "images/orthographic/right.png")
        ).convert("RGBA")
        self.oimages["yaw"] = self.pimg.Image.open(os.path.join(self.basepath, "images/orthographic/top.png")).convert(
            "RGBA"
        )

    def buildCache(self):
        if not any(self.cache["roll"]):
            for i in range(-30, 30):
                self.cache["roll"][i] = self.tkimg.ImageTk.PhotoImage(self.oimages["roll"].rotate(i))
                self.cache["pitch"][i] = self.tkimg.ImageTk.PhotoImage(self.oimages["pitch"].rotate(i))
                self.cache["yaw"][i] = self.tkimg.ImageTk.PhotoImage(self.oimages["yaw"].rotate(i))

    def getImage(self, axis, angle):
        try:
            self.cache[axis][angle]
        except:
            self.cache[axis][angle] = self.tkimg.ImageTk.PhotoImage(self.oimages[axis].rotate(angle))
        return self.cache[axis][angle]

        # === VIEWS ===#

    def serviceManager(self):
        self.widgets["servicelabel"] = Tkinter.Label(
            self.widgets["tframe"],
            text="IMU / IMU Service",
            anchor=NW,
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
            font=self.fonts["heading"],
        )
        self.widgets["servicelabel"].grid(column=0, row=self.gridrow, sticky="EW")

        self.gridrow += 1

        self.widgets["sframe"] = Tkinter.Frame(self.widgets["tframe"], bg=self.colours["bg"])
        self.widgets["sframe"].grid(column=0, row=self.gridrow, sticky="W")

        self.widgets["statusLabel"] = Tkinter.Label(
            self.widgets["sframe"],
            text="Status",
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
            font=self.fonts["heading2"],
        )
        self.widgets["statusLabel"].grid(column=0, row=0, sticky="EW")

        self.variables["status"] = Tkinter.StringVar()
        self.widgets["statusdata"] = Tkinter.Label(
            self.widgets["sframe"],
            textvariable=self.variables["status"],
            bg=self.colours["bg"],
            fg=self.colours["fg"],
            font=self.fonts["heading2"],
        )
        self.widgets["statusdata"].grid(column=0, row=1, padx=50, sticky="EW")

        self.widgets["start"] = Tkinter.Button(
            self.widgets["sframe"],
            text=u"Start",
            image=self.images["play"],
            command=self.OnStartClick,
            bg=self.colours["buttonbg"],
            activebackground=self.colours["buttonhighlightbg"],
            highlightbackground=self.colours["buttonborder"],
        )
        self.widgets["start"].grid(column=1, row=1, sticky="W")

        self.widgets["stop"] = Tkinter.Button(
            self.widgets["sframe"],
            text=u"Stop",
            image=self.images["stop"],
            command=self.OnStopClick,
            bg=self.colours["buttonbg"],
            activebackground=self.colours["buttonhighlightbg"],
            highlightbackground=self.colours["buttonborder"],
        )
        self.widgets["stop"].grid(column=2, row=1, sticky="W")

        if self.scheduler.tasks["imu_watcher"].stopped == False:
            self.variables["status"].set("Running")
            self.widgets["start"].configure(state="disabled")
        else:
            self.variables["status"].set("Stopped")
            self.widgets["stop"].configure(state="disabled")

        self.gridrow += 1

        self.widgets["orientframe"] = Tkinter.Frame(self.widgets["tframe"], bg=self.colours["bg"])
        self.widgets["orientframe"].grid(column=0, row=self.gridrow, sticky="W")

        self.widgets["orientLabel"] = Tkinter.Label(
            self.widgets["orientframe"], text="Mounted", bg=self.colours["bg"], fg=self.colours["headingfg"], height=3
        )
        self.widgets["orientLabel"].grid(column=0, row=0, padx=10, sticky="EW")

        self.widgets["orientLabel"] = Tkinter.Label(
            self.widgets["orientframe"], text="Facing", bg=self.colours["bg"], fg=self.colours["headingfg"], height=3
        )
        self.widgets["orientLabel"].grid(column=1, row=0, padx=10, sticky="EW")

        self.widgets["orientLabel"] = Tkinter.Label(
            self.widgets["orientframe"],
            text=self.specification.imu["facing"],
            bg=self.colours["bg"],
            fg=self.colours["valuefg"],
            height=3,
        )
        self.widgets["orientLabel"].grid(column=2, row=0, padx=10, sticky="EW")

        self.widgets["orientLabel"] = Tkinter.Label(
            self.widgets["orientframe"], text="Offset", bg=self.colours["bg"], fg=self.colours["headingfg"], height=3
        )
        self.widgets["orientLabel"].grid(column=3, row=0, padx=10, sticky="EW")

        self.widgets["orientLabel"] = Tkinter.Label(
            self.widgets["orientframe"],
            text=self.specification.imu["offset"],
            bg=self.colours["bg"],
            fg=self.colours["valuefg"],
            height=3,
        )
        self.widgets["orientLabel"].grid(column=4, row=0, padx=10, sticky="EW")

    def showOrthographic(self):
        if not IMU.isAvailable():
            return self.unavailable()

        self.open()

        self.serviceManager()

        self.gridrow += 1

        self.widgets["frameLabel"] = Tkinter.Label(
            self.widgets["tframe"],
            text="IMU / Orthographic",
            anchor=NW,
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
            font=self.fonts["heading"],
        )
        self.widgets["frameLabel"].grid(column=0, row=self.gridrow, sticky="W")

        self.gridrow += 1

        self.widgets["oframe"] = Tkinter.Frame(self.widgets["tframe"], bg=self.colours["bg"])
        self.widgets["oframe"].grid(column=0, row=self.gridrow, columnspan=3, sticky="EW")

        self.widgets["rollLabel"] = Tkinter.Label(
            self.widgets["oframe"],
            text="Roll",
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
            font=self.fonts["heading2"],
        )
        self.widgets["rollLabel"].grid(column=0, row=self.gridrow, sticky="EW")

        self.widgets["pitchLabel"] = Tkinter.Label(
            self.widgets["oframe"],
            text="Pitch",
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
            font=self.fonts["heading2"],
        )
        self.widgets["pitchLabel"].grid(column=1, row=self.gridrow, sticky="EW")

        self.widgets["yawLabel"] = Tkinter.Label(
            self.widgets["oframe"],
            text="Yaw",
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
            font=self.fonts["heading2"],
        )
        self.widgets["yawLabel"].grid(column=2, row=self.gridrow, sticky="EW")

        self.gridrow += 1

        self.widgets["rollCanvas"] = Tkinter.Canvas(
            self.widgets["oframe"], borderwidth=0, bg=self.colours["bg"], highlightthickness=0, width=280, height=280
        )
        self.widgets["rollCanvas"].grid(column=0, row=self.gridrow, padx=10, sticky="NE")
        self.shapes["rollImage"] = self.widgets["rollCanvas"].create_image(150, 150, image=self.getImage("roll", 0))

        self.widgets["pitchCanvas"] = Tkinter.Canvas(
            self.widgets["oframe"], borderwidth=0, bg=self.colours["bg"], highlightthickness=0, width=280, height=280
        )
        self.widgets["pitchCanvas"].grid(column=1, row=self.gridrow, padx=10, sticky="NE")
        self.shapes["pitchImage"] = self.widgets["pitchCanvas"].create_image(150, 150, image=self.getImage("pitch", 0))

        self.widgets["yawCanvas"] = Tkinter.Canvas(
            self.widgets["oframe"], borderwidth=0, bg=self.colours["bg"], highlightthickness=0, width=280, height=280
        )
        self.widgets["yawCanvas"].grid(column=2, row=self.gridrow, padx=10, sticky="NE")
        self.shapes["yawImage"] = self.widgets["yawCanvas"].create_image(150, 150, image=self.getImage("yaw", 0))

    def updateOrtho(self):
        try:
            self.last
        except:
            self.last = {"roll": 0, "pitch": 0, "yaw": 0}
        try:
            metric = self.imu.metrics["complement"].value
            if self.last["roll"] != metric["r"]:
                self.last["roll"] = metric["r"]
                self.widgets["rollCanvas"].itemconfigure(
                    self.shapes["rollImage"], image=self.getImage("roll", int(-metric["r"]))
                )
            if self.last["pitch"] != metric["p"]:
                self.last["pitch"] = metric["p"]
                self.widgets["pitchCanvas"].itemconfigure(
                    self.shapes["pitchImage"], image=self.getImage("pitch", int(-metric["p"]))
                )
            if self.last["yaw"] != metric["y"]:
                self.last["yaw"] = metric["y"]
                self.widgets["yawCanvas"].itemconfigure(
                    self.shapes["yawImage"], image=self.getImage("yaw", int(metric["y"]))
                )
        except:
            pass

    def unavailable(self):
        self.open()

        self.widgets["frameLabel"] = Tkinter.Label(
            self.widgets["tframe"],
            text="IMU / Unavailable",
            anchor=NW,
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
            font=self.fonts["heading"],
        )
        self.widgets["frameLabel"].grid(column=0, row=self.gridrow, sticky="EW")

        self.gridrow += 1

        self.widgets["frameLabel"] = Tkinter.Label(
            self.widgets["tframe"],
            text="The MPU6050 has not been detected.",
            anchor=NW,
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
        )
        self.widgets["frameLabel"].grid(column=0, row=self.gridrow, sticky="EW")

        # === ACTIONS ===#

    def OnStartClick(self):
        self.widgets["start"].configure(state="disabled")
        self.widgets["stop"].configure(state="normal")
        self.variables["status"].set("Running")
        Setting.set("imu_watch_raw", True)
        Setting.set("imu_watch_norm", True)
        Setting.set("imu_watch_low", True)
        Setting.set("imu_watch_com", True)
        self.imu.start()
        self.scheduler.startTask("ortho")

    def OnStopClick(self):
        self.widgets["start"].configure(state="normal")
        self.widgets["stop"].configure(state="disabled")
        self.variables["status"].set("Stopped")
        self.scheduler.stopTask("ortho")
        self.imu.stop()

    def OnShowOrthographicClick(self):
        if not self.dm.installRequired():
            self.buildCache()
            self.showOrthographic()
        else:
            self.open()
            self.dm.addManager()
class TkGravityManager(TkPage):
	def __init__(self, parent, gui, **options):
		super(TkGravityManager,self).__init__(parent, gui, **options)
		self.initDependencyManager()
		if(hasattr(self.gui, 'scheduler')):
			self.scheduler = self.gui.scheduler
		else:
			self.scheduler = Scheduler()
		if(not self.pm.installRequired()):
			if(hasattr(self.gui, 'imu')):
				self.imu = self.gui.imu
			else:
				self.imu = self.gui.imu = IMU(self.scheduler, (not Setting.get('imu_autostart', False)))
			self.groundcoords = [[0, 237], [800, 237], [800, 800], [0, 800]]
			self.centre = complex(237,237)
			self.shapes = {}
			self.cache = {}
			self.basepath = os.getcwd()
			self.pimg = self.gui.getModule('PIL.Image')
			self.tkimg = self.gui.getModule('PIL.ImageTk')
			self.initImages()
			self.scheduler.addTask('gravity_display', self.updateGravity, 0.2, True)
	def initDependencyManager(self):
		dependencies = [
			{'package':'python-imaging', 'installer': 'apt-get'},
			{'package':'python-imaging-tk', 'installer': 'apt-get'},
			{'package':'tk8.5-dev', 'installer': 'apt-get'},
			{'package':'tcl8.5-dev', 'installer': 'apt-get'},
			{'package':'pillow', 'installer': 'pip', 'version': '2.6.1'}
		]
		self.pm = TkDependencyManager(self.widget, dependencies, 'Gravity Manager', self.gui)
	def initImages(self):
		self.oimages = {}
		self.oimages['reticle'] = self.pimg.Image.open(os.path.join(self.basepath, 'images/horizon/reticle.png')).convert('RGBA')
		self.oimages['mask'] = self.pimg.Image.open(os.path.join(self.basepath, 'images/horizon/mask.png')).convert('RGBA')
	def getImage(self, name, angle):
		try:
			self.cache[name]
		except:
			self.cache[name] = {}
		try:
			self.cache[name][angle]
		except:
			self.cache[name][angle] = self.tkimg.ImageTk.PhotoImage(self.oimages[name].rotate(angle))
		return self.cache[name][angle]
	def setup(self):
		try:
			self.gui.menus['imu']
		except:
			self.gui.menus['imu'] = Tkinter.Menu(self.gui.menubar, tearoff=0, bg=self.colours['menubg'], fg=self.colours['menufg'], activeforeground=self.colours['menuactivefg'], activebackground=self.colours['menuactivebg'])
			self.addMenu(label="IMU", menu=self.gui.menus['imu'])
		self.gui.menus['imu'].insert_command(2, label="Gravity", command=self.OnGravityClick)
	
	#=== VIEWS ===#
	def serviceManager(self):
		self.widgets['servicelabel'] = Tkinter.Label(self.widgets['tframe'],text='IMU / IMU Service', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['servicelabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['sframe'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['sframe'].grid(column=0,row=self.gridrow, sticky='W')
		
		self.widgets['statusLabel'] = Tkinter.Label(self.widgets['sframe'],text='Status', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['statusLabel'].grid(column=0,row=0,sticky='EW')
		
		self.variables['status'] = Tkinter.StringVar()
		self.widgets['statusdata'] = Tkinter.Label(self.widgets['sframe'],textvariable=self.variables['status'], bg=self.colours['bg'], fg=self.colours['fg'], font=self.fonts['heading2'])
		self.widgets['statusdata'].grid(column=0,row=1,padx=50, sticky='EW')
		
		self.widgets['start'] = Tkinter.Button(self.widgets['sframe'],text=u"Start", image=self.images['play'], command=self.OnStartClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['start'].grid(column=1,row=1,sticky='W')
		
		self.widgets['stop'] = Tkinter.Button(self.widgets['sframe'],text=u"Stop", image=self.images['stop'], command=self.OnStopClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['stop'].grid(column=2,row=1,sticky='W')
		
		if(self.scheduler.tasks['imu_watcher'].stopped == False):
			self.variables['status'].set('Running')
			self.widgets['start'].configure(state='disabled')
		else:
			self.variables['status'].set('Stopped')
			self.widgets['stop'].configure(state='disabled')
	def showGravity(self):
		if (not IMU.isAvailable()):
			return self.unavailable()
		
		self.open()
		
		self.serviceManager()
		
		self.gridrow += 1
		
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='IMU / Gravity', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='W')
		
		self.gridrow += 1
		
		self.widgets['gframe'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['gframe'].grid(column=0,row=self.gridrow, columnspan = 3, sticky='EW')
		self.widgets['gframe'].columnconfigure(0, weight=1)
		self.widgets['tframe'].columnconfigure(0, weight=1)

		self.widgets['rollLabel'] = Tkinter.Label(self.widgets['gframe'],text='TBD', bg=self.colours['bg'], fg=self.colours['fg'], font=self.fonts['heading2'])
		self.widgets['rollLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['hCanvas'] = Tkinter.Canvas(self.widgets['gframe'], borderwidth=0, bg=self.colours['bg'], highlightthickness=0, width=474, height=474)
		self.widgets['hCanvas'].grid(column=0,row=self.gridrow, padx= 10,sticky='EW')
		self.shapes['skyplane'] = self.widgets['hCanvas'].create_polygon([(0, 0), (474, 0), (474, 474), (0, 474)], fill='#fff')
		self.shapes['groundplane'] = self.widgets['hCanvas'].create_polygon(self.groundcoords, fill='#828282')
		self.shapes['mask'] = self.widgets['hCanvas'].create_image(self.centre.real, self.centre.imag, image=self.getImage('mask',0))
		self.shapes['reticle'] = self.widgets['hCanvas'].create_image(self.centre.real, self.centre.imag, image=self.getImage('reticle',0))
		
		self.widgets['pitchLabel'] = Tkinter.Label(self.widgets['gframe'],text='TBD', anchor=W, bg=self.colours['bg'], fg=self.colours['fg'], font=self.fonts['heading2'])
		self.widgets['pitchLabel'].grid(column=1,row=self.gridrow,sticky='NS')
	def updateGravity(self):
		try:
			self.last
		except:
			self.last = { 'roll': 0, 'pitch': 0, 'yaw': 0 }
		metric = self.imu.metrics['acc_ang'].value
		if(metric != None):
			p = int(metric['p'])
			r = int(metric['r'])
			if(self.last['pitch'] != p or self.last['roll'] != r):
				newcoords = [x[:] for x in self.groundcoords]
				if(self.last['pitch'] != p):
					self.last['pitch'] = p
					self.widgets['pitchLabel'].configure(text=str(p), fg=self.colours['valuefg'])
				for c in newcoords:
					c[1] += 4.444 * -p
				if(self.last['roll'] != r):
					self.last['roll'] = r
					self.widgets['rollLabel'].configure(text=str(r), fg=self.colours['valuefg'])
				cangle = cmath.exp(math.radians(r)*1j)
				newpoly = []
				for x, y in newcoords:
					new = cangle * (complex(x,y) - self.centre) + self.centre
					newpoly.append(int(new.real))
					newpoly.append(int(new.imag))
				self.widgets['hCanvas'].coords(self.shapes['groundplane'], *newpoly)
	def unavailable(self):
		self.open()
		
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='IMU / Unavailable', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='The MPU6050 has not been detected.', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
	#=== ACTIONS ===#
	def OnStartClick(self):
		self.widgets['start'].configure(state='disabled')
		self.widgets['stop'].configure(state='normal')
		self.variables['status'].set('Running')
		Setting.set('imu_watch_norm', True)
		Setting.set('imu_watch_low', True)
		Setting.set('imu_watch_ang', True)
		self.imu.start()
		self.scheduler.startTask('gravity_display')
	def OnStopClick(self):
		self.widgets['start'].configure(state='normal')
		self.widgets['stop'].configure(state='disabled')
		self.variables['status'].set('Stopped')
		self.scheduler.stopTask('gravity_display')
		self.imu.stop()
	def OnToggleAutostartClick(self):
		self.autostart = Setting.set('imu_autostart', self.variables['autostart'].get())
	def OnGravityClick(self):
		if(not self.pm.installRequired()):
			self.showGravity()
		else:
			self.open()
			self.pm.addManager()
Esempio n. 7
0
class TkRPCManager(TkPage):
	def __init__(self, parent, gui, **options):
		""" Initializes TkRPCManager object
		
		@param parent
		@param gui
		@param options
		"""
		super(TkRPCManager,self).__init__(parent, gui, **options)
		self.scheduler = self.gui.scheduler
		self.now = lambda: int(round(time.time() * 1000))
		self.urlshown = None
		dependencies = [
			{'package':'OpenSSL', 'installer': 'apt-get'},
			{'package':'python-openssl', 'installer': 'apt-get'}
		]
		self.dm = TkDependencyManager(self.widget, dependencies, 'RPC Manager', self.gui)
		if(not self.dm.installRequired()):
			self.ssl = SSLManager()
			self.scheduler.addTask('rpc_url_watcher', self.__hideUrl, 10)
			try:
				self.rpcserver = TkRPCManager.rpcserver
			except:
				TkRPCManager.rpcserver = self.rpcserver = self.gui.getClass('SRPC.SRPCServer')(motionScheduler = self.gui.motionScheduler, specification = self.gui.specification, scheduler = self.gui.scheduler)
	def setup(self):
		""" setup gui menu
		"""
		self.gui.menus['rpc'] = Tkinter.Menu(self.gui.menubar, tearoff=0, bg=self.colours['menubg'], fg=self.colours['menufg'], activeforeground=self.colours['menuactivefg'], activebackground=self.colours['menuactivebg'])
		self.gui.menus['rpc'].add_command(label="Manage Server", command=self.OnManageRPCClick)
		self.addMenu(label="RPC", menu=self.gui.menus['rpc'])
	
	#=== VIEWS ===#
	def serverManager(self):
		""" view - RPC service manager
		"""
		self.open()
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='RPC Server', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['serviceLabel'] = Tkinter.Label(self.widgets['tframe'],text='Service', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['serviceLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.variables['status'] = Tkinter.StringVar()
		self.widgets['statusdata'] = Tkinter.Label(self.widgets['tframe'],textvariable=self.variables['status'], bg=self.colours['bg'], fg=self.colours['fg'], font=self.fonts['heading2'])
		self.widgets['statusdata'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['controlframe'] = Tkinter.Frame(self.widgets['tframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['controlframe'].grid(column = 1, row = self.gridrow, padx=20, columnspan=2, sticky = "WENS")
		
		self.widgets['startbutton'] = Tkinter.Button(self.widgets['controlframe'],text=u"Start RPC Server", image=self.images['play'], command=self.OnStartClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['startbutton'].grid(column=1,row=0, padx=10)
		
		self.widgets['stopbutton'] = Tkinter.Button(self.widgets['controlframe'],text=u"Stop RPC Server", image=self.images['stop'], command=self.OnStopClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['stopbutton'].grid(column=2,row=0, padx=10)
		
		self.variables['autostart'] = Tkinter.BooleanVar()
		self.variables['autostart'].set(Setting.get('rpc_autostart', False))
		self.widgets['autostartentry'] = Tkinter.Checkbutton(self.widgets['controlframe'], text="Autostart", variable=self.variables['autostart'], command=self.OnToggleAutostartClick, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.widgets['autostartentry'].grid(column=3,row=0, padx=10)
		
		if(self.rpcserver.isRunning() == False):
			self.variables['status'].set('Stopped')
			self.widgets['startbutton'].configure(state='normal')
			self.widgets['stopbutton'].configure(state='disabled')
		else:
			self.variables['status'].set('Running')
			self.widgets['startbutton'].configure(state='disabled')
			self.widgets['stopbutton'].configure(state='normal')
		
		self.gridrow += 1
		
		self.widgets['sslLabel'] = Tkinter.Label(self.widgets['tframe'],text='SSL Certificate', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['sslLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['startdateLabel'] = Tkinter.Label(self.widgets['tframe'],text='Start Date', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['startdateLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['startdateData'] = Tkinter.Label(self.widgets['tframe'],text=str(self.ssl.start), bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['startdateData'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.widgets['ccframe'] = Tkinter.Frame(self.widgets['tframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['ccframe'].grid(column = 3, row = self.gridrow, padx=20, columnspan=4, rowspan=5, sticky = "WENS")
		
		self.widgets['ccLabel'] = Tkinter.Label(self.widgets['ccframe'],text='Valid Country Codes', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'])
		self.widgets['ccLabel'].grid(column=0,row=0, sticky='EW')
		
		self.widgets['ccSubframe'] = Tkinter.Frame(self.widgets['ccframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['ccSubframe'].grid(column = 0, row = 1, sticky = "WENS")
		
		r,c = 0,0
		cols = 20
		
		for s in self.ssl.countryCodes():
			self.widgets['ccLabel'+s] = Tkinter.Label(self.widgets['ccSubframe'],text=s, anchor='nw', bg=self.colours['bg'], fg=self.colours['fg'])
			self.widgets['ccLabel'+s].grid(column=c,row=r,sticky='EW')
			#if (c == cols-1):
			#	r += 1
			if (c < cols):
				c = c+1 
			else:
				c = 0
				r+=1
		
		self.gridrow += 1
		
		self.widgets['enddateLabel'] = Tkinter.Label(self.widgets['tframe'],text='End Date', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['enddateLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['enddateData'] = Tkinter.Label(self.widgets['tframe'],text=str(self.ssl.end), bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['enddateData'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['domainLabel'] = Tkinter.Label(self.widgets['tframe'],text='Domain', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['domainLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['domain'] = Tkinter.StringVar()
		self.widgets['domainentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['domain'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['domainentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['domain'].set(Setting.get('rpc_server_ssl_domain', 'localhost'))
		
		self.gridrow += 1
		
		self.widgets['companyLabel'] = Tkinter.Label(self.widgets['tframe'],text='Company', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['companyLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['company'] = Tkinter.StringVar()
		self.widgets['companyentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['company'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['companyentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['company'].set(Setting.get('rpc_server_ssl_company', 'TestCo'))
		
		self.gridrow += 1
		
		self.widgets['countryLabel'] = Tkinter.Label(self.widgets['tframe'],text='Country', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['countryLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['country'] = Tkinter.StringVar()
		self.widgets['countryentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['country'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['countryentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['country'].set(Setting.get('rpc_server_ssl_country', 'GB'))
		
		self.gridrow += 1
		
		self.widgets['settingsLabel'] = Tkinter.Label(self.widgets['tframe'],text='Settings', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['settingsLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['hostnameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Hostname', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['hostnameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['hostname'] = Tkinter.StringVar()
		self.widgets['hostnameentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['hostname'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['hostnameentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['hostname'].set(Setting.get('rpc_server_hostname', 'localhost'))
		
		self.widgets['efframe'] = Tkinter.Frame(self.widgets['tframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['efframe'].grid(column = 3, row = self.gridrow, padx=20, columnspan=6, rowspan=4, sticky = "WENS")
		
		self.widgets['efLabel'] = Tkinter.Label(self.widgets['efframe'],text='Exposed Functions', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'])
		self.widgets['efLabel'].grid(column=0,row=0, sticky='EW')
		
		self.widgets['efSubframe'] = Tkinter.Frame(self.widgets['efframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['efSubframe'].grid(column = 0, row = 1, sticky = "WENS")
		r,c = 0,0
		cols = 4
		for t in self.rpcserver.listMethods():
			self.widgets[t+'Label'] = Tkinter.Label(self.widgets['efSubframe'],text=t, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
			self.widgets[t+'Label'].grid(column=c,row=r, padx=10,sticky='EW')
			if (c < cols):
				c = c+1 
			else:
				c = 0
				r+=1
		
		self.gridrow += 1
		
		self.widgets['portLabel'] = Tkinter.Label(self.widgets['tframe'],text='Port', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['portLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['port'] = Tkinter.IntVar()
		self.widgets['portentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['port'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['portentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['port'].set(Setting.get('rpc_server_port', 9000))
		
		self.gridrow += 1
		
		self.widgets['usernameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Username', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['usernameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['username'] = Tkinter.StringVar()
		self.widgets['usernameentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['username'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['usernameentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['username'].set(Setting.get('rpc_server_username', 'remoteuser'))
		
		self.gridrow += 1
		
		self.widgets['passwordLabel'] = Tkinter.Label(self.widgets['tframe'],text='Password', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['passwordLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['password'] = Tkinter.StringVar()
		self.widgets['passwordentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['password'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['passwordentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['password'].set(Setting.get('rpc_server_password', str(uuid.uuid4())))
		
		self.widgets['genbutton'] = Tkinter.Button(self.widgets['tframe'],text=u"Generate Key", image=self.images['process'], bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'], command=self.OnGeneratePasswordClick)
		self.widgets['genbutton'].grid(column=2,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['urlLabel'] = Tkinter.Label(self.widgets['tframe'],text='URL', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['urlLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['url'] = Tkinter.Label(self.widgets['tframe'],text='Click show or copy', anchor=NW, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['url'].grid(column=1,row=self.gridrow, columnspan=6, sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['optionsFrame'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['optionsFrame'].grid(column=0,row=self.gridrow,columnspan=2, sticky='EW')
		
		self.gridrow = 0
		
		self.widgets['saveLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Save', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['saveLabel'].grid(column=0,row=self.gridrow, padx=5, sticky='EW')
		self.widgets['regenLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Regenerate SSL', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['regenLabel'].grid(column=1,row=self.gridrow,padx=5, sticky='EW')
		self.widgets['showUrlLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Show URL', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['showUrlLabel'].grid(column=2,row=self.gridrow,padx=5, sticky='EW')
		self.widgets['copyUrlLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Copy URL', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['copyUrlLabel'].grid(column=3,row=self.gridrow,padx=5, sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['saveserver'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Save", image=self.images['save'], command=self.OnSaveServerClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['saveserver'].grid(column=0,row=self.gridrow)
		self.widgets['regen'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Regen", image=self.images['process'], command=self.OnRegenSSLClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['regen'].grid(column=1,row=self.gridrow)
		self.widgets['show'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Show", image=self.images['find'], command=self.OnShowUrlClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['show'].grid(column=2,row=self.gridrow)
		self.widgets['copy'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Copy", image=self.images['ram'], command=self.OnCopyUrlClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['copy'].grid(column=3,row=self.gridrow)
	
	#=== ACTIONS ===#
	def OnStartClick(self):
		""" action - start the RPC service
		"""
		self.variables['status'].set('Running')
		self.rpcserver.start()
		self.widgets['startbutton'].configure(state='disabled')
		self.widgets['stopbutton'].configure(state='normal')
	def OnStopClick(self):
		""" action - stop the RPC service
		"""
		self.variables['status'].set('Stopped')
		self.rpcserver.stop()
		self.widgets['startbutton'].configure(state='normal')
		self.widgets['stopbutton'].configure(state='disabled')
	def OnToggleAutostartClick(self):
		""" action - toggle RPC service autostart
		"""
		self.autostart = Setting.set('rpc_autostart', self.variables['autostart'].get())
	
	def OnManageRPCClick(self):
		""" action - display RPC service management page
		"""
		if(not self.dm.installRequired()):
			self.serverManager()
		else:
			self.open()
			self.dm.addManager()
	def OnSaveServerClick(self):
		""" action - save server config
		"""
		if(self.variables['hostname'].get() != '' and self.variables['port'].get() > 1000 and len(self.variables['username'].get()) > 4 and len(self.variables['password'].get()) > 4):
			hostname = Setting.set('rpc_server_hostname', self.variables['hostname'].get())
			port = Setting.set('rpc_server_port', self.variables['port'].get())
			username = Setting.set('rpc_server_username', self.variables['username'].get())
			password = Setting.set('rpc_server_password', self.variables['password'].get())
			self.notifier.addNotice('RPC server settings saved')
		else:
			self.notifier.addNotice('Invalid RPC server settings.', 'warning')
	def OnGeneratePasswordClick(self):
		""" action - generates a new password
		"""
		self.variables['password'].set(str(uuid.uuid4()))
		self.notifier.addNotice('New password generated. Click Save to apply it', 'warning')
	def OnRegenSSLClick(self):
		""" action - regenerates SSL certificate
		"""
		if(self.__validSSLDomain(self.variables['domain'].get())):
			if(self.__validSSLCompany(self.variables['company'].get())):
				if(self.__validSSLCountry(self.variables['country'].get())):
					domain = Setting.set('rpc_server_ssl_domain', self.variables['domain'].get())
					company = Setting.set('rpc_server_ssl_company', self.variables['company'].get())
					country = Setting.set('rpc_server_ssl_country', self.variables['country'].get())
					self.ssl.generateCertificate()
					self.notifier.addNotice('SSL Certifice regenerated successfully')
				else:
					self.notifier.addNotice('Invalid country code','error')
			else:
				self.notifier.addNotice('Invalid company name','error')
		else:
			self.notifier.addNotice('Invalid domain','error')
		self.serverManager()
	def OnShowUrlClick(self):
		""" action - shows the url based on current configuration
		"""
		url = 'https://{0}:{1}@{2}:{3}'.format(Setting.get('rpc_server_username', 'remoteuser'), Setting.get('rpc_server_password', str(uuid.uuid4())), Setting.get('rpc_server_hostname', 'localhost'), Setting.get('rpc_server_port', 9000))
		self.widgets['url'].configure(text=url)
		self.urlshown = self.now()
	def OnCopyUrlClick(self):
		""" action - copies the url to clipboard
		"""
		url = 'https://{0}:{1}@{2}:{3}'.format(Setting.get('rpc_server_username', 'remoteuser'), Setting.get('rpc_server_password', str(uuid.uuid4())), Setting.get('rpc_server_hostname', 'localhost'), Setting.get('rpc_server_port', 9000))
		self.gui.clipboard_clear()
		self.gui.clipboard_append(url)
		self.notifier.addNotice('The RPC URL has been copied to clipboard')
	
	#=== UTILS ===#
	def __hideUrl(self):
		""" util - auto hides the url after 10 seconds
		"""
		if(self.urlshown != None):
			if(self.urlshown <= self.now()-10000):
				self.widgets['url'].configure(text='Click show or copy')
				self.urlshown = None
				self.notifier.addNotice('URL hidden for security purposes')
	def __validSSLDomain(self, domain):
		""" util - validate SSL domain
		
		@param domain str
		"""
		try:
			assert len(domain) > 4
			assert not r"/" in domain
			return True
		except:
			pass
		return False
	def __validSSLCompany(self, company):
		""" util - validate SSL company
		
		@param company str
		"""
		try:
			assert len(company) > 4
			assert not r"/" in company
			return True
		except:
			pass
		return False
	def __validSSLCountry(self, country):
		""" util - validate SSL company
		
		@param country str
		"""
		try:
			assert country != ''
			assert any(country in s for s in self.ssl.countryCodes())
			return True
		except:
			pass
		return False
Esempio n. 8
0
class TkRPCManager(TkPage):
	def __init__(self, parent, gui, **options):
		super(TkRPCManager,self).__init__(parent, gui, **options)
		self.scheduler = self.gui.scheduler
		self.now = lambda: int(round(time.time() * 1000))
		self.urlshown = None
		dependencies = [
			{'package':'OpenSSL', 'installer': 'apt-get'},
			{'package':'python-openssl', 'installer': 'apt-get'}
		]
		self.dm = TkDependencyManager(self.widget, dependencies, 'RPC Manager', self.gui)
		if(not self.dm.installRequired()):
			self.ssl = SSLManager()
			self.scheduler.addTask('rpc_url_watcher', self.__hideUrl, 10)
			try:
				self.rpcserver = TkRPCManager.rpcserver
			except:
				TkRPCManager.rpcserver = self.rpcserver = self.gui.getClass('SRPC.SRPCServer')(motionScheduler = self.gui.motionScheduler, specification = self.gui.specification, scheduler = self.gui.scheduler)
	def setup(self):
		self.gui.menus['rpc'] = Tkinter.Menu(self.gui.menubar, tearoff=0, bg=self.colours['menubg'], fg=self.colours['menufg'], activeforeground=self.colours['menuactivefg'], activebackground=self.colours['menuactivebg'])
		self.gui.menus['rpc'].add_command(label="Manage Server", command=self.OnManageRPCClick)
		self.addMenu(label="RPC", menu=self.gui.menus['rpc'])
	
	#=== VIEWS ===#
	def serverManager(self):
		self.open()
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='RPC Server', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['serviceLabel'] = Tkinter.Label(self.widgets['tframe'],text='Service', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['serviceLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.variables['status'] = Tkinter.StringVar()
		self.widgets['statusdata'] = Tkinter.Label(self.widgets['tframe'],textvariable=self.variables['status'], bg=self.colours['bg'], fg=self.colours['fg'], font=self.fonts['heading2'])
		self.widgets['statusdata'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['controlframe'] = Tkinter.Frame(self.widgets['tframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['controlframe'].grid(column = 1, row = self.gridrow, padx=20, columnspan=2, sticky = "WENS")
		
		self.widgets['startbutton'] = Tkinter.Button(self.widgets['controlframe'],text=u"Start RPC Server", image=self.images['play'], command=self.OnStartClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['startbutton'].grid(column=1,row=0, padx=10)
		
		self.widgets['stopbutton'] = Tkinter.Button(self.widgets['controlframe'],text=u"Stop RPC Server", image=self.images['stop'], command=self.OnStopClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['stopbutton'].grid(column=2,row=0, padx=10)
		
		self.variables['autostart'] = Tkinter.BooleanVar()
		self.variables['autostart'].set(Setting.get('rpc_autostart', False))
		self.widgets['autostartentry'] = Tkinter.Checkbutton(self.widgets['controlframe'], text="Autostart", variable=self.variables['autostart'], command=self.OnToggleAutostartClick, bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
		self.widgets['autostartentry'].grid(column=3,row=0, padx=10)
		
		if(self.rpcserver.isRunning() == False):
			self.variables['status'].set('Stopped')
			self.widgets['startbutton'].configure(state='normal')
			self.widgets['stopbutton'].configure(state='disabled')
		else:
			self.variables['status'].set('Running')
			self.widgets['startbutton'].configure(state='disabled')
			self.widgets['stopbutton'].configure(state='normal')
		
		self.gridrow += 1
		
		self.widgets['sslLabel'] = Tkinter.Label(self.widgets['tframe'],text='SSL Certificate', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['sslLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['startdateLabel'] = Tkinter.Label(self.widgets['tframe'],text='Start Date', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['startdateLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['startdateData'] = Tkinter.Label(self.widgets['tframe'],text=str(self.ssl.start), bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['startdateData'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.widgets['ccframe'] = Tkinter.Frame(self.widgets['tframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['ccframe'].grid(column = 3, row = self.gridrow, padx=20, columnspan=4, rowspan=5, sticky = "WENS")
		
		self.widgets['ccLabel'] = Tkinter.Label(self.widgets['ccframe'],text='Valid Country Codes', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'])
		self.widgets['ccLabel'].grid(column=0,row=0, sticky='EW')
		
		self.widgets['ccSubframe'] = Tkinter.Frame(self.widgets['ccframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['ccSubframe'].grid(column = 0, row = 1, sticky = "WENS")
		
		r,c = 0,0
		cols = 20
		
		for s in self.ssl.countryCodes():
			self.widgets['ccLabel'+s] = Tkinter.Label(self.widgets['ccSubframe'],text=s, anchor='nw', bg=self.colours['bg'], fg=self.colours['fg'])
			self.widgets['ccLabel'+s].grid(column=c,row=r,sticky='EW')
			#if (c == cols-1):
			#	r += 1
			if (c < cols):
				c = c+1 
			else:
				c = 0
				r+=1
		
		self.gridrow += 1
		
		self.widgets['enddateLabel'] = Tkinter.Label(self.widgets['tframe'],text='End Date', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['enddateLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['enddateData'] = Tkinter.Label(self.widgets['tframe'],text=str(self.ssl.end), bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['enddateData'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['domainLabel'] = Tkinter.Label(self.widgets['tframe'],text='Domain', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['domainLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['domain'] = Tkinter.StringVar()
		self.widgets['domainentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['domain'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['domainentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['domain'].set(Setting.get('rpc_server_ssl_domain', 'localhost'))
		
		self.gridrow += 1
		
		self.widgets['companyLabel'] = Tkinter.Label(self.widgets['tframe'],text='Company', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['companyLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['company'] = Tkinter.StringVar()
		self.widgets['companyentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['company'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['companyentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['company'].set(Setting.get('rpc_server_ssl_company', 'TestCo'))
		
		self.gridrow += 1
		
		self.widgets['countryLabel'] = Tkinter.Label(self.widgets['tframe'],text='Country', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['countryLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['country'] = Tkinter.StringVar()
		self.widgets['countryentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['country'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['countryentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['country'].set(Setting.get('rpc_server_ssl_country', 'GB'))
		
		self.gridrow += 1
		
		self.widgets['settingsLabel'] = Tkinter.Label(self.widgets['tframe'],text='Settings', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
		self.widgets['settingsLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['hostnameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Hostname', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['hostnameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['hostname'] = Tkinter.StringVar()
		self.widgets['hostnameentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['hostname'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['hostnameentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['hostname'].set(Setting.get('rpc_server_hostname', 'localhost'))
		
		self.widgets['efframe'] = Tkinter.Frame(self.widgets['tframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['efframe'].grid(column = 3, row = self.gridrow, padx=20, columnspan=6, rowspan=4, sticky = "WENS")
		
		self.widgets['efLabel'] = Tkinter.Label(self.widgets['efframe'],text='Exposed Functions', anchor='nw', bg=self.colours['bg'], fg=self.colours['headingfg'])
		self.widgets['efLabel'].grid(column=0,row=0, sticky='EW')
		
		self.widgets['efSubframe'] = Tkinter.Frame(self.widgets['efframe'], borderwidth=0, bg = self.colours['bg'])
		self.widgets['efSubframe'].grid(column = 0, row = 1, sticky = "WENS")
		r,c = 0,0
		cols = 4
		for t in self.rpcserver.listMethods():
			self.widgets[t+'Label'] = Tkinter.Label(self.widgets['efSubframe'],text=t, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
			self.widgets[t+'Label'].grid(column=c,row=r, padx=10,sticky='EW')
			if (c < cols):
				c = c+1 
			else:
				c = 0
				r+=1
		
		self.gridrow += 1
		
		self.widgets['portLabel'] = Tkinter.Label(self.widgets['tframe'],text='Port', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['portLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['port'] = Tkinter.IntVar()
		self.widgets['portentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['port'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['portentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['port'].set(Setting.get('rpc_server_port', 9000))
		
		self.gridrow += 1
		
		self.widgets['usernameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Username', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['usernameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['username'] = Tkinter.StringVar()
		self.widgets['usernameentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['username'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['usernameentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['username'].set(Setting.get('rpc_server_username', 'remoteuser'))
		
		self.gridrow += 1
		
		self.widgets['passwordLabel'] = Tkinter.Label(self.widgets['tframe'],text='Password', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['passwordLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['password'] = Tkinter.StringVar()
		self.widgets['passwordentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['password'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['passwordentry'].grid(column=1,row=self.gridrow,sticky='EW')
		self.variables['password'].set(Setting.get('rpc_server_password', str(uuid.uuid4())))
		
		self.widgets['genbutton'] = Tkinter.Button(self.widgets['tframe'],text=u"Generate Key", image=self.images['process'], bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'], command=self.OnGeneratePasswordClick)
		self.widgets['genbutton'].grid(column=2,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['urlLabel'] = Tkinter.Label(self.widgets['tframe'],text='URL', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['urlLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['url'] = Tkinter.Label(self.widgets['tframe'],text='Click show or copy', anchor=NW, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['url'].grid(column=1,row=self.gridrow, columnspan=6, sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['optionsFrame'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['optionsFrame'].grid(column=0,row=self.gridrow,columnspan=2, sticky='EW')
		
		self.gridrow = 0
		
		self.widgets['saveLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Save', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['saveLabel'].grid(column=0,row=self.gridrow, padx=5, sticky='EW')
		self.widgets['regenLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Regenerate SSL', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['regenLabel'].grid(column=1,row=self.gridrow,padx=5, sticky='EW')
		self.widgets['showUrlLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Show URL', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['showUrlLabel'].grid(column=2,row=self.gridrow,padx=5, sticky='EW')
		self.widgets['copyUrlLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Copy URL', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['copyUrlLabel'].grid(column=3,row=self.gridrow,padx=5, sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['saveserver'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Save", image=self.images['save'], command=self.OnSaveServerClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['saveserver'].grid(column=0,row=self.gridrow)
		self.widgets['regen'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Regen", image=self.images['process'], command=self.OnRegenSSLClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['regen'].grid(column=1,row=self.gridrow)
		self.widgets['show'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Show", image=self.images['find'], command=self.OnShowUrlClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['show'].grid(column=2,row=self.gridrow)
		self.widgets['copy'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Copy", image=self.images['ram'], command=self.OnCopyUrlClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['copy'].grid(column=3,row=self.gridrow)
	
	#=== ACTIONS ===#
	##== Service ==##
	def OnStartClick(self):
		self.variables['status'].set('Running')
		self.rpcserver.start()
		self.widgets['startbutton'].configure(state='disabled')
		self.widgets['stopbutton'].configure(state='normal')
	def OnStopClick(self):
		self.variables['status'].set('Stopped')
		self.rpcserver.stop()
		self.widgets['startbutton'].configure(state='normal')
		self.widgets['stopbutton'].configure(state='disabled')
	def OnToggleAutostartClick(self):
		self.autostart = Setting.set('rpc_autostart', self.variables['autostart'].get())
	
	##== Management ==##
	def OnManageRPCClick(self):
		if(not self.dm.installRequired()):
			self.serverManager()
		else:
			self.open()
			self.dm.addManager()
	def OnSaveServerClick(self):
		if(self.variables['hostname'].get() != '' and self.variables['port'].get() > 1000 and len(self.variables['username'].get()) > 4 and len(self.variables['password'].get()) > 4):
			hostname = Setting.set('rpc_server_hostname', self.variables['hostname'].get())
			port = Setting.set('rpc_server_port', self.variables['port'].get())
			username = Setting.set('rpc_server_username', self.variables['username'].get())
			password = Setting.set('rpc_server_password', self.variables['password'].get())
			self.notifier.addNotice('RPC server settings saved')
		else:
			self.notifier.addNotice('Invalid RPC server settings.', 'warning')
	def OnGeneratePasswordClick(self):
		self.variables['password'].set(str(uuid.uuid4()))
		self.notifier.addNotice('New password generated. Click Save to apply it', 'warning')
	def OnRegenSSLClick(self):
		if(self.__validSSLDomain(self.variables['domain'].get())):
			if(self.__validSSLCompany(self.variables['company'].get())):
				if(self.__validSSLCountry(self.variables['country'].get())):
					domain = Setting.set('rpc_server_ssl_domain', self.variables['domain'].get())
					company = Setting.set('rpc_server_ssl_company', self.variables['company'].get())
					country = Setting.set('rpc_server_ssl_country', self.variables['country'].get())
					self.ssl.generateCertificate()
					self.notifier.addNotice('SSL Certifice regenerated successfully')
				else:
					self.notifier.addNotice('Invalid country code','error')
			else:
				self.notifier.addNotice('Invalid company name','error')
		else:
			self.notifier.addNotice('Invalid domain','error')
		self.serverManager()
	def OnShowUrlClick(self):
		url = 'https://{0}:{1}@{2}:{3}'.format(Setting.get('rpc_server_username', 'remoteuser'), Setting.get('rpc_server_password', str(uuid.uuid4())), Setting.get('rpc_server_hostname', 'localhost'), Setting.get('rpc_server_port', 9000))
		self.widgets['url'].configure(text=url)
		self.urlshown = self.now()
	def OnCopyUrlClick(self):
		url = 'https://{0}:{1}@{2}:{3}'.format(Setting.get('rpc_server_username', 'remoteuser'), Setting.get('rpc_server_password', str(uuid.uuid4())), Setting.get('rpc_server_hostname', 'localhost'), Setting.get('rpc_server_port', 9000))
		self.gui.clipboard_clear()
		self.gui.clipboard_append(url)
		self.notifier.addNotice('The RPC URL has been copied to clipboard')
	
	#=== UTILS ===#
	def __hideUrl(self):
		if(self.urlshown != None):
			if(self.urlshown <= self.now()-10000):
				self.widgets['url'].configure(text='Click show or copy')
				self.urlshown = None
				self.notifier.addNotice('URL hidden for security purposes')
	def __validSSLDomain(self, domain):
		try:
			assert len(domain) > 4
			assert not r"/" in domain
			return True
		except:
			pass
		return False
	def __validSSLCompany(self, company):
		try:
			assert len(company) > 4
			assert not r"/" in company
			return True
		except:
			pass
		return False
	def __validSSLCountry(self, country):
		try:
			assert country != ''
			assert any(country in s for s in self.ssl.countryCodes())
			return True
		except:
			pass
		return False
class TkNetworkManager(TkPage):
	def __init__(self, parent, gui, **options):
		""" Initializes TkNetworkManager object
		
		@param parent
		@param gui
		@param options
		"""
		super(TkNetworkManager,self).__init__(parent, gui, **options)
		self.pm = TkDependencyManager(self.widget, {'package':'nmap', 'installer': 'apt-get'}, 'Network Manager', self.gui)
		if(hasattr(self.gui, 'scheduler')):
			self.scheduler = self.gui.scheduler
		else:
			self.scheduler = Scheduler.GetInstance()
	def setup(self):
		""" setup gui menu
		"""
		self.gui.menus['network'] = Tkinter.Menu(self.gui.menubar, tearoff=0, bg=self.colours['menubg'], fg=self.colours['menufg'], activeforeground=self.colours['menuactivefg'], activebackground=self.colours['menuactivebg'])
		self.gui.menus['network'].add_command(label="Neighbourhood", command=self.OnManageNetworkClick)
		self.addMenu(label="Network", menu=self.gui.menus['network'])
	
	#=== VIEWS ===#
	def listNodes(self):
		""" view - list nodes
		"""
		self.open()
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Network / Neighbourhood', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		self.gridrow += 1
		
		self.widgets['nframe'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['nframe'].grid(column=0,row=self.gridrow, sticky='EW')
		
		self.widgets['scanLabel'] = Tkinter.Label(self.widgets['nframe'],text='Scanning network... please wait.', bg=self.colours['bg'], fg=self.colours['fg'], font=self.fonts['heading2'])
		self.widgets['scanLabel'].grid(column=0,row=0,sticky='EW')
	def updateNodes(self):
		""" util - update nodes ui
		"""
		try:
			self.widgets['nodes']
		except:
			self.widgets['nodes'] = {}
		if(len(self.network.nodes) > 0):
			try:
				self.widgets['scanLabel'].grid_forget()
				del(self.widgets['scanLabel'])
			except:
				pass
			row = 0
			keys = self.network.nodes.keys()
			keys.sort()
			for k, v in self.network.nodes.iteritems():
				try:
					self.widgets['nodes'][k]
				except:
					self.widgets['nodes'][k] = Tkinter.Frame(self.widgets['nframe'], bg=self.colours['bg'])
					self.widgets['nodes'][k].grid(column=0,row=row, sticky='EW')
					
					text = v['ip']
					if(self.network.myip == v['ip']):
						text = '{0} (Me)'.format(v['ip'])
						
					self.widgets['ip'.format(k)] = Tkinter.Label(self.widgets['nodes'][k],text=text, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading2'])
					self.widgets['ip'.format(k)].grid(column=0,row=0,sticky='EW')
					
					self.widgets['macLabel'.format(k)] = Tkinter.Label(self.widgets['nodes'][k],text='Mac Address', bg=self.colours['bg'], fg=self.colours['headingfg'])
					self.widgets['macLabel'.format(k)].grid(column=0,row=1,sticky='EW')
					
					self.widgets['macData'.format(k)] = Tkinter.Label(self.widgets['nodes'][k],text=v['mac'], bg=self.colours['bg'], fg=self.colours['fg'])
					self.widgets['macData'.format(k)].grid(column=1,row=1,sticky='EW')
					
					self.widgets['brandLabel'.format(k)] = Tkinter.Label(self.widgets['nodes'][k],text='Brand', bg=self.colours['bg'], fg=self.colours['headingfg'])
					self.widgets['brandLabel'.format(k)].grid(column=0,row=2,sticky='EW')
					
					self.widgets['brandData'.format(k)] = Tkinter.Label(self.widgets['nodes'][k],text=v['brand'], bg=self.colours['bg'], fg=self.colours['fg'])
					self.widgets['brandData'.format(k)].grid(column=1,row=2,sticky='EW')
					
					self.widgets['servicesLabel'.format(k)] = Tkinter.Label(self.widgets['nodes'][k],text='Services', bg=self.colours['bg'], fg=self.colours['headingfg'])
					self.widgets['servicesLabel'.format(k)].grid(column=0,row=3,sticky='EW')
					
					self.widgets['servicesData'.format(k)] = Tkinter.Frame(self.widgets['nodes'][k], bg=self.colours['bg'])
					self.widgets['servicesData'.format(k)].grid(column=1,row=3,sticky='EW')
					srow = 0
					
					self.widgets['portLabel'.format(srow)] = Tkinter.Label(self.widgets['servicesData'.format(k)],text='Port', bg=self.colours['bg'], fg=self.colours['headingfg'])
					self.widgets['portLabel'.format(srow)].grid(column=0,row=srow,sticky='EW')
					
					self.widgets['protocolLabel'.format(srow)] = Tkinter.Label(self.widgets['servicesData'.format(k)],text='Protocol', bg=self.colours['bg'], fg=self.colours['headingfg'])
					self.widgets['protocolLabel'.format(srow)].grid(column=1,row=srow,sticky='EW')
					
					self.widgets['stateLabel'.format(srow)] = Tkinter.Label(self.widgets['servicesData'.format(k)],text='State', bg=self.colours['bg'], fg=self.colours['headingfg'])
					self.widgets['stateLabel'.format(srow)].grid(column=2,row=srow,sticky='EW')
					
					self.widgets['serviceLabel'.format(srow)] = Tkinter.Label(self.widgets['servicesData'.format(k)],text='Service', bg=self.colours['bg'], fg=self.colours['headingfg'])
					self.widgets['serviceLabel'.format(srow)].grid(column=3,row=srow,sticky='EW')
					
					srow += 1
					
					for s in v['services']:
						self.widgets['port'.format(srow)] = Tkinter.Label(self.widgets['servicesData'.format(k)],text=s['port'], bg=self.colours['bg'], fg=self.colours['fg'])
						self.widgets['port'.format(srow)].grid(column=0,row=srow,sticky='EW')
						self.widgets['protocol'.format(srow)] = Tkinter.Label(self.widgets['servicesData'.format(k)],text=s['protocol'], bg=self.colours['bg'], fg=self.colours['fg'])
						self.widgets['protocol'.format(srow)].grid(column=1,row=srow,sticky='EW')
						self.widgets['state'.format(srow)] = Tkinter.Label(self.widgets['servicesData'.format(k)],text=s['state'], bg=self.colours['bg'], fg=self.colours['fg'])
						self.widgets['state'.format(srow)].grid(column=2,row=srow,sticky='EW')
						self.widgets['service'.format(srow)] = Tkinter.Label(self.widgets['servicesData'.format(k)],text=s['service'], bg=self.colours['bg'], fg=self.colours['fg'])
						self.widgets['service'.format(srow)].grid(column=3,row=srow,sticky='EW')
						srow += 1
				row += 1
	
	#=== ACTIONS ===#
	def OnManageNetworkClick(self):
		""" action - display network page
		"""
		if(not self.pm.installRequired()):
			try:
				self.network
			except:
				self.network = Network()
			try:
				self.widgets['nodes']
			except:
				self.widgets['nodes'] = {}
			for v in self.widgets['nodes'].values():
				v.grid_forget()
			self.widgets['nodes'] = {}
			self.listNodes()
			self.scheduler.addTask('network_nodes', self.updateNodes, 5)
		else:
			self.open()
			self.pm.addManager()
Esempio n. 10
0
class TkNetworkManager(TkPage):
    def __init__(self, parent, gui, **options):
        super(TkNetworkManager, self).__init__(parent, gui, **options)
        self.pm = TkDependencyManager(
            self.widget, {"package": "nmap", "installer": "apt-get"}, "Network Manager", self.gui
        )
        if hasattr(self.gui, "scheduler"):
            self.scheduler = self.gui.scheduler
        else:
            self.scheduler = Scheduler()

    def setup(self):
        self.gui.menus["network"] = Tkinter.Menu(
            self.gui.menubar,
            tearoff=0,
            bg=self.colours["menubg"],
            fg=self.colours["menufg"],
            activeforeground=self.colours["menuactivefg"],
            activebackground=self.colours["menuactivebg"],
        )
        self.gui.menus["network"].add_command(label="Neighbourhood", command=self.OnManageNetworkClick)
        self.addMenu(label="Network", menu=self.gui.menus["network"])

        # === VIEWS ===#

    def listNodes(self):
        self.open()
        self.widgets["frameLabel"] = Tkinter.Label(
            self.widgets["tframe"],
            text="Network / Neighbourhood",
            anchor=NW,
            bg=self.colours["bg"],
            fg=self.colours["headingfg"],
            font=self.fonts["heading"],
        )
        self.widgets["frameLabel"].grid(column=0, row=self.gridrow, sticky="EW")
        self.gridrow += 1

        self.widgets["nframe"] = Tkinter.Frame(self.widgets["tframe"], bg=self.colours["bg"])
        self.widgets["nframe"].grid(column=0, row=self.gridrow, sticky="EW")

        self.widgets["scanLabel"] = Tkinter.Label(
            self.widgets["nframe"],
            text="Scanning network... please wait.",
            bg=self.colours["bg"],
            fg=self.colours["fg"],
            font=self.fonts["heading2"],
        )
        self.widgets["scanLabel"].grid(column=0, row=0, sticky="EW")

    def updateNodes(self):
        try:
            self.widgets["nodes"]
        except:
            self.widgets["nodes"] = {}
        if len(self.network.nodes) > 0:
            try:
                self.widgets["scanLabel"].grid_forget()
                del (self.widgets["scanLabel"])
            except:
                pass
            row = 0
            keys = self.network.nodes.keys()
            keys.sort()
            for k, v in self.network.nodes.iteritems():
                try:
                    self.widgets["nodes"][k]
                except:
                    self.widgets["nodes"][k] = Tkinter.Frame(self.widgets["nframe"], bg=self.colours["bg"])
                    self.widgets["nodes"][k].grid(column=0, row=row, sticky="EW")

                    text = v["ip"]
                    if self.network.myip == v["ip"]:
                        text = "{0} (Me)".format(v["ip"])

                    self.widgets["ip".format(k)] = Tkinter.Label(
                        self.widgets["nodes"][k],
                        text=text,
                        bg=self.colours["bg"],
                        fg=self.colours["headingfg"],
                        font=self.fonts["heading2"],
                    )
                    self.widgets["ip".format(k)].grid(column=0, row=0, sticky="EW")

                    self.widgets["macLabel".format(k)] = Tkinter.Label(
                        self.widgets["nodes"][k],
                        text="Mac Address",
                        bg=self.colours["bg"],
                        fg=self.colours["headingfg"],
                    )
                    self.widgets["macLabel".format(k)].grid(column=0, row=1, sticky="EW")

                    self.widgets["macData".format(k)] = Tkinter.Label(
                        self.widgets["nodes"][k], text=v["mac"], bg=self.colours["bg"], fg=self.colours["fg"]
                    )
                    self.widgets["macData".format(k)].grid(column=1, row=1, sticky="EW")

                    self.widgets["brandLabel".format(k)] = Tkinter.Label(
                        self.widgets["nodes"][k], text="Brand", bg=self.colours["bg"], fg=self.colours["headingfg"]
                    )
                    self.widgets["brandLabel".format(k)].grid(column=0, row=2, sticky="EW")

                    self.widgets["brandData".format(k)] = Tkinter.Label(
                        self.widgets["nodes"][k], text=v["brand"], bg=self.colours["bg"], fg=self.colours["fg"]
                    )
                    self.widgets["brandData".format(k)].grid(column=1, row=2, sticky="EW")

                    self.widgets["servicesLabel".format(k)] = Tkinter.Label(
                        self.widgets["nodes"][k], text="Services", bg=self.colours["bg"], fg=self.colours["headingfg"]
                    )
                    self.widgets["servicesLabel".format(k)].grid(column=0, row=3, sticky="EW")

                    self.widgets["servicesData".format(k)] = Tkinter.Frame(
                        self.widgets["nodes"][k], bg=self.colours["bg"]
                    )
                    self.widgets["servicesData".format(k)].grid(column=1, row=3, sticky="EW")
                    srow = 0

                    self.widgets["portLabel".format(srow)] = Tkinter.Label(
                        self.widgets["servicesData".format(k)],
                        text="Port",
                        bg=self.colours["bg"],
                        fg=self.colours["headingfg"],
                    )
                    self.widgets["portLabel".format(srow)].grid(column=0, row=srow, sticky="EW")

                    self.widgets["protocolLabel".format(srow)] = Tkinter.Label(
                        self.widgets["servicesData".format(k)],
                        text="Protocol",
                        bg=self.colours["bg"],
                        fg=self.colours["headingfg"],
                    )
                    self.widgets["protocolLabel".format(srow)].grid(column=1, row=srow, sticky="EW")

                    self.widgets["stateLabel".format(srow)] = Tkinter.Label(
                        self.widgets["servicesData".format(k)],
                        text="State",
                        bg=self.colours["bg"],
                        fg=self.colours["headingfg"],
                    )
                    self.widgets["stateLabel".format(srow)].grid(column=2, row=srow, sticky="EW")

                    self.widgets["serviceLabel".format(srow)] = Tkinter.Label(
                        self.widgets["servicesData".format(k)],
                        text="Service",
                        bg=self.colours["bg"],
                        fg=self.colours["headingfg"],
                    )
                    self.widgets["serviceLabel".format(srow)].grid(column=3, row=srow, sticky="EW")

                    srow += 1

                    for s in v["services"]:
                        self.widgets["port".format(srow)] = Tkinter.Label(
                            self.widgets["servicesData".format(k)],
                            text=s["port"],
                            bg=self.colours["bg"],
                            fg=self.colours["fg"],
                        )
                        self.widgets["port".format(srow)].grid(column=0, row=srow, sticky="EW")
                        self.widgets["protocol".format(srow)] = Tkinter.Label(
                            self.widgets["servicesData".format(k)],
                            text=s["protocol"],
                            bg=self.colours["bg"],
                            fg=self.colours["fg"],
                        )
                        self.widgets["protocol".format(srow)].grid(column=1, row=srow, sticky="EW")
                        self.widgets["state".format(srow)] = Tkinter.Label(
                            self.widgets["servicesData".format(k)],
                            text=s["state"],
                            bg=self.colours["bg"],
                            fg=self.colours["fg"],
                        )
                        self.widgets["state".format(srow)].grid(column=2, row=srow, sticky="EW")
                        self.widgets["service".format(srow)] = Tkinter.Label(
                            self.widgets["servicesData".format(k)],
                            text=s["service"],
                            bg=self.colours["bg"],
                            fg=self.colours["fg"],
                        )
                        self.widgets["service".format(srow)].grid(column=3, row=srow, sticky="EW")
                        srow += 1
                row += 1

                # === ACTIONS ===#

    def OnManageNetworkClick(self):
        if not self.pm.installRequired():
            try:
                self.network
            except:
                self.network = Network()
            try:
                self.widgets["nodes"]
            except:
                self.widgets["nodes"] = {}
            for v in self.widgets["nodes"].values():
                v.grid_forget()
            self.widgets["nodes"] = {}
            self.listNodes()
            self.scheduler.addTask("network_nodes", self.updateNodes, 5)
        else:
            self.open()
            self.pm.addManager()