Beispiel #1
0
def getCPUSpeedString():
	if getMachineBuild() in ('vusolo4k','vuultimo4k'):
		return "1,5 GHz"
	elif getMachineBuild() in ('formuler1', 'triplex'):
		return "1,3 GHz"
	elif getMachineBuild() in ('vuuno4k','dm900', 'gb7252', 'dags7252'):
		return "1,7 GHz"
	elif getMachineBuild() in ('hd51','hd52','sf4008','vs1500','et1x000','h7'):
		try:
			import binascii
			f = open('/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency', 'rb')
			clockfrequency = f.read()
			f.close()
			return "%s MHz" % str(round(int(binascii.hexlify(clockfrequency), 16)/1000000,1))
		except:
			return "1,7 GHz"
	else:
		try:
			file = open('/proc/cpuinfo', 'r')
			lines = file.readlines()
			for x in lines:
				splitted = x.split(': ')
				if len(splitted) > 1:
					splitted[1] = splitted[1].replace('\n','')
					if splitted[0].startswith("cpu MHz"):
						mhz = float(splitted[1].split(' ')[0])
						if mhz and mhz >= 1000:
							mhz = "%s GHz" % str(round(mhz/1000,1))
						else:
							mhz = "%s MHz" % str(round(mhz,1))
			file.close()
			return mhz
		except IOError:
			return "unavailable"
Beispiel #2
0
	def __init__(self):
		Renderer.__init__(self)
		self.PicLoad = ePicLoad()
		self.PicLoad.PictureData.get().append(self.updatePicon)
		self.piconsize = (0,0)
		self.pngname = ""
		self.lastPath = None
		if getBoxType() == 'vuultimo' or getMachineBuild() == "inihdp":
			pngname = findLcdPicon("lcd_picon_default")
		else:
			pngname = findLcdPicon("picon_default")
		self.defaultpngname = None
		if not pngname:
			if getBoxType() == 'vuultimo' or getMachineBuild() == "inihdp":
				tmp = resolveFilename(SCOPE_ACTIVE_SKIN, "lcd_picon_default.png")
			else:
				tmp = resolveFilename(SCOPE_ACTIVE_SKIN, "picon_default.png")
			if pathExists(tmp):
				pngname = tmp
			else:
				if getBoxType() == 'vuultimo' or getMachineBuild() == "inihdp":
					pngname = resolveFilename(SCOPE_ACTIVE_SKIN, "lcd_picon_default.png")
				else:
					pngname = resolveFilename(SCOPE_ACTIVE_SKIN, "picon_default.png")
		if os.path.getsize(pngname):
			self.defaultpngname = pngname
Beispiel #3
0
	def updateList(self):
		self.list = []
		list2 = []
		self.Console = Console()
		self.Console.ePopen("sfdisk -l | grep swap | awk '{print $(NF-9)}' >/tmp/devices.tmp")
		sleep(0.5)
		f = open('/tmp/devices.tmp', 'r')
		swapdevices = f.read()
		f.close()
		if path.exists('/tmp/devices.tmp'):
			remove('/tmp/devices.tmp')
		swapdevices = swapdevices.replace('\n','')
		swapdevices = swapdevices.split('/')
		f = open('/proc/partitions', 'r')
		for line in f.readlines():
			parts = line.strip().split()
			if not parts:
				continue
			device = parts[3]
			if not search('sd[a-z][1-9]',device) and not search('mmcblk[0-9]p[1-9]',device):
				continue
			if getMachineBuild() in ('gbmv200','multibox','h9combo','v8plus','hd60','hd61','vuduo4k','ustym4kpro','beyonwizv2','sf8008','cc1','dags72604','u51','u52','u53','u54','vuzero4k','u5','sf5008','et13000','et1x000','vuuno4k','vuuno4kse', 'vuultimo4k', 'vusolo4k', 'hd51', 'hd52', 'dm820', 'dm7080', 'sf4008', 'dm900', 'dm920', 'gb7252', 'dags7252', 'vs1500','h7','8100s') and search('mmcblk0p[1-9]',device):
				continue
			if getMachineBuild() in ('xc7439','osmio4k') and search('mmcblk1p[1-9]',device):
				continue
			if device in list2:
				continue
			if device in swapdevices:
				continue
			self.buildMy_rec(device)
			list2.append(device)
		f.close()
		self['config'].list = self.list
		self['config'].l.setList(self.list)
		self['Linconn'].hide()
Beispiel #4
0
	def updateList2(self):
		self.activityTimer.stop()
		self.list = []
		list2 = []
		f = open('/proc/partitions', 'r')
		for line in f.readlines():
			parts = line.strip().split()
			if not parts:
				continue
			device = parts[3]
			if not search('sd[a-z][1-9]',device) and not search('mmcblk[0-9]p[1-9]',device):
				continue
			if getMachineBuild() in ('vuzero4k','u5','sf5008','et13000','et1x000','vuuno4k','vuuno4kse', 'vuultimo4k', 'vusolo4k', 'hd51', 'hd52', 'dm820', 'dm7080', 'sf4008', 'dm900', 'dm920', 'gb7252', 'dags7252', 'vs1500','h7','8100s') and search('mmcblk0p[1-9]',device):
				continue
			if getMachineBuild() in ('xc7439') and search('mmcblk1p[1-9]',device):
				continue
			if getMachineBuild() in ('u5') and search('mmcblk1p[1]',device):
				continue
			if device in list2:
				continue
			self.buildMy_rec(device)
			list2.append(device)

		f.close()
		self['list'].list = self.list
		self['lab1'].hide()
Beispiel #5
0
	def getBlockDevInfo(self, blockdev):
		devpath = "/sys/block/" + blockdev
		error = False
		removable = False
		BLACKLIST=[]
		if getMachineBuild() in ('vuzero4k','et1x000','vuuno4k','vuuno4kse','vuultimo4k','vusolo4k','hd51','hd52','sf4008','dm900','dm7080','dm820', 'gb7252', 'dags7252', 'vs1500','h7','8100s','et13000','sf5008'):
			BLACKLIST=["mmcblk0"]
		elif getMachineBuild() in ('xc7439'):
			BLACKLIST=["mmcblk1"]
		elif getMachineBuild() in ('u5','u5pvr'):
			BLACKLIST=["mmcblk0", "mmcblk1"]

		blacklisted = False
		if blockdev[:7] in BLACKLIST:
			blacklisted = True
		if blockdev.startswith("mmcblk") and (re.search(r"mmcblk\dboot", blockdev) or re.search(r"mmcblk\drpmb", blockdev)):
			blacklisted = True
		is_cdrom = False
		partitions = []
		try:
			if os.path.exists(devpath + "/removable"):
				removable = bool(int(readFile(devpath + "/removable")))
			if os.path.exists(devpath + "/dev"):
				dev = int(readFile(devpath + "/dev").split(':')[0])
			else:
				dev = None
			devlist = [1, 7, 31, 253, 254] # ram, loop, mtdblock, romblock, ramzswap
			if dev in devlist:
				blacklisted = True
			if blockdev[0:2] == 'sr':
				is_cdrom = True
			if blockdev[0:2] == 'hd':
				try:
					media = readFile("/proc/ide/%s/media" % blockdev)
					if "cdrom" in media:
						is_cdrom = True
				except IOError:
					error = True
			# check for partitions
			if not is_cdrom and os.path.exists(devpath):
				for partition in os.listdir(devpath):
					if partition[0:len(blockdev)] != blockdev:
						continue
					if dev == 179 and not re.search(r"mmcblk\dp\d+", partition):
						continue
					partitions.append(partition)
			else:
				self.cd = blockdev
		except IOError:
			error = True
		# check for medium
		medium_found = True
		try:
			if os.path.exists("/dev/" + blockdev):
				open("/dev/" + blockdev).close()
		except IOError, err:
			if err.errno == 159: # no medium present
				medium_found = False
	def initDevice(self):
		print "[BluetoothManager] initDevice"
		cmd = "hciconfig hci0 up"
		if getBoxType() in ("spycat4k","spycat4kcombo","osmio4k"):
			cmd = "hciattach ttyS1 qca | hciconfig hci0 up"
		if getMachineBuild() in ("xc7346") or getBoxType() in ("spycat4kmini"):
			cmd = "hciattach ttyS1 rtk_h5 | hciconfig hci0 up"
		if getMachineBuild() in ("xc7362") or getBoxType() in ("osnino"):
			cmd = "hciattach ttyS2 rtk_h5 | hciconfig hci0 up"
		self.taskManager.append(cmd, self.cbPrintAvailBTDev, self.cbRunNextTask)
		cmd = "hcitool dev" ## check if hci0 is on the dev list, then make scan
		self.taskManager.append(cmd, self.cbPrintAvailBTDev, self.cbStopDone)
		self.taskManager.next()
def getChipSetString():
	if getMachineBuild() in ('dm7080','dm820'):
		return "7435"
	elif getMachineBuild() in ('hd51'):
		return "7251S"
	else:
		try:
			f = open('/proc/stb/info/chipset', 'r')
			chipset = f.read()
			f.close()
			return str(chipset.lower().replace('\n','').replace('bcm','').replace('brcm','').replace('sti',''))
		except IOError:
			return "unavailable"
Beispiel #8
0
	def list_files(self, PATH):
		files = []
		if SystemInfo["HaveMultiBoot"]:
			path = PATH
			if getMachineBuild() in ("hd51","vs1500","h7"):
				for name in os.listdir(path):
					if name != 'bootname' and os.path.isfile(os.path.join(path, name)):
						try:
							cmdline = self.read_startup("/boot/" + name).split("=",3)[3].split(" ",1)[0]
						except IndexError:
							continue
						cmdline_startup = self.read_startup("/boot/STARTUP").split("=",3)[3].split(" ",1)[0]
						if (cmdline != cmdline_startup) and (name != "STARTUP"):
							files.append(name)
				files.insert(0,"STARTUP")
			elif getMachineBuild() in ("8100s"):
				for name in os.listdir(path):
					if name != 'bootname' and os.path.isfile(os.path.join(path, name)):
						try:
							cmdline = self.read_startup("/boot/" + name).split("=",4)[4].split(" ",1)[0]
						except IndexError:
							continue
						cmdline_startup = self.read_startup("/boot/STARTUP").split("=",4)[4].split(" ",1)[0]
						if (cmdline != cmdline_startup) and (name != "STARTUP"):
							files.append(name)
				files.insert(0,"STARTUP")
			elif getMachineBuild() in ("gb7252"):
				for name in os.listdir(path):
					if name != 'bootname' and os.path.isfile(os.path.join(path, name)):
						try:
							cmdline = self.read_startup("/boot/" + name).split("=",1)[1].split(" ",1)[0]
						except IndexError:
							continue
						cmdline_startup = self.read_startup("/boot/STARTUP").split("=",1)[1].split(" ",1)[0]
						if (cmdline != cmdline_startup) and (name != "STARTUP"):
							files.append(name)
				files.insert(0,"STARTUP")
			else:
				for name in os.listdir(path):
					if name != 'bootname' and os.path.isfile(os.path.join(path, name)):
						try:
							cmdline = self.read_startup("/boot/" + name).split("=",1)[1].split(" ",1)[0]
						except IndexError:
							continue
						cmdline_startup = self.read_startup("/boot/cmdline.txt").split("=",1)[1].split(" ",1)[0]
						if (cmdline != cmdline_startup) and (name != "cmdline.txt"):
							files.append(name)
				files.insert(0,"cmdline.txt")
		else:
			files = "None"
		return files
Beispiel #9
0
	def doBackup1(self):
		print '[ImageManager] Stage1: Creating tmp folders.', self.BackupDirectory
		print '[ImageManager] Stage1: Creating backup Folders.'
		if path.exists(self.WORKDIR):
			rmtree(self.WORKDIR)
		mkdir(self.WORKDIR, 0644)
		print '[ImageManager] Stage1: Create root folder.'
		if path.exists(self.TMPDIR + '/root') and path.ismount(self.TMPDIR + '/root'):
			system('umount ' + self.TMPDIR + '/root')
		elif path.exists(self.TMPDIR + '/root'):
			rmtree(self.TMPDIR + '/root')
		if path.exists(self.TMPDIR):
			rmtree(self.TMPDIR)
		makedirs(self.TMPDIR + '/root', 0644)
		makedirs(self.MAINDESTROOT, 0644)
		self.commands = []
		print '[ImageManager] Stage1: Making Root Image.'
		makedirs(self.MAINDEST, 0644)
		if self.ROOTFSTYPE == 'jffs2':
			print '[ImageManager] Stage1: JFFS2 Detected.'
			if getMachineBuild() == 'vuuno':
				JFFS2OPTIONS = " --disable-compressor=lzo -126976 -l -p125829120"
			if getMachineBuild() in ('dm800', 'dm800se','dm500hd'):
				JFFS2OPTIONS = " --eraseblock=0x4000 -n -l"
			else:
				JFFS2OPTIONS = " --disable-compressor=lzo --eraseblock=0x20000 -n -l"
			self.commands.append('mount --bind / ' + self.TMPDIR + '/root')
			self.commands.append('mount -t jffs2 /dev/mtdblock/2 ' + self.TMPDIR + '/boot')
			self.commands.append('mkfs.jffs2 --root=' + self.TMPDIR + '/root --faketime --output=' + self.WORKDIR + '/root.jffs2' + JFFS2OPTIONS)
			if getMachineBuild() in ('dm800', 'dm800se', 'dm500hd'):
				self.commands.append('mkfs.jffs2 --root=' + self.TMPDIR + '/boot --faketime --output=' + self.WORKDIR + '/boot.jffs2' + JFFS2OPTIONS)
		else:
			print '[ImageManager] Stage1: UBIFS Detected.'
			UBINIZE = 'ubinize'
			UBINIZE_ARGS = getMachineUBINIZE()
			MKUBIFS_ARGS = getMachineMKUBIFS()
			output = open(self.WORKDIR + '/ubinize.cfg', 'w')
			output.write('[ubifs]\n')
			output.write('mode=ubi\n')
			output.write('image=' + self.WORKDIR + '/root.ubi\n')
			output.write('vol_id=0\n')
			output.write('vol_type=dynamic\n')
			output.write('vol_name=rootfs\n')
			output.write('vol_flags=autoresize\n')
			output.close()
			self.commands.append('mount --bind / ' + self.TMPDIR + '/root')
			self.commands.append('touch ' + self.WORKDIR + '/root.ubi')
			self.commands.append('mkfs.ubifs -r ' + self.TMPDIR + '/root -o ' + self.WORKDIR + '/root.ubi ' + MKUBIFS_ARGS)
			self.commands.append('ubinize -o ' + self.WORKDIR + '/root.ubifs ' + UBINIZE_ARGS + ' ' + self.WORKDIR + '/ubinize.cfg')
		self.Console.eBatch(self.commands, self.Stage1Complete, debug=False)
Beispiel #10
0
def getChipSetString():
    if getMachineBuild() in ("dm7080", "dm820"):
        return "7435"
    elif getBoxType() == "blackbox7405":
        return "7413"
    elif getMachineBuild() in ("hd51"):
        return "7251S"
    else:
        try:
            f = open("/proc/stb/info/chipset", "r")
            chipset = f.read()
            f.close()
            return str(chipset.lower().replace("\n", "").replace("bcm", "").replace("brcm", "").replace("sti", ""))
        except IOError:
            return "unavailable"
Beispiel #11
0
	def Start_Flashing(self):
		print "Start Flashing"
		cmdlist = []
		if os.path.exists(ofgwritePath):
			text = _("Flashing: ")
			if self.simulate:
				text += _("Simulate (no write)")
				if SystemInfo["HaveMultiBoot"]:
					cmdlist.append("%s -n -r -k -m%s %s > /dev/null 2>&1" % (ofgwritePath, self.multi, flashTmp))
				elif getMachineBuild() in ("u5","u5pvr"):
					cmdlist.append("%s -n -r%s -k%s %s > /dev/null 2>&1" % (ofgwritePath, MTDROOTFS, MTDKERNEL, flashTmp))
				else:
					cmdlist.append("%s -n -r -k %s > /dev/null 2>&1" % (ofgwritePath, flashTmp))
				self.close()
				message = "echo -e '\n"
				message += _('Show only found image and mtd partitions.\n')
				message += "'"
			else:
				text += _("root and kernel")
				if SystemInfo["HaveMultiBoot"]:
					if self.List not in ("STARTUP","cmdline.txt"):
						os.system('mkfs.ext4 -F ' + self.devrootfs)
					cmdlist.append("%s -r -k -m%s %s > /dev/null 2>&1" % (ofgwritePath, self.multi, flashTmp))
					if self.List not in ("STARTUP","cmdline.txt"):
						cmdlist.append("umount -fl /oldroot_bind")
						cmdlist.append("umount -fl /newroot")
				elif getMachineBuild() in ("u5","u5pvr"):
					cmdlist.append("%s -r%s -k%s %s > /dev/null 2>&1" % (ofgwritePath, MTDROOTFS, MTDKERNEL, flashTmp))
				else:
					cmdlist.append("%s -r -k %s > /dev/null 2>&1" % (ofgwritePath, flashTmp))
				message = "echo -e '\n"
				if self.List not in ("STARTUP","cmdline.txt") and SystemInfo["HaveMultiBoot"]:
					message += _('ofgwrite flashing ready.\n')
					message += _('please press exit to go back to the menu.\n')
				else:
					message += _('ofgwrite will stop enigma2 now to run the flash.\n')
					message += _('Your STB will freeze during the flashing process.\n')
					message += _('Please: DO NOT reboot your STB and turn off the power.\n')
					message += _('The image or kernel will be flashing and auto booted in few minutes.\n')
					if self.box() == 'gb800solo':
						message += _('GB800SOLO takes about 20 mins !!\n')
				message += "'"
				cmdlist.append(message)
				self.session.open(Console, title = text, cmdlist = cmdlist, finishedCallback = self.quit, closeOnSuccess = False)
				if not self.simulate:
					fbClass.getInstance().lock()
				if self.List not in ("STARTUP","cmdline.txt"):
					self.close()
Beispiel #12
0
 def __init__(self):
     Renderer.__init__(self)
     self.PicLoad = ePicLoad()
     self.PicLoad.PictureData.get().append(self.updatePicon)
     self.piconsize = (0, 0)
     self.pngname = ''
     self.lastPath = None
     if getBoxType() in ('vuultimo', 'et10000', 'mutant2400', 'quadbox2400') or getMachineBuild() in 'inihdp':
         pngname = findLcdPicon('lcd_picon_default')
     else:
         pngname = findLcdPicon('picon_default')
     self.defaultpngname = None
     if not pngname:
         if getBoxType() in ('vuultimo', 'et10000', 'mutant2400', 'quadbox2400') or getMachineBuild() in 'inihdp':
             tmp = resolveFilename(SCOPE_ACTIVE_SKIN, 'lcd_picon_default.png')
         else:
             tmp = resolveFilename(SCOPE_ACTIVE_SKIN, 'picon_default.png')
         if pathExists(tmp):
             pngname = tmp
         elif getBoxType() in ('vuultimo', 'et10000', 'mutant2400', 'quadbox2400') or getMachineBuild() in 'inihdp':
             pngname = resolveFilename(SCOPE_ACTIVE_SKIN, 'lcd_picon_default.png')
         else:
             pngname = resolveFilename(SCOPE_ACTIVE_SKIN, 'picon_default.png')
     if os.path.getsize(pngname):
         self.defaultpngname = pngname
     return
Beispiel #13
0
def profile(id):
	now = time.time() - profile_start
	if profile_file:
		profile_file.write("%7.3f\t%s\n" % (now, id))

		if id in profile_data:
			t = profile_data[id]
			if total_time:
				perc = t * (PERCENTAGE_END - PERCENTAGE_START) / total_time + PERCENTAGE_START
			else:
				perc = PERCENTAGE_START
			try:
				if getBoxType() in ("classm", "axodin", "axodinc", "starsatlx", "evo", "genius", "galaxym6" ):
					f = open("/dev/dbox/oled0", "w")
					f.write("%d" % perc)
				elif getBoxType() in ('gb800solo', 'gb800se', 'gb800seplus'):
					f = open("/dev/mcu", "w")
					f.write("%d  \n" % perc)
				elif getBoxType() in ("mixosf5", "gi9196m"):
					f = open("/proc/progress", "w")
					f.write("%d" % perc)
				elif getMachineBuild() in ("inihdp", "inihdx"):
					f = open("/proc/vfd", "w")
					f.write("Loading %d%%" % perc)
				else:
					f = open("/proc/progress", "w")
					f.write("%d \n" % perc)
				f.close()
			except IOError:
				pass
Beispiel #14
0
def profile(id):
    global profile_file
    now = time.time() - profile_start
    if profile_file:
        profile_file.write('%7.3f\t%s\n' % (now, id))
        if id in profile_data:
            t = profile_data[id]
            if total_time:
                perc = t * (PERCENTAGE_END - PERCENTAGE_START) / total_time + PERCENTAGE_START
            else:
                perc = PERCENTAGE_START
            try:
                if boxtype in ('classm', 'axodin', 'axodinc', 'starsatlx', 'evo', 'genius', 'galaxym6'):
                    f = open('/dev/dbox/oled0', 'w')
                    f.write('%d' % perc)
                elif boxtype in ('gb800solo', 'gb800se', 'gb800seplus', 'gbultrase'):
                    f = open('/dev/mcu', 'w')
                    f.write('%d  \n' % perc)
                elif boxtype in ('mixosf5', 'gi9196m'):
                    f = open('/proc/progress', 'w')
                    f.write('%d' % perc)
                elif getMachineBuild() in ('inihdp', 'inihde2', 'inihde', 'inihdx'):
                    f = open('/proc/vfd', 'w')
                    f.write('Loading %d %%' % perc)
                elif boxtype in ('amikomini', 'amiko8900', 'sognorevolution', 'arguspingulux', 'arguspinguluxmini', 'sparkreloaded', 'sabsolo', 'sparklx', 'gis8120'):
                    f = open('/proc/vfd', 'w')
                    f.write('%d \n' % perc)
                else:
                    f = open('/proc/progress', 'w')
                    f.write('%d \n' % perc)
                f.close()
            except IOError:
                pass
Beispiel #15
0
	def updateList(self):
		self.list = []
		list2 = []
		self.Console = Console()
		self.Console.ePopen("sfdisk -l | grep swap | awk '{print $(NF-9)}' >/tmp/devices.tmp")
		sleep(0.5)
		f = open('/tmp/devices.tmp', 'r')
		swapdevices = f.read()
		f.close()
		if path.exists('/tmp/devices.tmp'):
			remove('/tmp/devices.tmp')
		swapdevices = swapdevices.replace('\n','')
		swapdevices = swapdevices.split('/')
		f = open('/proc/partitions', 'r')
		for line in f.readlines():
			parts = line.strip().split()
			if not parts:
				continue
			device = parts[3]
			if not search('sd[a-z][1-9]',device) and not search('mmcblk[0-9]p[1-9]',device):
				continue
			if getMachineBuild() in ('et1x000','vuuno4k', 'vuultimo4k', 'vusolo4k', 'hd51', 'hd52', 'dm820', 'dm7080', 'sf4008', 'dm900', 'gb7252', 'dags7252', 'vs1500','h7') and search('mmcblk0p[1-9]',device):
				continue
			if device in list2:
				continue
			if device in swapdevices:
				continue
			self.buildMy_rec(device)
			list2.append(device)
		f.close()
		self['config'].list = self.list
		self['config'].l.setList(self.list)
		self['Linconn'].hide()
Beispiel #16
0
 def __init__(self):
     Renderer.__init__(self)
     VariableText.__init__(self)
     if getMachineBuild() == 'inihdp':
         self.stringlength = 25
     else:
         self.stringlength = 16
Beispiel #17
0
def kernelMismatch():
	# returns True if a kernal mismatch is found. i.e. STB kernel does not match feeds kernel
	import zlib
	import re

	kernelversion = about.getKernelVersionString().strip()
	if kernelversion == "unknown":
		print '[OnlineVersionCheck][kernelMismatch] unable to retrieve kernel version from STB'
		return False

	uri = "%s/%s/Packages.gz" % (getFeedsUrl(), getMachineBuild())
	try:
		req = urllib2.Request(uri)
		d = urllib2.urlopen(req)
		gz_data = d.read()
	except:
		print '[OnlineVersionCheck][kernelMismatch] error fetching %s' % uri
		return False

	try:
		packages = zlib.decompress(gz_data, 16+zlib.MAX_WBITS)
	except:
		print '[OnlineVersionCheck][kernelMismatch] failed to decompress gz_data'
		return False

	pattern = "kernel-([0-9]+[.][0-9]+[.][0-9]+)"
	matches = re.findall(pattern, packages)
	if matches:
		match = sorted(matches,key=lambda s: list(map(int, s.split('.'))))[-1]
		if match != kernelversion:
			print '[OnlineVersionCheck][kernelMismatch] kernel mismatch found. STB kernel=%s, feeds kernel=%s' % (kernelversion, match)
			return True

	print '[OnlineVersionCheck][kernelMismatch] no kernel mismatch found'
	return False
Beispiel #18
0
def createTransCodingConfig(encoder):
	if fileExists(getProcPath(encoder ,"bitrate")):
		if getBoxType() in ('vusolo2') or getMachineBuild() in ('dags3', 'dags4'):
			choice = ConfigSelection(default = "400000", choices=[("-1", "Auto"), ("50000", "50 Kbits"), ("100000", "100 Kbits"), ("150000", "150 Kbits"), ("200000", "200 Kbits"), ("250000", "250 Kbits"), ("300000", "300 Kbits"), ("350000", "350 Kbits"), ("400000", "400 Kbits"), ("450000", "450 Kbits"), ("500000", "500 Kbits"), ("600000", "600 Kbits"), ("700000", "700 Kbits"), ("800000", "800 Kbits"), ("900000", "900 Kbits"), ("1000000", "1 Mbits")])
		elif getBoxType() in ('gbquad', 'gbquadplus'):
			choice = ConfigSelection(default = "-1", choices=[("-1", "Auto"), ("50000", "50 Kbits"), ("100000", "100 Kbits"), ("150000", "150 Kbits"), ("200000", "200 Kbits"), ("250000", "250 Kbits"), ("300000", "300 Kbits"), ("350000", "350 Kbits"), ("400000", "400 Kbits"), ("450000", "450 Kbits"), ("500000", "500 Kbits"), ("600000", "600 Kbits"), ("700000", "700 Kbits"), ("800000", "800 Kbits"), ("900000", "900 Kbits"), ("1000000", "1 Mbits")])
		else:
			choice = ConfigSelection(default = "2000000", choices=[("-1", "Auto"), ("100000", "100 Kbits"), ("150000", "150 Kbits"), ("200000", "200 Kbits"), ("250000", "250 Kbits"), ("300000", "300 Kbits"), ("350000", "350 Kbits"), ("400000", "400 Kbits"), ("450000", "450 Kbits"), ("500000", "500 Kbits"), ("750000", "750 Kbits"), ("1000000", "1 Mbits"), ("1500000", "1.5 Mbits"), ("2000000", "2 Mbits"), ("2500000", "2.5 Mbits"), ("3000000", "3 Mbits"), ("3500000", "3.5 Mbits"), ("4000000", "4 Mbits"), ("4500000", "4.5 Mbits"), ("5000000", "5 Mbits"), ("10000000", "10 Mbits")])
		config.plugins.transcodingsetup.encoder[int(encoder)].bitrate = choice

	if fileExists(getProcPath(encoder ,"framerate")):
		if getBoxType() in ('gbquad', 'gbquadplus'):
			choice = ConfigSelection(default = "-1", choices = [("-1", "Auto"), ("23976", "23.976 fps"), ("24000", "24 fps"), ("25000", "25 fps"), ("29970", "29.970 fps")])
		else:
			choice = ConfigSelection(default = "50000", choices = [("-1", "Auto"), ("23976", "23.976 fps"), ("24000", "24 fps"), ("25000", "25 fps"), ("29970", "29.970 fps"), ("30000", "30 fps"), ("50000", "50 fps"), ("59940", "59.940 fps"), ("60000", "60 fps")])
		config.plugins.transcodingsetup.encoder[int(encoder)].framerate = choice

	if checkSupportAdvanced():
		if (hasattr(config.plugins.transcodingsetup.encoder[int(encoder)], "bitrate") or hasattr(config.plugins.transcodingsetup.encoder[int(encoder)], "framerate")):
			choice = ConfigSelection(default = "Off", choices = [ ("On", _("On")), ("Off", _("Off")) ])
			config.plugins.transcodingsetup.encoder[int(encoder)].automode = choice

		if fileExists(getProcPath(encoder, "resolution")):
			resolution_choices = [("480p", _("480p")), ("576p", _("576p")), ("720p", _("720p")), ("320x240", _("320x240")), ("160x120", _("160x120"))]
			if getBoxType() in ("vusolo4k"):
				resolution_choices.insert(3, ("1080p", _("1080p")))
			choice = ConfigSelection(default = "480p", choices=resolution_choices)
			config.plugins.transcodingsetup.encoder[int(encoder)].resolution = choice

		if fileExists(getProcPath(encoder, "aspectratio")):
			choice = ConfigSelection(default = "2", choices = [ ("0", _("auto")), ("1", _("4x3")), ("2", _("16x9")) ])
			config.plugins.transcodingsetup.encoder[int(encoder)].aspectratio = choice

		if fileExists(getProcPath(encoder, "audiocodec")):
			choice = ConfigSelection(default = "aac", choices = [("mpg", _("mpg")), ("mp3", _("mp3")), ("aac", _("aac")), ("aac+", _("aac+")), ("aac+loas", _("aac+loas")), ("aac+adts", _("aac+adts")), ("ac3", _("ac3"))])
			config.plugins.transcodingsetup.encoder[int(encoder)].audiocodec = choice

		if fileExists(getProcPath(encoder, "videocodec")):
			choice = ConfigSelection(default = "h264", choices = [ ("h264", _("h264")) ])
			config.plugins.transcodingsetup.encoder[int(encoder)].videocodec = choice

		if fileExists(getProcPath(encoder, "gopframeb")):
			choice = ConfigInteger(default = 0, limits = (0, 60))
			config.plugins.transcodingsetup.encoder[int(encoder)].gopframeb = choice

		if fileExists(getProcPath(encoder, "gopframep")):
			choice = ConfigInteger(default = 29, limits = (0, 60))
			config.plugins.transcodingsetup.encoder[int(encoder)].gopframep = choice

		if fileExists(getProcPath(encoder, "level")):
			choice = ConfigSelection(default = "3.1", choices = [("1.0", _("1.0")), ("2.0", _("2.0")),
				("2.1", _("2.1")), ("2.2", _("2.2")), ("3.0", _("3.0")), ("3.1", _("3.1")),
				("3.2", _("3.2")), ("4.0", _("4.0")), ("4.1", _("4.1")), ("4.2", _("4.2")),
				("5.0", _("5.0")), ("low", _("low")), ("main", _("main")), ("high", _("high"))])
			config.plugins.transcodingsetup.encoder[int(encoder)].level = choice

		if fileExists(getProcPath(encoder, "profile")):
			choice = ConfigSelection(default = "baseline", choices = [("baseline", _("baseline")), ("simple", _("simple")), ("main", _("main")), ("high", _("high")), ("advanced simple", _("advancedsimple"))])
			config.plugins.transcodingsetup.encoder[int(encoder)].profile = choice
Beispiel #19
0
	def keyBackup(self):
		self.sel = self['list'].getCurrent()
		if getMachineBuild() in ('vusolo4k','hd51','hd52'):
				self.session.open(MessageBox, _("Sorry function not yet supported in this model"), MessageBox.TYPE_INFO, timeout=10)
		elif self.sel:
			message = _("Are you ready to create a backup image ?")
			ybox = self.session.openWithCallback(self.doBackup, MessageBox, message, MessageBox.TYPE_YESNO)
			ybox.setTitle(_("Backup Confirmation"))
Beispiel #20
0
	def getlog(self):
		global ocram
		try:
			sourcefile = 'http://feed.atemio4you.com/' + getImageVersion() + '/' + getMachineBuild() + '/'  + self.logtype + '-git.log'
			sourcefile,headers = urllib.urlretrieve(sourcefile)
			rename(sourcefile,'/tmp/' + self.logtype + '-git.log')
			fd = open('/tmp/' + self.logtype + '-git.log', 'r')
			releasenotes = fd.read()
			fd.close()
		except:
			releasenotes = '404 Not Found'
		if '404 Not Found' not in releasenotes:
			releasenotes = releasenotes.replace('[atemio] Release.', 'atemio: build 000')
			releasenotes = releasenotes.replace('\natemio: build',"\n\natemio: build")
			releasenotes = releasenotes.split('\n\n')
			ver = -1
			releasever = ""
			viewrelease = ""
			while not releasever.isdigit():
				ver += 1
				releasever = releasenotes[int(ver)].split('\n')
				releasever = releasever[0].split(' ')
				if len(releasever) > 2:
					releasever = releasever[2].replace(':',"")
				else:
					releasever = releasever[0].replace(':',"")
			if self.logtype == 'oe':
				if int(getImageBuild()) == 1:
					imagever = int(getImageBuild())-1
				else:
					imagever = int(getImageBuild())
			else:
				imagever = int(getImageBuild())+0
			while int(releasever) > int(imagever):
				if ocram:
					viewrelease += releasenotes[int(ver)]+'\n'+ocram+'\n'
					ocram = ""
				else:
					viewrelease += releasenotes[int(ver)]+'\n\n'
				ver += 1
				releasever = releasenotes[int(ver)].split('\n')
				releasever = releasever[0].split(' ')
				releasever = releasever[2].replace(':',"")
			if not viewrelease and ocram:
				viewrelease = ocram
				ocram = ""
			self["text"].setText(viewrelease)
			summarytext = viewrelease.split(':\n')
			try:
				self['title_summary'].setText(summarytext[0]+':')
				self['text_summary'].setText(summarytext[1])
			except:
				self['title_summary'].setText("")
				self['text_summary'].setText(viewrelease)
		else:
			self['title_summary'].setText("")
			self['text_summary'].setText(_("Error downloading change log."))
			self['text'].setText(_("Error downloading change log."))
Beispiel #21
0
 def getBlockDevInfo(self, blockdev):
     devpath = "/sys/block/" + blockdev
     error = False
     removable = False
     blacklisted = False
     is_cdrom = False
     partitions = []
     try:
         if os.path.exists(devpath + "/removable"):
             removable = bool(int(readFile(devpath + "/removable")))
         if os.path.exists(devpath + "/dev"):
             dev = int(readFile(devpath + "/dev").split(":")[0])
         else:
             dev = None
         if getMachineBuild() in (
             "vuuno4k",
             "vuultimo4k",
             "vusolo4k",
             "hd51",
             "hd52",
             "sf4008",
             "dm900",
             "dm7080",
             "dm820",
         ):
             devlist = [1, 7, 31, 253, 254, 179]  # ram, loop, mtdblock, romblock, ramzswap, mmc
         else:
             devlist = [1, 7, 31, 253, 254]  # ram, loop, mtdblock, romblock, ramzswap
         if dev in devlist:
             blacklisted = True
         if blockdev[0:2] == "sr":
             is_cdrom = True
         if blockdev[0:2] == "hd":
             try:
                 media = readFile("/proc/ide/%s/media" % blockdev)
                 if "cdrom" in media:
                     is_cdrom = True
             except IOError:
                 error = True
                 # check for partitions
         if not is_cdrom and os.path.exists(devpath):
             for partition in os.listdir(devpath):
                 if partition[0 : len(blockdev)] != blockdev:
                     continue
                 partitions.append(partition)
         else:
             self.cd = blockdev
     except IOError:
         error = True
         # check for medium
     medium_found = True
     try:
         if os.path.exists("/dev/" + blockdev):
             open("/dev/" + blockdev).close()
     except IOError, err:
         if err.errno == 159:  # no medium present
             medium_found = False
Beispiel #22
0
	def __init__(self, session):
		Screen.__init__(self, session)
		self.session = session
		self.selection = 0
		if getMachineBuild() in ("hd51","vs1500","h7","8100s"):
			self.devrootfs = "/dev/mmcblk0p3"
		elif getMachineBuild() in ("gb7252"):
			self.devrootfs = "/dev/mmcblk0p4"
		else:
			self.devrootfs = "/dev/mmcblk1p3"
		self.multi = 1
		self.list = self.list_files("/boot")
		self.MTDKERNEL = getMachineMtdKernel()
		self.MTDROOTFS = getMachineMtdRoot()

		Screen.setTitle(self, _("Flash On the Fly"))
		if SystemInfo["HaveMultiBoot"]:
			self["key_blue"] = Button(_("Multiboot Select"))
			self.read_current_multiboot()
		else:
			self["key_blue"] = Button(_(" "))
		self["key_green"] = Button(_("Online"))
		self["key_red"] = Button(_("Exit"))
		self["key_yellow"] = Button(_("Local"))
		self["info-local"] = Label(_("Local = Flash a image from local path /hdd/images"))
		self["info-online"] = Label(_("Online = Download a image and flash it"))

		self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
		{
			"blue": self.blue,
			"yellow": self.yellow,
			"green": self.green,
			"red": self.quit,
			"cancel": self.quit,
		}, -2)
		if SystemInfo["HaveMultiBoot"]:
			if SystemInfo["HasRootSubdir"]:
				self.multi = self.find_rootfssubdir(self.list[self.selection])
			elif getMachineBuild() in ("gb7252"):
				self.multi = self.read_startup("/boot/" + self.list[self.selection]).split(".",1)[1].split(":",1)[0]
			else:
				self.multi = self.read_startup("/boot/" + self.list[self.selection]).split(".",1)[1].split(" ",1)[0]
			self.multi = self.multi[-1:]
			print "[Flash Online] MULTI:",self.multi
Beispiel #23
0
def onMountpointRemoved(mountpoint):
    if getBoxType() in ('vuultimo', 'et10000', 'mutant2400', 'quadbox2400') or getMachineBuild() in 'inihdp':
        path = os.path.join(mountpoint, 'piconlcd') + '/'
    else:
        path = os.path.join(mountpoint, 'picon') + '/'
    try:
        searchPaths.remove(path)
        print '[LcdPicon] removed path:', path
    except:
        pass
Beispiel #24
0
	def keyResstore(self):
		self.sel = self['list'].getCurrent()
		if getMachineBuild() in ('vusolo4k','hd51','hd52'):
			self.session.open(MessageBox, _("Sorry function not yet supported in this model - Try Image Flasher"), MessageBox.TYPE_INFO, timeout=10)
		elif self.sel:
			message = _("Are you sure you want to restore this image:\n ") + self.sel
			ybox = self.session.openWithCallback(self.keyResstore2, MessageBox, message, MessageBox.TYPE_YESNO)
			ybox.setTitle(_("Restore Confirmation"))
		else:
			self.session.open(MessageBox, _("You have no image to restore."), MessageBox.TYPE_INFO, timeout=10)
Beispiel #25
0
	def backupRunning(self):
		self.populate_List()
		self.BackupRunning = False
		for job in Components.Task.job_manager.getPendingJobs():
			if job.name.startswith(_("Image Manager")):
				self.BackupRunning = False
		if getMachineBuild() in ('vusolo4k','hd51','hd52'):
				self["key_green"].setText(_("Unavailable"))
		else:
			self["key_green"].setText(_("New Backup"))
			self.activityTimer.startLongTimer(5)
Beispiel #26
0
def getChipSetString():
	if getMachineBuild() in ('gb73625'):
		return "BCM73625"
	else:
		try:
			f = open('/proc/stb/info/chipset', 'r')
			chipset = f.read()
			f.close()
			return str(chipset.lower().replace('\n','').replace('bcm','BCM').replace('brcm','BRCM').replace('sti',''))
		except IOError:
			return "unavailable"
Beispiel #27
0
def onMountpointRemoved(mountpoint):
	global searchPaths
	if getBoxType() == 'vuultimo' or getMachineBuild() == "inihdp":
		path = os.path.join(mountpoint, 'piconlcd') + '/'
	else:
		path = os.path.join(mountpoint, 'picon') + '/'
	try:
		searchPaths.remove(path)
		print "[LcdPicon] removed path:", path
	except:
		pass
Beispiel #28
0
	def read_current_multiboot(self):
		if getMachineBuild() in ("cc1","sf8008"):
			if self.list[self.selection] == "Recovery":
				cmdline = self.read_startup("/boot/STARTUP").split("=",1)[1].split(" ",1)[0]
			else:
				cmdline = self.read_startup("/boot/" + self.list[self.selection]).split("=",1)[1].split(" ",1)[0]
		cmdline = cmdline.lstrip("/dev/")
		self.MTDROOTFS = cmdline
		self.MTDKERNEL = cmdline[:-1] + str(int(cmdline[-1:]) -1)
		print "[Flash Online] kernel device: ",self.MTDKERNEL
		print "[Flash Online] rootfsdevice: ",self.MTDROOTFS
Beispiel #29
0
def getCpuCoresString():
	try:
		file = open('/proc/cpuinfo', 'r')
		lines = file.readlines()
		for x in lines:
			splitted = x.split(': ')
			if len(splitted) > 1:
				splitted[1] = splitted[1].replace('\n','')
				if splitted[0].startswith("processor"):
					if getMachineBuild() in ('u5','u51','u52','u53','u5pvr','h9','sf8008','sf8008s','sf8008t','hd60','hd61','i55plus'):
						cores = 4
					elif getMachineBuild() in ('u41','u42'):
						cores = 2
					elif int(splitted[1]) > 0:
						cores = 2
					else:
						cores = 1
		file.close()
		return cores
	except IOError:
		return "unavailable"
Beispiel #30
0
	def blue(self):
		if SystemInfo["HaveMultiBoot"]:
			self.selection = self.selection + 1
			if self.selection == len(self.list):
				self.selection = 0
			self["key_blue"].setText(_(self.list[self.selection]))
			if getMachineBuild() in ("gb7252"):
				self.multi = self.read_startup("/boot/" + self.list[self.selection]).split(".",1)[1].split(":",1)[0]
				self.multi = self.multi[-1:]
			else:
				self.multi = self.read_startup("/boot/" + self.list[self.selection]).split(".",1)[1].split(" ",1)[0]
				self.multi = self.multi[-1:]
			print "[Flash ESI-Online] MULTI:",self.multi
			if getMachineBuild() in ("hd51","vs1500","h7"):
				cmdline = self.read_startup("/boot/" + self.list[self.selection]).split("=",3)[3].split(" ",1)[0]
			elif getMachineBuild() in ("8100s"):
				cmdline = self.read_startup("/boot/" + self.list[self.selection]).split("=",4)[4].split(" ",1)[0]
			else:
				cmdline = self.read_startup("/boot/" + self.list[self.selection]).split("=",1)[1].split(" ",1)[0]
			self.devrootfs = cmdline
			print "[Flash ESI-Online] MULTI rootfs ", self.devrootfs
Beispiel #31
0
def getAboutText():
    AboutText = ""
    AboutText += _("Model:\t%s %s\n") % (getMachineBrand(), getMachineName())
    AboutText += _("OEM Model:\t\t%s\n") % getMachineBuild()

    bootloader = ""
    if path.exists('/sys/firmware/devicetree/base/bolt/tag'):
        f = open('/sys/firmware/devicetree/base/bolt/tag', 'r')
        bootloader = f.readline().replace('\x00', '').replace('\n', '')
        f.close()
        AboutText += _("Bootloader:\t\t%s\n") % (bootloader)

    if path.exists('/proc/stb/info/chipset'):
        AboutText += _("Chipset:\t%s") % about.getChipSetString() + "\n"

    cpuMHz = ""
    if getMachineBuild() in ('vusolo4k', 'vuultimo4k', 'vuzero4k'):
        cpuMHz = "   (1,5 GHz)"
    elif getMachineBuild() in ('formuler1tc', 'formuler1', 'triplex',
                               'tiviaraplus'):
        cpuMHz = "   (1,3 GHz)"
    elif getMachineBuild() in ('u5', 'u53', 'u52', 'u5pvr', 'h9'):
        cpuMHz = "   (1,6 GHz)"
    elif getMachineBuild() in ('vuuno4kse', 'vuuno4k', 'dm900', 'dm920',
                               'gb7252', 'dags7252', 'xc7439', '8100s'):
        cpuMHz = "   (1,7 GHz)"
    elif getMachineBuild() in ('sf5008', 'et13000', 'et1x000', 'hd52', 'hd51',
                               'sf4008', 'vs1500', 'h7'):
        try:
            import binascii
            f = open(
                '/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency',
                'rb')
            clockfrequency = f.read()
            f.close()
            cpuMHz = "   (%s MHz)" % str(
                round(int(binascii.hexlify(clockfrequency), 16) / 1000000, 1))
        except:
            cpuMHz = "   (1,7 GHz)"
    else:
        if path.exists('/proc/cpuinfo'):
            f = open('/proc/cpuinfo', 'r')
            temp = f.readlines()
            f.close()
            try:
                for lines in temp:
                    lisp = lines.split(': ')
                    if lisp[0].startswith('cpu MHz'):
                        #cpuMHz = "   (" +  lisp[1].replace('\n', '') + " MHz)"
                        cpuMHz = "   (" + str(
                            int(float(lisp[1].replace('\n', '')))) + " MHz)"
                        break
            except:
                pass

    AboutText += _("CPU:\t%s") % about.getCPUString() + cpuMHz + "\n"
    AboutText += _("Cores:\t%s") % about.getCpuCoresString() + "\n"

    imagestarted = ""
    bootname = ''
    if path.exists('/boot/bootname'):
        f = open('/boot/bootname', 'r')
        bootname = f.readline().split('=')[1]
        f.close()

    if path.exists('/boot/STARTUP'):
        f = open('/boot/STARTUP', 'r')
        f.seek(22)
        image = f.read(1)
        f.close()
        if bootname: bootname = "   (%s)" % bootname
        AboutText += _(
            "Selected Image:\t%s") % "STARTUP_" + image + bootname + "\n"
    elif path.exists('/boot/cmdline.txt'):
        f = open('/boot/cmdline.txt', 'r')
        f.seek(38)
        image = f.read(1)
        f.close()
        if bootname: bootname = "   (%s)" % bootname
        AboutText += _(
            "Selected Image:\t%s") % "STARTUP_" + image + bootname + "\n"

    AboutText += _("Version:\t%s") % getImageVersion() + "\n"
    AboutText += _("Build:\t%s") % getImageBuild() + "\n"
    AboutText += _("Kernel:\t%s") % about.getKernelVersionString() + "\n"

    string = getDriverDate()
    year = string[0:4]
    month = string[4:6]
    day = string[6:8]
    driversdate = '-'.join((year, month, day))
    AboutText += _("Drivers:\t%s") % driversdate + "\n"

    AboutText += _("GStreamer:\t%s") % about.getGStreamerVersionString() + "\n"
    AboutText += _("Python:\t%s") % about.getPythonVersionString() + "\n"

    if getMachineBuild() not in ('h9', 'vuzero4k', 'sf5008', 'et13000',
                                 'et1x000', 'hd51', 'hd52', 'vusolo4k',
                                 'vuuno4k', 'vuuno4kse', 'vuultimo4k',
                                 'sf4008', 'dm820', 'dm7080', 'dm900', 'dm920',
                                 'gb7252', 'dags7252', 'vs1500', 'h7',
                                 'xc7439', '8100s', 'u5', 'u5pvr', 'u52',
                                 'u53'):
        AboutText += _("Installed:\t%s") % about.getFlashDateString() + "\n"

    AboutText += _("Last update:\t%s") % getEnigmaVersionString() + "\n"

    fp_version = getFPVersion()
    if fp_version is None:
        fp_version = ""
    elif fp_version != 0:
        fp_version = _("Frontprocessor version: %s") % fp_version
        AboutText += fp_version + "\n"

    tempinfo = ""
    if path.exists('/proc/stb/sensors/temp0/value'):
        f = open('/proc/stb/sensors/temp0/value', 'r')
        tempinfo = f.read()
        f.close()
    elif path.exists('/proc/stb/fp/temp_sensor'):
        f = open('/proc/stb/fp/temp_sensor', 'r')
        tempinfo = f.read()
        f.close()
    elif path.exists('/proc/stb/sensors/temp/value'):
        f = open('/proc/stb/sensors/temp/value', 'r')
        tempinfo = f.read()
        f.close()
    if tempinfo and int(tempinfo.replace('\n', '')) > 0:
        mark = str('\xc2\xb0')
        AboutText += _("System temperature:\t%s") % tempinfo.replace(
            '\n', '').replace(' ', '') + mark + "C\n"

    tempinfo = ""
    if path.exists('/proc/stb/fp/temp_sensor_avs'):
        f = open('/proc/stb/fp/temp_sensor_avs', 'r')
        tempinfo = f.read()
        f.close()
    elif path.exists('/sys/devices/virtual/thermal/thermal_zone0/temp'):
        try:
            f = open('/sys/devices/virtual/thermal/thermal_zone0/temp', 'r')
            tempinfo = f.read()
            tempinfo = tempinfo[:-4]
            f.close()
        except:
            tempinfo = ""
    if tempinfo and int(tempinfo.replace('\n', '')) > 0:
        mark = str('\xc2\xb0')
        AboutText += _("Processor temperature:\t%s") % tempinfo.replace(
            '\n', '').replace(' ', '') + mark + "C\n"
    AboutLcdText = AboutText.replace('\t', ' ')

    return AboutText, AboutLcdText
Beispiel #32
0
    def getBlockDevInfo(self, blockdev):
        devpath = "/sys/block/" + blockdev
        error = False
        removable = False
        BLACKLIST = []
        if getMachineBuild() in ('gbmv200', 'gb7252', 'gb72604'):
            BLACKLIST = ["mmcblk0"]
        elif getMachineBuild() in ('dummy', ):
            BLACKLIST = ["mmcblk1"]

        blacklisted = False
        if blockdev[:7] in BLACKLIST:
            blacklisted = True
        if blockdev.startswith("mmcblk") and (
                re.search(r"mmcblk\dboot", blockdev)
                or re.search(r"mmcblk\drpmb", blockdev)):
            blacklisted = True
        is_cdrom = False
        bootdevice = None
        partitions = []
        try:
            if os.path.exists('/dev/root'):
                bootdevice = os.readlink('/dev/root')
            if os.path.exists(devpath + "/removable"):
                removable = bool(int(readFile(devpath + "/removable")))
            if os.path.exists(devpath + "/dev"):
                dev = readFile(devpath + "/dev")
                subdev = int(dev.split(':')[1])
                dev = int(dev.split(':')[0])
            else:
                dev = None
                subdev = None
            # blacklist ram, loop, mtdblock, romblock, ramzswap
            blacklisted = dev in [1, 7, 31, 253, 254]
            # blacklist non-root eMMC devices
            if not blacklisted and dev == 179:
                if subdev != 0:
                    blacklisted = True
                elif bootdevice.startswith(blockdev):
                    blacklisted = True
            if blockdev[0:2] == 'sr':
                is_cdrom = True
            if blockdev[0:2] == 'hd':
                try:
                    media = readFile("/proc/ide/%s/media" % blockdev)
                    if "cdrom" in media:
                        is_cdrom = True
                except IOError:
                    error = True
            # check for partitions
            if not is_cdrom and os.path.exists(devpath):
                for partition in os.listdir(devpath):
                    if partition[0:len(blockdev)] != blockdev:
                        continue
                    if dev == 179 and not re.search(r"mmcblk\dp\d+",
                                                    partition):
                        continue
                    partitions.append(partition)
            else:
                self.cd = blockdev
        except IOError:
            error = True
        # check for medium
        medium_found = True
        try:
            if os.path.exists("/dev/" + blockdev):
                open("/dev/" + blockdev).close()
        except IOError, err:
            if err.errno == 159:  # no medium present
                medium_found = False
Beispiel #33
0
from Components.Label import Label
from Components.ActionMap import ActionMap
from Components.About import about
from Components import Harddisk
from Screens.Console import Console
from Screens.MessageBox import MessageBox
from time import time, strftime, localtime
from os import path, system, makedirs, listdir, walk, statvfs, remove
import commands
import datetime
from boxbranding import getBoxType, getMachineBrand, getMachineName, getDriverDate, getImageVersion, getImageBuild, getBrandOEM, getMachineBuild, getImageFolder, getMachineUBINIZE, getMachineMKUBIFS, getMachineMtdKernel, getMachineMtdRoot, getMachineKernelFile, getMachineRootFile, getImageFileSystem

VERSION = "Version 6.2 openATV"

HaveGZkernel = True
if getMachineBuild() in ('ustym4kpro', 'hd60', 'i55plus', 'osmio4k', 'sf8008',
                         'cc1', 'dags72604', 'u51', 'u52', 'u53', 'h9',
                         'vuzero4k', 'u5', 'u5pvr', 'sf5008', 'et13000',
                         'et1x000', "vuuno4k", "vuuno4kse", "vuultimo4k",
                         "vusolo4k", "spark", "spark7162", "hd51", "hd52",
                         "sf4008", "dags7252", "gb7252", "vs1500", "h7",
                         'xc7439', '8100s'):
    HaveGZkernel = False


def Freespace(dev):
    statdev = statvfs(dev)
    space = (statdev.f_bavail * statdev.f_frsize) / 1024
    print "[FULL BACKUP] Free space on %s = %i kilobytes" % (dev, space)
    return space
Beispiel #34
0
    def doFullBackup(self, DIRECTORY):
        self.DIRECTORY = DIRECTORY
        self.TITLE = _("Fullbackup on %s") % (self.DIRECTORY)
        self.START = time()
        self.DATE = strftime("%Y%m%d_%H%M", localtime(self.START))
        self.IMAGEVERSION = self.imageInfo()
        if "ubi" in self.ROOTFSTYPE.split():
            self.MKFS = "/usr/sbin/mkfs.ubifs"
        elif "tar.bz2" in self.ROOTFSTYPE.split(
        ) or SystemInfo["HasMultiBootGB"]:
            self.MKFS = "/bin/tar"
            self.BZIP2 = "/usr/bin/bzip2"
        else:
            self.MKFS = "/usr/sbin/mkfs.jffs2"
        self.UBINIZE = "/usr/sbin/ubinize"
        self.NANDDUMP = "/usr/sbin/nanddump"
        self.WORKDIR = "%s/bi" % self.DIRECTORY
        self.TARGET = "XX"

        ## TESTING IF ALL THE TOOLS FOR THE BUILDING PROCESS ARE PRESENT
        if not path.exists(self.MKFS):
            text = "%s not found !!" % self.MKFS
            self.session.open(MessageBox, _(text), type=MessageBox.TYPE_ERROR)
            return
        if not path.exists(self.NANDDUMP):
            text = "%s not found !!" % self.NANDDUMP
            self.session.open(MessageBox, _(text), type=MessageBox.TYPE_ERROR)
            return

        self.SHOWNAME = "%s %s" % (self.MACHINEBRAND, self.MODEL)
        self.MAINDESTOLD = "%s/%s" % (self.DIRECTORY, self.MODEL)
        self.MAINDEST = "%s/%s" % (self.DIRECTORY, self.IMAGEFOLDER)
        self.EXTRA = "%s/fullbackup_%s/%s/%s" % (self.DIRECTORY, self.MODEL,
                                                 self.DATE, self.IMAGEFOLDER)
        self.EXTRAOLD = "%s/fullbackup_%s/%s/%s" % (self.DIRECTORY, self.MODEL,
                                                    self.DATE, self.MODEL)
        print "[ImageBackup] SHOWNAME: ", self.SHOWNAME
        print "[ImageBackup] MAINDESTOLD: ", self.MAINDESTOLD
        print "[ImageBackup] EXTRA: ", self.EXTRA
        print "[ImageBackup] EXTRAOLD: ", self.EXTRAOLD

        self.message = "echo -e '\n"
        self.message += (_("Fullback for %s\n" % self.SHOWNAME)).upper()
        self.message += VERSION + '\n'
        self.message += "____________________________________________________\n"
        self.message += _(
            "Please be patient, a fullbackup will now be created.\n")
        if self.ROOTFSTYPE == "ubi":
            self.message += _("Due to the used filesystem, the fullbackup\n")
            self.message += _(
                "will take about 3-12 minutes for this system.\n")
        elif SystemInfo["HasMultiBoot"] and self.list[
                self.selection] == "Recovery":
            self.message += _("because of the used filesystem the backup\n")
            self.message += _("will take about 30 minutes for this system.\n")
        elif "tar.bz2" in self.ROOTFSTYPE.split(
        ) or SystemInfo["HasMultiBootGB"]:
            self.message += _("because of the used filesystem the backup\n")
            self.message += _("will take about 1-4 minutes for this system.\n")
        else:
            self.message += _(
                "This will take about 2-9 minutes for this system.\n")
        self.message += "____________________________________________________\n"
        self.message += "'"

        ## PREPARING THE BUILDING ENVIRONMENT
        system("rm -rf %s" % self.WORKDIR)
        if not path.exists(self.WORKDIR):
            makedirs(self.WORKDIR)
        if not path.exists("/tmp/bi/root"):
            makedirs("/tmp/bi/root")
        system("sync")
        if SystemInfo["HasMultiBootGB"]:
            system("mount /dev/%s /tmp/bi/root" % self.MTDROOTFS)
        else:
            system("mount --bind / /tmp/bi/root")

        if "jffs2" in self.ROOTFSTYPE.split():
            cmd1 = "%s --root=/tmp/bi/root --faketime --output=%s/root.jffs2 %s" % (
                self.MKFS, self.WORKDIR, self.MKUBIFS_ARGS)
            cmd2 = None
            cmd3 = None
            print "[ImageBackup] jffs2 cmd1: ", cmd1
            print "[ImageBackup] jffs2 cmd2: ", cmd2
            print "[ImageBackup] jffs2 cmd3: ", cmd3
        elif "tar.bz2" in self.ROOTFSTYPE.split(
        ) or SystemInfo["HasMultiBootGB"]:
            cmd1 = "%s -cf %s/rootfs.tar -C /tmp/bi/root --exclude=/var/nmbd/* ." % (
                self.MKFS, self.WORKDIR)
            cmd2 = "%s %s/rootfs.tar" % (self.BZIP2, self.WORKDIR)
            cmd3 = None
            print "[ImageBackup] tar.bz2 cmd1: ", cmd1
            print "[ImageBackup] tar.bz2 cmd2: ", cmd2
            print "[ImageBackup] tar.bz2 cmd3: ", cmd3
        else:
            f = open("%s/ubinize.cfg" % self.WORKDIR, "w")
            f.write("[ubifs]\n")
            f.write("mode=ubi\n")
            f.write("image=%s/root.ubi\n" % self.WORKDIR)
            f.write("vol_id=0\n")
            f.write("vol_type=dynamic\n")
            f.write("vol_name=rootfs\n")
            f.write("vol_flags=autoresize\n")
            f.close()
            ff = open("%s/root.ubi" % self.WORKDIR, "w")
            ff.close()
            cmd1 = "%s -r /tmp/bi/root -o %s/root.ubi %s" % (
                self.MKFS, self.WORKDIR, self.MKUBIFS_ARGS)
            cmd2 = "%s -o %s/root.ubifs %s %s/ubinize.cfg" % (
                self.UBINIZE, self.WORKDIR, self.UBINIZE_ARGS, self.WORKDIR)
            cmd3 = "mv %s/root.ubifs %s/root.%s" % (self.WORKDIR, self.WORKDIR,
                                                    self.ROOTFSTYPE)
            print "[ImageBackup] ubifs cmd1: ", cmd1
            print "[ImageBackup] ubifs cmd2: ", cmd2
            print "[ImageBackup] ubifs cmd3: ", cmd3

        cmdlist = []
        cmdlist.append(self.message)
        cmdlist.append('echo "Create: rootfs dump %s\n"' % self.ROOTFSTYPE)
        cmdlist.append(cmd1)
        if cmd2:
            cmdlist.append(cmd2)
        if cmd3:
            cmdlist.append(cmd3)

        if self.ROOTFSBIN == "rootfs.tar.bz2":
            cmdlist.append("chmod 644 %s/rootfs.%s" %
                           (self.WORKDIR, self.ROOTFSTYPE))
        else:
            cmdlist.append("chmod 644 %s/root.%s" %
                           (self.WORKDIR, self.ROOTFSTYPE))

        if self.MODEL in ("gbquad4k", "gbue4k"):
            cmdlist.append('echo " "')
            cmdlist.append('echo "Create: boot dump boot.bin"')
            cmdlist.append('echo " "')
            cmdlist.append("dd if=/dev/mmcblk0p1 of=%s/boot.bin" %
                           self.WORKDIR)
            cmdlist.append('echo " "')
            cmdlist.append('echo "Create: rescue dump rescue.bin"')
            cmdlist.append('echo " "')
            cmdlist.append("dd if=/dev/mmcblk0p3 of=%s/rescue.bin" %
                           self.WORKDIR)

        cmdlist.append('echo " "')
        cmdlist.append('echo "Create: kernel dump"')
        cmdlist.append('echo " "')
        if SystemInfo["HasMultiBootGB"]:
            cmdlist.append("dd if=/dev/%s of=%s/kernel.bin" %
                           (self.MTDKERNEL, self.WORKDIR))
        elif self.MTDKERNEL == "mmcblk0p1" or self.MTDKERNEL == "mmcblk0p3":
            cmdlist.append("dd if=/dev/%s of=%s/%s" %
                           (self.MTDKERNEL, self.WORKDIR, self.KERNELBIN))
        else:
            cmdlist.append("nanddump -a -f %s/vmlinux.gz /dev/%s" %
                           (self.WORKDIR, self.MTDKERNEL))
        cmdlist.append('echo " "')

        if HaveGZkernel:
            cmdlist.append('echo "Check: kerneldump"')
        cmdlist.append("sync")

        if SystemInfo["HasMultiBoot"] and self.list[
                self.selection] == "Recovery":
            GPT_OFFSET = 0
            GPT_SIZE = 1024
            BOOT_PARTITION_OFFSET = int(GPT_OFFSET) + int(GPT_SIZE)
            BOOT_PARTITION_SIZE = 3072
            KERNEL_PARTITION_OFFSET = int(BOOT_PARTITION_OFFSET) + int(
                BOOT_PARTITION_SIZE)
            KERNEL_PARTITION_SIZE = 8192
            ROOTFS_PARTITION_OFFSET = int(KERNEL_PARTITION_OFFSET) + int(
                KERNEL_PARTITION_SIZE)
            ROOTFS_PARTITION_SIZE = 819200
            SECOND_KERNEL_PARTITION_OFFSET = int(
                ROOTFS_PARTITION_OFFSET) + int(ROOTFS_PARTITION_SIZE)
            SECOND_ROOTFS_PARTITION_OFFSET = int(
                SECOND_KERNEL_PARTITION_OFFSET) + int(KERNEL_PARTITION_SIZE)
            THRID_KERNEL_PARTITION_OFFSET = int(
                SECOND_ROOTFS_PARTITION_OFFSET) + int(ROOTFS_PARTITION_SIZE)
            THRID_ROOTFS_PARTITION_OFFSET = int(
                THRID_KERNEL_PARTITION_OFFSET) + int(KERNEL_PARTITION_SIZE)
            FOURTH_KERNEL_PARTITION_OFFSET = int(
                THRID_ROOTFS_PARTITION_OFFSET) + int(ROOTFS_PARTITION_SIZE)
            FOURTH_ROOTFS_PARTITION_OFFSET = int(
                FOURTH_KERNEL_PARTITION_OFFSET) + int(KERNEL_PARTITION_SIZE)
            SWAP_PARTITION_OFFSET = int(FOURTH_ROOTFS_PARTITION_OFFSET) + int(
                ROOTFS_PARTITION_SIZE)
            EMMC_IMAGE = "%s/disk.img" % self.WORKDIR
            EMMC_IMAGE_SIZE = 3817472
            IMAGE_ROOTFS_SIZE = 196608
            cmdlist.append('echo " "')
            cmdlist.append('echo "Create: Recovery Fullbackup disk.img"')
            cmdlist.append('echo " "')
            cmdlist.append('dd if=/dev/zero of=%s bs=1024 count=0 seek=%s' %
                           (EMMC_IMAGE, EMMC_IMAGE_SIZE))
            cmdlist.append('parted -s %s mklabel gpt' % EMMC_IMAGE)
            PARTED_END_BOOT = int(BOOT_PARTITION_OFFSET) + int(
                BOOT_PARTITION_SIZE)
            cmdlist.append(
                'parted -s %s unit KiB mkpart boot fat16 %s %s' %
                (EMMC_IMAGE, BOOT_PARTITION_OFFSET, PARTED_END_BOOT))
            PARTED_END_KERNEL1 = int(KERNEL_PARTITION_OFFSET) + int(
                KERNEL_PARTITION_SIZE)
            cmdlist.append(
                'parted -s %s unit KiB mkpart kernel1 %s %s' %
                (EMMC_IMAGE, KERNEL_PARTITION_OFFSET, PARTED_END_KERNEL1))
            PARTED_END_ROOTFS1 = int(ROOTFS_PARTITION_OFFSET) + int(
                ROOTFS_PARTITION_SIZE)
            cmdlist.append(
                'parted -s %s unit KiB mkpart rootfs1 ext2 %s %s' %
                (EMMC_IMAGE, ROOTFS_PARTITION_OFFSET, PARTED_END_ROOTFS1))
            PARTED_END_KERNEL2 = int(SECOND_KERNEL_PARTITION_OFFSET) + int(
                KERNEL_PARTITION_SIZE)
            cmdlist.append('parted -s %s unit KiB mkpart kernel2 %s %s' %
                           (EMMC_IMAGE, SECOND_KERNEL_PARTITION_OFFSET,
                            PARTED_END_KERNEL2))
            PARTED_END_ROOTFS2 = int(SECOND_ROOTFS_PARTITION_OFFSET) + int(
                ROOTFS_PARTITION_SIZE)
            cmdlist.append('parted -s %s unit KiB mkpart rootfs2 ext2 %s %s' %
                           (EMMC_IMAGE, SECOND_ROOTFS_PARTITION_OFFSET,
                            PARTED_END_ROOTFS2))
            PARTED_END_KERNEL3 = int(THRID_KERNEL_PARTITION_OFFSET) + int(
                KERNEL_PARTITION_SIZE)
            cmdlist.append('parted -s %s unit KiB mkpart kernel3 %s %s' %
                           (EMMC_IMAGE, THRID_KERNEL_PARTITION_OFFSET,
                            PARTED_END_KERNEL3))
            PARTED_END_ROOTFS3 = int(THRID_ROOTFS_PARTITION_OFFSET) + int(
                ROOTFS_PARTITION_SIZE)
            cmdlist.append('parted -s %s unit KiB mkpart rootfs3 ext2 %s %s' %
                           (EMMC_IMAGE, THRID_ROOTFS_PARTITION_OFFSET,
                            PARTED_END_ROOTFS3))
            PARTED_END_KERNEL4 = int(FOURTH_KERNEL_PARTITION_OFFSET) + int(
                KERNEL_PARTITION_SIZE)
            cmdlist.append('parted -s %s unit KiB mkpart kernel4 %s %s' %
                           (EMMC_IMAGE, FOURTH_KERNEL_PARTITION_OFFSET,
                            PARTED_END_KERNEL4))
            PARTED_END_ROOTFS4 = int(FOURTH_ROOTFS_PARTITION_OFFSET) + int(
                ROOTFS_PARTITION_SIZE)
            cmdlist.append('parted -s %s unit KiB mkpart rootfs4 ext2 %s %s' %
                           (EMMC_IMAGE, FOURTH_ROOTFS_PARTITION_OFFSET,
                            PARTED_END_ROOTFS4))
            PARTED_END_SWAP = int(EMMC_IMAGE_SIZE) - 1024
            cmdlist.append(
                'parted -s %s unit KiB mkpart swap linux-swap %s %s' %
                (EMMC_IMAGE, SWAP_PARTITION_OFFSET, PARTED_END_SWAP))
            cmdlist.append('dd if=/dev/zero of=%s/boot.img bs=1024 count=%s' %
                           (self.WORKDIR, BOOT_PARTITION_SIZE))
            cmdlist.append('mkfs.msdos -S 512 %s/boot.img' % self.WORKDIR)
            cmdlist.append(
                "echo \"boot emmcflash0.kernel1 \'brcm_cma=440M@328M brcm_cma=192M@768M root=/dev/mmcblk0p3 rw rootwait %s_4.boxmode=1\'\" > %s/STARTUP"
                % (getMachineBuild(), self.WORKDIR))
            cmdlist.append(
                "echo \"boot emmcflash0.kernel1 \'brcm_cma=440M@328M brcm_cma=192M@768M root=/dev/mmcblk0p3 rw rootwait %s_4.boxmode=1\'\" > %s/STARTUP_1"
                % (getMachineBuild(), self.WORKDIR))
            cmdlist.append(
                "echo \"boot emmcflash0.kernel2 \'brcm_cma=440M@328M brcm_cma=192M@768M root=/dev/mmcblk0p5 rw rootwait %s_4.boxmode=1\'\" > %s/STARTUP_2"
                % (getMachineBuild(), self.WORKDIR))
            cmdlist.append(
                "echo \"boot emmcflash0.kernel3 \'brcm_cma=440M@328M brcm_cma=192M@768M root=/dev/mmcblk0p7 rw rootwait %s_4.boxmode=1\'\" > %s/STARTUP_3"
                % (getMachineBuild(), self.WORKDIR))
            cmdlist.append(
                "echo \"boot emmcflash0.kernel4 \'brcm_cma=440M@328M brcm_cma=192M@768M root=/dev/mmcblk0p9 rw rootwait %s_4.boxmode=1\'\" > %s/STARTUP_4"
                % (getMachineBuild(), self.WORKDIR))
            cmdlist.append('mcopy -i %s/boot.img -v %s/STARTUP ::' %
                           (self.WORKDIR, self.WORKDIR))
            cmdlist.append('mcopy -i %s/boot.img -v %s/STARTUP_1 ::' %
                           (self.WORKDIR, self.WORKDIR))
            cmdlist.append('mcopy -i %s/boot.img -v %s/STARTUP_2 ::' %
                           (self.WORKDIR, self.WORKDIR))
            cmdlist.append('mcopy -i %s/boot.img -v %s/STARTUP_3 ::' %
                           (self.WORKDIR, self.WORKDIR))
            cmdlist.append('mcopy -i %s/boot.img -v %s/STARTUP_4 ::' %
                           (self.WORKDIR, self.WORKDIR))
            cmdlist.append(
                'dd conv=notrunc if=%s/boot.img of=%s bs=1024 seek=%s' %
                (self.WORKDIR, EMMC_IMAGE, BOOT_PARTITION_OFFSET))
            cmdlist.append(
                'dd conv=notrunc if=/dev/%s of=%s bs=1024 seek=%s' %
                (self.MTDKERNEL, EMMC_IMAGE, KERNEL_PARTITION_OFFSET))
            cmdlist.append(
                'dd if=/dev/%s of=%s bs=1024 seek=%s' %
                (self.MTDROOTFS, EMMC_IMAGE, ROOTFS_PARTITION_OFFSET))
        self.session.open(Console,
                          title=self.TITLE,
                          cmdlist=cmdlist,
                          finishedCallback=self.doFullBackupCB,
                          closeOnSuccess=True)
Beispiel #35
0
class AVSwitch:
	hw_type = HardwareInfo().get_device_name()
	has_rca = getHaveRCA() in ('True',)
	has_dvi = getHaveDVI() in ('True',)
	has_jack = getHaveAVJACK() in ('True',)
	has_scart = getHaveSCART() in ('True',)

	print "SystemInfo", "MachineBuild", getMachineBuild()
	print "SystemInfo", "BoxType", getBoxType()
	print "SystemInfo", "BrandOEM", getBrandOEM()
	print "SystemInfo", "DisplayType", getDisplayType()
	print "SystemInfo", "HaveRCA", getHaveRCA()
	print "SystemInfo", "getHaveDVI", getHaveDVI()
	print "SystemInfo", "HaveYUV", getHaveYUV()
	print "SystemInfo", "HaveSCART", getHaveSCART()
	print "SystemInfo", "HaveAVJACK", getHaveAVJACK()
	print "SystemInfo", "HaveSCARTYUV", getHaveSCARTYUV()
	print "SystemInfo", "HaveHDMI", getHaveHDMI()
	print "SystemInfo", "MachineMtdRoot", getMachineMtdRoot()
	print "VideoWizard", "has_dvi", has_dvi
	print "VideoWizard", "has_rca", has_rca
	print "VideoWizard", "has_jack", has_jack
	print "VideoWizard", "has_scart", has_scart
	print "AVSwitch", "Scart-YPbPr", SystemInfo["Scart-YPbPr"]
	print "AVSwitch", "no_YPbPr", SystemInfo["no_YPbPr"]
	print "AVSwitch", "yellow_RCA_no_scart", SystemInfo["yellow_RCA_no_scart"]
	print "AVSwitch", "no_yellow_RCA__no_scart", SystemInfo["no_yellow_RCA__no_scart"]

	rates = { } # high-level, use selectable modes.
	modes = { }  # a list of (high-level) modes for a certain port.

	rates["PAL"]  = { "50Hz":  { 50: "pal" },
					  "60Hz":  { 60: "pal60" },
					  "multi": { 50: "pal", 60: "pal60" } }

	rates["NTSC"]  = { "60Hz": { 60: "ntsc" } }

	rates["Multi"] = { "multi": { 50: "pal", 60: "ntsc" } }

	rates["480i"] = { "60Hz": { 60: "480i" } }

	rates["576i"] = { "50Hz": { 50: "576i" } }

	rates["480p"] = { "60Hz": { 60: "480p" } }

	rates["576p"] = { "50Hz": { 50: "576p" } }

	rates["720p"] = { "50Hz": { 50: "720p50" },
					  "60Hz": { 60: "720p" },
					  "multi": { 50: "720p50", 60: "720p" } }

	rates["1080i"] = { "50Hz":  { 50: "1080i50" },
					   "60Hz":  { 60: "1080i" },
					   "multi": { 50: "1080i50", 60: "1080i" } }

	rates["1080p"] = { "50Hz":  { 50: "1080p50" },
					   "60Hz":  { 60: "1080p" },
					   "multi": { 50: "1080p50", 60: "1080p" } }

	rates["2160p"] = { "50Hz":  { 50: "2160p50" },
					   "60Hz":  { 60: "2160p" },
					   "multi": { 50: "2160p50", 60: "2160p" } }

	rates["2160p30"] = { "multi": { 50: "2160p25", 60: "2160p30" } }

	rates["PC"] = {
		"1024x768": { 60: "1024x768" }, # not possible on DM7025
		"800x600" : { 60: "800x600" },  # also not possible
		"720x480" : { 60: "720x480" },
		"720x576" : { 60: "720x576" },
		"1280x720": { 60: "1280x720" },
		"1280x720 multi": { 50: "1280x720_50", 60: "1280x720" },
		"1920x1080": { 60: "1920x1080"},
		"1920x1080 multi": { 50: "1920x1080", 60: "1920x1080_50" },
		"1280x1024" : { 60: "1280x1024"},
		"1366x768" : { 60: "1366x768"},
		"1366x768 multi" : { 50: "1366x768", 60: "1366x768_50" },
		"1280x768": { 60: "1280x768" },
		"640x480" : { 60: "640x480" }
	}

	modes["Scart"] = ["PAL", "NTSC", "Multi"]
	# modes["DVI-PC"] = ["PC"]

	modes["HDMI"] = SystemInfo["VideoModes"][0] 
	widescreen_modes = SystemInfo["VideoModes"][1]

	modes["YPbPr"] = modes["HDMI"]
	if getBoxType() in ('dm500hd', 'dm800', 'vuuno', 'vusolo', 'vusolo2', 'vuultimo', 'vuduo', 'vuduo2'):
		
		if SystemInfo["Scart-YPbPr"]:
		modes["Scart-YPbPr"] = modes["HDMI"]

	# if "DVI-PC" in modes and not getModeList("DVI-PC"):
	# 	print "[VideoHardware] remove DVI-PC because of not existing modes"
	# 	del modes["DVI-PC"]

	if "YPbPr" in modes and SystemInfo["no_YPbPr"]:
		del modes["YPbPr"]

	if "Scart" in modes and SystemInfo["yellow_RCA_no_scart"]:
		modes["RCA"] = modes["Scart"]
		del modes["Scart"]

	if "Scart" in modes and SystemInfo["no_yellow_RCA__no_scart"]:
		del modes["Scart"]

	def __init__(self):
		self.last_modes_preferred =  [ ]
		self.on_hotplug = CList()
		self.current_mode = None
		self.current_port = None

		self.readAvailableModes()

		self.createConfig()
		self.readPreferredModes()

	def readAvailableModes(self):
		try:
			f = open("/proc/stb/video/videomode_choices")
			modes = f.read()[:-1]
			f.close()
		except IOError:
			print "[VideoHardware] couldn't read available videomodes."
			modes = [ ]
			return modes
		return modes.split(' ')

	def readPreferredModes(self):
		try:
			f = open("/proc/stb/video/videomode_preferred")
			modes = f.read()[:-1]
			f.close()
			self.modes_preferred = modes.split(' ')
		except IOError:
			print "[VideoHardware] reading preferred modes failed, using all modes"
			self.modes_preferred = self.readAvailableModes()

		if self.modes_preferred != self.last_modes_preferred:
			self.last_modes_preferred = self.modes_preferred
			self.on_hotplug("HDMI") # must be HDMI

	# check if a high-level mode with a given rate is available.
	def isModeAvailable(self, port, mode, rate):
		rate = self.rates[mode][rate]
		for mode in rate.values():
			if mode not in self.readAvailableModes():
				return False
		return True

	def isWidescreenMode(self, port, mode):
		return mode in self.widescreen_modes

	def setMode(self, port, mode, rate, force = None):
		print "[VideoHardware] setMode - port: %s, mode: %s, rate: %s" % (port, mode, rate)

		# config.av.videoport.setValue(port)
		# we can ignore "port"
		self.current_mode = mode
		self.current_port = port
		modes = self.rates[mode][rate]

		mode_50 = modes.get(50)
		mode_60 = modes.get(60)
		if mode_50 is None or force == 60:
			mode_50 = mode_60
		if mode_60 is None or force == 50:
			mode_60 = mode_50

		if os.path.exists('/proc/stb/video/videomode_50hz') and getBoxType() not in (''):
			f = open("/proc/stb/video/videomode_50hz", "w")
			f.write(mode_50)
			f.close()
		if os.path.exists('/proc/stb/video/videomode_60hz') and getBoxType() not in (''):
			f = open("/proc/stb/video/videomode_60hz", "w")
			f.write(mode_60)
			f.close()
		try:
			set_mode = modes.get(int(rate[:2]))
		except: # not support 50Hz, 60Hz for 1080p
			set_mode = mode_50
		f = open("/proc/stb/video/videomode", "w")
		f.write(set_mode)
		f.close()
		map = {"cvbs": 0, "rgb": 1, "svideo": 2, "yuv": 3}
		self.setColorFormat(map[config.av.colorformat.value])

	def saveMode(self, port, mode, rate):
		config.av.videoport.setValue(port)
		config.av.videoport.save()
		if port in config.av.videomode:
			config.av.videomode[port].setValue(mode)
			config.av.videomode[port].save()
		if mode in config.av.videorate:
			config.av.videorate[mode].setValue(rate)
			config.av.videorate[mode].save()

	def isPortAvailable(self, port):
		# fixme
		return True

	def isPortUsed(self, port):
		if port == "HDMI":
			self.readPreferredModes()
			return len(self.modes_preferred) != 0
		else:
			return True

	def getPortList(self):
		return [port for port in self.modes if self.isPortAvailable(port)]

	# get a list with all modes, with all rates, for a given port.
	def getModeList(self, port):
		res = [ ]
		for mode in self.modes[port]:
			# list all rates which are completely valid
			rates = [rate for rate in self.rates[mode] if self.isModeAvailable(port, mode, rate)]

			# if at least one rate is ok, add this mode
			if len(rates):
				res.append( (mode, rates) )
		return res

	def createConfig(self, *args):
		hw_type = HardwareInfo().get_device_name()
		has_hdmi = HardwareInfo().has_hdmi()
		lst = []

		config.av.videomode = ConfigSubDict()
		config.av.videorate = ConfigSubDict()

		# create list of output ports
		portlist = self.getPortList()
		for port in portlist:
			descr = port
			if 'HDMI' in port:
				lst.insert(0, (port, descr))
			else:
				lst.append((port, descr))

			modes = self.getModeList(port)
			if len(modes):
				config.av.videomode[port] = ConfigSelection(choices = [mode for (mode, rates) in modes])
			for (mode, rates) in modes:
				config.av.videorate[mode] = ConfigSelection(choices = rates)
		config.av.videoport = ConfigSelection(choices = lst)

	def setInput(self, input):
		INPUT = { "ENCODER": 0, "SCART": 1, "AUX": 2 }
		eAVSwitch.getInstance().setInput(INPUT[input])

	def setColorFormat(self, value):
		if not self.current_port:
			self.current_port = config.av.videoport.value
		if self.current_port in ("YPbPr", "Scart-YPbPr"):
			eAVSwitch.getInstance().setColorFormat(3)
		elif self.current_port in ("RCA"):
			eAVSwitch.getInstance().setColorFormat(0)
		else:
			eAVSwitch.getInstance().setColorFormat(value)

	def setConfiguredMode(self):
		port = config.av.videoport.value
		if port not in config.av.videomode:
			print "[VideoHardware] current port not available, not setting videomode"
			return

		mode = config.av.videomode[port].value

		if mode not in config.av.videorate:
			print "[VideoHardware] current mode not available, not setting videomode"
			return

		rate = config.av.videorate[mode].value
		self.setMode(port, mode, rate)

	def setAspect(self, cfgelement):
		print "[VideoHardware] setting aspect: %s" % cfgelement.value
		f = open("/proc/stb/video/aspect", "w")
		f.write(cfgelement.value)
		f.close()

	def setWss(self, cfgelement):
		if not cfgelement.value:
			wss = "auto(4:3_off)"
		else:
			wss = "auto"
		print "[VideoHardware] setting wss: %s" % wss
		f = open("/proc/stb/denc/0/wss", "w")
		f.write(wss)
		f.close()

	def setPolicy43(self, cfgelement):
		print "[VideoHardware] setting policy: %s" % cfgelement.value
		f = open("/proc/stb/video/policy", "w")
		f.write(cfgelement.value)
		f.close()

	def setPolicy169(self, cfgelement):
		if os.path.exists("/proc/stb/video/policy2"):
			print "[VideoHardware] setting policy2: %s" % cfgelement.value
			f = open("/proc/stb/video/policy2", "w")
			f.write(cfgelement.value)
			f.close()

	def getOutputAspect(self):
		ret = (16,9)
		port = config.av.videoport.value
		if port not in config.av.videomode:
			print "[VideoHardware] current port not available in getOutputAspect!!! force 16:9"
		else:
			mode = config.av.videomode[port].value
			force_widescreen = self.isWidescreenMode(port, mode)
			is_widescreen = force_widescreen or config.av.aspect.value in ("16:9", "16:10")
			is_auto = config.av.aspect.value == "auto"
			if is_widescreen:
				if force_widescreen:
					pass
				else:
					aspect = {"16:9": "16:9", "16:10": "16:10"}[config.av.aspect.value]
					if aspect == "16:10":
						ret = (16,10)
			elif is_auto:
				try:
					aspect_str = open("/proc/stb/vmpeg/0/aspect", "r").read()
					if aspect_str == "1": # 4:3
						ret = (4,3)
				except IOError:
					pass
			else:  # 4:3
				ret = (4,3)
		return ret

	def getFramebufferScale(self):
		aspect = self.getOutputAspect()
		fb_size = getDesktop(0).size()
		return aspect[0] * fb_size.height(), aspect[1] * fb_size.width()

	def getAspectRatioSetting(self):
		valstr = config.av.aspectratio.value
		if valstr == "4_3_letterbox":
			val = 0
		elif valstr == "4_3_panscan":
			val = 1
		elif valstr == "16_9":
			val = 2
		elif valstr == "16_9_always":
			val = 3
		elif valstr == "16_10_letterbox":
			val = 4
		elif valstr == "16_10_panscan":
			val = 5
		elif valstr == "16_9_letterbox":
			val = 6
		return val

iAVSwitch = AVSwitch()

def InitAVSwitch():
	config.av.yuvenabled = ConfigBoolean(default=True)
	colorformat_choices = {"cvbs": _("CVBS"), "rgb": _("RGB"), "svideo": _("S-Video")}
	# when YUV is not enabled, don't let the user select it
	if config.av.yuvenabled.value:
		colorformat_choices["yuv"] = _("YPbPr")

	config.av.autores = ConfigSelection(choices={"disabled": _("Disabled"), "all": _("All resolutions"), "hd": _("only HD")}, default="disabled")
	choicelist = []
	for i in range(5, 16):
		choicelist.append(("%d" % i, ngettext("%d second", "%d seconds", i) % i))
	config.av.autores_label_timeout = ConfigSelection(default = "5", choices = [("0", _("Not Shown"))] + choicelist)
	config.av.autores_delay = ConfigSelectionNumber(min = 0, max = 15000, stepwidth = 500, default = 500, wraparound = True)
	config.av.autores_deinterlace = ConfigYesNo(default=False)
	config.av.autores_sd = ConfigSelection(choices={"720p": _("720p"), "1080i": _("1080i")}, default="720p")
	config.av.autores_480p24 = ConfigSelection(choices={"480p24": _("480p 24Hz"), "720p24": _("720p 24Hz"), "1080p24": _("1080p 24Hz")}, default="1080p24")
	config.av.autores_720p24 = ConfigSelection(choices={"720p24": _("720p 24Hz"), "1080p24": _("1080p 24Hz")}, default="1080p24")
	config.av.autores_1080p24 = ConfigSelection(choices={"1080p24": _("1080p 24Hz"), "1080p25": _("1080p 25Hz")}, default="1080p24")
	config.av.autores_1080p25 = ConfigSelection(choices={"1080p25": _("1080p 25Hz"), "1080p50": _("1080p 50Hz")}, default="1080p25")
	config.av.autores_1080p30 = ConfigSelection(choices={"1080p30": _("1080p 30Hz"), "1080p60": _("1080p 60Hz")}, default="1080p30")
	config.av.autores_2160p24 = ConfigSelection(choices={"2160p24": _("2160p 24Hz"), "2160p25": _("2160p 25Hz"), "2160p30": _("2160p 30Hz")}, default="2160p24")
	config.av.autores_2160p25 = ConfigSelection(choices={"2160p25": _("2160p 25Hz"), "2160p50": _("2160p 50Hz")}, default="2160p25")
	config.av.autores_2160p30 = ConfigSelection(choices={"2160p30": _("2160p 30Hz"), "2160p60": _("2160p 60Hz")}, default="2160p30")
	config.av.colorformat = ConfigSelection(choices=colorformat_choices, default="rgb")
	config.av.aspectratio = ConfigSelection(choices={
			"4_3_letterbox": _("4:3 Letterbox"),
			"4_3_panscan": _("4:3 PanScan"),
			"16_9": _("16:9"),
			"16_9_always": _("16:9 always"),
			"16_10_letterbox": _("16:10 Letterbox"),
			"16_10_panscan": _("16:10 PanScan"),
			"16_9_letterbox": _("16:9 Letterbox")},
			default = "16_9")
	config.av.aspect = ConfigSelection(choices={
			"4:3": _("4:3"),
			"16:9": _("16:9"),
			"16:10": _("16:10"),
			"auto": _("Automatic")},
			default = "16:9")
	policy2_choices = {
	# TRANSLATORS: (aspect ratio policy: black bars on top/bottom) in doubt, keep english term.
	"letterbox": _("Letterbox"),
	# TRANSLATORS: (aspect ratio policy: cropped content on left/right) in doubt, keep english term
	"panscan": _("Pan&scan"),
	# TRANSLATORS: (aspect ratio policy: display as fullscreen, even if this breaks the aspect)
	"scale": _("Just scale")}
	if os.path.exists("/proc/stb/video/policy2_choices"):
		f = open("/proc/stb/video/policy2_choices")
		if "auto" in f.readline():
			# TRANSLATORS: (aspect ratio policy: always try to display as fullscreen, when there is no content (black bars) on left/right, even if this breaks the aspect.
			policy2_choices.update({"auto": _("Auto")})
		f.close()
	config.av.policy_169 = ConfigSelection(choices=policy2_choices, default = "letterbox")
	policy_choices = {
	# TRANSLATORS: (aspect ratio policy: black bars on left/right) in doubt, keep english term.
	"panscan": _("Pillarbox"),
	# TRANSLATORS: (aspect ratio policy: cropped content on left/right) in doubt, keep english term
	"letterbox": _("Pan&scan"),
	# TRANSLATORS: (aspect ratio policy: display as fullscreen, with stretching the left/right)
	# "nonlinear": _("Nonlinear"),
	# TRANSLATORS: (aspect ratio policy: display as fullscreen, even if this breaks the aspect)
	"bestfit": _("Just scale")}
	if os.path.exists("/proc/stb/video/policy_choices"):
		f = open("/proc/stb/video/policy_choices")
		if "auto" in f.readline():
			# TRANSLATORS: (aspect ratio policy: always try to display as fullscreen, when there is no content (black bars) on left/right, even if this breaks the aspect.
			policy_choices.update({"auto": _("Auto")})
		f.close()
	config.av.policy_43 = ConfigSelection(choices=policy_choices, default = "panscan")
	config.av.tvsystem = ConfigSelection(choices = {"pal": _("PAL"), "ntsc": _("NTSC"), "multinorm": _("multinorm")}, default="pal")
	config.av.wss = ConfigEnableDisable(default = True)
	config.av.generalAC3delay = ConfigSelectionNumber(-1000, 1000, 5, default = 0)
	config.av.generalPCMdelay = ConfigSelectionNumber(-1000, 1000, 5, default = 0)
	config.av.vcrswitch = ConfigEnableDisable(default = False)

	config.av.aspect.setValue('16:9')
	config.av.aspect.addNotifier(iAVSwitch.setAspect)
	config.av.wss.addNotifier(iAVSwitch.setWss)
	config.av.policy_43.addNotifier(iAVSwitch.setPolicy43)
	config.av.policy_169.addNotifier(iAVSwitch.setPolicy169)

	def setColorFormat(configElement):
		if config.av.videoport and config.av.videoport.value in ("YPbPr", "Scart-YPbPr"):
			iAVSwitch.setColorFormat(3)
		elif config.av.videoport and config.av.videoport.value in ("RCA"):
			iAVSwitch.setColorFormat(0)
		else:
			map = {"cvbs": 0, "rgb": 1, "svideo": 2, "yuv": 3}
			iAVSwitch.setColorFormat(map[configElement.value])
	config.av.colorformat.addNotifier(setColorFormat)

	def setAspectRatio(configElement):
		map = {"4_3_letterbox": 0, "4_3_panscan": 1, "16_9": 2, "16_9_always": 3, "16_10_letterbox": 4, "16_10_panscan": 5, "16_9_letterbox" : 6}
		iAVSwitch.setAspectRatio(map[configElement.value])

	iAVSwitch.setInput("ENCODER") # init on startup
	SystemInfo["ScartSwitch"] = eAVSwitch.getInstance().haveScartSwitch()

	if SystemInfo["Canedidchecking"]:
		def setEDIDBypass(configElement):
			try:
				f = open("/proc/stb/hdmi/bypass_edid_checking", "w")
				f.write(configElement.value)
				f.close()
			except:
				pass
		config.av.bypass_edid_checking = ConfigSelection(choices={
				"00000000": _("off"),
				"00000001": _("on")},
				default = "00000000")
		config.av.bypass_edid_checking.addNotifier(setEDIDBypass)
	else:
		config.av.bypass_edid_checking = ConfigNothing()

	if SystemInfo["havecolorspace"]:
		def setHDMIColorspace(configElement):
			try:
				f = open("/proc/stb/video/hdmi_colorspace", "w")
				f.write(configElement.value)
				f.close()
			except:
				pass
		if getBoxType() in ('vuzero4k','vusolo4k','vuuno4k','vuuno4kse','vuultimo4k'):
			config.av.hdmicolorspace = ConfigSelection(choices={
					"Edid(Auto)": _("Auto"),
					"Hdmi_Rgb": _("RGB"),
					"444": _("YCbCr444"),
					"422": _("YCbCr422"),
					"420": _("YCbCr420")},
					default = "Edid(Auto)")
		else:
			config.av.hdmicolorspace = ConfigSelection(choices={
					"auto": _("auto"),
					"rgb": _("rgb"),
					"420": _("420"),
					"422": _("422"),
					"444": _("444")},
					default = "auto")
		config.av.hdmicolorspace.addNotifier(setHDMIColorspace)
	else:
		config.av.hdmicolorspace = ConfigNothing()

	if SystemInfo["havecolorimetry"]:
		def setHDMIColorimetry(configElement):
			try:
				f = open("/proc/stb/video/hdmi_colorimetry", "w")
				f.write(configElement.value)
				f.close()
			except:
				pass
		config.av.hdmicolorimetry = ConfigSelection(choices={
				"Auto": _("Auto"),
				"bt2020ncl": _("BT 2020 NCL"),
				"bt2020cl": _("BT 2020 CL"),
				"bt709": _("BT 709")},
				default = "Auto")
		config.av.hdmicolorimetry.addNotifier(setHDMIColorimetry)
	else:
		config.av.hdmicolorimetry = ConfigNothing()

	if SystemInfo["haveboxmode"]:
		def setBoxmode(configElement):
			try:
				f = open("/proc/stb/info/boxmode", "w")
				f.write(configElement.value)
				f.close()
			except:
				pass
		config.av.boxmode = ConfigSelection(choices={
				"12": _("PIP enabled, no HDR"),
				"1": _("HDR, 12bit 4:2:0/4:2:2, no PIP")},
				default = "12")
		config.av.boxmode.addNotifier(setBoxmode)
	else:
		config.av.boxmode = ConfigNothing()

	if SystemInfo["havehdmicolordepth"]:
		def setHdmiColordepth(configElement):
			try:
				f = open("/proc/stb/video/hdmi_colordepth", "w")
				f.write(configElement.value)
				f.close()
			except:
				pass
		config.av.hdmicolordepth = ConfigSelection(choices={
				"auto": _("Auto"),
				"8bit": _("8bit"),
				"10bit": _("10bit"),
				"12bit": _("12bit")},
				default = "auto")
		config.av.hdmicolordepth.addNotifier(setHdmiColordepth)
	else:
		config.av.hdmicolordepth = ConfigNothing()

	if SystemInfo["Canaudiosource"]:
		def setAudioSource(configElement):
			try:
				f = open("/proc/stb/hdmi/audio_source", "w")
				f.write(configElement.value)
				f.close()
			except:
				pass
		config.av.audio_source = ConfigSelection(choices={
				"pcm": _("PCM"),
				"spdif": _("SPDIF")},
				default="pcm")
		config.av.audio_source.addNotifier(setAudioSource)
	else:
		config.av.audio_source = ConfigNothing()

	if SystemInfo["Can3DSurround"]:
		def set3DSurround(configElement):
			f = open("/proc/stb/audio/3d_surround", "w")
			f.write(configElement.value)
			f.close()
		choice_list = [("none", _("off")), ("hdmi", _("HDMI")), ("spdif", _("SPDIF")), ("dac", _("DAC"))]
		config.av.surround_3d = ConfigSelection(choices = choice_list, default = "none")
		config.av.surround_3d.addNotifier(set3DSurround)
	else:
		config.av.surround_3d = ConfigNothing()

	if SystemInfo["Can3DSpeaker"]:
		def set3DSurroundSpeaker(configElement):
			f = open("/proc/stb/audio/3d_surround_speaker_position", "w")
			f.write(configElement.value)
			f.close()
		choice_list = [("center", _("center")), ("wide", _("wide")), ("extrawide", _("extra wide"))]
		config.av.surround_3d_speaker = ConfigSelection(choices = choice_list, default = "center")
		config.av.surround_3d_speaker.addNotifier(set3DSurroundSpeaker)
	else:
		config.av.surround_3d_speaker = ConfigNothing()

	if SystemInfo["CanAutoVolume"]:
		def setAutoVolume(configElement):
			f = open("/proc/stb/audio/avl", "w")
			f.write(configElement.value)
			f.close()
		choice_list = [("none", _("off")), ("hdmi", _("HDMI")), ("spdif", _("SPDIF")), ("dac", _("DAC"))]
		config.av.autovolume = ConfigSelection(choices = choice_list, default = "none")
		config.av.autovolume.addNotifier(setAutoVolume)
	else:
		config.av.autovolume = ConfigNothing()

	if SystemInfo["supportPcmMultichannel"]:
		def setPCMMultichannel(configElement):
			open("/proc/stb/audio/multichannel_pcm", "w").write(configElement.value and "enable" or "disable")
		config.av.pcm_multichannel = ConfigYesNo(default = False)
		config.av.pcm_multichannel.addNotifier(setPCMMultichannel)

	if SystemInfo["CanDownmixAC3"]:
		def setAC3Downmix(configElement):
			open("/proc/stb/audio/ac3", "w").write(configElement.value and "downmix" or "passthrough")
			if SystemInfo.get("supportPcmMultichannel", False) and not configElement.value:
				SystemInfo["CanPcmMultichannel"] = True
			else:
				SystemInfo["CanPcmMultichannel"] = False
				if SystemInfo["supportPcmMultichannel"]:
					config.av.pcm_multichannel.setValue(False)
		config.av.downmix_ac3 = ConfigYesNo(default = True)
		config.av.downmix_ac3.addNotifier(setAC3Downmix)

	if SystemInfo["CanDownmixDTS"]:
		def setDTSDownmix(configElement):
			open("/proc/stb/audio/dts", "w").write(configElement.value and "downmix" or "passthrough")
		config.av.downmix_dts = ConfigYesNo(default = True)
		config.av.downmix_dts.addNotifier(setDTSDownmix)

	if SystemInfo["CanDownmixAAC"]:
		def setAACDownmix(configElement):
			open("/proc/stb/audio/aac", "w").write(configElement.value and "downmix" or "passthrough")
		config.av.downmix_aac = ConfigYesNo(default = True)
		config.av.downmix_aac.addNotifier(setAACDownmix)


	if SystemInfo["CanAACTranscode"]:
		def setAACTranscode(configElement):
			open("/proc/stb/audio/aac_transcode", "w").write(configElement.value)
		config.av.transcodeaac = ConfigSelection(default = "off", choices = [("off", _("off")), ("ac3", _("AC3")), ("dts", _("DTS"))])
		config.av.transcodeaac.addNotifier(setAACTranscode)
	else:
		config.av.transcodeaac = ConfigNothing()

	if SystemInfo["HasScaler_sharpness"]:
		def setScaler_sharpness(config):
			myval = int(config.value)
			try:
				print "[VideoHardware] setting scaler_sharpness to: %0.8X" % myval
				f = open("/proc/stb/vmpeg/0/pep_scaler_sharpness", "w")
				f.write("%0.8X" % myval)
				f.close()
				f = open("/proc/stb/vmpeg/0/pep_apply", "w")
				f.write("1")
				f.close()
			except IOError:
				print "[VideoHardware] couldn't write pep_scaler_sharpness"

		if getBoxType() in ('gbquad', 'gbquadplus'):
			config.av.scaler_sharpness = ConfigSlider(default=5, limits=(0,26))
		else:
			config.av.scaler_sharpness = ConfigSlider(default=13, limits=(0,26))
		config.av.scaler_sharpness.addNotifier(setScaler_sharpness)
	else:
		config.av.scaler_sharpness = NoSave(ConfigNothing())

	config.av.edid_override = ConfigYesNo(default = False)

	iAVSwitch.setConfiguredMode()

class VideomodeHotplug:
	def __init__(self):
		pass

	def start(self):
		iAVSwitch.on_hotplug.append(self.hotplug)

	def stop(self):
		iAVSwitch.on_hotplug.remove(self.hotplug)

	def hotplug(self, what):
		print "[VideoHardware] hotplug detected on port '%s'" % what
		port = config.av.videoport.value
		mode = config.av.videomode[port].value
		rate = config.av.videorate[mode].value

		if not iAVSwitch.isModeAvailable(port, mode, rate):
			print "[VideoHardware] mode %s/%s/%s went away!" % (port, mode, rate)
			modelist = iAVSwitch.getModeList(port)
			if not len(modelist):
				print "[VideoHardware] sorry, no other mode is available (unplug?). Doing nothing."
				return
			mode = modelist[0][0]
			rate = modelist[0][1]
			print "[VideoHardware] setting %s/%s/%s" % (port, mode, rate)
			iAVSwitch.setMode(port, mode, rate)

hotplug = None

def startHotplug():
	global hotplug
	hotplug = VideomodeHotplug()
	hotplug.start()

def stopHotplug():
	global hotplug
	hotplug.stop()

def InitiVideomodeHotplug(**kwargs):
	startHotplug()
Beispiel #36
0
from boxbranding import getBoxType, getMachineBrand, getMachineBuild, getBrandOEM
from Tools.StbHardware import getFPVersion
import os

boxtype = getBoxType()
machinebuild = getMachineBuild()
machinebrand = getMachineBrand()
brandoem = getBrandOEM()


class RcModelOE:
    def __init__(self):
        pass

    def rcIsDefault(self):
        if self.getRcFolder() != 'dmm0':
            return False
        return True

    def readFile(self, target):
        fp = open(target, 'r')
        out = fp.read()
        fp.close()
        return out.split()[0]

    def process(self, line):
        if line.lower().startswith('config.usage.rc_model='):
            parts = line.split('=')
            folder = parts[-1].rstrip()
            if os.path.isfile('/usr/share/enigma2/rc_models/' + folder +
                              '/rc.png') and os.path.isfile(
Beispiel #37
0
def runScreenTest():
	config.misc.startCounter.value += 1
	config.misc.startCounter.save()

	profile("readPluginList")
	plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))

	profile("Init:Session")
	nav = Navigation(config.misc.isNextRecordTimerAfterEventActionAuto.value, config.misc.isNextPowerTimerAfterEventActionAuto.value)
	session = Session(desktop=enigma.getDesktop(0), summary_desktop=enigma.getDesktop(1), navigation=nav)

	CiHandler.setSession(session)

	screensToRun = [p.__call__ for p in plugins.getPlugins(PluginDescriptor.WHERE_WIZARD)]

	profile("wizards")
	screensToRun += wizardManager.getWizards()
	screensToRun.append((100, InfoBar.InfoBar))
	screensToRun.sort()

	enigma.ePythonConfigQuery.setQueryFunc(configfile.getResolvedKey)

	def runNextScreen(session, screensToRun, *result):
		if result:
			enigma.quitMainloop(*result)
			return

		screen = screensToRun[0][1]
		args = screensToRun[0][2:]
		if screensToRun:
			session.openWithCallback(boundFunction(runNextScreen, session, screensToRun[1:]), screen, *args)
		else:  # FIXME: This is patently wrong. Getting screen/args would have caused an exception, if screensToRun was false
			session.open(screen, *args)  # FIXME: Both lines can probably be deleted.

	runNextScreen(session, screensToRun)

	profile("Init:VolumeControl")
	vol = VolumeControl(session)
	profile("Init:PowerKey")
	global Screens
	Screens.Standby.powerKey = power = PowerKey(session)
	profile("Init:VideoResolutionKey")
	resolution = VideoResolutionKey(session)

	if getBoxType() in ('mixosf5', 'mixosf7', 'mixoslumi', 'gi9196m', 'maram9', 'ixussone', 'ixussone') or getMachineBuild() in ('inihde', 'inihdx'):
		profile("VFDSYMBOLS")
		import Components.VfdSymbols
		Components.VfdSymbols.SymbolsCheck(session)

	# we need session.scart to access it from within menu.xml
	session.scart = AutoScartControl(session)

	profile("Init:Trashcan")
	import Tools.Trashcan
	Tools.Trashcan.init(session)

	profile("Init:AutoVideoMode")
	import Screens.VideoMode
	Screens.VideoMode.autostart(session)

	profile("RunReactor")
	profile_final()
	runReactor()

	profile("wakeup")

	# get currentTime
	nowTime = time()
	if not config.misc.SyncTimeUsing.getValue() == "0" or getBoxType().startswith('gb') or getMachineProcModel().startswith('ini'):
		print "dvb time sync disabled... so set RTC now to current linux time!", strftime("%a %d %b %Y %H:%M", localtime(nowTime))
		setRTCtime(nowTime)

	wakeupList = [
		x for x in (
			(session.nav.RecordTimer.getNextRecordingTime(), 0, session.nav.RecordTimer.isNextRecordAfterEventActionAuto()),
			(session.nav.RecordTimer.getNextZapTime(), 1),
			(plugins.getNextWakeupTime(), 2),
			(session.nav.PowerTimer.getNextPowerManagerTime(), 3, session.nav.PowerTimer.isNextPowerManagerAfterEventActionAuto())
		)
		if x[0] != -1
	]
	wakeupList.sort()
	recordTimerWakeupAuto = False
	if wakeupList and wakeupList[0][1] != 3:
		startTime = wakeupList[0]
		if (startTime[0] - nowTime) < 270:  # no time to switch box back on
			wptime = nowTime + 30  # so switch back on in 30 seconds
		else:
			if getBoxType().startswith("gb"):
				wptime = startTime[0] - 120  # Gigaboxes already start 2 min. before wakeup time
			else:
				wptime = startTime[0] - 240

		# if not config.misc.SyncTimeUsing.value == "0" or getBrandOEM() == 'gigablue':
		# 	print "dvb time sync disabled... so set RTC now to current linux time!", strftime("%a %d %b %Y %H:%M", localtime(nowTime))
		# 	setRTCtime(nowTime)
		print "set wakeup time to", strftime("%a %d %b %Y %H:%M", localtime(wptime))
		setFPWakeuptime(wptime)
		recordTimerWakeupAuto = startTime[1] == 0 and startTime[2]
		print 'recordTimerWakeupAuto', recordTimerWakeupAuto
	config.misc.isNextRecordTimerAfterEventActionAuto.value = recordTimerWakeupAuto
	config.misc.isNextRecordTimerAfterEventActionAuto.save()

	PowerTimerWakeupAuto = False
	if wakeupList and wakeupList[0][1] == 3:
		startTime = wakeupList[0]
		if (startTime[0] - nowTime) < 60:  # no time to switch box back on
			wptime = nowTime + 30  # so switch back on in 30 seconds
		else:
			if getBoxType().startswith("gb"):
				wptime = startTime[0] + 120  # Gigaboxes already start 2 min. before wakeup time
			else:
				wptime = startTime[0]

		# if not config.misc.SyncTimeUsing.value == "0" or getBrandOEM() == 'gigablue':
		# 	print "dvb time sync disabled... so set RTC now to current linux time!", strftime("%a %d %b %Y %H:%M", localtime(nowTime))
		# 	setRTCtime(nowTime)
		print "set wakeup time to", strftime("%a %d %b %Y %H:%M", localtime(wptime + 60))
		setFPWakeuptime(wptime)
		PowerTimerWakeupAuto = startTime[1] == 3 and startTime[2]
		print 'PowerTimerWakeupAuto', PowerTimerWakeupAuto
	config.misc.isNextPowerTimerAfterEventActionAuto.value = PowerTimerWakeupAuto
	config.misc.isNextPowerTimerAfterEventActionAuto.save()

	profile("stopService")
	session.nav.stopService()
	profile("nav shutdown")
	session.nav.shutdown()

	profile("configfile.save")
	configfile.save()
	from Screens import InfoBarGenerics
	InfoBarGenerics.saveResumePoints()

	return 0
Beispiel #38
0
from __future__ import print_function
import boxbranding
print("getMachineBuild=%s<" % boxbranding.getMachineBuild())
print("getMachineMake=%s<" % boxbranding.getMachineMake())
print("getMachineProcModel=%s<" % boxbranding.getMachineProcModel())
print("getMachineBrand=%s<" % boxbranding.getMachineBrand())
print("getMachineName=%s<" % boxbranding.getMachineName())
print("getMachineMtdKernel=%s<" % boxbranding.getMachineMtdKernel())
print("getMachineKernelFile=%s<" % boxbranding.getMachineKernelFile())
print("getMachineMtdRoot=%s<" % boxbranding.getMachineMtdRoot())
print("getMachineRootFile=%s<" % boxbranding.getMachineRootFile())
print("getMachineMKUBIFS=%s<" % boxbranding.getMachineMKUBIFS())
print("getMachineUBINIZE=%s<" % boxbranding.getMachineUBINIZE())
print("getBoxType=%s<" % boxbranding.getBoxType())
print("getBrandOEM=%s<" % boxbranding.getBrandOEM())
print("getOEVersion=%s<" % boxbranding.getOEVersion())
print("getDriverDate=%s<" % boxbranding.getDriverDate())
print("getImageVersion=%s<" % boxbranding.getImageVersion())
print("getImageBuild=%s<" % boxbranding.getImageBuild())
print("getImageDevBuild=%s<" % boxbranding.getImageDevBuild())
print("getImageType=%s<" % boxbranding.getImageType())
print("getImageDistro=%s<" % boxbranding.getImageDistro())
print("getImageFolder=%s<" % boxbranding.getImageFolder())
print("getImageFileSystem=%s<" % boxbranding.getImageFileSystem())
print("getImageDevBuild=%s<" % boxbranding.getImageDevBuild())
print("getImageType=%s<" % boxbranding.getImageType())
print("getMachineMake=%s<" % boxbranding.getMachineMake())
print("getImageArch=%s<" % boxbranding.getImageArch())
print("getFeedsUrl=%s<" % boxbranding.getFeedsUrl())
print("getDisplayType=%s<" % boxbranding.getDisplayType())
print("getHaveHDMI=%s<" % boxbranding.getHaveHDMI())
Beispiel #39
0
	def __init__(self, session):
		Screen.__init__(self, session)
		self.setTitle(_("About"))
		hddsplit = skin.parameters.get("AboutHddSplit", 0)

		model = getBoxType()

		procmodel = getBoxProc()

		stbplatform = boxbranding.getMachineBuild()

		AboutText = _("Hardware: ") + model + "\n"
		if stbplatform != model:
			AboutText += _("Platform: ") + stbplatform + "\n"
		if procmodel != model:
			AboutText += _("Proc model: ") + procmodel + "\n"

		procmodeltype = getBoxProcType()
		if procmodeltype is not None and procmodeltype != "unknown":
			AboutText += _("Hardware type: ") + procmodeltype + "\n"

		hwserial = getHWSerial()
		if hwserial is not None and hwserial != "unknown":
			AboutText += _("Hardware serial: ") + hwserial + "\n"
		if hwserial is not None and hwserial == "unknown":
			AboutText += _("Hardware serial: ") + about.getCPUSerial() + "\n"

		AboutText += _("Brand/Meta: ") + getBoxBrand() + "\n"

		AboutText += "\n"
		cpu = about.getCPUInfoString()
		AboutText += _("CPU: ") + cpu + "\n"
		AboutText += _("CPU brand: ") + about.getCPUBrand() + "\n"

		socfamily = boxbranding.getSoCFamily()
		if socfamily is not None:
			AboutText += _("SoC family: ") + socfamily + "\n"

		AboutText += _("CPU architecture: ") + about.getCPUArch() + "\n"

		if not boxbranding.getDisplayType().startswith(' '):
			AboutText += "\n"
			AboutText += _("Display type: ") + boxbranding.getDisplayType() + "\n"

		# [WanWizard] Removed until we find a reliable way to determine the installation date
		# AboutText += _("Installed: ") + about.getFlashDateString() + "\n"

		EnigmaVersion = about.getEnigmaVersionString()
		EnigmaVersion = EnigmaVersion.rsplit("-", EnigmaVersion.count("-") - 2)
		if len(EnigmaVersion) == 3:
			EnigmaVersion = EnigmaVersion[0] + " (" + EnigmaVersion[2] + "-" + EnigmaVersion[1] + ")"
		else:
			EnigmaVersion = EnigmaVersion[0] + " (" + EnigmaVersion[1] + ")"
		EnigmaVersion = _("Enigma2 version: ") + EnigmaVersion
		self["EnigmaVersion"] = StaticText(EnigmaVersion)
		AboutText += "\n" + EnigmaVersion + "\n"
		AboutText += _("Last update: ") + about.getUpdateDateString() + "\n"
		AboutText += _("Enigma2 (re)starts: %d\n") % config.misc.startCounter.value
		AboutText += _("Enigma2 debug level: %d\n") % eGetEnigmaDebugLvl()

		if fileExists("/etc/openvision/mediaservice"):
			mediaservice = open("/etc/openvision/mediaservice", "r").read().strip()
			AboutText += _("Media service: ") + mediaservice.replace("enigma2-plugin-systemplugins-","") + "\n"

		AboutText += "\n"

		AboutText += _("Drivers version: ") + about.getDriverInstalledDate() + "\n"
		AboutText += _("Kernel version: ") + boxbranding.getKernelVersion() + "\n"

		GStreamerVersion = _("GStreamer version: ") + about.getGStreamerVersionString(cpu).replace("GStreamer","")
		self["GStreamerVersion"] = StaticText(GStreamerVersion)
		AboutText += "\n" + GStreamerVersion + "\n"

		FFmpegVersion = _("FFmpeg version: ") + about.getFFmpegVersionString()
		self["FFmpegVersion"] = StaticText(FFmpegVersion)
		AboutText += FFmpegVersion + "\n"

		AboutText += "\n"
		AboutText += _("Python version: ") + about.getPythonVersionString() + "\n"
		AboutText += "\n"

		fp_version = getFPVersion()
		if fp_version is None:
			fp_version = ""
		else:
			fp_version = _("Frontprocessor version: %s") % fp_version

			AboutText += fp_version + "\n"

		self["FPVersion"] = StaticText(fp_version)

		AboutText += _('Skin & Resolution: %s (%sx%s)\n') % (config.skin.primary_skin.value.split('/')[0], getDesktop(0).size().width(), getDesktop(0).size().height())

		self["TunerHeader"] = StaticText(_("Detected NIMs:"))
		AboutText += "\n"
		AboutText += _("Detected NIMs:") + "\n"

		nims = nimmanager.nimListCompressed()
		for count in range(len(nims)):
			if count < 4:
				self["Tuner" + str(count)] = StaticText(nims[count])
			else:
				self["Tuner" + str(count)] = StaticText("")
			AboutText += nims[count] + "\n"

		self["HDDHeader"] = StaticText(_("Detected HDD:"))
		AboutText += "\n"
		AboutText += _("Detected HDD:") + "\n"

		hddlist = harddiskmanager.HDDList()
		hddinfo = ""
		if hddlist:
			formatstring = hddsplit and "%s:%s, %.1f %sB %s" or "%s\n(%s, %.1f %sB %s)"
			for count in range(len(hddlist)):
				if hddinfo:
					hddinfo += "\n"
				hdd = hddlist[count][1]
				if int(hdd.free()) > 1024:
					hddinfo += formatstring % (hdd.model(), hdd.capacity(), hdd.Totalfree()/1024.0, "G", _("free"))
				else:
					hddinfo += formatstring % (hdd.model(), hdd.capacity(), hdd.Totalfree(), "M", _("free"))
		else:
			hddinfo = _("none")
		self["hddA"] = StaticText(hddinfo)
		AboutText += hddinfo + "\n\n" + _("Network Info:")
		for x in about.GetIPsFromNetworkInterfaces():
			AboutText += "\n" + x[0] + ": " + x[1]
		AboutText += '\n\n' + _("Uptime") + ": " + about.getBoxUptime()

		self["AboutScrollLabel"] = ScrollLabel(AboutText)
		self["key_green"] = Button(_("Translations"))
		self["key_red"] = Button(_("Latest Commits"))
		self["key_yellow"] = Button(_("Troubleshoot"))
		self["key_blue"] = Button(_("Memory Info"))

		self["actions"] = ActionMap(["ColorActions", "SetupActions", "DirectionActions"],
			{
				"cancel": self.close,
				"ok": self.close,
				"red": self.showCommits,
				"green": self.showTranslationInfo,
				"blue": self.showMemoryInfo,
				"yellow": self.showTroubleshoot,
				"up": self["AboutScrollLabel"].pageUp,
				"down": self["AboutScrollLabel"].pageDown
			})
Beispiel #40
0
	def erase(self):
		self.currentSelected = self["config"].l.getCurrentSelection()
		if self.currentSelected[0][1] != "Queued":
			if SystemInfo["HasRootSubdir"]:
				message = _("Removal of this slot will not show in %s Gui.  Are you sure you want to delete image slot %s ?") %(getMachineBuild(), self.currentSelected[0][1])
				ybox = self.session.openWithCallback(self.doErase, MessageBox, message, MessageBox.TYPE_YESNO, default=True)
				ybox.setTitle(_("Remove confirmation"))
			else:
				message = _("Are you sure you want to delete image slot %s ?") %self.currentSelected[0][1]
				ybox = self.session.openWithCallback(self.doErase, MessageBox, message, MessageBox.TYPE_YESNO, default=True)
				ybox.setTitle(_("Remove confirmation"))
		self.startit()
Beispiel #41
0
SystemInfo["OledDisplay"] = fileExists("/dev/dbox/oled0") or getBoxType() in ('osminiplus')
SystemInfo["LcdDisplay"] = fileExists("/dev/dbox/lcd0")
SystemInfo["FBLCDDisplay"] = fileCheck("/proc/stb/fb/sd_detach")
SystemInfo["DeepstandbySupport"] = HardwareInfo().has_deepstandby()
SystemInfo["Fan"] = fileCheck("/proc/stb/fp/fan")
SystemInfo["FanPWM"] = SystemInfo["Fan"] and fileCheck("/proc/stb/fp/fan_pwm")
SystemInfo["StandbyPowerLed"] = fileExists("/proc/stb/power/standbyled")
SystemInfo["LEDButtons"] = getBoxType() == 'vuultimo'
SystemInfo["WakeOnLAN"] = fileCheck("/proc/stb/power/wol") or fileCheck("/proc/stb/fp/wol")
SystemInfo["HDMICEC"] = (fileExists("/dev/hdmi_cec") or fileExists("/dev/misc/hdmi_cec0")) and fileExists("/usr/lib/enigma2/python/Plugins/SystemPlugins/HdmiCEC/plugin.pyo")
SystemInfo["SABSetup"] = fileExists("/usr/lib/enigma2/python/Plugins/SystemPlugins/SABnzbd/plugin.pyo")
SystemInfo["SeekStatePlay"] = False
SystemInfo["GraphicLCD"] = getBoxType() in ('vuultimo', 'xpeedlx3', 'et10000', 'mutant2400', 'quadbox2400', 'sezammarvel', 'atemionemesis', 'mbultra', 'beyonwizt4')
SystemInfo["Blindscan"] = fileExists("/usr/lib/enigma2/python/Plugins/SystemPlugins/Blindscan/plugin.pyo")
SystemInfo["Satfinder"] = fileExists("/usr/lib/enigma2/python/Plugins/SystemPlugins/Satfinder/plugin.pyo")
SystemInfo["HasExternalPIP"] = getMachineBuild() not in ('et9x00', 'et6x00', 'et5x00') and fileCheck("/proc/stb/vmpeg/1/external")
SystemInfo["hasPIPVisibleProc"] = fileCheck("/proc/stb/vmpeg/1/visible")
SystemInfo["VideoDestinationConfigurable"] = fileExists("/proc/stb/vmpeg/0/dst_left")
SystemInfo["GBWOL"] = fileExists("/usr/bin/gigablue_wol")
SystemInfo["LCDSKINSetup"] = path.exists("/usr/share/enigma2/display")
SystemInfo["VFD_scroll_repeats"] = fileCheck("/proc/stb/lcd/scroll_repeats")
SystemInfo["VFD_scroll_delay"] = fileCheck("/proc/stb/lcd/scroll_delay")
SystemInfo["VFD_initial_scroll_delay"] = fileCheck("/proc/stb/lcd/initial_scroll_delay")
SystemInfo["VFD_final_scroll_delay"] = fileCheck("/proc/stb/lcd/final_scroll_delay")
SystemInfo["LCDMiniTV"] = fileExists("/proc/stb/lcd/mode")
SystemInfo["LCDMiniTVPiP"] = SystemInfo["LCDMiniTV"] and getBoxType() != 'gb800ueplus'
SystemInfo["LcdLiveTV"] = fileCheck("/proc/stb/fb/sd_detach") or fileCheck("/proc/stb/lcd/live_enable")
SystemInfo["LcdLiveTVPiP"] = fileCheck("/proc/stb/lcd/live_decoder")
SystemInfo["MiniTV"] = fileCheck("/proc/stb/fb/sd_detach") or fileCheck("/proc/stb/lcd/live_enable")
SystemInfo["FastChannelChange"] = False
SystemInfo["CIHelper"] = fileExists("/usr/bin/cihelper")
Beispiel #42
0
    or fileExists("/dev/misc/hdmi_cec0")) and fileExists(
        "/usr/lib/enigma2/python/Plugins/SystemPlugins/HdmiCEC/plugin.pyo")
SystemInfo["SABSetup"] = fileExists(
    "/usr/lib/enigma2/python/Plugins/SystemPlugins/SABnzbd/plugin.pyo")
SystemInfo["SeekStatePlay"] = False
SystemInfo["StatePlayPause"] = False
SystemInfo["StandbyState"] = False
SystemInfo["GraphicLCD"] = getBoxType() in ('vuultimo', 'xpeedlx3', 'et10000',
                                            'mutant2400', 'quadbox2400',
                                            'sezammarvel', 'atemionemesis',
                                            'mbultra', 'beyonwizt4')
SystemInfo["Blindscan"] = fileExists(
    "/usr/lib/enigma2/python/Plugins/SystemPlugins/Blindscan/plugin.pyo")
SystemInfo["Satfinder"] = fileExists(
    "/usr/lib/enigma2/python/Plugins/SystemPlugins/Satfinder/plugin.pyo")
SystemInfo["HasExternalPIP"] = getMachineBuild() not in (
    'et9x00', 'et6x00', 'et5x00') and fileCheck("/proc/stb/vmpeg/1/external")
SystemInfo["hasPIPVisibleProc"] = fileCheck("/proc/stb/vmpeg/1/visible")
SystemInfo["VideoDestinationConfigurable"] = fileExists(
    "/proc/stb/vmpeg/0/dst_left")
SystemInfo["GBWOL"] = fileExists("/usr/bin/gigablue_wol")
SystemInfo["LCDSKINSetup"] = path.exists("/usr/share/enigma2/display")
SystemInfo["7segment"] = getDisplayType() in ('7segment')
SystemInfo["grautec"] = fileExists("/tmp/usbtft")
SystemInfo["isGBIPBOX"] = fileExists("/usr/lib/enigma2/python/gbipbox.so")
SystemInfo["CIHelper"] = fileExists("/usr/bin/cihelper")
SystemInfo["3DMode"] = fileCheck("/proc/stb/fb/3dmode") or fileCheck(
    "/proc/stb/fb/primary/3d")
SystemInfo["3DZNorm"] = fileCheck("/proc/stb/fb/znorm") or fileCheck(
    "/proc/stb/fb/primary/zoffset")
SystemInfo["CanUse3DModeChoices"] = fileExists(
Beispiel #43
0
    or model.startswith('et7')) and pathExists('/proc/stb/ir/rc/type')
SystemInfo["HasFullHDSkinSupport"] = model not in ("et4000", "et5000", "sh1",
                                                   "hd500c", "hd1100",
                                                   "xp1000", "lc", "sf8")
SystemInfo["HasBypassEdidChecking"] = fileCheck(
    "/proc/stb/hdmi/bypass_edid_checking")
SystemInfo["HasColorspace"] = fileCheck("/proc/stb/video/hdmi_colorspace")
SystemInfo["HasColorspaceSimple"] = SystemInfo[
    "HasColorspace"] and model in "vusolo4k"
SystemInfo["HasMultichannelPCM"] = fileCheck(
    "/proc/stb/audio/multichannel_pcm")
SystemInfo["HasMMC"] = "root" in cmdline and cmdline["root"].startswith(
    "/dev/mmcblk")
SystemInfo["HaveMultiBoot"] = (fileCheck("/boot/STARTUP")
                               or fileCheck("/boot/cmdline.txt"))
SystemInfo["HaveMultiBootDS"] = fileCheck("/boot/STARTUP") and getMachineBuild(
) in ('cc1', 'sf8008') and fileCheck("/dev/sda")
SystemInfo["CommonInterfaceCIDelay"] = fileCheck("/proc/stb/tsmux/rmx_delay")
SystemInfo["HasTranscoding"] = pathExists("/proc/stb/encoder/0") or fileCheck(
    "/dev/bcm_enc0")
SystemInfo["HasH265Encoder"] = fileHas("/proc/stb/encoder/0/vcodec_choices",
                                       "h265")
SystemInfo["CanNotDoSimultaneousTranscodeAndPIP"] = model in "vusolo4k"
SystemInfo["HasColordepth"] = fileCheck("/proc/stb/video/hdmi_colordepth")
SystemInfo["HasFrontDisplayPicon"] = model in ("vusolo4k", "et8500")
SystemInfo["Has24hz"] = fileCheck("/proc/stb/video/videomode_24hz")
SystemInfo["Has2160p"] = fileHas("/proc/stb/video/videomode_preferred",
                                 "2160p50")
SystemInfo["HasHDMIpreemphasis"] = fileCheck("/proc/stb/hdmi/preemphasis")
SystemInfo["HasColorimetry"] = fileCheck("/proc/stb/video/hdmi_colorimetry")
SystemInfo["HasHdrType"] = fileCheck("/proc/stb/video/hdmi_hdrtype")
SystemInfo["HasHDMI-CEC"] = HardwareInfo().has_hdmi() and fileExists(
Beispiel #44
0
    def __init__(self, session):
        Screen.__init__(self, session)
        self.skinName = "Standby"
        self.avswitch = AVSwitch()

        print "[Standby] enter standby"
        SystemInfo["StandbyState"] = True

        self["actions"] = ActionMap(
            ["StandbyActions"], {
                "power": self.Power,
                "power_make": self.Power_make,
                "power_break": self.Power_break,
                "power_long": self.Power_long,
                "power_repeat": self.Power_repeat,
                "discrete_on": self.Power
            }, -1)

        globalActionMap.setEnabled(False)

        self.ignoreKeyBreakTimer = eTimer()
        self.standbyStopServiceTimer = eTimer()
        self.standbyStopServiceTimer.callback.append(self.stopService)
        self.timeHandler = None

        #mute adc
        self.setMute()

        if SystemInfo["Display"] and SystemInfo["LCDMiniTV"]:
            # set LCDminiTV off
            setLCDModeMinitTV("0")

        self.paused_service = None
        self.prev_running_service = None
        self.prev_running_service = self.session.nav.getCurrentlyPlayingServiceOrGroup(
        )
        service = self.prev_running_service and self.prev_running_service.toString(
        )
        if service:
            if service.startswith("1:") and service.rsplit(
                    ":", 1)[1].startswith("/"):
                self.paused_service = self.session.current_dialog
                self.paused_service.pauseService()
        if not self.paused_service:
            self.timeHandler = eDVBLocalTimeHandler.getInstance()
            if self.timeHandler.ready():
                if self.session.nav.getCurrentlyPlayingServiceOrGroup():
                    self.stopService()
                else:
                    self.standbyStopServiceTimer.startLongTimer(5)
                self.timeHandler = None
            else:
                self.timeHandler.m_timeUpdated.get().append(self.stopService)
        if self.session.pipshown:
            from Screens.InfoBar import InfoBar
            InfoBar.instance and hasattr(
                InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()

        #set input to vcr scart
        if SystemInfo["ScartSwitch"]:
            self.avswitch.setInput("SCART")
        else:
            self.avswitch.setInput("AUX")

        if (getBrandOEM() in ('fulan', 'clap', 'dinobot') or getMachineBuild()
                in ('gbmv200', 'sf8008', 'sf8008m', 'ustym4kpro', 'beyonwizv2',
                    'viper4k')):
            try:
                open("/proc/stb/hdmi/output", "w").write("off")
            except:
                pass

        if int(
                config.usage.hdd_standby_in_standby.value
        ) != -1:  # HDD standby timer value (box in standby) / -1 = same as when box is active
            for hdd in harddiskmanager.HDDList():
                hdd[1].setIdleTime(
                    int(config.usage.hdd_standby_in_standby.value))

        self.onFirstExecBegin.append(self.__onFirstExecBegin)
        self.onClose.append(self.__onClose)
    def save(self):
        print "[MultiBootStartup] select new startup: ", self.list[
            self.selection]
        ret = system("cp -f '/boot/%s' /boot/STARTUP" %
                     self.list[self.selection])
        if ret:
            self.session.open(
                MessageBox,
                _("File '/boot/%s' copy to '/boot/STARTUP' failed!") %
                self.list[self.selection], MessageBox.TYPE_ERROR)
            self.getCurrent()
            return

        writeoption = already = failboot = False
        newboot = boot = self.readlineFile('/boot/STARTUP')

        if self.checkBootEntry(boot):
            failboot = True
        elif self.option_enabled:
            for x in self.optionsList:
                if (x[0] + "'" in boot or x[0] + " "
                        in boot) and x[0] != self.optionsList[self.option][0]:
                    newboot = boot.replace(x[0],
                                           self.optionsList[self.option][0])
                    if self.optionsList[self.option][0] == "boxmode=1":
                        newboot = newboot.replace("520M@248M", "440M@328M")
                        newboot = newboot.replace("200M@768M", "192M@768M")
                    elif self.optionsList[self.option][0] == "boxmode=12":
                        newboot = newboot.replace("440M@328M", "520M@248M")
                        newboot = newboot.replace("192M@768M", "200M@768M")
                    writeoption = True
                    break
                elif (x[0] + "'" in boot or x[0] + " "
                      in boot) and x[0] == self.optionsList[self.option][0]:
                    already = True
                    break
            if not (writeoption or already):
                if "boxmode" in boot:
                    failboot = True
                elif self.option:
                    newboot = boot.replace(
                        "rootwait", "rootwait %s_4.%s" %
                        (getMachineBuild(), self.optionsList[self.option][0]))
                    if self.optionsList[self.option][0] == "boxmode=1":
                        newboot = newboot.replace("520M@248M", "440M@328M")
                        newboot = newboot.replace("200M@768M", "192M@768M")
                    elif self.optionsList[self.option][0] == "boxmode=12":
                        newboot = newboot.replace("440M@328M", "520M@248M")
                        newboot = newboot.replace("192M@768M", "200M@768M")
                    writeoption = True

        if self.enable_bootnamefile:
            if failboot:
                self.writeFile('/boot/bootname', 'STARTUP_1=STARTUP_1')
            else:
                self.writeFile(
                    '/boot/bootname',
                    '%s=%s' % ('STARTUP_%s' % getMachineBuild(), boot[22:23],
                               self.list[self.selection]))

        message = _("Do you want to reboot now with selected image?")
        if failboot:
            print "[MultiBootStartup] wrong bootsettings: " + boot
            if '/dev/mmcblk0p3' in Harddisk.getextdevices("ext4"):
                if self.writeFile(
                        '/boot/STARTUP',
                        "boot emmcflash0.kernel1 'brcm_cma=440M@328M brcm_cma=192M@768M root=/dev/mmcblk0p3 rw rootwait'"
                ):
                    txt = _("Next boot will start from Image 1.")
                else:
                    txt = _("Can not repair file %s") % (
                        "'/boot/STARTUP'") + "\n" + _(
                            "Caution, next boot is starts with these settings!"
                        ) + "\n"
            else:
                txt = _(
                    "Alternative Image 1 partition for boot repair not found."
                ) + "\n" + _(
                    "Caution, next boot is starts with these settings!") + "\n"
            message = _("Wrong Bootsettings detected!") + "\n\n%s\n\n%s\n" % (
                boot, txt) + _("Do you want to reboot now?")
        elif writeoption:
            if not self.writeFile('/boot/STARTUP', newboot):
                txt = _("Can not write file %s") % (
                    "'/boot/STARTUP'") + "\n" + _(
                        "Caution, next boot is starts with these settings!"
                    ) + "\n"
                message = _("Write error!") + "\n\n%s\n\n%s\n" % (
                    boot, txt) + _("Do you want to reboot now?")

        #verify boot
        if failboot or writeoption:
            boot = self.readlineFile('/boot/STARTUP')
            if self.checkBootEntry(boot):
                txt = _("Error in file %s") % ("'/boot/STARTUP'") + "\n" + _(
                    "Caution, next boot is starts with these settings!") + "\n"
                message = _("Command line error!") + "\n\n%s\n\n%s\n" % (
                    boot, txt) + _("Do you want to reboot now?")

        self.session.openWithCallback(self.restartBOX, MessageBox, message,
                                      MessageBox.TYPE_YESNO)
Beispiel #46
0
def runScreenTest():
    config.misc.startCounter.value += 1

    profile("readPluginList")
    plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))

    profile("Init:Session")
    nav = Navigation(config.misc.nextWakeup.value)
    #nav = Navigation(config.misc.isNextRecordTimerAfterEventActionAuto.value, config.misc.isNextPowerTimerAfterEventActionAuto.value)
    session = Session(desktop=enigma.getDesktop(0),
                      summary_desktop=enigma.getDesktop(1),
                      navigation=nav)

    CiHandler.setSession(session)

    profile("wizards")
    screensToRun = []
    RestoreSettings = None
    if os.path.exists("/media/hdd/images/config/settings"
                      ) and config.misc.firstrun.value:
        if autorestoreLoop():
            RestoreSettings = True
            from Plugins.SystemPlugins.SoftwareManager.BackupRestore import RestoreScreen
            os.system("rm /media/hdd/images/config/settings")
            session.open(RestoreScreen, runRestore=True)
        else:
            os.system("rm /media/hdd/images/config/settings")
            screensToRun = [
                p.__call__
                for p in plugins.getPlugins(PluginDescriptor.WHERE_WIZARD)
            ]
            screensToRun += wizardManager.getWizards()
    else:
        if os.path.exists("/media/hdd/images/config/autorestore"):
            os.system('rm -f /media/hdd/images/config/autorestore')
        screensToRun = [
            p.__call__
            for p in plugins.getPlugins(PluginDescriptor.WHERE_WIZARD)
        ]
        screensToRun += wizardManager.getWizards()

    screensToRun.append((100, InfoBar.InfoBar))
    screensToRun.sort()
    print screensToRun

    enigma.ePythonConfigQuery.setQueryFunc(configfile.getResolvedKey)

    def runNextScreen(session, screensToRun, *result):
        config.easysetup = ConfigSubsection()
        config.easysetup.restart = ConfigBoolean(default=False)
        if config.easysetup.restart.value == True:
            print "restart after Wizard2"
            config.easysetup.restart.setValue(False)
            config.easysetup.restart.save()
            enigma.quitMainloop(3)
        if result:
            print "[mytest.py] quitMainloop #3"
            enigma.quitMainloop(*result)
            return

        screen = screensToRun[0][1]
        args = screensToRun[0][2:]
        if screensToRun:
            session.openWithCallback(
                boundFunction(runNextScreen, session, screensToRun[1:]),
                screen, *args)
        else:
            session.open(screen, *args)

    if not RestoreSettings:
        runNextScreen(session, screensToRun)

    profile("Init:VolumeControl")
    vol = VolumeControl(session)
    profile("Init:PowerKey")
    power = PowerKey(session)
    power.timerstdby()
    if boxtype in (
            'alien5', 'osninopro', 'osnino', 'osninoplus', 'alphatriple',
            'spycat4kmini', 'tmtwin4k', 'mbmicrov2', 'revo4k', 'force3uhd',
            'wetekplay', 'wetekplay2', 'wetekhub', 'dm7020hd', 'dm7020hdv2',
            'osminiplus', 'osmega', 'sf3038', 'spycat', 'e4hd', 'e4hdhybrid',
            'mbmicro', 'et7500', 'mixosf5', 'mixosf7', 'mixoslumi', 'gi9196m',
            'maram9', 'ixussone', 'ixusszero', 'uniboxhd1', 'uniboxhd2',
            'uniboxhd3', 'sezam5000hd', 'mbtwin', 'sezam1000hd', 'mbmini',
            'atemio5x00', 'beyonwizt3', '9910lx', '9911lx',
            '9920lx') or getBrandOEM() in ('fulan') or getMachineBuild() in (
                'u41', 'dags7362', 'dags73625', 'dags5', 'ustym4kpro',
                'sf8008', 'sf8008m', 'cc1', 'gbmv200'):
        profile("VFDSYMBOLS")
        import Components.VfdSymbols
        Components.VfdSymbols.SymbolsCheck(session)

    # we need session.scart to access it from within menu.xml
    session.scart = AutoScartControl(session)

    profile("Init:Trashcan")
    import Tools.Trashcan
    Tools.Trashcan.init(session)

    profile("Init:AutoVideoMode")
    import Screens.VideoMode
    Screens.VideoMode.autostart(session)

    profile("RunReactor")
    profile_final()

    if boxtype in ('sf8', 'classm', 'axodin', 'axodinc', 'starsatlx', 'genius',
                   'evo'):
        f = open("/dev/dbox/oled0", "w")
        f.write('-E2-')
        f.close()

    print "lastshutdown=%s		(True = last shutdown was OK)" % config.usage.shutdownOK.value
    print "NOK shutdown action=%s" % config.usage.shutdownNOK_action.value
    print "bootup action=%s" % config.usage.boot_action.value

    if not config.usage.shutdownOK.value and not config.usage.shutdownNOK_action.value == 'normal' or not config.usage.boot_action.value == 'normal':
        print "last shutdown = %s" % config.usage.shutdownOK.value
        import Screens.PowerLost
        Screens.PowerLost.PowerLost(session)

    config.usage.shutdownOK.setValue(False)
    config.usage.shutdownOK.save()
    if not RestoreSettings:
        configfile.save()

    # kill showiframe if it is running (sh4 hack...)
    if getMachineBuild() in ('spark', 'spark7162'):
        os.system("killall -9 showiframe")

    runReactor()
    print "[mytest.py] normal shutdown"

    config.misc.startCounter.save()
    config.usage.shutdownOK.setValue(True)
    config.usage.shutdownOK.save()

    profile("wakeup")
    #get currentTime
    nowTime = time()
    if not config.misc.SyncTimeUsing.value == "0" or getBoxType().startswith(
            'gb') or getMachineProcModel().startswith('ini'):
        print "dvb time sync disabled... so set RTC now to current linux time!", strftime(
            "%Y/%m/%d %H:%M", localtime(nowTime))
        setRTCtime(nowTime)

    wakeupList = [
        x for x in (
            (session.nav.RecordTimer.getNextRecordingTime(), 0,
             session.nav.RecordTimer.isNextRecordAfterEventActionAuto()),
            (session.nav.RecordTimer.getNextZapTime(),
             1), (plugins.getNextWakeupTime(), 2),
            (session.nav.PowerTimer.getNextPowerManagerTime(), 3,
             session.nav.PowerTimer.isNextPowerManagerAfterEventActionAuto()))
        if x[0] != -1
    ]
    wakeupList.sort()
    recordTimerWakeupAuto = False
    if wakeupList and wakeupList[0][1] != 3:
        startTime = wakeupList[0]
        if (startTime[0] - nowTime) < 270:  # no time to switch box back on
            wptime = nowTime + 30  # so switch back on in 30 seconds
        else:
            if getBoxType().startswith("gb"):
                wptime = startTime[
                    0] - 120  # Gigaboxes already starts 2 min. before wakeup time
            else:
                wptime = startTime[0] - 240
        if startTime[1] == 3:
            nextPluginName = " (%s)" % nextPluginName
        #if not config.misc.SyncTimeUsing.value == "0" or getBoxType().startswith('gb'):
        #	print "dvb time sync disabled... so set RTC now to current linux time!", strftime("%Y/%m/%d %H:%M", localtime(nowTime))
        #	setRTCtime(nowTime)
        print "set wakeup time to", strftime("%Y/%m/%d %H:%M",
                                             localtime(wptime))
        setFPWakeuptime(wptime)
        recordTimerWakeupAuto = startTime[1] == 0 and startTime[2]
        print 'recordTimerWakeupAuto', recordTimerWakeupAuto
    config.misc.isNextRecordTimerAfterEventActionAuto.value = recordTimerWakeupAuto
    config.misc.isNextRecordTimerAfterEventActionAuto.save()

    PowerTimerWakeupAuto = False
    if wakeupList and wakeupList[0][1] == 3:
        startTime = wakeupList[0]
        if (startTime[0] - nowTime) < 60:  # no time to switch box back on
            wptime = nowTime + 30  # so switch back on in 30 seconds
        else:
            if getBoxType().startswith("gb"):
                wptime = startTime[
                    0] + 120  # Gigaboxes already starts 2 min. before wakeup time
            else:
                wptime = startTime[0]
        #if not config.misc.SyncTimeUsing.value == "0" or getBoxType().startswith('gb'):
        #	print "dvb time sync disabled... so set RTC now to current linux time!", strftime("%Y/%m/%d %H:%M", localtime(nowTime))
        #	setRTCtime(nowTime)
        print "set wakeup time to", strftime("%Y/%m/%d %H:%M",
                                             localtime(wptime + 60))
        setFPWakeuptime(wptime)
        PowerTimerWakeupAuto = startTime[1] == 3 and startTime[2]
        print 'PowerTimerWakeupAuto', PowerTimerWakeupAuto
    config.misc.isNextPowerTimerAfterEventActionAuto.value = PowerTimerWakeupAuto
    config.misc.isNextPowerTimerAfterEventActionAuto.save()

    profile("stopService")
    session.nav.stopService()
    profile("nav shutdown")
    session.nav.shutdown()

    profile("configfile.save")
    configfile.save()
    from Screens import InfoBarGenerics
    InfoBarGenerics.saveResumePoints()

    return 0
Beispiel #47
0
from Components.Label import Label
from Components.ActionMap import ActionMap
from Components.About import about
from Components import Harddisk
from Screens.Console import Console
from Screens.MessageBox import MessageBox
from time import time, strftime, localtime
from os import path, system, makedirs, listdir, walk, statvfs, remove
import commands
import datetime
from boxbranding import getBoxType, getMachineBrand, getMachineName, getDriverDate, getImageVersion, getImageBuild, getBrandOEM, getMachineBuild, getImageFolder, getMachineUBINIZE, getMachineMKUBIFS, getMachineMtdKernel, getMachineMtdRoot, getMachineKernelFile, getMachineRootFile, getImageFileSystem

VERSION = _("Version") + " 6.2 openATV"

HaveGZkernel = True
if getMachineBuild() in ('multibox', 'vuduo4k', 'v8plus', 'ustym4kpro', 'hd60',
                         'hd61', 'i55plus', 'osmio4k', 'sf8008', 'sf8008s',
                         'sf8008t', 'cc1', 'dags72604', 'u51', 'u52', 'u53',
                         'u54', 'u55', 'h9', 'h9combo', 'vuzero4k', 'u5',
                         'u5pvr', 'sf5008', 'et13000', 'et1x000', "vuuno4k",
                         "vuuno4kse", "vuultimo4k", "vusolo4k", "spark",
                         "spark7162", "hd51", "hd52", "sf4008", "dags7252",
                         "gb7252", "vs1500", "h7", 'xc7439', '8100s'):
    HaveGZkernel = False


def Freespace(dev):
    statdev = statvfs(dev)
    space = (statdev.f_bavail * statdev.f_frsize) / 1024
    print "[FULL BACKUP] Free space on %s = %i kilobytes" % (dev, space)
    return space
Beispiel #48
0
from Components.Label import Label
from Components.ActionMap import ActionMap
from Components.About import about
from Components import Harddisk
from Screens.Console import Console
from Screens.MessageBox import MessageBox
from time import time, strftime, localtime
from os import path, system, makedirs, listdir, walk, statvfs
import commands
import datetime
from boxbranding import getBoxType, getMachineBrand, getMachineName, getDriverDate, getImageVersion, getImageBuild, getBrandOEM, getMachineBuild, getImageFolder, getMachineUBINIZE, getMachineMKUBIFS, getMachineMtdKernel, getMachineMtdRoot, getMachineKernelFile, getMachineRootFile, getImageFileSystem

VERSION = "Version 1.0 teamBlue"

HaveGZkernel = True
if getMachineBuild() in ("vusolo4k", "spark", "spark7162", "hd51", "hd52",
                         "gb7252"):
    HaveGZkernel = False


def Freespace(dev):
    statdev = statvfs(dev)
    space = (statdev.f_bavail * statdev.f_frsize) / 1024
    print "[ImageBackup] Free space on %s = %i kilobytes" % (dev, space)
    return space


class ImageBackup(Screen):
    skin = """
	<screen position="center,center" size="560,400" title="Image Backup">
		<ePixmap position="0,360"   zPosition="1" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
Beispiel #49
0
def getAboutText():
    AboutText = ""
    AboutText += _("Model:\t\t%s %s\n") % (getMachineBrand(), getMachineName())
    AboutText += _("OEM Model:\t\t%s\n") % getMachineBuild()

    bootloader = ""
    if path.exists('/sys/firmware/devicetree/base/bolt/tag'):
        f = open('/sys/firmware/devicetree/base/bolt/tag', 'r')
        bootloader = f.readline().replace('\x00', '').replace('\n', '')
        f.close()
        AboutText += _("Bootloader:\t\t%s\n") % (bootloader)

    if path.exists('/proc/stb/info/chipset'):
        AboutText += _("Chipset:\t\t%s") % about.getChipSetString() + "\n"

    cpuMHz = ""
    if getMachineBuild() in ('u41', 'u42', 'u43'):
        cpuMHz = _("   (1.0 GHz)")
    elif getMachineBuild() in ('dags72604', 'vusolo4k', 'vuultimo4k',
                               'vuzero4k', 'gb72604'):
        cpuMHz = _("   (1.5 GHz)")
    elif getMachineBuild() in ('formuler1tc', 'formuler1', 'triplex',
                               'tiviaraplus'):
        cpuMHz = _("   (1.3 GHz)")
    elif getMachineBuild() in ('gbmv200', 'u51', 'u5', 'u53', 'u532', 'u533',
                               'u52', 'u54', 'u55', 'u56', 'u5pvr', 'h9',
                               'h9combo', 'h10', 'cc1', 'sf8008', 'sf8008m',
                               'hd60', 'hd61', 'i55plus', 'ustym4kpro',
                               'beyonwizv2', 'viper4k', 'v8plus', 'multibox'):
        cpuMHz = _("   (1.6 GHz)")
    elif getMachineBuild() in ('vuuno4kse', 'vuuno4k', 'dm900', 'dm920',
                               'gb7252', 'dags7252', 'xc7439', '8100s'):
        cpuMHz = _("   (1.7 GHz)")
    elif getMachineBuild() in ('alien5', ):
        cpuMHz = _("   (2.0 GHz)")
    elif getMachineBuild() in ('vuduo4k', ):
        cpuMHz = _("   (2.1 GHz)")
    elif getMachineBuild() in ('sf5008', 'et13000', 'et1x000', 'hd52', 'hd51',
                               'sf4008', 'vs1500', 'h7', 'osmio4k',
                               'osmio4kplus', 'osmini4k'):
        try:
            import binascii
            f = open(
                '/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency',
                'rb')
            clockfrequency = f.read()
            f.close()
            cpuMHz = _("   (%s MHz)") % str(
                round(int(binascii.hexlify(clockfrequency), 16) / 1000000, 1))
        except:
            cpuMHz = _("   (1.7 GHz)")
    else:
        if path.exists('/proc/cpuinfo'):
            f = open('/proc/cpuinfo', 'r')
            temp = f.readlines()
            f.close()
            try:
                for lines in temp:
                    lisp = lines.split(': ')
                    if lisp[0].startswith('cpu MHz'):
                        #cpuMHz = "   (" +  lisp[1].replace('\n', '') + " MHz)"
                        cpuMHz = "   (" + str(
                            int(float(lisp[1].replace('\n', '')))) + " MHz)"
                        break
            except:
                pass

    AboutText += _("CPU:\t\t%s") % about.getCPUString() + cpuMHz + "\n"
    AboutText += _("Cores:\t\t%s") % about.getCpuCoresString() + "\n"

    imagestarted = ""
    bootname = ''
    if path.exists('/boot/bootname'):
        f = open('/boot/bootname', 'r')
        bootname = f.readline().split('=')[1]
        f.close()
    if SystemInfo["canMultiBoot"]:
        slot = image = GetCurrentImage()
        bootmode = ""
        part = _("eMMC slot %s") % slot
        if SystemInfo["canMode12"]:
            bootmode = _("bootmode = %s") % GetCurrentImageMode()
        if SystemInfo["HasHiSi"] and "sda" in SystemInfo["canMultiBoot"][slot][
                'device']:
            if slot > 4:
                image -= 4
            else:
                image -= 1
            part = "SDcard slot %s (%s) " % (
                image, SystemInfo["canMultiBoot"][slot]['device'])
        AboutText += _("Selected Image:\t\t%s") % _("STARTUP_") + str(
            slot) + "  " + part + " " + bootmode + "\n"

    AboutText += _("Version:\t\t%s") % getImageVersion() + "\n"
    AboutText += _("Build:\t\t%s") % getImageBuild() + "\n"
    AboutText += _("Kernel:\t\t%s") % about.getKernelVersionString() + "\n"

    string = getDriverDate()
    year = string[0:4]
    month = string[4:6]
    day = string[6:8]
    driversdate = '-'.join((year, month, day))
    AboutText += _("Drivers:\t\t%s") % MyDateConverter(driversdate) + "\n"

    AboutText += _(
        "GStreamer:\t\t%s") % about.getGStreamerVersionString() + "\n"
    AboutText += _("Python:\t\t%s") % about.getPythonVersionString() + "\n"

    MyFlashDate = about.getFlashDateString()
    if MyFlashDate != _("unknown"):
        AboutText += _("Installed:\t\t%s") % MyFlashDate + "\n"

    AboutText += _("Last update:\t\t%s") % MyDateConverter(
        getEnigmaVersionString()) + "\n"

    fp_version = getFPVersion()
    if fp_version is None:
        fp_version = ""
    elif fp_version != 0:
        fp_version = _("Frontprocessor version: %s") % fp_version
        AboutText += fp_version + "\n"

    tempinfo = ""
    if path.exists('/proc/stb/sensors/temp0/value'):
        f = open('/proc/stb/sensors/temp0/value', 'r')
        tempinfo = f.read()
        f.close()
    elif path.exists('/proc/stb/fp/temp_sensor'):
        f = open('/proc/stb/fp/temp_sensor', 'r')
        tempinfo = f.read()
        f.close()
    elif path.exists('/proc/stb/sensors/temp/value'):
        f = open('/proc/stb/sensors/temp/value', 'r')
        tempinfo = f.read()
        f.close()
    if tempinfo and int(tempinfo.replace('\n', '')) > 0:
        mark = str('\xc2\xb0')
        AboutText += _("System temperature:\t%s") % tempinfo.replace(
            '\n', '').replace(' ', '') + mark + "C\n"

    tempinfo = ""
    if path.exists('/proc/stb/fp/temp_sensor_avs'):
        f = open('/proc/stb/fp/temp_sensor_avs', 'r')
        tempinfo = f.read()
        f.close()
    elif path.exists('/proc/stb/power/avs'):
        f = open('/proc/stb/power/avs', 'r')
        tempinfo = f.read()
        f.close()
    elif path.exists('/sys/devices/virtual/thermal/thermal_zone0/temp'):
        try:
            f = open('/sys/devices/virtual/thermal/thermal_zone0/temp', 'r')
            tempinfo = f.read()
            tempinfo = tempinfo[:-4]
            f.close()
        except:
            tempinfo = ""
    elif path.exists('/proc/hisi/msp/pm_cpu'):
        try:
            for line in open('/proc/hisi/msp/pm_cpu').readlines():
                line = [x.strip() for x in line.strip().split(":")]
                if line[0] in ("Tsensor"):
                    temp = line[1].split("=")
                    temp = line[1].split(" ")
                    tempinfo = temp[2]
                    if getMachineBuild() in ('u41', 'u42', 'u43'):
                        tempinfo = str(int(tempinfo) - 15)
        except:
            tempinfo = ""
    if tempinfo and int(tempinfo.replace('\n', '')) > 0:
        mark = str('\xc2\xb0')
        AboutText += _("Processor temperature:\t%s") % tempinfo.replace(
            '\n', '').replace(' ', '') + mark + "C\n"
    AboutLcdText = AboutText.replace('\t', ' ')

    return AboutText, AboutLcdText
Beispiel #50
0
from Components.Label import Label
from Components.ActionMap import ActionMap
from Components.About import about
from Components import Harddisk
from Screens.Console import Console
from Screens.MessageBox import MessageBox
from time import time, strftime, localtime
from os import path, system, makedirs, listdir, walk, statvfs, remove
import commands
import datetime
from boxbranding import getBoxType, getMachineBrand, getMachineName, getDriverDate, getImageVersion, getImageBuild, getBrandOEM, getMachineBuild, getImageFolder, getMachineUBINIZE, getMachineMKUBIFS, getMachineMtdKernel, getMachineMtdRoot, getMachineKernelFile, getMachineRootFile, getImageFileSystem

VERSION = "Version 6.1 SFteam"

HaveGZkernel = True
if getMachineBuild() in ('h9', 'vuzero4k', 'u5', 'u5pvr', 'sf5008', 'et13000',
                         'et1x000', "vuuno4k", "vuuno4kse", "vuultimo4k",
                         "vusolo4k", "spark", "spark7162", "hd51", "hd52",
                         "sf4008", "dags7252", "gb7252", "vs1500", "h7",
                         'xc7439', '8100s'):
    HaveGZkernel = False


def Freespace(dev):
    statdev = statvfs(dev)
    space = (statdev.f_bavail * statdev.f_frsize) / 1024
    print "[FULL BACKUP] Free space on %s = %i kilobytes" % (dev, space)
    return space


class ImageBackup(Screen):