Esempio n. 1
0
	def OnViewAddonClick(self):
		""" action - open file manager to bundled blender addon location
		"""
		res = self.__openFileManager(os.path.join(AmsEnvironment.AppPath(), 'help/blender-addon'))
		if(res):
			self.notifier.addNotice('Now showing: Bundled Addon in file manager')
		else:
			self.notifier.addNotice('Unable to open: '+os.path.join(AmsEnvironment.AppPath(), 'help/blender-addon'), 'error')
    def initIcons(self):
        """ Loads required icon images
		"""
        try:
            self.icons
        except:
            self.icons = {}
            self.icons['folderimg'] = Tkinter.PhotoImage(file=os.path.join(
                AmsEnvironment.AppPath(), 'images', 'camera', 'folder.gif'))
            self.icons['stillimg'] = Tkinter.PhotoImage(file=os.path.join(
                AmsEnvironment.AppPath(), 'images', 'camera', 'still.gif'))
            self.icons['videoimg'] = Tkinter.PhotoImage(file=os.path.join(
                AmsEnvironment.AppPath(), 'images', 'camera', 'video.gif'))
Esempio n. 3
0
    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)
Esempio n. 4
0
	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)
Esempio n. 5
0
    def __init__(self, gui, base='help'):
        """ for parsing html
		
		@param gui
		@param base
		"""
        self.colours = gui.colours
        self.fonts = gui.fonts
        self.images = {}
        self.base = os.path.join(AmsEnvironment.AppPath(), base)
        self.buildIndex()
Esempio n. 6
0
    def __init__(self, name='NewTheme', screen=None):
        """ Initializes the Theme object
		"""
        self.name = name
        if (screen != None):
            self.screen = screen
        else:
            self.screen = {'width': 0, 'height': 0}
        self.basepath = os.path.join(AmsEnvironment.AppPath(), 'themes',
                                     self.safeName())
        self.filepath = '{0}/{1}.theme.xml'.format(self.basepath, self.name)
        self.profiles, self.images, self.colours, self.fonts = {}, {}, {}, {}
	def loadCache(self):
		""" initialises the dependency cache either with stored data or an empty dict 
		"""
		self.cache = {}
		self.cachepath = os.path.join(AmsEnvironment.FilePath(), 'Dependencies')
		self.cachefile = os.path.join(self.cachepath, '{}-cache.json'.format(self.__safeName()))
		if os.path.isfile(self.cachefile):
			try:
				f = open(self.cachefile, 'r')
				contents = f.read()
				f.close()
				self.cache = json.loads(contents)
			except:
				pass
Esempio n. 8
0
    def query(self):
        """ gets a list of available themes
		"""
        basepath = os.path.join(AmsEnvironment.AppPath(), 'themes')
        dirs = os.listdir(basepath)
        themes = {}
        if (len(dirs) > 0):
            for d in dirs:
                if (os.path.isdir(os.path.join(basepath, d))
                        and os.path.exists('{0}/{1}/{2}.theme.xml'.format(
                            basepath, d, d))):
                    themes[d] = Theme(d)
                    themes[d].load()
        return themes
Esempio n. 9
0
    def view(self):
        """ view - display logo
		"""
        self.open()
        self.logo = Tkinter.PhotoImage(file=os.path.join(
            AmsEnvironment.AppPath(), 'images', 'pre-flight', 'vwave.gif'))
        self.widgets['frameLabel'] = Tkinter.Label(
            self.widget,
            text="logo",
            image=self.logo,
            anchor=S,
            bg=self.colours['bg'],
            fg=self.colours['headingfg'],
            highlightthickness=0)
        self.widgets['frameLabel'].grid(column=0, row=0, sticky='S')
        self.widgets['frameLabel'].logo = self.logo
Esempio n. 10
0
    def __init__(self, name='', storedvalue='', type='string'):
        """ Initializes the Setting object
		the setting class provides a type of variable which can be fetched from the database with a default value. if the setting doesn't exist, it is created.
		accessing settings in a loop does not cause multiple queries. setting values are cached.
		
		@param name str
		@param storedvalue
		@param type str
		"""
        try:
            Setting.cache
        except:
            Setting.cache = {}
        self.name = name
        self.type = type
        self.storedvalue = storedvalue
        super(Setting, self).__init__(dbpath=os.path.join(
            AmsEnvironment.FilePath(), 'settings', 'settings.db'))
Esempio n. 11
0
	def __init__(self):
		""" Initializes KeyboardThread object
		
		@param specification
		@param motionScheduler
		@param scheduler
		@param useTask
		"""
		self.scheduler = Scheduler.GetInstance()
		appInfo = AmsEnvironment.AppInfo()
		self.useTask = False if appInfo['command_script'] == 'GUI.py' and Setting.get('kb_use_tk_callback', True) else True
		self.terminalStatus = True
		try:
			termios.tcgetattr(sys.stdin.fileno())
		except:
			self.terminalStatus = False #not running in terminal
		self.callbacks = {}
		self.asciimap = AsciiMap()
		if (self.useTask):
			self.scheduler.addTask('kb_watcher', self.check, interval = 0.01, stopped=(not Setting.get('kb_autostart', False)))
Esempio n. 12
0
	def __init__(self, name, history = 0, archive = True, batch = 10):
		""" Initializes a Metric object
		A metric is like a variable but it collects changes and saves them in batches to an archive in CSV format. Older archives are compressed and added to cold storage.
		This was designed to have as smaller footprint on CPU and RAM as possible while still recording every historic value
		
		@param name - should be unique to each instance of the Metric class - characters which cannot be used as directory names will be stripped or replaced
		@param history - the amount of time in milliseconds used to retain values in memory. 0 = no previous values, -1 = all previous values, 1000 = the last seconds worth
		@param archive - create an archive of historic values for later examination
		@param batch
		"""
		self.name = self.__cleanseName(name)
		self.history = history
		self.__archive = archive
		self.__batch = batch
		self.__coldstored = False
		self.now = lambda: int(round(time.time() * 1000))
		self.__values = []
		try:
			Metric.metrics
		except:
			Metric.metrics = {}
		try:
			Metric.__session
		except:
			Metric.__session = {}
			Metric.__session['date'] = datetime.date.today()
			Metric.filebase = AmsEnvironment.FilePath()
			Metric.__session['archivepath'] = os.path.join(Metric.filebase, 'archive')
			Metric.__session['archivepattern'] = re.compile(r'(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+)-(?P<name>.+)\.csv')
			Metric.__session['coldpattern'] = re.compile(r'(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+).tar.gz')
			Metric.__session['datapattern'] = re.compile(r'(?P<t>\d+),(?P<dt>\w+),(?P<v>.*)')
			Metric.__session['coldfolder'] = 'coldstorage'
			Metric.__session['coldstored'] = False
			Metric.__session['coldpath'] = os.path.join(Metric.__session['archivepath'], Metric.__session['coldfolder'])
			if not os.path.exists(Metric.__session['coldpath']):
				os.makedirs(Metric.__session['coldpath'])
		try:
			Metric.metrics[self.name]
		except:
			Metric.metrics[name] = self
		Metric.index()
Esempio n. 13
0
	def __init__(self, name = '', timestamp = 0, datatype = '', strvalue = '', datavalue = None, archive = True, batch = 10):
		""" Initializes MetricValue object
		In-memory objects which hold historic values of a metric
		they are also responsible for archiving themselves
		"""
		self.name = name
		self.timestamp = timestamp
		self.datatype = datatype
		self.strvalue = strvalue
		self.datavalue = datavalue
		self.__archive = archive
		self.__batch = batch
		try:
			MetricValue.queue
		except:
			MetricValue.queue = {}
			MetricValue.counters = {}
		try:
			MetricValue.__session
		except:
			MetricValue.__session = {}
			MetricValue.filebase = AmsEnvironment.FilePath()
			MetricValue.__session['date'] = datetime.date.today()
			MetricValue.__session['path'] = os.path.join(MetricValue.filebase, 'archive')
			MetricValue.__session['header'] = 't,dt,v\r\n'
			MetricValue.__session['template'] = '{0},{1},{2}\r\n'
			MetricValue.__session['writing'] = False
			if not os.path.exists(MetricValue.__session['path']):
				os.makedirs(MetricValue.__session['path'])
		self.__session['file'] = '{0}-{1}.csv'.format(MetricValue.__session['date'],self.name)
		self.__session['abs'] = os.path.join(MetricValue.__session['path'], self.__session['file'])
		try:
			MetricValue.queue[self.name]
		except:
			MetricValue.queue[self.name] = []
			MetricValue.counters[self.name] = 0
			if self.__archive and not os.path.exists(self.__session['abs']):
				f = open(self.__session['abs'], 'w')
				f.write(MetricValue.__session['header'])
				f.close()
Esempio n. 14
0
    def __init__(self, scheduler=None):
        """ Initializes the TrayIcon object
		"""
        if (scheduler != None):
            self.scheduler = scheduler
        else:
            self.scheduler = Scheduler.Scheduler.GetInstance()
        self.enabled = True
        try:
            icon = gtk.StatusIcon()
        except:
            self.enabled = False
        else:
            self.widgets = {'tray': icon}
            self.initLeftMenu()
            self.initRightMenu()
            self.widgets['tray'].set_visible(True)
            self.widgets['tray'].set_tooltip_text('AllMyServos')
            self.widgets['tray'].set_from_file(
                os.path.join(AmsEnvironment.AppPath(), 'images', 'tray-icon',
                             'tray-icon.png'))
            self.scheduler.addTask('tray_update', self.update, 0.01, False)
Esempio n. 15
0
    def displayAppInfo(self):
        """ display app information
		
		@return gtk.VBox
		"""
        vbox = gtk.VBox(spacing=3)
        vbox.set_visible(True)
        info = AmsEnvironment.AppInfo()

        if (any(info)):
            for k, v in info.items():
                if (isinstance(v, str)):
                    p = self.displayPair(k, v)
                    vbox.pack_start(p, True, True, 1)
                elif (isinstance(v, list)):
                    p = self.displayPair(k, ''.join(v))
                    vbox.pack_start(p, True, True, 1)
        else:
            l = gtk.Label()
            l.set_text('App Info Unavailable')
            l.set_visible(True)
            vbox.pack_start(l, True, True, 6)

        return vbox
    def editProfile(self):
        """ view - edit profile
		"""
        self.open()

        self.widgets['mainlabel'] = Tkinter.Label(
            self.widgets['tframe'],
            text='Camera / Timelapse / Edit',
            anchor=NW,
            bg=self.colours['bg'],
            fg=self.colours['headingfg'],
            font=self.fonts['heading'])
        self.widgets['mainlabel'].grid(column=0,
                                       row=self.gridrow,
                                       columnspan=2,
                                       pady=10,
                                       sticky='EW')

        self.gridrow += 1

        self.widgets['activeLabel'] = Tkinter.Label(self.widgets['tframe'],
                                                    text='Active',
                                                    bg=self.colours['bg'],
                                                    fg=self.colours['fg'])
        self.widgets['activeLabel'].grid(column=0,
                                         row=self.gridrow,
                                         padx=10,
                                         sticky='W')

        self.variables['active'] = Tkinter.BooleanVar()
        self.variables['active'].set(self.profile.jsonData['active'])
        self.widgets['activeentry'] = Tkinter.Checkbutton(
            self.widgets['tframe'],
            variable=self.variables['active'],
            text='',
            anchor=W,
            command=self.OnToggleActive,
            bg=self.colours['inputbg'],
            fg=self.colours['inputfg'],
            activebackground=self.colours['activebg'],
            selectcolor=self.colours['inputbg'],
            disabledforeground=self.colours['greyborder'])
        self.widgets['activeentry'].grid(column=1,
                                         row=self.gridrow,
                                         padx=5,
                                         sticky="W")

        self.gridrow += 1

        self.widgets['nameLabel'] = Tkinter.Label(self.widgets['tframe'],
                                                  text='Name',
                                                  bg=self.colours['bg'],
                                                  fg=self.colours['fg'])
        self.widgets['nameLabel'].grid(column=0,
                                       row=self.gridrow,
                                       padx=10,
                                       sticky='W')
        self.variables['name'] = Tkinter.StringVar()
        if (self.profile.jsonData['name'] != ''):
            self.variables['name'].set(self.profile.jsonData['name'])
        self.widgets['nameentry'] = Tkinter.Entry(
            self.widgets['tframe'],
            textvariable=self.variables['name'],
            bg=self.colours['inputbg'],
            fg=self.colours['inputfg'])
        self.widgets['nameentry'].grid(column=1,
                                       row=self.gridrow,
                                       pady=10,
                                       sticky='W')

        self.gridrow += 1

        self.widgets['capLabel'] = Tkinter.Label(self.widgets['tframe'],
                                                 text='Capture Mode',
                                                 bg=self.colours['bg'],
                                                 fg=self.colours['fg'])
        self.widgets['capLabel'].grid(column=0,
                                      row=self.gridrow,
                                      padx=10,
                                      sticky='W')

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

        self.widgets['stillimg'] = Tkinter.PhotoImage(file=os.path.join(
            AmsEnvironment.AppPath(), 'images', 'camera', 'still.gif'))
        self.widgets['recstillbutton'] = Tkinter.Button(
            self.widgets['rmframe'],
            text=u"Still",
            image=self.widgets['stillimg'],
            command=self.OnStillModeClick,
            bg=self.colours['bg'],
            activebackground=self.colours['bg'],
            highlightbackground=self.colours['buttonborder'])
        self.widgets['recstillbutton'].grid(column=0, row=self.gridrow)

        self.widgets['videoimg'] = Tkinter.PhotoImage(file=os.path.join(
            AmsEnvironment.AppPath(), 'images', 'camera', 'video.gif'))
        self.widgets['recvidbutton'] = Tkinter.Button(
            self.widgets['rmframe'],
            text=u"Video",
            image=self.widgets['videoimg'],
            command=self.OnVideoModeClick,
            bg=self.colours['bg'],
            activebackground=self.colours['bg'],
            highlightbackground=self.colours['buttonborder'])
        self.widgets['recvidbutton'].grid(column=1, row=self.gridrow)

        self.widgets['recmodeLabel'] = Tkinter.Label(
            self.widgets['rmframe'],
            text='Video'
            if self.profile.jsonData['cap_mode'] == 'video' else 'Photo',
            anchor=W,
            bg=self.colours['bg'],
            fg=self.colours['valuefg'])
        self.widgets['recmodeLabel'].grid(column=2,
                                          row=self.gridrow,
                                          padx=10,
                                          sticky='EW')

        self.gridrow += 1

        self.widgets['waitLabel'] = Tkinter.Label(self.widgets['tframe'],
                                                  text='Wait',
                                                  bg=self.colours['bg'],
                                                  fg=self.colours['fg'])
        self.widgets['waitLabel'].grid(column=0,
                                       row=self.gridrow,
                                       padx=10,
                                       sticky='W')

        self.widgets['waitframe'] = Tkinter.Frame(self.widgets['tframe'],
                                                  bg=self.colours['bg'])
        self.widgets['waitframe'].grid(column=1,
                                       row=self.gridrow,
                                       columnspan=2,
                                       sticky='EW')

        self.gridrow += 1

        self.widgets['profileLabel'] = Tkinter.Label(self.widgets['tframe'],
                                                     text='Camera Profile',
                                                     bg=self.colours['bg'],
                                                     fg=self.colours['fg'])
        self.widgets['profileLabel'].grid(column=0,
                                          row=self.gridrow,
                                          padx=10,
                                          sticky='W')

        self.variables['cam_profile'] = Tkinter.StringVar()
        camProfile = self.profile.getCamProfile(
        ) if self.profile.jsonData['cam_profile'] != None else None
        if (camProfile != None):
            self.variables['cam_profile'].set(
                camProfile.jsonData['profile_name'])
        else:
            self.variables['cam_profile'].set(
                self.camera.cam_profile.jsonData['profile_name'])

        names = Camera.CameraProfile.GetAllNames()

        self.widgets['camproentry'] = Tkinter.OptionMenu(
            self.widgets['tframe'], self.variables['cam_profile'], *names)
        self.widgets['camproentry'].config(
            bg=self.colours['inputbg'],
            fg=self.colours['inputfg'],
            activeforeground=self.colours['activefg'],
            activebackground=self.colours['activebg'])
        self.widgets['camproentry'].grid(column=1,
                                         row=self.gridrow,
                                         sticky='W')

        self.gridrow += 1

        self.updateCapMode()

        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['backLabel'] = Tkinter.Label(self.widgets['optionsFrame'],
                                                  text='Back',
                                                  bg=self.colours['bg'],
                                                  fg=self.colours['fg'],
                                                  height=2)
        self.widgets['backLabel'].grid(column=0, row=self.gridrow, sticky='EW')
        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=1, row=self.gridrow, sticky='EW')
        if (self.profile.blobExists()):
            self.widgets['deleteLabel'] = Tkinter.Label(
                self.widgets['optionsFrame'],
                text='Delete',
                bg=self.colours['bg'],
                fg=self.colours['fg'],
                height=2)
            self.widgets['deleteLabel'].grid(column=2,
                                             row=self.gridrow,
                                             sticky='EW')

        self.gridrow += 1

        self.widgets['back'] = Tkinter.Button(
            self.widgets['optionsFrame'],
            text=u"Back",
            image=self.images['back'],
            command=self.OnManageClick,
            bg=self.colours['buttonbg'],
            activebackground=self.colours['buttonhighlightbg'],
            highlightbackground=self.colours['buttonborder'])
        self.widgets['back'].grid(column=0, row=self.gridrow)
        self.widgets['savepro'] = Tkinter.Button(
            self.widgets['optionsFrame'],
            text=u"Save Profile",
            image=self.images['save'],
            command=self.OnSaveProfileClick,
            bg=self.colours['buttonbg'],
            activebackground=self.colours['buttonhighlightbg'],
            highlightbackground=self.colours['buttonborder'])
        self.widgets['savepro'].grid(column=1, row=self.gridrow)
        if (self.profile.blobExists()):
            self.widgets['deletepro'] = Tkinter.Button(
                self.widgets['optionsFrame'],
                text=u"Delete Profile",
                image=self.images['delete'],
                command=self.OnDeleteProfileClick,
                bg=self.colours['buttonbg'],
                activebackground=self.colours['buttonhighlightbg'],
                highlightbackground=self.colours['buttonborder'])
            self.widgets['deletepro'].grid(column=2, row=self.gridrow)
Esempio n. 17
0
class PreFlight:
	interfaces = { 'i2c': { 'interface': 'i2c_arm', 'enabled': False } }
	i2cModules = { 'i2c-bcm2708': False, 'i2c-dev': False}
	blacklist = { 'i2c-bcm2708': False }
	prep = [
		{'command': ['sudo', 'apt-get', '-q', '-y', 'update'], 'done': False },
		{'command': ['sudo', 'apt-get', '-q', '-y', 'upgrade'], 'done': False }
	]
	dependencies = [ 
		{'package': 'python-dev', 'installer': 'apt-get', 'installed': False },
		{'package': 'python-pip', 'installer': 'apt-get', 'installed': False },
		{'package': 'python-smbus', 'installer': 'apt-get', 'installed': False },
		{'package': 'i2c-tools', 'installer': 'apt-get', 'installed': False}
		]
	cache = {}
	cachepath = os.path.join(AmsEnvironment.FilePath(), 'PreFlight')
	cachefile = os.path.join(cachepath, 'cache.json')
	@staticmethod
	def status():
		""" gets the status of pre flight checks
		
		@return bool
		"""
		PreFlight.loadCache()
		try:
			if ('result' in PreFlight.cache.keys()):
				if(PreFlight.cache['result'] == True):
					#only use cache if all checks have passed
					PreFlight.interfaces = PreFlight.cache['interfaces']
					PreFlight.i2cModules = PreFlight.cache['modules']
					PreFlight.blacklist = PreFlight.cache['blacklist']
					PreFlight.prep = PreFlight.cache['prep']
					PreFlight.dependencies = PreFlight.cache['dependencies']
					return True
		except:
			pass
		return PreFlight.updateCache()
	@staticmethod
	def loadCache():
		""" load cached data if available
		"""
		if os.path.isfile(PreFlight.cachefile):
			try:
				f = open(PreFlight.cachefile, 'r')
				contents = f.read()
				f.close()
				PreFlight.cache = json.loads(contents)
			except:
				pass
	@staticmethod
	def updateCache():
		""" update cache data
		
		@return bool
		"""
		res = False
		if not os.path.exists(PreFlight.cachepath):
			os.makedirs(PreFlight.cachepath)
		interfaces = PreFlight.__checkInterfaces()
		mod = PreFlight.__checkModules()
		blk = PreFlight.__checkBlacklist()
		dep = PreFlight.__checkDependencies()
		if(interfaces and mod and blk and dep):
			res = True
		PreFlight.cache = { 'interfaces': PreFlight.interfaces, 'modules': PreFlight.i2cModules, 'blacklist': PreFlight.blacklist, 'prep': PreFlight.prep, 'dependencies': PreFlight.dependencies, 'result': res }
		f = open(PreFlight.cachefile, 'w')
		f.write(json.dumps(PreFlight.cache))
		f.close()
		return res
	@staticmethod
	def report():
		""" gets a full report of pre flight checks
		
		@return dict
		"""
		return { 'interfaces': PreFlight.interfaces, 'modules': PreFlight.i2cModules, 'blacklist': PreFlight.blacklist, 'prep': PreFlight.prep, 'dependencies': PreFlight.dependencies }
	@staticmethod
	def configure():
		""" performs configuration changes
		"""
		PreFlight.__configureInterfaces()
		PreFlight.__configureModules()
		PreFlight.__configureBlacklist()
		PreFlight.__performPrep()
		PreFlight.__configureDependencies()
		PreFlight.__reboot()
	@staticmethod
	def getPiI2CBusNumber():
		""" Gets the I2C bus number /dev/i2c#
		
		@return int
		"""
		return 1 if PreFlight.getPiRevision() > 1 else 0
	@staticmethod
	def getPiRevision():
		"""Gets the version number of the Raspberry Pi board
		Courtesy quick2wire-python-api
		https://github.com/quick2wire/quick2wire-python-api
		
		@return int
		"""
		try:
			with open('/proc/cpuinfo','r') as f:
				for line in f:
					if line.startswith('Revision'):
						return 1 if line.rstrip()[-1] in ['1','2'] else 2
		except:
			return 0
	@staticmethod
	def __checkInterfaces():
		""" check for interface line in config.txt
		
		@return bool
		"""
		f = open('/boot/config.txt', 'r')
		config = f.read()
		f.close()
		for k, v in PreFlight.interfaces.items():
			onPattern = re.compile(r'^dtparam={0}=on$'.format(v['interface']), re.MULTILINE)
			if (onPattern.search(config)):
				v['enabled'] = True #entry exists uncommented
		disabled = [ k for k, v in PreFlight.interfaces.items() if v['enabled'] == False ]
		if (not any(disabled)):
			return True
		return False
	@staticmethod
	def __checkModules():
		""" check modules for i2c lines
		
		@return bool
		"""
		names = PreFlight.i2cModules.keys()
		f = open('/etc/modules', 'r')
		for l in f:
			line = l.strip()
			if line in names:
				PreFlight.i2cModules[line] = True
		f.close()
		missing = [ k for k, v in PreFlight.i2cModules.iteritems() if v == False ]
		if(not any(missing)):
			return True
		return False
	@staticmethod
	def __checkBlacklist():
		""" check blacklist contents
		
		@return bool
		"""
		lines = []
		f = open('/etc/modprobe.d/raspi-blacklist.conf', 'r')
		for l in f:
			lines.append(l.strip())
		for k in PreFlight.blacklist.keys():
			if 'blacklist {}'.format(k) in lines:
				PreFlight.blacklist[k] = False
			else:
				PreFlight.blacklist[k] = True
		found = [ k for k, v in PreFlight.blacklist.iteritems() if v == False ]
		f.close()
		if(not any(found)):
			return True
		return False
	@staticmethod
	def __checkDependencies():
		""" check package dependencies
		
		@return bool
		"""
		for k, v in enumerate(PreFlight.dependencies):
			PreFlight.dependencies[k]['installed'] = True if PreFlight.__isInstalled(v) == 2 else False
		missing = [ d for d in PreFlight.dependencies if d['installed'] == False ]
		if(not any(missing)):
			return True
		return False
	
	@staticmethod
	def __configureInterfaces():
		""" append required lines to config.txt
		"""
		f = open('/boot/config.txt', 'r')
		config = f.read()
		f.close()
		writeRequired = False
		for k, v in PreFlight.interfaces.items():
			onPattern = re.compile(r'^dtparam={0}=on$'.format(v['interface']), re.MULTILINE)
			offPattern = re.compile(r'^dtparam={0}=off$'.format(v['interface']), re.MULTILINE)
			if (not onPattern.search(config)):
				#only perform configuration if it isn't already on
				if (offPattern.search(config)):
					#change entry
					config = config.replace('dtparam={0}=off'.format(v['interface']), 'dtparam={0}=on'.format(v['interface']))
					writeRequired = True
				else:
					#append entry
					if (config.endswith('\n')):
						config = config + 'dtparam={0}=on\n'.format(v['interface']) #append w/o newline prefix
					else:
						config = config + '\ndtparam={0}=on\n'.format(v['interface']) #append with newline prefix
					writeRequired = True
		if (writeRequired and len(config) > 10):
			f = open('/boot/config.txt', 'w')
			f.write(config)
			f.close()
	@staticmethod
	def __configureModules():
		""" append required line to modules
		"""
		names = PreFlight.i2cModules.keys()
		lines = []
		f = open('/etc/modules', 'r')
		for l in f:
			line = l.strip()
			lines.append(line)
			if line in names:
				PreFlight.i2cModules[line] = True
		f.close()
		missing = [ k for k, v in PreFlight.i2cModules.iteritems() if v == False ]
		if(any(missing)):
			for m in missing:
				lines.append(m)
			f = open('/etc/modules', 'w')
			f.write('\n'.join(lines))
			f.close()
	@staticmethod
	def __configureBlacklist():
		""" comment required lines from blacklist
		"""
		blnames = {'blacklist {}'.format(k): k for k in PreFlight.blacklist.keys()}
		lines = []
		saveneeded = False
		f = open('/etc/modprobe.d/raspi-blacklist.conf', 'r')
		for l in f:
			line = l.strip()
			lines.append(line)
			if line in blnames:
				lines[-1] = '#{}'.format(lines[-1])
				PreFlight.blacklist[blnames[line]] = True
				saveneeded = True
		f.close()
		if(saveneeded):
			f = open('/etc/modprobe.d/raspi-blacklist.conf', 'w')
			f.write('\n'.join(lines))
			f.close()
	@staticmethod
	def __configureDependencies():
		""" install required dependencies
		"""
		for k, v in enumerate(PreFlight.dependencies):
			if(not v['installed']):
				if(v['installer'] == 'apt-get'):
					PreFlight.dependencies[k]['installed'] = PreFlight.__installAptGetDependency(v)
				elif(v['installer'] == 'pip'):
					PreFlight.dependencies[k]['installed'] = PreFlight.__installPipDependency(v)
	@staticmethod
	def __performPrep():
		""" run preparation commands
		"""
		for k, v in enumerate(PreFlight.prep):
			p = Popen(v['command'], stdout=PIPE)
			o = p.communicate()[0]
			if(p.returncode == 0):
				PreFlight.prep[k]['done'] = True
	@staticmethod
	def __isInstalled(dependency):
		""" check if a dependency is installed or not
		status 0 = not installed
		status 1 = update required
		status 2 = installed
		
		@param dependency dict
		
		@return int
		"""
		status = 0
		if(dependency['installer'] == 'apt-get'):
			p = Popen(['dpkg','-s',dependency['package']], stdout=PIPE, stderr=PIPE)
			o = p.communicate()[0]
			if(p.returncode == 0):
				o = o.split('\n')
				pattern = re.compile(r'Status\:\s?(?P<status>.+)')
				for l in o:
					if(pattern.match(l)):
						status = 2
						break
		elif(dependency['installer'] == 'pip'):
			if(len(dependency['package']) > 0):
				try:
					p = Popen(['pip','search',dependency['package']], stdout=PIPE)
					o = p.communicate()[0]
					if(p.returncode == 0):
						o = o.split('\n')
						pattern = re.compile(r'(?P<package>[^\s]+)\s+-\s+(?P<description>.+)')
						installedpattern = re.compile(r'.*installed:\s+(?P<version>.*)',re.IGNORECASE)
						packagematch = -1
						line = 0
						for l in o:
							matches = pattern.match(l)
							if(matches):
								if(matches.group('package').lower() == dependency['package'].lower()):
									packagematch = line
							matches = installedpattern.match(l)
							if(matches and packagematch == line-1):
								v = matches.group('version')
								dv = str(dependency['version'])
								num = v.split(' ')[0]
								if(dv == 'latest' and 'latest' in v):
									status = 2
								elif(dv != 'latest' and StrictVersion(dv) <= StrictVersion(num)):
									status = 2
								else:
									status = 1
								break
							line += 1
				except:
					pass
		return status
	@staticmethod
	def __installAptGetDependency(dependency):
		""" install apt-get dependency
		
		@param dependency dict
		
		@return bool
		"""
		installed = False
		try:
			if(len(dependency['package']) > 0):
				command = ['sudo','apt-get','-q','-y','install', dependency['package'] ]
				p = Popen(command, stdout=PIPE)
				o = p.communicate()[0]
				if(p.returncode == 0):
					installed = True
		except:
			pass
		return installed
	@staticmethod
	def __installPipDependency(dependency):
		""" install pip dependency
		
		@return bool
		"""
		installed = False
		try:
			if(len(dependency['package']) > 0):
				command = ['sudo', 'pip', 'install', dependency['package'], '--upgrade']
				p = Popen(command, stdout=PIPE)
				o = p.communicate()[0]
				if(p.returncode == 0):
					installed = True
		except:
			pass
		return installed
	@staticmethod
	def __reboot():
		""" start rebooting
		"""
		p = Popen(['sudo','reboot'], stdout=PIPE)
		o = p.communicate()[0]
Esempio n. 18
0
	def initTrayIcon(self):
		""" Initializes the system tray icon
		"""
		if (AmsEnvironment.IsLxdeRunning()):
			self.trayIcon = TrayIcon.TrayIcon(self.scheduler)
			self.trayIcon.setExitCallback(self.shutDown)
Esempio n. 19
0
    def initInfo(self):
        """ Establishes information for the camera
		"""
        self.info = {
            'cam_start':
            0,
            'streaming': {
                'enabled': False,
                'running': False,
                'connected': False
            },
            'revision':
            0,
            'max_res': (0, 0),
            'max_framerate':
            0,
            'still_res_modes': {
                '320x240': (320, 240),
                '640x480': (640, 480),
                '1024x768': (1024, 768),
                '1280x720': (1280, 720),
                '1440x900': (1440, 900),
                '1600x1200': (1600, 1200),
                '1920x1080': (1920, 1080),
                '2048x1536': (2048, 1536),
                '2560x1600': (2560, 1600),
            },
            'video_res_modes': {
                '320x240': (320, 240),
                '640x480': (640, 480),
                '1024x768': (1024, 768),
                '1280x720': (1280, 720),
                '1920x1080': (1920, 1080)
            },
            'fps_options': {
                '320x240': [15, 24, 30, 60, 90, 120],
                '640x480': [15, 24, 30, 60, 90],
                '1024x768': [15, 24, 30, 60],
                '1280x720': [15, 24, 30],
                '1920x1080': [15, 24, 30],
            },
            'exposure_modes': [
                'auto',
                'night',
                'nightpreview',
                'backlight',
                'spotlight',
                'sports',
                'snow',
                'beach',
                'verylong',
                'fixedfps',
                'antishake',
                'fireworks',
            ],
            'awb_modes': [
                'off', 'auto', 'sunlight', 'cloudy', 'shade', 'tungsten',
                'fluorescent', 'incandescent', 'flash', 'horizon'
            ],
            'effects': {},
            'sharpness_range': (-100, 100),
            'contrast_range': (-100, 100),
            'brightness_range': (0, 100),
            'saturation_range': (-100, 100),
            'zoom_range': (0, 1),
            'awb_range': (0.0, 8.0),
            'iso_range': [
                'Auto',
                '100',
                '200',
                '300',
                '400',
                '500',
                '600',
                '700',
                '800',
            ],
            'rotations': [0, 90, 180, 270],
            'formats': {
                'video': {
                    'h264': 'h264',
                    'mjpeg': 'mjpg'
                },
                'still': {
                    'jpeg': 'jpg',
                    'png': 'png',
                    'gif': 'gif',
                    'bmp': 'bmp'
                }
            },
            'file_path':
            os.path.join(AmsEnvironment.FilePath(), 'camera'),
            'overscan': {
                'enabled': False,
                'size': [48, 48, 48, 48]
            },
            'cam_config': {
                'start_x': False,
                'gpu_mem': 0,
                'hardware': False
            }
        }
        camConfig = self.__getCamConfig()
        if ('overscan' in camConfig.keys()):
            self.info['overscan'] = camConfig['overscan']
        if ('cam_config' in camConfig.keys()):
            self.info['cam_config'] = camConfig['cam_config']
        if (self.info['cam_config']['start_x']):
            try:
                if (not hasattr(self, 'cam')):
                    self.cam = PiCamera()
                    self.info['cam_config']['hardware'] = True
            except:
                self.info['cam_config']['hardware'] = False
            if (self.info['cam_config']['hardware']):
                self.info['max_res'] = self.cam.MAX_RESOLUTION if (hasattr(
                    self.cam, 'MAX_RESOLUTION')) else (0, 0)
                if (self.info['max_res'][0] == 2592):
                    self.info['revision'] = 1
                elif (self.info['max_res'][0] == 3280):
                    self.info['revision'] = 2
                self.info['max_framerate'] = self.cam.MAX_FRAMERATE if (
                    hasattr(self.cam, 'MAX_FRAMERATE')) else 0
                self.info['exposure_modes'] = self.cam.EXPOSURE_MODES if (
                    hasattr(self.cam, 'EXPOSURE_MODES')) else {}
                self.info['effects'] = self.cam.IMAGE_EFFECTS if (hasattr(
                    self.cam, 'IMAGE_EFFECTS')) else {}
                self.cam.close()
Esempio n. 20
0
class JsonBlob(object):
    basepath = os.path.join(AmsEnvironment.FilePath(), 'jsonblob')
    indexpath = os.path.join(basepath, 'index.json')
    constructors = {}
    indexexists = False
    indexed = False
    index = {}

    @staticmethod
    def reindex(force=False):
        """ collects information about available blobs from the file system
		
		@param force
		"""
        if (not os.path.exists(JsonBlob.basepath)):
            os.makedirs(JsonBlob.basepath)
        if (os.path.exists(JsonBlob.indexpath)):
            JsonBlob.indexexists = True

        if (force == False and JsonBlob.indexexists):
            f = open(JsonBlob.indexpath, 'r')
            JsonBlob.index = json.loads(f.read())
            f.close()
        else:
            mods = [
                x for x in os.listdir(JsonBlob.basepath) if not 'index' in x
            ]
            for m in mods:
                if (os.path.isdir(os.path.join(JsonBlob.basepath, m))):
                    JsonBlob.index[m] = {'module': m, 'classes': {}}
                    classes = [
                        x
                        for x in os.listdir(os.path.join(JsonBlob.basepath, m))
                        if not 'index' in x
                    ]
                    for c in classes:
                        if (os.path.isdir(os.path.join(JsonBlob.basepath, m,
                                                       c))):
                            JsonBlob.index[m]['classes'][c] = {
                                'class': c,
                                'rows': []
                            }
                            rows = [
                                x for x in os.listdir(
                                    os.path.join(JsonBlob.basepath, m, c))
                                if '.json' in x
                            ]
                            for row in rows:
                                splitrow = os.path.splitext(row)
                                if (len(splitrow) == 2
                                        and splitrow[1] == '.json'):
                                    JsonBlob.index[m]['classes'][c][
                                        'rows'].append(splitrow[0])
            f = open(JsonBlob.indexpath, 'wb')
            f.write(json.dumps(JsonBlob.index))
            f.close()
        JsonBlob.indexed = True

    @staticmethod
    def find(jbModule, jbType, jbIndex):
        """ returns the saved data or an empty dict
		
		@param jbModule
		@param jbType
		@param jbIndex
		
		@return dict
		"""
        typepath = os.path.join(JsonBlob.basepath, jbModule, jbType)
        if (jbIndex != None and os.path.exists(typepath)):
            rowpath = os.path.join(typepath, jbIndex + '.json')
            if (os.path.exists(rowpath)):
                f = open(rowpath, 'r')
                data = json.loads(f.read())
                f.close()
                return data
        return {}

    @staticmethod
    def all(jbModule=None, jbType=None):
        """ returns a dict of saved objects (keyed by jbIndex) or empty dict
		
		@param jbModule
		@param jbType
		
		@return dict
		"""
        JsonBlob.reindex(not JsonBlob.indexed)
        if (jbModule != None and jbType != None):
            if (jbModule in JsonBlob.index.keys()
                    and jbType in JsonBlob.index[jbModule]['classes'].keys()):
                return JsonBlob.hydrate(
                    jbModule, jbType,
                    JsonBlob.index[jbModule]['classes'][jbType]['rows'])
        return {}

    @staticmethod
    def hydrate(jbModule=None, jbType=None, ids=[]):
        """ builds a dict of instantiated objects
		
		@param jbModule
		@param jbType
		@param ids
		
		@return dict
		"""
        res = {}
        if (jbModule in JsonBlob.index.keys()):
            if (jbType in JsonBlob.index[jbModule]['classes']):
                try:
                    JsonBlob.constructors[jbModule]
                except:
                    JsonBlob.constructors[jbModule] = {
                        'object': __import__(jbModule),
                        'classes': {}
                    }
                try:
                    JsonBlob.constructors[jbModule]['classes'][jbType]
                except:
                    JsonBlob.constructors[jbModule]['classes'][
                        jbType] = getattr(
                            JsonBlob.constructors[jbModule]['object'], jbType)
                if (any(JsonBlob.index[jbModule]['classes'][jbType]['rows'])
                        and any(ids)):
                    for id in ids:
                        res[id] = JsonBlob.constructors[jbModule]['classes'][
                            jbType](id)
        return res

    def __init__(self, index=None, autoload=True):
        """ configures JsonBlob settings and loads any saved data for this jbIndex
		
		@param index
		@param autoload
		"""
        self.jbModule = type(self).__module__
        self.jbType = type(self).__name__
        self.jbIndex = index if index != None else str(uuid.uuid4())
        if (autoload):
            self.jsonData = JsonBlob.find(self.jbModule, self.jbType,
                                          self.jbIndex)

    def reload(self):
        """ reinitializes the jsonData
		"""
        self.jsonData = JsonBlob.find(self.jbModule, self.jbType, self.jbIndex)

    def save(self):
        """ saves the current jsonData
		"""
        typepath = self.getTypePath()
        if (not os.path.exists(typepath)):
            os.makedirs(typepath)
        f = open(self.getRowPath(), 'wb')
        f.write(json.dumps(self.jsonData))
        f.close()
        JsonBlob.reindex(force=True)

    def delete(self):
        """ deletes any saved data
		"""
        os.remove(self.getRowPath())
        JsonBlob.reindex(force=True)

    def blobExists(self):
        """ checks whether saved data exists for this object
		
		@return bool
		"""
        return os.path.exists(self.getRowPath())

    def getModulePath(self):
        """ returns the full file path for the module directory
		
		@return str
		"""
        return os.path.join(JsonBlob.basepath, self.jbModule)

    def getTypePath(self):
        """ returns the full file path for the type directory
		
		@return str
		"""
        return os.path.join(JsonBlob.basepath, self.jbModule, self.jbType)

    def getRowPath(self):
        """ returns the full file path for the object data
		
		@return str
		"""
        return os.path.join(JsonBlob.basepath, self.jbModule, self.jbType,
                            self.jbIndex + '.json')

    def getRowFileName(self):
        """ returns the file name for the object
		
		@return str
		"""
        return self.jbIndex + '.json'
Esempio n. 21
0
#!/usr/bin/env python
from __future__ import division
import signal, socket, time, string, sys, getopt, math, threading, smbus, select, os, struct, logging, subprocess
from __bootstrap import AmsEnvironment
from math import *
from numpy import array, dot
from array import *
from datetime import datetime

logpath = os.path.join(AmsEnvironment.FilePath(), 'imu')
if (not os.path.exists(logpath)):
    os.makedirs(logpath)

LOG_FILENAME = os.path.join(logpath, 'logging.out')
logging.basicConfig(
    filename=LOG_FILENAME,
    level=logging.DEBUG,
)
logging.disable(logging.CRITICAL)


############################################################################################
#
#  Adafruit i2c interface plus bug fix
#
############################################################################################
class I2C:
    @staticmethod
    def getPiRevision():
        "Gets the version number of the Raspberry Pi board"
        # Courtesy quick2wire-python-api