예제 #1
0
    def __init__(self, session, feid):
        self.initcomplete = False
        self.feid = feid
        self.oldref = None
        self.frontendData = None
        service = session and session.nav.getCurrentService()
        feinfo = service and service.frontendInfo()
        self.frontendData = feinfo and feinfo.getAll(True)
        del feinfo
        del service

        if not self.openFrontend():
            self.oldref = session.nav.getCurrentlyPlayingServiceReference()
            session.nav.stopService()  # try to disable foreground service
            if not self.openFrontend():
                if session.pipshown:  # try to disable pip
                    session.pipshown = False
                    del session.pip
                    if not self.openFrontend():
                        self.frontend = None  # in normal case this should not happen

        ScanSetup.__init__(self, session)
        Screen.setTitle(self, _("Satfinder"))
        self.tuner = Tuner(self.frontend)
        self["introduction"].setText("")
        self["Frontend"] = FrontendStatus(
            frontend_source=lambda: self.frontend, update_interval=100)
        self.initcomplete = True
        self.onClose.append(self.__onClose)
예제 #2
0
	def TunerTypeChanged(self):
		fe_id = int(self.scan_nims.value)
		multiType = config.Nims[fe_id].multiType
		system = multiType.getText()
		if (system in ('DVB-S', 'DVB-S2') and config.Nims[fe_id].dvbs.configMode.value == "nothing") or \
			(system in ('DVB-T', 'DVB-T2') and config.Nims[fe_id].dvbt.configMode.value == "nothing") or \
			(system in ('DVB-C') and config.Nims[fe_id].dvbc.configMode.value == "nothing") or \
			(system in ('ATSC') and config.Nims[fe_id].atsc.configMode.value == "nothing"):
			return
		slot = nimmanager.nim_slots[fe_id]
		print("dvb_api_version ", iDVBFrontend.dvb_api_version)
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)

		if slot.isMultiType():
			eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, "dummy", False) #to force a clear of m_delsys_whitelist
			types = slot.getMultiTypeList()
			import six
			for FeType in six.itervalues(types):
				if FeType in ("DVB-S", "DVB-S2", "DVB-S2X") and config.Nims[slot.slot].dvbs.configMode.value == "nothing":
					continue
				elif FeType in ("DVB-T", "DVB-T2") and config.Nims[slot.slot].dvbt.configMode.value == "nothing":
					continue
				elif FeType in ("DVB-C", "DVB-C2") and config.Nims[slot.slot].dvbc.configMode.value == "nothing":
					continue
				elif FeType in ("ATSC") and config.Nims[slot.slot].atsc.configMode.value == "nothing":
					continue
				eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, FeType, True)
		else:
			eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, slot.getType())


#			if not path.exists("/proc/stb/frontend/%d/mode" % fe_id) and iDVBFrontend.dvb_api_version >= 5:
		print("api >=5 and new style tuner driver")
		if self.frontend:
			if system == 'DVB-C':
				ret = self.frontend.changeType(iDVBFrontend.feCable)
			elif system in ('DVB-T', 'DVB-T2'):
				ret = self.frontend.changeType(iDVBFrontend.feTerrestrial)
			elif system in ('DVB-S', 'DVB-S2'):
				ret = self.frontend.changeType(iDVBFrontend.feSatellite)
			elif system == 'ATSC':
				ret = self.frontend.changeType(iDVBFrontend.feATSC)
			else:
				ret = False
			if not ret:
				print("%d: tunerTypeChange to '%s' failed" % (fe_id, system))
			else:
				print("new system ", system)
		else:
			print("%d: tunerTypeChange to '%s' failed (BUSY)" % (fe_id, multiType.getText()))
		self.retune()
예제 #3
0
	def prepareScanData(self, orb, pol, band, is_scan):
		self.is_runable = False
		self.orb_position = orb[0]
		self.feid = int(self.scan_nims.value)
		tab_hilow = {"high" : 1, "low" : 0}
		tab_pol = {
			"horizontal" : eDVBFrontendParametersSatellite.Polarisation_Horizontal, 
			"vertical" : eDVBFrontendParametersSatellite.Polarisation_Vertical,
			"circular left" : eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
			"circular right" : eDVBFrontendParametersSatellite.Polarisation_CircularRight
		}

		returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

		if not self.openFrontend():
			self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					self.session.pipshown = False
					del self.session.pip
					if not self.openFrontend():
						self.frontend = None
		self.tuner = Tuner(self.frontend)

		if tab_hilow[band]:
			self.scan_sat.frequency.value = 12515
		else:
			self.scan_sat.frequency.value = 11015
		returnvalue = (self.scan_sat.frequency.value,
					 0,
					 tab_pol[pol],
					 0,
					 0,
					 orb[0],
					 eDVBFrontendParametersSatellite.System_DVB_S,
					 0,
					 0,
					 0)
		self.tuner.tune(returnvalue)

		if self.getNimSocket(self.feid) < 0:
			print "can't find i2c number!!"
			return
		try:
			cmd = "%s %d %d %d %d %d %d %d %d" % (self.binName, self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value/1000000, self.blindscan_stop_symbol.value/1000000, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		except: return
		print "prepared command : [%s]" % (cmd)
		self.blindscan_container = eConsoleAppContainer()
		self.blindscan_container.appClosed.append(self.blindscanContainerClose)
		self.blindscan_container.dataAvail.append(self.blindscanContainerAvail)
		self.blindscan_container.execute(cmd)

		tmpstr = "Look for available transponders.\nThis works will take several minutes.\n\n   - Current Status : %d/%d\n   - Orbital Positions : %s\n   - Polarization : %s\n   - Bandwidth : %s" %(self.running_count, self.max_count, orb[1], pol, band)
		if is_scan :
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionClose, MessageBox, _(tmpstr), MessageBox.TYPE_INFO)
		else:
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionNone, MessageBox, _(tmpstr), MessageBox.TYPE_INFO)
예제 #4
0
    def statusCallback(self):
        if self.state == 0:
            if self.port_index == 0:
                self.clearNimEntries()
                config.Nims[self.feid].dvbs.diseqcA.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 1:
                self.clearNimEntries()
                config.Nims[self.feid].dvbs.diseqcB.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 2:
                self.clearNimEntries()
                config.Nims[self.feid].dvbs.diseqcC.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 3:
                self.clearNimEntries()
                config.Nims[self.feid].dvbs.diseqcD.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])

            if self.nr_of_ports == 4:
                config.Nims[self.feid].dvbs.diseqcMode.value = "diseqc_a_b_c_d"
            elif self.nr_of_ports == 2:
                config.Nims[self.feid].dvbs.diseqcMode.value = "diseqc_a_b"
            else:
                config.Nims[self.feid].dvbs.diseqcMode.value = "single"

            config.Nims[self.feid].dvbs.configMode.value = "simple"
            config.Nims[
                self.feid].dvbs.simpleDiSEqCSetVoltageTone = self.simple_tone
            config.Nims[
                self.
                feid].dvbs.simpleDiSEqCOnlyOnSatChange = self.simple_sat_change

            self.saveAndReloadNimConfig()
            self.state += 1

        elif self.state == 1:
            InitNimManager(nimmanager)

            self.tuner = Tuner(self.frontend)
            if self.raw_channel:
                self.raw_channel.requestTsidOnid()
            self.tuner.tune(self.sat_frequencies[self.index])

            self["statusbar"].setText(
                _("Checking tuner %d\nDiSEqC port %s for %s") %
                (self.feid, self.diseqc_ports[self.port_index],
                 self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
            self["tunerstatusbar"].setText(" ")

            self.count = 0
            self.state = 0

            self.startTunerStatusTimer()
            return

        self.startStatusTimer()
예제 #5
0
 def __onShow(self):
     if self.oldref is not None:
         self.session.nav.stopService()  # try to disable foreground service
     if not self.openFrontend():
         if self.session.pipshown:  # try to disable pip
             self.session.pipshown = False
             del self.session.pip
             if not self.openFrontend():
                 self.frontend = None  # in normal case this should not happen
     self.tuner = Tuner(self.frontend)
     self.retune(None)
예제 #6
0
 def prepareFrontend(self):
     self.frontend = None
     if not self.openFrontend():
         self.session.nav.stopService()
         if not self.openFrontend():
             if self.session.pipshown:
                 self.session.pipshown = False
                 del self.session.pip
                 if not self.openFrontend():
                     self.frontend = None
     self.tuner = Tuner(self.frontend)
     self.retune(None)
예제 #7
0
	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown: # try to disable pip
					self.session.pipshown = False
					del self.session.pip
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)
예제 #8
0
파일: plugin.py 프로젝트: kingvuplus/b-p
	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)
예제 #9
0
파일: plugin.py 프로젝트: kingvuplus/ME
 def prepareFrontend(self):
     self.frontend = None
     if not self.openFrontend():
         self.session.nav.stopService()
         if not self.openFrontend():
             if self.session.pipshown:
                 from Screens.InfoBar import InfoBar
                 InfoBar.instance and hasattr(
                     InfoBar.instance,
                     'showPiP') and InfoBar.instance.showPiP()
                 if not self.openFrontend():
                     self.frontend = None
     self.tuner = Tuner(self.frontend)
     self.retune(None)
예제 #10
0
 def initFrontend(self):
     if self.oldref is None:
         self.oldref = self.session.nav.getCurrentlyPlayingServiceReference(
         )
     if not self.openFrontend():
         self.prev_ref = True
         self.session.nav.stopService()  # try to disable foreground service
         if not self.openFrontend():
             if self.session.pipshown:  # try to disable pip
                 self.session.pipshown = False
                 del self.session.pip
                 if not self.openFrontend():
                     self.frontend = None  # in normal case this should not happen
     self.tuner = Tuner(self.frontend)
예제 #11
0
	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"):
			self.updatePreDefTransponders()
		self.createSetup()
		self.retune()
예제 #12
0
 def initFrontend(self):
     if self.oldref is None:
         self.oldref = self.session.nav.getCurrentlyPlayingServiceReference(
         )
     if not self.openFrontend():
         self.prev_ref = True
         self.session.nav.stopService()
         if not self.openFrontend():
             if self.session.pipshown:
                 self.session.pipshown = False
                 del self.session.pip
                 if not self.openFrontend():
                     self.frontend = None
     self.tuner = Tuner(self.frontend)
     self.retune(None)
예제 #13
0
파일: plugin.py 프로젝트: kolombek/enigma2
	def __init__(self, session, feid):
		self.initcomplete = False
		self.feid = feid
		self.oldref = None
		self.frontendData = None
		service = session and session.nav.getCurrentService()
		feinfo = service and service.frontendInfo()
		self.frontendData = feinfo and feinfo.getAll(True)
		del feinfo
		del service

		if not self.openFrontend():
			self.oldref = session.nav.getCurrentlyPlayingServiceReference()
			session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if session.pipshown: # try to disable pip
					session.pipshown = False
					del session.pip
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen

		ScanSetup.__init__(self, session)
		Screen.setTitle(self, _("Satfinder"))
		self.tuner = Tuner(self.frontend)
		self["introduction"].setText("")
		self["Frontend"] = FrontendStatus(frontend_source = lambda : self.frontend, update_interval = 100)
		self.initcomplete = True
		self.onClose.append(self.__onClose)
예제 #14
0
 def prepareFrontend(self):
     self.frontend = None
     if not self.openFrontend():
         self.session.nav.stopService()
         if not self.openFrontend():
             if self.session.pipshown:  # try to disable pip
                 if hasattr(self.session, 'infobar'):
                     if self.session.infobar.servicelist.dopipzap:
                         self.session.infobar.servicelist.togglePipzap()
                 if hasattr(self.session, 'pip'):
                     del self.session.pip
                 self.session.pipshown = False
                 if not self.openFrontend():
                     self.frontend = None  # in normal case this should not happen
     self.tuner = Tuner(self.frontend)
     self.retune(None)
예제 #15
0
	def prepareFrontend(self):
		self.frontend = None
		if hasattr(self, 'raw_channel'):
			del self.raw_channel
		if not self.openFrontend():
			oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			stop_current_service = True
			if oldref and self.getCurrentTuner is not None:
				if self.getCurrentTuner < 4 and self.feid != self.getCurrentTuner:
					stop_current_service = False
			if stop_current_service:
				self.session.nav.stopService()
				self.getCurrentTuner = None
			if not self.openFrontend():
				if self.session.pipshown:
					if hasattr(self.session, 'infobar'):
						slist = self.session.infobar.servicelist
						if slist and slist.dopipzap:
							slist.togglePipzap()
					self.session.pipshown = False
					if hasattr(self.session, 'pip'):
						del self.session.pip
					self.openFrontend()
		if self.frontend == None :
			text = _("Sorry, this tuner is in use.")
			if self.session.nav.getRecordings():
				text += "\n"
				text += _("Maybe the reason that recording is currently running.")
			self.session.open(MessageBox, text, MessageBox.TYPE_ERROR)
			return False
		self.tuner = Tuner(self.frontend)
		return True
예제 #16
0
파일: plugin.py 프로젝트: Open-Plus/opgui
	def TunerTypeChanged(self):
		fe_id = int(self.scan_nims.value)
		multiType = config.Nims[fe_id].multiType
		system = multiType.getText()
		if (system in ('DVB-S','DVB-S2') and config.Nims[fe_id].dvbs.configMode.value == "nothing") or \
			(system in ('DVB-T','DVB-T2') and config.Nims[fe_id].dvbt.configMode.value == "nothing") or \
			(system in ('DVB-C') and config.Nims[fe_id].dvbc.configMode.value == "nothing") or \
			(system in ('ATSC') and config.Nims[fe_id].atsc.configMode.value == "nothing") :
			return
		slot = nimmanager.nim_slots[fe_id]
		print "dvb_api_version ",iDVBFrontend.dvb_api_version
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)

		if slot.isMultiType():
			eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, "dummy", False) #to force a clear of m_delsys_whitelist
			types = slot.getMultiTypeList()
			for FeType in types.itervalues():
				if FeType in ("DVB-S", "DVB-S2", "DVB-S2X") and config.Nims[slot.slot].dvbs.configMode.value == "nothing":
					continue
				elif FeType in ("DVB-T", "DVB-T2") and config.Nims[slot.slot].dvbt.configMode.value == "nothing":
					continue
				elif FeType in ("DVB-C", "DVB-C2") and config.Nims[slot.slot].dvbc.configMode.value == "nothing":
					continue
				elif FeType in ("ATSC") and config.Nims[slot.slot].atsc.configMode.value == "nothing":
					continue
				eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, FeType, True)
		else:
			eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, slot.getType())


#			if not path.exists("/proc/stb/frontend/%d/mode" % fe_id) and iDVBFrontend.dvb_api_version >= 5:
		print "api >=5 and new style tuner driver"
		if self.frontend:
			if system == 'DVB-C':
				ret = self.frontend.changeType(iDVBFrontend.feCable)
			elif system in ('DVB-T','DVB-T2'):
				ret = self.frontend.changeType(iDVBFrontend.feTerrestrial)
			elif system in ('DVB-S','DVB-S2'):
				ret = self.frontend.changeType(iDVBFrontend.feSatellite)
			elif system == 'ATSC':
				ret = self.frontend.changeType(iDVBFrontend.feATSC)
			else:
				ret = False
			if not ret:
				print "%d: tunerTypeChange to '%s' failed" %(fe_id, system)
			else:
				print "new system ",system
		else:
			print "%d: tunerTypeChange to '%s' failed (BUSY)" %(fe_id, multiType.getText())
		self.retune()
예제 #17
0
	def prepareFrontend(self):
		self.frontend = None
		if hasattr(self, 'raw_channel'):
			del self.raw_channel
		if not self.openFrontend():
			self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					self.session.pipshown = False
					del self.session.pip
					self.openFrontend()
		if self.frontend == None :
			self.session.open(MessageBox, _("Sorry, this tuner is in use."), MessageBox.TYPE_ERROR)
			return False
		self.tuner = Tuner(self.frontend)
		return True
예제 #18
0
 def TunerTypeChanged(self):
     fe_id = int(self.scan_nims.value)
     multiType = config.Nims[fe_id].multiType
     system = multiType.getText()
     if (system in ('DVB-S','DVB-S2') and config.Nims[fe_id].dvbs.configMode.value == "nothing") or \
      (system in ('DVB-T','DVB-T2') and config.Nims[fe_id].dvbt.configMode.value == "nothing") or \
      (system in ('DVB-C') and config.Nims[fe_id].dvbc.configMode.value == "nothing"):
         self.createSetup()
         return
     nim = nimmanager.nim_slots[fe_id]
     print "dvb_api_version ", iDVBFrontend.dvb_api_version
     self.frontend = None
     if not self.openFrontend():
         self.session.nav.stopService()
         if not self.openFrontend():
             if self.session.pipshown:
                 from Screens.InfoBar import InfoBar
                 InfoBar.instance and hasattr(
                     InfoBar.instance,
                     "showPiP") and InfoBar.instance.showPiP()
                 if not self.openFrontend():
                     self.frontend = None  # in normal case this should not happen
     self.tuner = Tuner(self.frontend)
     eDVBResourceManager.getInstance().setFrontendType(
         nim.frontend_id, nim.getType())
     #			if not path.exists("/proc/stb/frontend/%d/mode" % fe_id) and iDVBFrontend.dvb_api_version >= 5:
     print "api >=5 and new style tuner driver"
     if self.frontend:
         if system == 'DVB-C':
             ret = self.frontend.changeType(iDVBFrontend.feCable)
         elif system in ('DVB-T', 'DVB-T2'):
             ret = self.frontend.changeType(iDVBFrontend.feTerrestrial)
         elif system in ('DVB-S', 'DVB-S2'):
             ret = self.frontend.changeType(iDVBFrontend.feSatellite)
         elif system == 'ATSC':
             ret = self.frontend.changeType(iDVBFrontend.feATSC)
         else:
             ret = False
         if not ret:
             print "%d: tunerTypeChange to '%s' failed" % (fe_id, system)
         else:
             print "new system ", system
     else:
         print "%d: tunerTypeChange to '%s' failed (BUSY)" % (
             fe_id, multiType.getText())
     self.createSetup()
예제 #19
0
파일: plugin.py 프로젝트: popazerty/bh1
	def prepareScanData(self, orb, pol, band, is_scan):
		self.is_runable = False
		self.orb_position = orb[0]
		self.feid = int(self.scan_nims.value)
		tab_hilow = {"high" : 1, "low" : 0}
		tab_pol = {
			"horizontal" : eDVBFrontendParametersSatellite.Polarisation_Horizontal, 
			"vertical" : eDVBFrontendParametersSatellite.Polarisation_Vertical,
			"circular left" : eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
			"circular right" : eDVBFrontendParametersSatellite.Polarisation_CircularRight
		}

		returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

		if not self.openFrontend():
			self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					self.session.pipshown = False
					del self.session.pip
					if not self.openFrontend():
						self.frontend = None
		self.tuner = Tuner(self.frontend)

		if tab_hilow[band]:
			self.scan_sat.frequency.value = 12515
		else:
			self.scan_sat.frequency.value = 11015
		returnvalue = (self.scan_sat.frequency.value,
					 0,
					 tab_pol[pol],
					 0,
					 0,
					 orb[0],
					 eDVBFrontendParametersSatellite.System_DVB_S,
					 0,
					 0,
					 0)
		self.tuner.tune(returnvalue)

		if self.getNimSocket(self.feid) < 0:
			print "can't find i2c number!!"
			return
		try:
			cmd = "%s %d %d %d %d %d %d %d %d" % (self.binName, self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value/1000000, self.blindscan_stop_symbol.value/1000000, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		except: return
		print "prepared command : [%s]" % (cmd)
		self.blindscan_container = eConsoleAppContainer()
		self.blindscan_container.appClosed.append(self.blindscanContainerClose)
		self.blindscan_container.dataAvail.append(self.blindscanContainerAvail)
		self.blindscan_container.execute(cmd)

		tmpstr = "Look for available transponders.\nThis works will take several minutes.\n\n   - Current Status : %d/%d\n   - Orbital Positions : %s\n   - Polarization : %s\n   - Bandwidth : %s" %(self.running_count, self.max_count, orb[1], pol, band)
		if is_scan :
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionClose, MessageBox, _(tmpstr), MessageBox.TYPE_INFO)
		else:
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionNone, MessageBox, _(tmpstr), MessageBox.TYPE_INFO)
예제 #20
0
 def initFrontend(self):
     if self.oldref is None:
         self.oldref = self.session.nav.getCurrentlyPlayingServiceReference(
         )
     if not self.openFrontend():
         self.prev_ref = True
         self.session.nav.stopService()  # try to disable foreground service
         if not self.openFrontend():
             if self.session.pipshown:  # try to disable pip
                 self.session.pipshown = False
                 del self.session.pip
                 if not self.openFrontend():
                     self.frontend = None  # in normal case this should not happen
     try:
         self.tuner = Tuner(self.frontend)
         self["Frontend"] = FrontendStatus(
             frontend_source=lambda: self.frontend, update_interval=100)
     except:
         pass
예제 #21
0
    def statusCallback(self):
        if self.state == 0:
            if self.port_index == 0:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcA.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 1:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcB.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 2:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcC.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 3:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcD.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])

            if self.nr_of_ports == 4:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b_c_d"
            elif self.nr_of_ports == 2:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b"
            else:
                config.Nims[self.feid].diseqcMode.value = "single"

            config.Nims[self.feid].configMode.value = "simple"
            config.Nims[self.feid].simpleDiSEqCSetVoltageTone = self.simple_tone
            config.Nims[self.feid].simpleDiSEqCOnlyOnSatChange = self.simple_sat_change

            self.saveAndReloadNimConfig()
            self.state += 1

        elif self.state == 1:
            InitNimManager(nimmanager)

            self.tuner = Tuner(self.frontend)
            if self.raw_channel:
                self.raw_channel.requestTsidOnid()
            self.tuner.tune(self.sat_frequencies[self.index])

            self["statusbar"].setText(
                _("Checking tuner %s\nDiSEqC port %s for %s")
                % (
                    chr(self.feid + 65),
                    self.diseqc_ports[self.port_index],
                    self.sat_frequencies[self.index][self.SAT_TABLE_NAME],
                )
            )
            self["tunerstatusbar"].setText(" ")

            self.count = 0
            self.state = 0

            self.startTunerStatusTimer()
            return

        self.startStatusTimer()
예제 #22
0
	def __onShow(self):
		if self.oldref is not None:
			self.session.nav.stopService() # try to disable foreground service
		if not self.openFrontend():
			if self.session.pipshown: # try to disable pip
				self.session.pipshown = False
				del self.session.pip
				if not self.openFrontend():
					self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)
예제 #23
0
파일: plugin.py 프로젝트: kingvuplus/ME
 def prepareFrontend(self):
     self.frontend = None
     if not self.openFrontend():
         self.session.nav.stopService()
         if not self.openFrontend():
             if self.session.pipshown:
                 from Screens.InfoBar import InfoBar
                 InfoBar.instance and hasattr(InfoBar.instance, 'showPiP') and InfoBar.instance.showPiP()
                 if not self.openFrontend():
                     self.frontend = None
     self.tuner = Tuner(self.frontend)
     self.retune(None)
예제 #24
0
	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)
예제 #25
0
	def __init__(self, session, feid):
		self.initcomplete = False
		self.feid = feid
		self.oldref = None

		if not self.openFrontend():
			self.oldref = session.nav.getCurrentlyPlayingServiceReference()
			session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if session.pipshown: # try to disable pip
					session.pipshown = False
					session.deleteDialog(session.pip)
					del session.pip
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen

		ScanSetup.__init__(self, session, 'S')
		self.tuner = Tuner(self.frontend)
		self["introduction"].setText("")
		self["Frontend"] = FrontendStatus(frontend_source = lambda : self.frontend, update_interval = 100)
		self.initcomplete = True
		self.onClose.append(self.__onClose)
예제 #26
0
	def initFrontend(self):
		if self.oldref is None:
			self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
		if not self.openFrontend():
			self.prev_ref = True
			self.session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if self.session.pipshown: # try to disable pip
					self.session.pipshown = False
					del self.session.pip
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
예제 #27
0
파일: plugin.py 프로젝트: Adga52/enigma2
	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"):
			self.updatePreDefTransponders()
		self.createSetup()
		self.retune()
예제 #28
0
파일: plugin.py 프로젝트: OpenSH4/enigma2
	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown: # try to disable pip
					if hasattr(self.session, 'infobar'):
						if self.session.infobar.servicelist.dopipzap:
							self.session.infobar.servicelist.togglePipzap()
					if hasattr(self.session, 'pip'):
						del self.session.pip
					self.session.pipshown = False
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)
예제 #29
0
 def initFrontend(self):
     if self.oldref is None:
         self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
     if not self.openFrontend():
         self.prev_ref = True
         self.session.nav.stopService()  # try to disable foreground service
         if not self.openFrontend():
             if self.session.pipshown:  # try to disable pip
                 self.session.pipshown = False
                 del self.session.pip
                 if not self.openFrontend():
                     self.frontend = None  # in normal case this should not happen
     try:
         self.tuner = Tuner(self.frontend)
         self["Frontend"] = FrontendStatus(frontend_source=lambda: self.frontend, update_interval=100)
     except:
         pass
예제 #30
0
	def prepareFrontend(self):
		self.frontend = None
		if hasattr(self, 'raw_channel'):
			del self.raw_channel
		if not self.openFrontend():
			self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					self.session.pipshown = False
					del self.session.pip
					self.openFrontend()
		if self.frontend == None :
			self.session.open(MessageBox, _("Sorry, this tuner is in use."), MessageBox.TYPE_ERROR)
			return False
		self.tuner = Tuner(self.frontend)
		return True
예제 #31
0
    def keyGo(self):
        selected_nim = int(self.SelectedNimToList(self.select_nim.value))
        selected_position = self.positions_config_list[selected_nim].index
        nim_positions_list = [
            self.all_pos_per_dvbs_nim[int(
                self.select_nim.value)][selected_position]
        ]
        self.position = nim_positions_list[0][0]
        self.position_name = nim_positions_list[0][1]

        self.frontend = self.OpenFrontend()
        if self.frontend is None:
            self.oldref = self.session.nav.getCurrentlyPlayingServiceReference(
            )
            self.session.nav.stopService()
            self.frontend = self.OpenFrontend()
        if self.frontend is None:
            print "*** cannot open frontend"
            return

        self.i2cbus = self.GetI2CBusFromSlot(int(self.select_nim.value))

        if self.i2cbus < 0:
            print "*** Can't find i2c bus for this nim"
            return

        #print "*** selected_nim =", selected_nim
        #print "*** selected_position =", selected_position
        #print "*** nim_positions_list =", nim_positions_list
        #print "*** position =", self.PositionToString(self.position), "(", self.position, ")"
        #print "*** position_name =", self.position_name

        self.tuner = Tuner(self.frontend)

        self.polarisation = self.PolarisationFirst()
        self.lof = self.LOFFirst()
        self.enigma_transponders = []
        self.text_transponders = []
        self.xml_transponders = []

        self.status_screen = self.session.openWithCallback(
            self.CallbackStatusScreenDone, SatscanStatus, self)
예제 #32
0
파일: plugin.py 프로젝트: idrogeno/FusionOE
	def TunerTypeChanged(self):
		fe_id = int(self.scan_nims.value)
		multiType = config.Nims[fe_id].multiType
		system = multiType.getText()
		if (system in ('DVB-S','DVB-S2') and config.Nims[fe_id].dvbs.configMode.value == "nothing") or \
			(system in ('DVB-T','DVB-T2') and config.Nims[fe_id].dvbt.configMode.value == "nothing") or \
			(system in ('DVB-C') and config.Nims[fe_id].dvbc.configMode.value == "nothing"):
			self.createSetup()
			return
		nim = nimmanager.nim_slots[fe_id]
		print "dvb_api_version ",iDVBFrontend.dvb_api_version
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		eDVBResourceManager.getInstance().setFrontendType(nim.frontend_id, nim.getType())
#			if not path.exists("/proc/stb/frontend/%d/mode" % fe_id) and iDVBFrontend.dvb_api_version >= 5:
		print "api >=5 and new style tuner driver"
		if self.frontend:
			if system == 'DVB-C':
				ret = self.frontend.changeType(iDVBFrontend.feCable)
			elif system in ('DVB-T','DVB-T2'):
				ret = self.frontend.changeType(iDVBFrontend.feTerrestrial)
			elif system in ('DVB-S','DVB-S2'):
				ret = self.frontend.changeType(iDVBFrontend.feSatellite)
			elif system == 'ATSC':
				ret = self.frontend.changeType(iDVBFrontend.feATSC)
			else:
				ret = False
			if not ret:
				print "%d: tunerTypeChange to '%s' failed" %(fe_id, system)
			else:
				print "new system ",system
		else:
			print "%d: tunerTypeChange to '%s' failed (BUSY)" %(fe_id, multiType.getText())
		self.createSetup()
예제 #33
0
파일: plugin.py 프로젝트: OpenESI/Wetek-ESI
	def __init__(self, session, feid):
		self.session = session
		Screen.__init__(self, session)
		self.feid = feid
		self.oldref = None
		log.open(self.LOG_SIZE)
		if config.Nims[self.feid].configMode.value == 'advanced':
			self.advanced = True
			self.advancedconfig = config.Nims[self.feid].advanced
			self.advancedsats = self.advancedconfig.sat
			self.availablesats = map(lambda x: x[0], nimmanager.getRotorSatListForNim(self.feid))
		else:
			self.advanced = False

		cur = { }
		if not self.openFrontend():
			self.oldref = session.nav.getCurrentlyPlayingServiceReference()
			service = session.nav.getCurrentService()
			feInfo = service and service.frontendInfo()
			if feInfo:
				cur = feInfo.getTransponderData(True)
			del feInfo
			del service
			session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if session.pipshown: # try to disable pip
					service = self.session.pip.pipservice
					feInfo = service and service.frontendInfo()
					if feInfo:
						cur = feInfo.getTransponderData(True)
					del feInfo
					del service
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
				if not self.openFrontend():
					self.frontend = None # in normal case this should not happen
					if hasattr(self, 'raw_channel'):
						del self.raw_channel

		self.frontendStatus = { }
		self.diseqc = Diseqc(self.frontend)
		# True means we dont like that the normal sec stuff sends commands to the rotor!
		self.tuner = Tuner(self.frontend, ignore_rotor = True)

		tp = ( cur.get("frequency", 0) / 1000,
			cur.get("symbol_rate", 0) / 1000,
			cur.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal),
			cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto),
			cur.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown),
			cur.get("orbital_position", 0),
			cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S),
			cur.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK),
			cur.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
			cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown))

		self.tuner.tune(tp)
		self.isMoving = False
		self.stopOnLock = False

		self.red = Button("")
		self["key_red"] = self.red
		self.green = Button("")
		self["key_green"] = self.green
		self.yellow = Button("")
		self["key_yellow"] = self.yellow
		self.blue = Button("")
		self["key_blue"] = self.blue

		self.list = []
		self["list"] = ConfigList(self.list)

		self["snr_db"] = TunerInfo(TunerInfo.SNR_DB, statusDict = self.frontendStatus)
		self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE, statusDict = self.frontendStatus)
		self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE, statusDict = self.frontendStatus)
		self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR, statusDict = self.frontendStatus)
		self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR, statusDict = self.frontendStatus)
		self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE, statusDict = self.frontendStatus)

		self["frequency_value"] = Label("")
		self["symbolrate_value"] = Label("")
		self["fec_value"] = Label("")
		self["polarisation"] = Label("")
		self["status_bar"] = Label("")
		self.statusMsgTimeoutTicks = 0
		self.statusMsgBlinking = False
		self.statusMsgBlinkCount = 0
		self.statusMsgBlinkRate = 500 / self.UPDATE_INTERVAL	# milliseconds
		self.tuningChangedTo(tp)

		self["actions"] = NumberActionMap(["DirectionActions", "OkCancelActions", "ColorActions", "TimerEditActions", "InputActions"],
		{
			"ok": self.keyOK,
			"cancel": self.keyCancel,
			"up": self.keyUp,
			"down": self.keyDown,
			"left": self.keyLeft,
			"right": self.keyRight,
			"red": self.redKey,
			"green": self.greenKey,
			"yellow": self.yellowKey,
			"blue": self.blueKey,
			"log": self.showLog,
			"1": self.keyNumberGlobal,
			"2": self.keyNumberGlobal,
			"3": self.keyNumberGlobal,
			"4": self.keyNumberGlobal,
			"5": self.keyNumberGlobal,
			"6": self.keyNumberGlobal,
			"7": self.keyNumberGlobal,
			"8": self.keyNumberGlobal,
			"9": self.keyNumberGlobal,
			"0": self.keyNumberGlobal
		}, -1)

		self.updateColors("tune")

		self.statusTimer = eTimer()
		self.statusTimer.callback.append(self.updateStatus)
		self.collectingStatistics = False
		self.statusTimer.start(self.UPDATE_INTERVAL, True)
		self.dataAvailable = Event()
		self.onClose.append(self.__onClose)

		self.createConfig()
		self.createSetup()
예제 #34
0
파일: plugin.py 프로젝트: OpenESI/Wetek-ESI
class PositionerSetup(Screen):

	@staticmethod
	def satposition2metric(position):
		if position > 1800:
			position = 3600 - position
			orientation = "west"
		else:
			orientation = "east"
		return position, orientation

	@staticmethod
	def orbital2metric(position, orientation):
		if orientation == "west":
			position = 360 - position
		if orientation == "south":
			position = - position
		return position

	@staticmethod
	def longitude2orbital(position):
		if position >= 180:
			return 360 - position, "west"
		else:
			return position, "east"

	@staticmethod
	def latitude2orbital(position):
		if position >= 0:
			return position, "north"
		else:
			return -position, "south"

	UPDATE_INTERVAL = 50					# milliseconds
	STATUS_MSG_TIMEOUT = 2					# seconds
	LOG_SIZE = 16 * 1024					# log buffer size

	def __init__(self, session, feid):
		self.session = session
		Screen.__init__(self, session)
		self.feid = feid
		self.oldref = None
		log.open(self.LOG_SIZE)
		if config.Nims[self.feid].configMode.value == 'advanced':
			self.advanced = True
			self.advancedconfig = config.Nims[self.feid].advanced
			self.advancedsats = self.advancedconfig.sat
			self.availablesats = map(lambda x: x[0], nimmanager.getRotorSatListForNim(self.feid))
		else:
			self.advanced = False

		cur = { }
		if not self.openFrontend():
			self.oldref = session.nav.getCurrentlyPlayingServiceReference()
			service = session.nav.getCurrentService()
			feInfo = service and service.frontendInfo()
			if feInfo:
				cur = feInfo.getTransponderData(True)
			del feInfo
			del service
			session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if session.pipshown: # try to disable pip
					service = self.session.pip.pipservice
					feInfo = service and service.frontendInfo()
					if feInfo:
						cur = feInfo.getTransponderData(True)
					del feInfo
					del service
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
				if not self.openFrontend():
					self.frontend = None # in normal case this should not happen
					if hasattr(self, 'raw_channel'):
						del self.raw_channel

		self.frontendStatus = { }
		self.diseqc = Diseqc(self.frontend)
		# True means we dont like that the normal sec stuff sends commands to the rotor!
		self.tuner = Tuner(self.frontend, ignore_rotor = True)

		tp = ( cur.get("frequency", 0) / 1000,
			cur.get("symbol_rate", 0) / 1000,
			cur.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal),
			cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto),
			cur.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown),
			cur.get("orbital_position", 0),
			cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S),
			cur.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK),
			cur.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
			cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown))

		self.tuner.tune(tp)
		self.isMoving = False
		self.stopOnLock = False

		self.red = Button("")
		self["key_red"] = self.red
		self.green = Button("")
		self["key_green"] = self.green
		self.yellow = Button("")
		self["key_yellow"] = self.yellow
		self.blue = Button("")
		self["key_blue"] = self.blue

		self.list = []
		self["list"] = ConfigList(self.list)

		self["snr_db"] = TunerInfo(TunerInfo.SNR_DB, statusDict = self.frontendStatus)
		self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE, statusDict = self.frontendStatus)
		self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE, statusDict = self.frontendStatus)
		self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR, statusDict = self.frontendStatus)
		self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR, statusDict = self.frontendStatus)
		self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE, statusDict = self.frontendStatus)

		self["frequency_value"] = Label("")
		self["symbolrate_value"] = Label("")
		self["fec_value"] = Label("")
		self["polarisation"] = Label("")
		self["status_bar"] = Label("")
		self.statusMsgTimeoutTicks = 0
		self.statusMsgBlinking = False
		self.statusMsgBlinkCount = 0
		self.statusMsgBlinkRate = 500 / self.UPDATE_INTERVAL	# milliseconds
		self.tuningChangedTo(tp)

		self["actions"] = NumberActionMap(["DirectionActions", "OkCancelActions", "ColorActions", "TimerEditActions", "InputActions"],
		{
			"ok": self.keyOK,
			"cancel": self.keyCancel,
			"up": self.keyUp,
			"down": self.keyDown,
			"left": self.keyLeft,
			"right": self.keyRight,
			"red": self.redKey,
			"green": self.greenKey,
			"yellow": self.yellowKey,
			"blue": self.blueKey,
			"log": self.showLog,
			"1": self.keyNumberGlobal,
			"2": self.keyNumberGlobal,
			"3": self.keyNumberGlobal,
			"4": self.keyNumberGlobal,
			"5": self.keyNumberGlobal,
			"6": self.keyNumberGlobal,
			"7": self.keyNumberGlobal,
			"8": self.keyNumberGlobal,
			"9": self.keyNumberGlobal,
			"0": self.keyNumberGlobal
		}, -1)

		self.updateColors("tune")

		self.statusTimer = eTimer()
		self.statusTimer.callback.append(self.updateStatus)
		self.collectingStatistics = False
		self.statusTimer.start(self.UPDATE_INTERVAL, True)
		self.dataAvailable = Event()
		self.onClose.append(self.__onClose)

		self.createConfig()
		self.createSetup()

	def __onClose(self):
		self.statusTimer.stop()
		log.close()
		self.session.nav.playService(self.oldref)

	def restartPrevService(self, yesno):
		if yesno:
			if self.frontend:
				self.frontend = None
				del self.raw_channel
		else:
			self.oldref=None
		self.close(None)

	def keyCancel(self):
		if self.oldref:
			self.session.openWithCallback(self.restartPrevService, MessageBox, _("Zap back to service before positioner setup?"), MessageBox.TYPE_YESNO)
		else:
			self.restartPrevService(False)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
				else:
					print "getFrontend failed"
			else:
				print "getRawChannel failed"
		else:
			print "getResourceManager instance failed"
		return False

	def setLNB(self, lnb):
		try:
			self.sitelon = lnb.longitude.float
			self.longitudeOrientation = lnb.longitudeOrientation.value
			self.sitelat = lnb.latitude.float
			self.latitudeOrientation = lnb.latitudeOrientation.value
			self.tuningstepsize = lnb.tuningstepsize.float
			self.rotorPositions = lnb.rotorPositions.value
			self.turningspeedH = lnb.turningspeedH.float
			self.turningspeedV = lnb.turningspeedV.float
		except: # some reasonable defaults from NimManager
			self.sitelon = 5.1
			self.longitudeOrientation = 'east'
			self.sitelat = 50.767
			self.latitudeOrientation = 'north'
			self.tuningstepsize = 0.36
			self.rotorPositions = 99
			self.turningspeedH = 2.3
			self.turningspeedV = 1.7
		self.sitelat = PositionerSetup.orbital2metric(self.sitelat, self.latitudeOrientation)
		self.sitelon = PositionerSetup.orbital2metric(self.sitelon, self.longitudeOrientation)

	def getLNBfromConfig(self, orb_pos):
		lnb = None
		if orb_pos in self.availablesats:
			lnbnum = int(self.advancedsats[orb_pos].lnb.value)
			if not lnbnum:
				for allsats in range(3601, 3607):
					lnbnum = int(self.advancedsats[allsats].lnb.value)
					if lnbnum:
						break
			if lnbnum:
				self.printMsg(_("Using LNB %d") % lnbnum)
				lnb = self.advancedconfig.lnb[lnbnum]
		if not lnb:
			self.logMsg(_("Warning: no LNB; using factory defaults."), timeout = 4)
		return lnb

	def createConfig(self):
		rotorposition = 1
		orb_pos = 0
		self.printMsg(_("Using tuner %s") % chr(0x41 + self.feid))
		if not self.advanced:
			self.printMsg(_("Configuration mode: %s") % _("simple"))
			nim = config.Nims[self.feid]
			self.sitelon = nim.longitude.float
			self.longitudeOrientation = nim.longitudeOrientation.value
			self.sitelat = nim.latitude.float
			self.latitudeOrientation = nim.latitudeOrientation.value
			self.sitelat = PositionerSetup.orbital2metric(self.sitelat, self.latitudeOrientation)
			self.sitelon = PositionerSetup.orbital2metric(self.sitelon, self.longitudeOrientation)
			self.tuningstepsize = nim.tuningstepsize.float
			self.rotorPositions = nim.rotorPositions.value
			self.turningspeedH = nim.turningspeedH.float
			self.turningspeedV = nim.turningspeedV.float
		else:	# it is advanced
			self.printMsg(_("Configuration mode: %s") % _("advanced"))
			fe_data = { }
			self.frontend.getFrontendData(fe_data)
			self.frontend.getTransponderData(fe_data, True)
			orb_pos = fe_data.get("orbital_position", None)
			if orb_pos in self.availablesats:
				rotorposition = int(self.advancedsats[orb_pos].rotorposition.value)
			self.setLNB(self.getLNBfromConfig(orb_pos))
		self.positioner_tune = ConfigNothing()
		self.positioner_move = ConfigNothing()
		self.positioner_finemove = ConfigNothing()
		self.positioner_limits = ConfigNothing()
		self.positioner_storage = ConfigInteger(default = rotorposition, limits = (1, self.rotorPositions))
		self.allocatedIndices = []
		m = PositionerSetup.satposition2metric(orb_pos)
		self.orbitalposition = ConfigFloat(default = [int(m[0] / 10), m[0] % 10], limits = [(0,180),(0,9)])
		self.orientation = ConfigSelection([("east", _("East")), ("west", _("West"))], m[1])

	def createSetup(self):
		self.list.append((_("Tune and focus"), self.positioner_tune, "tune"))
		self.list.append((_("Movement"), self.positioner_move, "move"))
		self.list.append((_("Fine movement"), self.positioner_finemove, "finemove"))
		self.list.append((_("Set limits"), self.positioner_limits, "limits"))
		self.list.append((_("Memory index"), self.positioner_storage, "storage"))
		self.list.append((_("Goto"), self.orbitalposition, "goto"))
		self.list.append((" ", self.orientation, "goto"))
		self["list"].l.setList(self.list)

	def keyOK(self):
		pass

	def getCurrentConfigPath(self):
		return self["list"].getCurrent()[2]

	def keyUp(self):
		if not self.isMoving:
			self["list"].instance.moveSelection(self["list"].instance.moveUp)
			self.updateColors(self.getCurrentConfigPath())

	def keyDown(self):
		if not self.isMoving:
			self["list"].instance.moveSelection(self["list"].instance.moveDown)
			self.updateColors(self.getCurrentConfigPath())

	def keyNumberGlobal(self, number):
		self["list"].handleKey(KEY_0 + number)

	def keyLeft(self):
		self["list"].handleKey(KEY_LEFT)

	def keyRight(self):
		self["list"].handleKey(KEY_RIGHT)

	def updateColors(self, entry):
		if entry == "tune":
			self.red.setText(_("Tune"))
			self.green.setText(_("Auto focus"))
			self.yellow.setText(_("Calibrate"))
			self.blue.setText(_("Calculate"))
		elif entry == "move":
			if self.isMoving:
				self.red.setText(_("Stop"))
				self.green.setText(_("Stop"))
				self.yellow.setText(_("Stop"))
				self.blue.setText(_("Stop"))
			else:
				self.red.setText(_("Move west"))
				self.green.setText(_("Search west"))
				self.yellow.setText(_("Search east"))
				self.blue.setText(_("Move east"))
		elif entry == "finemove":
			self.red.setText("")
			self.green.setText(_("Step west"))
			self.yellow.setText(_("Step east"))
			self.blue.setText("")
		elif entry == "limits":
			self.red.setText(_("Limits off"))
			self.green.setText(_("Limit west"))
			self.yellow.setText(_("Limit east"))
			self.blue.setText(_("Limits on"))
		elif entry == "storage":
			self.red.setText("")
			self.green.setText(_("Store position"))
			self.yellow.setText(_("Goto position"))
			if self.advanced:
				self.blue.setText(_("Allocate"))
			else:
				self.blue.setText("")
		elif entry == "goto":
			self.red.setText("")
			self.green.setText(_("Goto 0"))
			self.yellow.setText(_("Goto X"))
			self.blue.setText("")
		else:
			self.red.setText("")
			self.green.setText("")
			self.yellow.setText("")
			self.blue.setText("")

	def printMsg(self, msg):
		print msg
		print>>log, msg

	def stopMoving(self):
		self.printMsg(_("Stop"))
		self.diseqccommand("stop")
		self.isMoving = False
		self.stopOnLock = False
		self.statusMsg(_("Stopped"), timeout = self.STATUS_MSG_TIMEOUT)

	def redKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.stopMoving()
			else:
				self.printMsg(_("Move west"))
				self.diseqccommand("moveWest", 0)
				self.isMoving = True
				self.statusMsg(_("Moving west ..."), blinking = True)
			self.updateColors("move")
		elif entry == "limits":
			self.printMsg(_("Limits off"))
			self.diseqccommand("limitOff")
			self.statusMsg(_("Limits cancelled"), timeout = self.STATUS_MSG_TIMEOUT)
		elif entry == "tune":
			fe_data = { }
			self.frontend.getFrontendData(fe_data)
			self.frontend.getTransponderData(fe_data, True)
			feparm = self.tuner.lastparm.getDVBS()
			fe_data["orbital_position"] = feparm.orbital_position
			self.statusTimer.stop()
			self.session.openWithCallback(self.tune, TunerScreen, self.feid, fe_data)

	def greenKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "tune":
			# Auto focus
			self.printMsg(_("Auto focus"))
			print>>log, (_("Site latitude") + "      : %5.1f %s") % PositionerSetup.latitude2orbital(self.sitelat)
			print>>log, (_("Site longitude") + "     : %5.1f %s") % PositionerSetup.longitude2orbital(self.sitelon)
			Thread(target = self.autofocus).start()
		elif entry == "move":
			if self.isMoving:
				self.stopMoving()
			else:
				self.printMsg(_("Search west"))
				self.isMoving = True
				self.stopOnLock = True
				self.diseqccommand("moveWest", 0)
				self.statusMsg(_("Searching west ..."), blinking = True)
			self.updateColors("move")
		elif entry == "finemove":
			self.printMsg(_("Step west"))
			self.diseqccommand("moveWest", 0xFF) # one step
			self.statusMsg(_("Stepped west"), timeout = self.STATUS_MSG_TIMEOUT)
		elif entry == "storage":
			self.printMsg(_("Store at index"))
			index = int(self.positioner_storage.value)
			self.diseqccommand("store", index)
			self.statusMsg((_("Position stored at index") + " %2d") % index, timeout = self.STATUS_MSG_TIMEOUT)
		elif entry == "limits":
			self.printMsg(_("Limit west"))
			self.diseqccommand("limitWest")
			self.statusMsg(_("West limit set"), timeout = self.STATUS_MSG_TIMEOUT)
		elif entry == "goto":
			self.printMsg(_("Goto 0"))
			self.diseqccommand("moveTo", 0)
			self.statusMsg(_("Moved to position 0"), timeout = self.STATUS_MSG_TIMEOUT)

	def yellowKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.stopMoving()
			else:
				self.printMsg(_("Move east"))
				self.isMoving = True
				self.stopOnLock = True
				self.diseqccommand("moveEast", 0)
				self.statusMsg(_("Searching east ..."), blinking = True)
			self.updateColors("move")
		elif entry == "finemove":
			self.printMsg(_("Step east"))
			self.diseqccommand("moveEast", 0xFF) # one step
			self.statusMsg(_("Stepped east"), timeout = self.STATUS_MSG_TIMEOUT)
		elif entry == "storage":
			self.printMsg(_("Goto index position"))
			index = int(self.positioner_storage.value)
			self.diseqccommand("moveTo", index)
			self.statusMsg((_("Moved to position at index") + " %2d") % index, timeout = self.STATUS_MSG_TIMEOUT)
		elif entry == "limits":
			self.printMsg(_("Limit east"))
			self.diseqccommand("limitEast")
			self.statusMsg(_("East limit set"), timeout = self.STATUS_MSG_TIMEOUT)
		elif entry == "goto":
			self.printMsg(_("Move to position X"))
			satlon = self.orbitalposition.float
			position = "%5.1f %s" % (satlon, self.orientation.value)
			print>>log, (_("Satellite longitude:") + " %s") % position
			satlon = PositionerSetup.orbital2metric(satlon, self.orientation.value)
			self.statusMsg((_("Moving to position") + " %s") % position, timeout = self.STATUS_MSG_TIMEOUT)
			self.gotoX(satlon)
		elif entry == "tune":
			# Start USALS calibration
			self.printMsg(_("USALS calibration"))
			print>>log, (_("Site latitude") + "      : %5.1f %s") % PositionerSetup.latitude2orbital(self.sitelat)
			print>>log, (_("Site longitude") + "     : %5.1f %s") % PositionerSetup.longitude2orbital(self.sitelon)
			Thread(target = self.gotoXcalibration).start()

	def blueKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.stopMoving()
			else:
				self.printMsg(_("Move east"))
				self.diseqccommand("moveEast", 0)
				self.isMoving = True
				self.statusMsg(_("Moving east ..."), blinking = True)
			self.updateColors("move")
		elif entry == "limits":
			self.printMsg(_("Limits on"))
			self.diseqccommand("limitOn")
			self.statusMsg(_("Limits enabled"), timeout = self.STATUS_MSG_TIMEOUT)
		elif entry == "tune":
			# Start (re-)calculate
			self.session.openWithCallback(self.recalcConfirmed, MessageBox, _("This will (re-)calculate all positions of your rotor and may remove previously memorised positions and fine-tuning!\nAre you sure?"), MessageBox.TYPE_YESNO, default = False, timeout = 10)
		elif entry == "storage":
			if self.advanced:
				self.printMsg(_("Allocate unused memory index"))
				while True:
					if not len(self.allocatedIndices):
						for sat in self.availablesats:
							current_index = int(self.advancedsats[sat].rotorposition.value)
							if current_index not in self.allocatedIndices:
								self.allocatedIndices.append(current_index)
						if len(self.allocatedIndices) == self.rotorPositions:
							self.statusMsg(_("No free index available"), timeout = self.STATUS_MSG_TIMEOUT)
							break
					index = 1
					if len(self.allocatedIndices):
						for i in sorted(self.allocatedIndices):
							if i != index:
								break
							index += 1
					if index <= self.rotorPositions:
						self.positioner_storage.value = index
						self["list"].invalidateCurrent()
						self.allocatedIndices.append(index)
						self.statusMsg((_("Index allocated:") + " %2d") % index, timeout = self.STATUS_MSG_TIMEOUT)
						break
					else:
						self.allocatedIndices = []

	def recalcConfirmed(self, yesno):
		if yesno:
			self.printMsg(_("Calculate all positions"))
			print>>log, (_("Site latitude") + "      : %5.1f %s") % PositionerSetup.latitude2orbital(self.sitelat)
			print>>log, (_("Site longitude") + "     : %5.1f %s") % PositionerSetup.longitude2orbital(self.sitelon)
			lon = self.sitelon
			if lon >= 180:
				lon -= 360
			if lon < -30:	# americas, make unsigned binary west positive polarity
				lon = -lon
			lon = int(round(lon)) & 0xFF
			lat = int(round(self.sitelat)) & 0xFF
			index = int(self.positioner_storage.value) & 0xFF
			self.diseqccommand("calc", (((index << 8) | lon) << 8) | lat)
			self.statusMsg(_("Calculation complete"), timeout = self.STATUS_MSG_TIMEOUT)

	def showLog(self):
		self.session.open(PositionerSetupLog)

	def diseqccommand(self, cmd, param = 0):
		print>>log, "Diseqc(%s, %X)" % (cmd, param)
		self.diseqc.command(cmd, param)
		self.tuner.retune()

	def tune(self, transponder):
		# re-start the update timer
		self.statusTimer.start(self.UPDATE_INTERVAL, True)
		if transponder is not None:
			self.tuner.tune(transponder)
			self.tuningChangedTo(transponder)
		feparm = self.tuner.lastparm.getDVBS()
		orb_pos = feparm.orbital_position
		m = PositionerSetup.satposition2metric(orb_pos)
		self.orbitalposition.value = [int(m[0] / 10), m[0] % 10]
		self.orientation.value = m[1]
		if self.advanced:
			if orb_pos in self.availablesats:
				rotorposition = int(self.advancedsats[orb_pos].rotorposition.value)
				self.positioner_storage.value = rotorposition
				self.allocatedIndices = []
			self.setLNB(self.getLNBfromConfig(orb_pos))

	def isLocked(self):
		return self.frontendStatus.get("tuner_locked", 0) == 1

	def statusMsg(self, msg, blinking = False, timeout = 0):			# timeout in seconds
		self.statusMsgBlinking = blinking
		if not blinking:
			self["status_bar"].visible = True
		self["status_bar"].setText(msg)
		self.statusMsgTimeoutTicks = (timeout * 1000 + self.UPDATE_INTERVAL / 2) / self.UPDATE_INTERVAL

	def updateStatus(self):
		self.statusTimer.start(self.UPDATE_INTERVAL, True)
		if self.frontend:
			self.frontend.getFrontendStatus(self.frontendStatus)
		self["snr_db"].update()
		self["snr_percentage"].update()
		self["ber_value"].update()
		self["snr_bar"].update()
		self["ber_bar"].update()
		self["lock_state"].update()
		if self.statusMsgBlinking:
			self.statusMsgBlinkCount += 1
			if self.statusMsgBlinkCount == self.statusMsgBlinkRate:
				self.statusMsgBlinkCount = 0
				self["status_bar"].visible = not self["status_bar"].visible
		if self.statusMsgTimeoutTicks > 0:
			self.statusMsgTimeoutTicks -= 1
			if self.statusMsgTimeoutTicks == 0:
				self["status_bar"].setText("")
				self.statusMsgBlinking = False
				self["status_bar"].visible = True
		if self.isLocked() and self.isMoving and self.stopOnLock:
			self.stopMoving()
			self.updateColors(self.getCurrentConfigPath())
		if self.collectingStatistics:
			self.low_rate_adapter_count += 1
			if self.low_rate_adapter_count == self.MAX_LOW_RATE_ADAPTER_COUNT:
				self.low_rate_adapter_count = 0
				self.snr_percentage += self["snr_percentage"].getValue(TunerInfo.SNR)
				self.lock_count += self["lock_state"].getValue(TunerInfo.LOCK)
				self.stat_count += 1
				if self.stat_count == self.max_count:
					self.collectingStatistics = False
					count = float(self.stat_count)
					self.lock_count /= count
					self.snr_percentage *= 100.0 / 0x10000 / count
					self.dataAvailable.set()

	def tuningChangedTo(self, tp):

		def setLowRateAdapterCount(symbolrate):
			# change the measurement time and update interval in case of low symbol rate,
			# since more time is needed for the front end in that case.
			# It is an heuristic determination without any pretence. For symbol rates
			# of 5000 the interval is multiplied by 3 until 15000 which is seen
			# as a high symbol rate. Linear interpolation elsewhere.
			return max(int(round((3 - 1) * (symbolrate - 15000) / (5000 - 15000) + 1)), 1)

		self.symbolrate = tp[1]
		self.polarisation = tp[2]
		self.MAX_LOW_RATE_ADAPTER_COUNT = setLowRateAdapterCount(self.symbolrate)
		transponderdata = ConvertToHumanReadable(self.tuner.getTransponderData(), "DVB-S")
		self["frequency_value"].setText(str(transponderdata.get("frequency")))
		self["symbolrate_value"].setText(str(transponderdata.get("symbol_rate")))
		self["fec_value"].setText(str(transponderdata.get("fec_inner")))
		self["polarisation"].setText(str(transponderdata.get("polarization")))
	
	@staticmethod
	def rotorCmd2Step(rotorCmd, stepsize):
		return round(float(rotorCmd & 0xFFF) / 0x10 / stepsize) * (1 - ((rotorCmd & 0x1000) >> 11))

	@staticmethod
	def gotoXcalc(satlon, sitelat, sitelon):
		def azimuth2Rotorcode(angle):
			gotoXtable = (0x00, 0x02, 0x03, 0x05, 0x06, 0x08, 0x0A, 0x0B, 0x0D, 0x0E)
			a = int(round(abs(angle) * 10.0))
			return ((a / 10) << 4) + gotoXtable[a % 10]

		satHourAngle = rotor_calc.calcSatHourangle(satlon, sitelat, sitelon)
		if sitelat >= 0: # Northern Hemisphere
			rotorCmd = azimuth2Rotorcode(180 - satHourAngle)
			if satHourAngle <= 180: # the east
				rotorCmd |= 0xE000
			else:					# west
				rotorCmd |= 0xD000
		else: # Southern Hemisphere
			if satHourAngle <= 180: # the east
				rotorCmd = azimuth2Rotorcode(satHourAngle) | 0xD000
			else: # west
				rotorCmd = azimuth2Rotorcode(360 - satHourAngle) | 0xE000
		return rotorCmd

	def gotoX(self, satlon):
		rotorCmd = PositionerSetup.gotoXcalc(satlon, self.sitelat, self.sitelon)
		self.diseqccommand("gotoX", rotorCmd)
		x = PositionerSetup.rotorCmd2Step(rotorCmd, self.tuningstepsize)
		print>>log, (_("Rotor step position:") + " %4d") % x
		return x

	def getTurningspeed(self):
		if self.polarisation == eDVBFrontendParametersSatellite.Polarisation_Horizontal:
			turningspeed = self.turningspeedH
		else:
			turningspeed = self.turningspeedV
		return max(turningspeed, 0.1)

	TURNING_START_STOP_DELAY = 1.600	# seconds
	MAX_SEARCH_ANGLE = 12.0				# degrees
	MAX_FOCUS_ANGLE = 6.0				# degrees
	LOCK_LIMIT = 0.1					# ratio
	MEASURING_TIME = 2.500				# seconds

	def measure(self, time = MEASURING_TIME):	# time in seconds
		self.snr_percentage = 0.0
		self.lock_count = 0.0
		self.stat_count = 0
		self.low_rate_adapter_count = 0
		self.max_count = max(int((time * 1000 + self.UPDATE_INTERVAL / 2)/ self.UPDATE_INTERVAL), 1)
		self.collectingStatistics = True
		self.dataAvailable.clear()
		self.dataAvailable.wait()

	def logMsg(self, msg, timeout = 0):
		self.statusMsg(msg, timeout = timeout)
		self.printMsg(msg)

	def sync(self):
		self.lock_count = 0.0
		n = 0
		while self.lock_count < (1 - self.LOCK_LIMIT) and n < 5:
			self.measure(time = 0.500)
			n += 1
		if self.lock_count < (1 - self.LOCK_LIMIT):
			return False
		return True

	randomGenerator = None
	def randomBool(self):
		if self.randomGenerator is None:
			self.randomGenerator = SystemRandom()
		return self.randomGenerator.random() >= 0.5

	def gotoXcalibration(self):

		def move(x):
			z = self.gotoX(x + satlon)
			time = int(abs(x - prev_pos) / turningspeed + 2 * self.TURNING_START_STOP_DELAY)
			sleep(time * self.MAX_LOW_RATE_ADAPTER_COUNT)
			return z

		def reportlevels(pos, level, lock):
			print>>log, (_("Signal quality") + " %5.1f" + chr(176) + "   : %6.2f") % (pos, level)
			print>>log, (_("Lock ratio") + "     %5.1f" + chr(176) + "   : %6.2f") % (pos, lock)

		def optimise(readings):
			xi = readings.keys()
			yi = map(lambda (x, y) : x, readings.values())
			x0 = sum(map(mul, xi, yi)) / sum(yi)
			xm = xi[yi.index(max(yi))]
			return x0, xm

		def toGeopos(x):
			if x < 0:
				return _("W")
			else:
				return _("E")

		def toGeoposEx(x):
			if x < 0:
				return _("west")
			else:
				return _("east")

		self.logMsg(_("GotoX calibration"))
		satlon = self.orbitalposition.float
		print>>log, (_("Satellite longitude:") + " %5.1f" + chr(176) + " %s") % (satlon, self.orientation.value)
		satlon = PositionerSetup.orbital2metric(satlon, self.orientation.value)
		prev_pos = 0.0						# previous relative position w.r.t. satlon
		turningspeed = self.getTurningspeed()

		x = 0.0								# relative position w.r.t. satlon
		dir = 1
		if self.randomBool():
			dir = -dir
		while abs(x) < self.MAX_SEARCH_ANGLE:
			if self.sync():
				break
			x += (1.0 * dir)						# one degree east/west
			self.statusMsg((_("Searching") + " " + toGeoposEx(dir) + " %2d" + chr(176)) % abs(x), blinking = True)
			move(x)
			prev_pos = x
		else:
			x = 0.0
			dir = -dir
			while abs(x) < self.MAX_SEARCH_ANGLE:
				x += (1.0 * dir)					# one degree east/west
				self.statusMsg((_("Searching") + " " + toGeoposEx(dir) + " %2d" + chr(176)) % abs(x), blinking = True)
				move(x)
				prev_pos = x
				if self.sync():
					break
			else:
				msg = _("Cannot find any signal ..., aborting !")
				self.printMsg(msg)
				self.statusMsg("")
				self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5)
				return
		x = round(x / self.tuningstepsize) * self.tuningstepsize
		move(x)
		prev_pos = x
		measurements = {}
		self.measure()
		print>>log, (_("Initial signal quality") + " %5.1f" + chr(176) + ": %6.2f") % (x, self.snr_percentage)
		print>>log, (_("Initial lock ratio") + "     %5.1f" + chr(176) + ": %6.2f") % (x, self.lock_count)
		measurements[x] = (self.snr_percentage, self.lock_count)

		start_pos = x
		x = 0.0
		dir = 1
		if self.randomBool():
			dir = -dir
		while x < self.MAX_FOCUS_ANGLE:
			x += self.tuningstepsize * dir					# one step east/west
			self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %5.1f" + chr(176)) % abs(x + start_pos), blinking = True)
			move(x + start_pos)
			prev_pos = x + start_pos
			self.measure()
			measurements[x + start_pos] = (self.snr_percentage, self.lock_count)
			reportlevels(x + start_pos, self.snr_percentage, self.lock_count)
			if self.lock_count < self.LOCK_LIMIT:
				break
		else:
			msg = _("Cannot determine") + " " + toGeoposEx(dir) + " " + _("limit ..., aborting !")
			self.printMsg(msg)
			self.statusMsg("")
			self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5)
			return
		x = 0.0
		dir = -dir
		self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %5.1f" + chr(176)) % abs(start_pos), blinking = True)
		move(start_pos)
		prev_pos = start_pos
		if not self.sync():
			msg = _("Sync failure moving back to origin !")
			self.printMsg(msg)
			self.statusMsg("")
			self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5)
			return
		while abs(x) < self.MAX_FOCUS_ANGLE:
			x += self.tuningstepsize * dir					# one step west/east
			self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %5.1f" + chr(176)) % abs(x + start_pos), blinking = True)
			move(x + start_pos)
			prev_pos = x + start_pos
			self.measure()
			measurements[x + start_pos] = (self.snr_percentage, self.lock_count)
			reportlevels(x + start_pos, self.snr_percentage, self.lock_count)
			if self.lock_count < self.LOCK_LIMIT:
				break
		else:
			msg = _("Cannot determine") + " " + toGeoposEx(dir) + " " + _("limit ..., aborting !")
			self.printMsg(msg)
			self.statusMsg("")
			self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5)
			return
		(x0, xm) = optimise(measurements)
		x = move(x0)
		if satlon > 180:
			satlon -= 360
		x0 += satlon
		xm += satlon
		print>>log, (_("Weighted position") + "     : %5.1f" + chr(176) + " %s") % (abs(x0), toGeopos(x0))
		print>>log, (_("Strongest position") + "    : %5.1f" + chr(176) + " %s") % (abs(xm), toGeopos(xm))
		self.logMsg((_("Final position at") + " %5.1f" + chr(176) + " %s / %d; " + _("offset is") + " %4.1f" + chr(176)) % (abs(x0), toGeopos(x0), x, x0 - satlon), timeout = 10)

	def autofocus(self):

		def move(x):
			if x > 0:
				self.diseqccommand("moveEast", (-x) & 0xFF)
			elif x < 0:
				self.diseqccommand("moveWest", x & 0xFF)
			if x != 0:
				time = int(abs(x) * self.tuningstepsize / turningspeed + 2 * self.TURNING_START_STOP_DELAY)
				sleep(time * self.MAX_LOW_RATE_ADAPTER_COUNT)

		def reportlevels(pos, level, lock):
			print>>log, (_("Signal quality") + " [%2d]   : %6.2f") % (pos, level)
			print>>log, (_("Lock ratio") + " [%2d]       : %6.2f") % (pos, lock)

		def optimise(readings):
			xi = readings.keys()
			yi = map(lambda (x, y) : x, readings.values())
			x0 = int(round(sum(map(mul, xi, yi)) / sum(yi)))
			xm = xi[yi.index(max(yi))]
			return x0, xm

		def toGeoposEx(x):
			if x < 0:
				return _("west")
			else:
				return _("east")

		self.logMsg(_("Auto focus commencing ..."))
		turningspeed = self.getTurningspeed()
		measurements = {}
		maxsteps = max(min(round(self.MAX_FOCUS_ANGLE / self.tuningstepsize), 0x1F), 3)
		self.measure()
		print>>log, (_("Initial signal quality:") + " %6.2f") % self.snr_percentage
		print>>log, (_("Initial lock ratio") + "    : %6.2f") % self.lock_count
		if self.lock_count < 1 - self.LOCK_LIMIT:
			msg = _("There is no signal to lock on !")
			self.printMsg(msg)
			self.statusMsg("")
			self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5)
			return
		print>>log, _("Signal OK, proceeding")
		x = 0
		dir = 1
		if self.randomBool():
			dir = -dir
		measurements[x] = (self.snr_percentage, self.lock_count)
		nsteps = 0
		while nsteps < maxsteps:
			x += dir
			self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %2d") % abs(x), blinking = True)
			move(dir) 		# one step
			self.measure()
			measurements[x] = (self.snr_percentage, self.lock_count)
			reportlevels(x, self.snr_percentage, self.lock_count)
			if self.lock_count < self.LOCK_LIMIT:
				break
			nsteps += 1
		else:
			msg = _("Cannot determine") + " " + toGeoposEx(dir) + " " + _("limit ..., aborting !")
			self.printMsg(msg)
			self.statusMsg("")
			self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5)
			return
		dir = -dir
		self.statusMsg(_("Moving") + " " + toGeoposEx(dir) + "  0", blinking = True)
		move(-x)
		if not self.sync():
			msg = _("Sync failure moving back to origin !")
			self.printMsg(msg)
			self.statusMsg("")
			self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5)
			return
		x = 0
		nsteps = 0
		while nsteps < maxsteps:
			x += dir
			self.statusMsg((_("Moving") + " " + toGeoposEx(dir) + " %2d") % abs(x), blinking = True)
			move(dir) 		# one step
			self.measure()
			measurements[x] = (self.snr_percentage, self.lock_count)
			reportlevels(x, self.snr_percentage, self.lock_count)
			if self.lock_count < self.LOCK_LIMIT:
				break
			nsteps += 1
		else:
			msg = _("Cannot determine") + " " + toGeoposEx(dir) + " " + _("limit ..., aborting !")
			self.printMsg(msg)
			self.statusMsg("")
			self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 5)
			return
		(x0, xm) = optimise(measurements)
		print>>log, (_("Weighted position") + "     : %2d") % x0
		print>>log, (_("Strongest position") + "    : %2d") % xm
		self.logMsg((_("Final position at index") + " %2d (%5.1f" + chr(176) + ")") % (x0, x0 * self.tuningstepsize), timeout = 6)
		move(x0 - x)
예제 #35
0
    def statusCallback(self):
        if self.state == 0:
            if self.port_index == 0 and self.diseqc[0] == "3600":
                self.clearNimEntries()
                config.Nims[self.feid].diseqcA.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 1 and self.diseqc[1] == "3600":
                self.clearNimEntries()
                config.Nims[self.feid].diseqcB.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 2 and self.diseqc[2] == "3600":
                self.clearNimEntries()
                config.Nims[self.feid].diseqcC.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 3 and self.diseqc[3] == "3600":
                self.clearNimEntries()
                config.Nims[self.feid].diseqcD.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])

            if self.nr_of_ports == 4:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b_c_d"
            elif self.nr_of_ports == 2:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b"
            else:
                config.Nims[self.feid].diseqcMode.value = "single"
                if self.sat_frequencies[self.index][
                        self.SAT_TABLE_ORBPOS] == 360 and not self.found_sats:
                    config.Nims[
                        self.feid].simpleDiSEqCSetCircularLNB.value = True
                    self.circular_setup = True

            config.Nims[self.feid].configMode.value = "simple"
            config.Nims[
                self.feid].simpleDiSEqCSetVoltageTone = self.simple_tone
            config.Nims[
                self.feid].simpleDiSEqCOnlyOnSatChange = self.simple_sat_change

            self.saveAndReloadNimConfig()
            self.state += 1

        elif self.state == 1:
            if self.diseqc[self.port_index] != "3600":
                self.statusTimer.stop()
                self.count = 0
                self.state = 0
                self.index = len(self.sat_frequencies) - 1
                self.tunerStopScan(False)
                return

            if self.circular_setup:
                if self.raw_channel:
                    self.raw_channel.receivedTsidOnid.get().remove(
                        self.gotTsidOnid)
                del self.frontend
                del self.raw_channel
                if not self.openFrontend():
                    self.frontend = None
                    self.raw_channel = None
                if self.raw_channel:
                    self.raw_channel.receivedTsidOnid.get().append(
                        self.gotTsidOnid)

            InitNimManager(nimmanager)

            self.tuner = Tuner(self.frontend)
            if self.raw_channel:
                self.raw_channel.requestTsidOnid()
            self.tuner.tune(self.sat_frequencies[self.index])

            self["statusbar"].setText(
                _("Checking tuner %s\nDiSEqC port %s for %s") %
                (chr(self.feid + 65), self.diseqc_ports[self.port_index],
                 self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
            self["tunerstatusbar"].setText(" ")

            self.count = 0
            self.state = 0

            self.startTunerStatusTimer()
            return

        self.startStatusTimer()
예제 #36
0
class Satfinder(ScanSetup, ServiceScan):
	def __init__(self, session):
		self.initcomplete = False
		service = session and session.nav.getCurrentService()
		feinfo = service and service.frontendInfo()
		self.frontendData = feinfo and feinfo.getAll(True)
		del feinfo
		del service

		self.typeOfTuningEntry = None
		self.systemEntry = None
		self.satfinderTunerEntry = None
		self.satEntry = None
		self.typeOfInputEntry = None

		ScanSetup.__init__(self, session)
		self.setTitle(_("Satfinder"))
		self["introduction"].setText(_("Press OK to scan"))
		self["Frontend"] = FrontendStatus(frontend_source = lambda : self.frontend, update_interval = 100)

		self["actions"] = ActionMap(["SetupActions", "ColorActions"],
		{
			"save": self.keyGoScan,
			"ok": self.keyGoScan,
			"cancel": self.keyCancel,
		}, -3)

		self.initcomplete = True
		self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.onClose.append(self.__onClose)
		self.onShow.append(self.prepareFrontend)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
		return False

	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)

	def __onClose(self):
		self.session.nav.playService(self.session.postScanService)

	def newConfig(self):
		cur = self["config"].getCurrent()
		if cur in (self.typeOfTuningEntry, self.systemEntry, self.typeOfInputEntry):
			self.createSetup()
		elif cur == self.satfinderTunerEntry:
			self.feid = int(self.satfinder_scan_nims.value)
			self.createSetup()
			self.prepareFrontend()
			if self.frontend == None:
				msg = _("Tuner not available.")
				if self.session.nav.RecordTimer.isRecording():
					msg += _("\nRecording in progress.")
				self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR)
		elif cur == self.satEntry:
			self.createSetup()
		else:
			self.retune(None)

	def createSetup(self):
		self.list = []
		self.satfinderTunerEntry = getConfigListEntry(_("Tuner"), self.satfinder_scan_nims)
		self.list.append(self.satfinderTunerEntry)
		if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"):
			self.tuning_sat = self.scan_satselection[self.getSelectedSatIndex(self.feid)]
			self.satEntry = getConfigListEntry(_('Satellite'), self.tuning_sat)
			self.list.append(self.satEntry)
			self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type)
			if len(nimmanager.getTransponders(int(self.tuning_sat.value))) < 1: # Only offer 'predefined transponder' if some transponders exist
				self.tuning_type.value = "single_transponder"
			else:
				self.list.append(self.typeOfTuningEntry)

			nim = nimmanager.nim_slots[self.feid]

			if self.tuning_type.value == "single_transponder":
				if nim.isCompatible("DVB-S2"):
					self.systemEntry = getConfigListEntry(_('System'), self.scan_sat.system)
					self.list.append(self.systemEntry)
				else:
					# downgrade to dvb-s, in case a -s2 config was active
					self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S
				self.list.append(getConfigListEntry(_('Frequency'), self.scan_sat.frequency))
				self.list.append(getConfigListEntry(_('Polarization'), self.scan_sat.polarization))
				self.list.append(getConfigListEntry(_('Symbol rate'), self.scan_sat.symbolrate))
				self.list.append(getConfigListEntry(_('Inversion'), self.scan_sat.inversion))
				if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
					self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec))
				elif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
					self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
					self.modulationEntry = getConfigListEntry(_('Modulation'), self.scan_sat.modulation)
					self.list.append(self.modulationEntry)
					self.list.append(getConfigListEntry(_('Roll-off'), self.scan_sat.rolloff))
					self.list.append(getConfigListEntry(_('Pilot'), self.scan_sat.pilot))
					self.list.append(getConfigListEntry(_('Input Stream ID'), self.scan_sat.is_id))
					self.list.append(getConfigListEntry(_("PLS Mode"), self.scan_sat.pls_mode))
					self.list.append(getConfigListEntry(_('PLS Code'), self.scan_sat.pls_code))
			elif self.tuning_type.value == "predefined_transponder":
				self.updatePreDefTransponders()
				self.list.append(getConfigListEntry(_("Transponder"), self.preDefTransponders))
		elif nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-C"):
			self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type)
			if config.Nims[self.feid].cable.scan_type.value != "provider" or len(nimmanager.getTranspondersCable(int(self.satfinder_scan_nims.value))) < 1: # only show 'predefined transponder' if in provider mode and transponders exist
				self.tuning_type.value = "single_transponder"
			else:
				self.list.append(self.typeOfTuningEntry)
			if self.tuning_type.value == "single_transponder":
				self.list.append(getConfigListEntry(_("Frequency"), self.scan_cab.frequency))
				self.list.append(getConfigListEntry(_("Inversion"), self.scan_cab.inversion))
				self.list.append(getConfigListEntry(_("Symbol rate"), self.scan_cab.symbolrate))
				self.list.append(getConfigListEntry(_("Modulation"), self.scan_cab.modulation))
				self.list.append(getConfigListEntry(_("FEC"), self.scan_cab.fec))
			elif self.tuning_type.value == "predefined_transponder":
				self.scan_nims.value = self.satfinder_scan_nims.value
				self.predefinedCabTranspondersList()
				self.list.append(getConfigListEntry(_('Transponder'), self.CableTransponders))
		elif nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T"):
			self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type)
			region = nimmanager.getTerrestrialDescription(int(self.satfinder_scan_nims.value))
			if len(nimmanager.getTranspondersTerrestrial(region)) < 1: # Only offer 'predefined transponder' if some transponders exist
				self.tuning_type.value = "single_transponder"
			else:
				self.list.append(self.typeOfTuningEntry)
			if self.tuning_type.value == "single_transponder":
				if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T2"):
					self.systemEntryTerr = getConfigListEntry(_('System'), self.scan_ter.system)
					self.list.append(self.systemEntryTerr)
				else:
					self.scan_ter.system.value = eDVBFrontendParametersTerrestrial.System_DVB_T
				self.typeOfInputEntry = getConfigListEntry(_("Use frequency or channel"), self.scan_input_as)
				if self.ter_channel_input:
					self.list.append(self.typeOfInputEntry)
				else:
					self.scan_input_as.value = self.scan_input_as.choices[0]
				if self.ter_channel_input and self.scan_input_as.value == "channel":
					channel = getChannelNumber(self.scan_ter.frequency.value*1000, self.ter_tnumber)
					if channel:
						self.scan_ter.channel.value = int(channel.replace("+","").replace("-",""))
					self.list.append(getConfigListEntry(_("Channel"), self.scan_ter.channel))
				else:
					prev_val = self.scan_ter.frequency.value
					self.scan_ter.frequency.value = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)/1000
					if self.scan_ter.frequency.value == 474000:
						self.scan_ter.frequency.value = prev_val
					self.list.append(getConfigListEntry(_("Frequency"), self.scan_ter.frequency))
				self.list.append(getConfigListEntry(_("Inversion"), self.scan_ter.inversion))
				self.list.append(getConfigListEntry(_("Bandwidth"), self.scan_ter.bandwidth))
				self.list.append(getConfigListEntry(_("Code rate HP"), self.scan_ter.fechigh))
				self.list.append(getConfigListEntry(_("Code rate LP"), self.scan_ter.feclow))
				self.list.append(getConfigListEntry(_("Modulation"), self.scan_ter.modulation))
				self.list.append(getConfigListEntry(_("Transmission mode"), self.scan_ter.transmission))
				self.list.append(getConfigListEntry(_("Guard interval"), self.scan_ter.guard))
				self.list.append(getConfigListEntry(_("Hierarchy info"), self.scan_ter.hierarchy))
				if self.scan_ter.system.value == eDVBFrontendParametersTerrestrial.System_DVB_T2:
					self.list.append(getConfigListEntry(_('PLP ID'), self.scan_ter.plp_id))
			elif self.tuning_type.value == "predefined_transponder":
				self.scan_nims.value = self.satfinder_scan_nims.value
				self.predefinedTerrTranspondersList()
				self.list.append(getConfigListEntry(_('Transponder'), self.TerrestrialTransponders))
		self.retune(None)
		self["config"].list = self.list
		self["config"].l.setList(self.list)

	def createConfig(self, foo):
		self.tuning_type = ConfigSelection(default = "predefined_transponder", choices = [("single_transponder", _("User defined transponder")), ("predefined_transponder", _("Predefined transponder"))])
		self.orbital_position = 192
		if self.frontendData and self.frontendData.has_key('orbital_position'):
			self.orbital_position = self.frontendData['orbital_position']
		ScanSetup.createConfig(self, self.frontendData)

		for x in (self.scan_sat.frequency,
			self.scan_sat.inversion, self.scan_sat.symbolrate,
			self.scan_sat.polarization, self.scan_sat.fec, self.scan_sat.pilot,
			self.scan_sat.fec_s2, self.scan_sat.fec, self.scan_sat.modulation,
			self.scan_sat.rolloff, self.scan_sat.system, self.scan_sat.is_id, self.scan_sat.pls_mode, self.scan_sat.pls_code,
			self.scan_ter.channel, self.scan_ter.frequency, self.scan_ter.inversion,
			self.scan_ter.bandwidth, self.scan_ter.fechigh, self.scan_ter.feclow,
			self.scan_ter.modulation, self.scan_ter.transmission,
			self.scan_ter.guard, self.scan_ter.hierarchy, self.scan_ter.plp_id,
			self.scan_cab.frequency, self.scan_cab.inversion, self.scan_cab.symbolrate,
			self.scan_cab.modulation, self.scan_cab.fec):
			x.addNotifier(self.retune, initial_call = False)

		satfinder_nim_list = []
		for n in nimmanager.nim_slots:
			if not (n.isCompatible("DVB-S") or n.isCompatible("DVB-T") or n.isCompatible("DVB-C")):
				continue
			if n.config_mode  in ("loopthrough", "satposdepends", "nothing"):
				continue
			if n.isCompatible("DVB-S") and n.config_mode == "advanced" and len(nimmanager.getSatListForNim(n.slot)) < 1:
				continue
			satfinder_nim_list.append((str(n.slot), n.friendly_full_description))
		self.satfinder_scan_nims = ConfigSelection(choices = satfinder_nim_list)
		if self.frontendData is not None and len(satfinder_nim_list) > 0: # open the plugin with the currently active NIM as default
			self.satfinder_scan_nims.setValue(str(self.frontendData.get("tuner_number", satfinder_nim_list[0][0])))

		self.feid = int(self.satfinder_scan_nims.value)

		self.satList = []
		self.scan_satselection = []
		for slot in nimmanager.nim_slots:
			if slot.isCompatible("DVB-S"):
				self.satList.append(nimmanager.getSatListForNim(slot.slot))
				self.scan_satselection.append(getConfigSatlist(self.orbital_position, self.satList[slot.slot]))
			else:
				self.satList.append(None)

		if self.frontendData:
			ttype = self.frontendData.get("tuner_type", "UNKNOWN")
			if ttype == "DVB-S" and self.predefinedTranspondersList(self.getSelectedSatIndex(self.feid)) is None and len(nimmanager.getTransponders(self.getSelectedSatIndex(self.feid))) > 0:
				self.tuning_type.value = "single_transponder"
			elif ttype == "DVB-T" and self.predefinedTerrTranspondersList() is None and len(nimmanager.getTranspondersTerrestrial(nimmanager.getTerrestrialDescription(self.feid))) > 0:
				self.tuning_type.value = "single_transponder"
			elif ttype == "DVB-C" and self.predefinedCabTranspondersList() is None and len(nimmanager.getTranspondersCable(self.feid)) > 0:
				self.tuning_type.value = "single_transponder"

	def getSelectedSatIndex(self, v):
		index    = 0
		none_cnt = 0
		for n in self.satList:
			if self.satList[index] is None:
				none_cnt += 1
			if index == int(v):
				return index-none_cnt
			index += 1
		return -1

	def updatePreDefTransponders(self):
		ScanSetup.predefinedTranspondersList(self, self.tuning_sat.orbital_position)

	def retuneCab(self, configElement):
		if not nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-C"):
			return
		if self.initcomplete:
			if self.tuning_type.value == "single_transponder":
				transponder = (
					self.scan_cab.frequency.value*1000,
					self.scan_cab.symbolrate.value*1000,
					self.scan_cab.modulation.value,
					self.scan_cab.fec.value,
					self.scan_cab.inversion.value
				)
				if self.initcomplete:
					self.tuner.tuneCab(transponder)
				self.transponder = transponder
			elif self.tuning_type.value == "predefined_transponder":
				tps = nimmanager.getTranspondersCable(int(self.satfinder_scan_nims.value))
				if len(tps) > self.CableTransponders.index :
					tp = tps[self.CableTransponders.index]
					# tp = 0 transponder type, 1 freq, 2 sym, 3 mod, 4 fec, 5 inv, 6 sys
					transponder = (tp[1], tp[2], tp[3], tp[4], tp[5])
					if self.initcomplete:
						self.tuner.tuneCab(transponder)
					self.transponder = transponder

	def retuneTerr(self, configElement):
		if not nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T"):
			return self.retuneCab(configElement)
		if self.initcomplete:
			if self.scan_input_as.value == "channel":
				frequency = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)
			else:
				frequency = self.scan_ter.frequency.value * 1000
			if self.tuning_type.value == "single_transponder":
				transponder = [
					2, #TERRESTRIAL
					frequency,
					self.scan_ter.bandwidth.value,
					self.scan_ter.modulation.value,
					self.scan_ter.fechigh.value,
					self.scan_ter.feclow.value,
					self.scan_ter.guard.value,
					self.scan_ter.transmission.value,
					self.scan_ter.hierarchy.value,
					self.scan_ter.inversion.value,
					self.scan_ter.system.value,
					self.scan_ter.plp_id.value]
				if self.initcomplete:
					self.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])
				self.transponder = transponder
			elif self.tuning_type.value == "predefined_transponder":
				region = nimmanager.getTerrestrialDescription(int(self.satfinder_scan_nims.value))
				tps = nimmanager.getTranspondersTerrestrial(region)
				if len(tps) > self.TerrestrialTransponders.index :
					transponder = tps[self.TerrestrialTransponders.index]
					# frequency 1, inversion 9, bandwidth 2, fechigh 4, feclow 5, modulation 3, transmission 7, guard 6, hierarchy 8, system 10, plp_id 11
					if self.initcomplete:
						self.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])
					self.transponder = transponder

	def retune(self, configElement): # satellite
		if not nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"):
			return self.retuneTerr(configElement)
		if not self.tuning_sat.value:
			return
		satpos = int(self.tuning_sat.value)
		if self.tuning_type.value == "single_transponder":
			if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
				fec = self.scan_sat.fec_s2.value
			else:
				fec = self.scan_sat.fec.value
			transponder = (
				self.scan_sat.frequency.value,
				self.scan_sat.symbolrate.value,
				self.scan_sat.polarization.value,
				fec,
				self.scan_sat.inversion.value,
				satpos,
				self.scan_sat.system.value,
				self.scan_sat.modulation.value,
				self.scan_sat.rolloff.value,
				self.scan_sat.pilot.value,
				self.scan_sat.is_id.value,
				self.scan_sat.pls_mode.value,
				self.scan_sat.pls_code.value)
			if self.initcomplete:
				self.tuner.tune(transponder)
			self.transponder = transponder
		elif self.tuning_type.value == "predefined_transponder":
			tps = nimmanager.getTransponders(satpos)
			if len(tps) > self.preDefTransponders.index:
				tp = tps[self.preDefTransponders.index]
				transponder = (tp[1] / 1000, tp[2] / 1000,
					tp[3], tp[4], 2, satpos, tp[5], tp[6], tp[8], tp[9], tp[10], tp[11], tp[12])
				if self.initcomplete:
					self.tuner.tune(transponder)
				self.transponder = transponder

	def keyGoScan(self):
		self.frontend = None
		if self.raw_channel:
			del(self.raw_channel)
		tlist = []
		if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"):
			self.addSatTransponder(tlist,
				self.transponder[0], # frequency
				self.transponder[1], # sr
				self.transponder[2], # pol
				self.transponder[3], # fec
				self.transponder[4], # inversion
				self.tuning_sat.orbital_position,
				self.transponder[6], # system
				self.transponder[7], # modulation
				self.transponder[8], # rolloff
				self.transponder[9], # pilot
				self.transponder[10],# input stream id
				self.transponder[11],# pls mode
				self.transponder[12] # pls mode
			)
		elif nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T"):
			parm = buildTerTransponder(
				self.transponder[1],  # frequency
				self.transponder[9],  # inversion
				self.transponder[2],  # bandwidth
				self.transponder[4],  # fechigh
				self.transponder[5],  # feclow
				self.transponder[3],  # modulation
				self.transponder[7],  # transmission
				self.transponder[6],  # guard
				self.transponder[8],  # hierarchy
				self.transponder[10], # system
				self.transponder[11]  # plp_id
			)
			tlist.append(parm)
		else: # DVB-C
			self.addCabTransponder(tlist,
				self.transponder[0], # frequency
				self.transponder[1], # sr
				self.transponder[2], # modulation
				self.transponder[3], # fec_inner
				self.transponder[4]  # inversion
			)
		self.startScan(tlist, self.feid)

	def startScan(self, tlist, feid):
		flags = 0
		networkid = 0
		self.session.openWithCallback(self.startScanCallback, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])

	def startScanCallback(self, answer=None):
		if answer:
			self.doCloseRecursive()

	def keyCancel(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			del self.raw_channel
		self.close(False)

	def doCloseRecursive(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			del self.raw_channel
		self.close(True)
예제 #37
0
class AutoDiseqc(Screen, ConfigListScreen):
	diseqc_ports = [
		"A", "B", "C", "D"
	]

	sat_frequencies = [
		# astra 282 EPG Background Radio
		( 
			11778,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Vertical,
			eDVBFrontendParametersSatellite.FEC_2_3,
			eDVBFrontendParametersSatellite.Inversion_Off,
			282,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			2004,
			2,
			"Astra 2 28.2e"),

		# astra 235 astra ses
		( 
			12168,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Vertical,
			eDVBFrontendParametersSatellite.FEC_3_4,
			eDVBFrontendParametersSatellite.Inversion_Off,
			235,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			3224,
			3,
			"Astra 3 23.5e"),

		# astra 192 zdf
		( 
			11953,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Horizontal,
			eDVBFrontendParametersSatellite.FEC_3_4,
			eDVBFrontendParametersSatellite.Inversion_Off,
			192,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			1079,
			1,
			"Astra 1 19.2e"),

		# hotbird 130 rai
		(
			10992,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Vertical,
			eDVBFrontendParametersSatellite.FEC_2_3,
			eDVBFrontendParametersSatellite.Inversion_Off,
			130,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			12400,
			318,
			"Hotbird 13.0e"),
	]

	SAT_TABLE_FREQUENCY = 0
	SAT_TABLE_SYMBOLRATE = 1
	SAT_TABLE_POLARISATION = 2
	SAT_TABLE_FEC = 3
	SAT_TABLE_INVERSION = 4
	SAT_TABLE_ORBPOS = 5
	SAT_TABLE_SYSTEM = 6
	SAT_TABLE_MODULATION = 7
	SAT_TABLE_ROLLOFF = 8
	SAT_TABLE_PILOT = 9
	SAT_TABLE_TSID = 10
	SAT_TABLE_ONID = 11
	SAT_TABLE_NAME = 12

	def __init__(self, session, feid, nr_of_ports, simple_tone, simple_sat_change):
		Screen.__init__(self, session)

		self["statusbar"] = StaticText(" ")
		self["tunerstatusbar"] = StaticText(" ")

		self.list = []
		ConfigListScreen.__init__(self, self.list, session = self.session)

		self["config"].list = self.list
		self["config"].l.setList(self.list)

		self["key_red"] = StaticText(_("Abort"))

		self.index = 0
		self.port_index = 0
		self.feid = feid
		self.nr_of_ports = nr_of_ports
		self.simple_tone = simple_tone
		self.simple_sat_change = simple_sat_change
		self.found_sats = []

		if not self.openFrontend():
			self.oldref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					if hasattr(self.session, 'infobar'):
						if self.session.infobar.servicelist and self.session.infobar.servicelist.dopipzap:
							self.session.infobar.servicelist.togglePipzap()
					if hasattr(self.session, 'pip'):
						del self.session.pip
					self.session.pipshown = False
				if not self.openFrontend():
					self.frontend = None
					self.raw_channel = None

		if self.raw_channel:
			self.raw_channel.receivedTsidOnid.get().append(self.gotTsidOnid)

		self["actions"] = ActionMap(["SetupActions"],
		{
			"cancel": self.keyCancel,
		}, -2)

		self.count = 0
		self.state = 0
		self.abort = False

		self.statusTimer = eTimer()
		self.statusTimer.callback.append(self.statusCallback)
		self.tunerStatusTimer = eTimer()
		self.tunerStatusTimer.callback.append(self.tunerStatusCallback)
		self.startStatusTimer()
		self.onClose.append(self.__onClose)

	def __onClose(self):
		if self.raw_channel:
			self.raw_channel.receivedTsidOnid.get().remove(self.gotTsidOnid)

	def keyCancel(self):
		self.abort = True

	def keyOK(self):
		return

	def keyLeft(self):
		return

	def keyRight(self):
		return

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
		return False

	def statusCallback(self):
		if self.state == 0:
			if self.port_index == 0:
				self.clearNimEntries()
				config.Nims[self.feid].diseqcA.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
			elif self.port_index == 1:
				self.clearNimEntries()
				config.Nims[self.feid].diseqcB.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
			elif self.port_index == 2:
				self.clearNimEntries()
				config.Nims[self.feid].diseqcC.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
			elif self.port_index == 3:
				self.clearNimEntries()
				config.Nims[self.feid].diseqcD.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])

			if self.nr_of_ports == 4:
				config.Nims[self.feid].diseqcMode.value = "diseqc_a_b_c_d"
			elif self.nr_of_ports == 2:
				config.Nims[self.feid].diseqcMode.value = "diseqc_a_b"
			else:
				config.Nims[self.feid].diseqcMode.value = "single"

			config.Nims[self.feid].configMode.value = "simple"
			config.Nims[self.feid].simpleDiSEqCSetVoltageTone = self.simple_tone
			config.Nims[self.feid].simpleDiSEqCOnlyOnSatChange = self.simple_sat_change

			self.saveAndReloadNimConfig()
			self.state += 1

		elif self.state == 1:
			InitNimManager(nimmanager)

			self.tuner = Tuner(self.frontend)
			if self.raw_channel:
				self.raw_channel.requestTsidOnid()
			self.tuner.tune(self.sat_frequencies[self.index])

			self["statusbar"].setText(_("Checking tuner %s\nDiSEqC port %s for %s") % (chr(self.feid+65), self.diseqc_ports[self.port_index], self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
			self["tunerstatusbar"].setText(" ")

			self.count = 0
			self.state = 0

			self.startTunerStatusTimer()
			return

		self.startStatusTimer()

	def startStatusTimer(self):
		self.statusTimer.start(100, True)

	def setupSave(self):
		self.clearNimEntries()
		for x in self.found_sats:
			if x[0] == "A":
				config.Nims[self.feid].diseqcA.value = "%d" % (x[1])
			elif x[0] == "B":
				config.Nims[self.feid].diseqcB.value = "%d" % (x[1])
			elif x[0] == "C":
				config.Nims[self.feid].diseqcC.value = "%d" % (x[1])
			elif x[0] == "D":
				config.Nims[self.feid].diseqcD.value = "%d" % (x[1])
		self.saveAndReloadNimConfig()

	def setupClear(self):
		self.clearNimEntries()
		self.saveAndReloadNimConfig()

	def clearNimEntries(self):
		config.Nims[self.feid].diseqcA.value = "3601"
		config.Nims[self.feid].diseqcB.value = "3601"
		config.Nims[self.feid].diseqcC.value = "3601"
		config.Nims[self.feid].diseqcD.value = "3601"

	def saveAndReloadNimConfig(self):
		config.Nims[self.feid].save()
		configfile.save()
		configfile.load()
		nimmanager.sec.update()

	def tunerStatusCallback(self):
		dict = {}
		if self.frontend:
			self.frontend.getFrontendStatus(dict)
		else:
			self.tunerStopScan(False)
			return

		if dict["tuner_state"] == "TUNING":
			self["tunerstatusbar"].setText(_("Tuner status:") + " " + _("TUNING"))
		elif dict["tuner_state"] == "LOCKED":
			self["tunerstatusbar"].setText(_("Tuner status:") + " " + _("ACQUIRING TSID/ONID"))

		elif dict["tuner_state"] == "LOSTLOCK" or dict["tuner_state"] == "FAILED":
			self["tunerstatusbar"].setText(_("Tuner status:") + " " + _("FAILED"))
			self.tunerStopScan(False)
			return

		self.count += 1
		if self.count > 15:
			self.startStatusTimer()
		else:
			self.startTunerStatusTimer()

	def startTunerStatusTimer(self):
		self.tunerStatusTimer.start(2000, True)

	def gotTsidOnid(self, tsid, onid):
		self.tunerStatusTimer.stop()
		if tsid == self.sat_frequencies[self.index][self.SAT_TABLE_TSID] and onid == self.sat_frequencies[self.index][self.SAT_TABLE_ONID]:
			self.tunerStopScan(True)
		else:
			self.tunerStopScan(False)

	def tunerStopScan(self, result):
		if self.abort:
			self.setupClear()
			self.close(False)
			return
		if result:
			self.found_sats.append((self.diseqc_ports[self.port_index], self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS], self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
			self.index = 0
			self.port_index += 1
		else:
			self.index += 1
			if len(self.sat_frequencies) == self.index:
				self.index = 0
				self.port_index += 1

		if len(self.found_sats) > 0:
			self.list = []
			for x in self.found_sats:
				self.list.append(getConfigListEntry((_("DiSEqC port %s: %s") % (x[0], x[2]))))
			self["config"].l.setList(self.list)

		if self.nr_of_ports == self.port_index:
			self.state = 99
			self.setupSave()
			self.close(len(self.found_sats) > 0)
			return

		for x in self.found_sats:
			if x[1] == self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS]:
				self.tunerStopScan(False)
				return

		self.startStatusTimer()
예제 #38
0
class PositionerSetup(Screen):
    skin = """
		<screen position="100,100" size="560,400" title="Positioner setup..." >
			<widget name="list" position="100,0" size="350,155" />

			<widget name="red" position="0,155" size="140,80" backgroundColor="red" halign="center" valign="center" font="Regular;21" />
			<widget name="green" position="140,155" size="140,80" backgroundColor="green" halign="center" valign="center" font="Regular;21" />
			<widget name="yellow" position="280,155" size="140,80" backgroundColor="yellow" halign="center" valign="center" font="Regular;21" />
			<widget name="blue" position="420,155" size="140,80" backgroundColor="blue" halign="center" valign="center" font="Regular;21" />

			<widget name="snr_db" position="60,245" size="150,22" halign="center" valign="center" font="Regular;21" />
			<eLabel text="SNR:" position="0,270" size="60,22" font="Regular;21" />
			<eLabel text="BER:" position="0,295" size="60,22" font="Regular;21" />
			<eLabel text="Lock:" position="0,320" size="60,22" font="Regular;21" />
			<widget name="snr_percentage" position="220,270" size="60,22" font="Regular;21" />
			<widget name="ber_value" position="220,295" size="60,22" font="Regular;21" />
			<widget name="lock_state" position="60,320" size="150,22" font="Regular;21" />
			<widget name="snr_bar" position="60,270" size="150,22" />
			<widget name="ber_bar" position="60,295" size="150,22" />

			<eLabel text="Frequency:" position="300,245" size="120,22" font="Regular;21" />
			<eLabel text="Symbolrate:" position="300,270" size="120,22" font="Regular;21" />
			<eLabel text="FEC:" position="300,295" size="120,22" font="Regular;21" />
			<widget name="frequency_value" position="420,245" size="120,22" font="Regular;21" />
			<widget name="symbolrate_value" position="420,270" size="120,22" font="Regular;21" />
			<widget name="fec_value" position="420,295" size="120,22" font="Regular;21" />
		</screen>"""

    def __init__(self, session, feid):
        self.skin = PositionerSetup.skin
        Screen.__init__(self, session)
        self.feid = feid
        self.oldref = None

        cur = {}
        if not self.openFrontend():
            self.oldref = session.nav.getCurrentlyPlayingServiceReference()
            service = session.nav.getCurrentService()
            feInfo = service and service.frontendInfo()
            if feInfo:
                cur = feInfo.getTransponderData(True)
            del feInfo
            del service
            session.nav.stopService()  # try to disable foreground service
            if not self.openFrontend():
                if session.pipshown:  # try to disable pip
                    service = self.session.pip.pipservice
                    feInfo = service and service.frontendInfo()
                    if feInfo:
                        cur = feInfo.getTransponderData()
                    del feInfo
                    del service
                    session.pipshown = False
                    del session.pip
                    if not self.openFrontend():
                        self.frontend = None  # in normal case this should not happen

        self.frontendStatus = {}
        self.diseqc = Diseqc(self.frontend)
        self.tuner = Tuner(self.frontend)

        tp = (cur.get("frequency", 0) / 1000, cur.get("symbol_rate", 0) / 1000,
              cur.get("polarization",
                      eDVBFrontendParametersSatellite.Polarisation_Horizontal),
              cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto),
              cur.get("inversion",
                      eDVBFrontendParametersSatellite.Inversion_Unknown),
              cur.get("orbital_position", 0),
              cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S),
              cur.get("modulation",
                      eDVBFrontendParametersSatellite.Modulation_QPSK),
              cur.get("rolloff",
                      eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
              cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown))

        self.tuner.tune(tp)
        self.createConfig()

        self.isMoving = False
        self.stopOnLock = False

        self.red = Label("")
        self["red"] = self.red
        self.green = Label("")
        self["green"] = self.green
        self.yellow = Label("")
        self["yellow"] = self.yellow
        self.blue = Label("")
        self["blue"] = self.blue

        self.list = []
        self["list"] = ConfigList(self.list)
        self.createSetup()

        self["snr_db"] = TunerInfo(TunerInfo.SNR_DB,
                                   statusDict=self.frontendStatus)
        self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE,
                                           statusDict=self.frontendStatus)
        self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE,
                                      statusDict=self.frontendStatus)
        self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR,
                                    statusDict=self.frontendStatus)
        self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR,
                                    statusDict=self.frontendStatus)
        self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE,
                                       statusDict=self.frontendStatus)

        self["frequency_value"] = Label("")
        self["symbolrate_value"] = Label("")
        self["fec_value"] = Label("")

        self["actions"] = ActionMap(
            ["DirectionActions", "OkCancelActions", "ColorActions"], {
                "ok": self.go,
                "cancel": self.keyCancel,
                "up": self.up,
                "down": self.down,
                "left": self.left,
                "right": self.right,
                "red": self.redKey,
                "green": self.greenKey,
                "yellow": self.yellowKey,
                "blue": self.blueKey,
            }, -1)

        self.updateColors("tune")

        self.statusTimer = eTimer()
        self.statusTimer.callback.append(self.updateStatus)
        self.statusTimer.start(50, True)
        self.onClose.append(self.__onClose)

    def __onClose(self):
        self.session.nav.playService(self.oldref)

    def restartPrevService(self, yesno):
        if yesno:
            if self.frontend:
                self.frontend = None
                del self.raw_channel
        else:
            self.oldref = None
        self.close(None)

    def keyCancel(self):
        if self.oldref:
            self.session.openWithCallback(
                self.restartPrevService, MessageBox,
                _("Zap back to service before positioner setup?"),
                MessageBox.TYPE_YESNO)
        else:
            self.restartPrevService(False)

    def openFrontend(self):
        res_mgr = eDVBResourceManager.getInstance()
        if res_mgr:
            self.raw_channel = res_mgr.allocateRawChannel(self.feid)
            if self.raw_channel:
                self.frontend = self.raw_channel.getFrontend()
                if self.frontend:
                    return True
                else:
                    print "getFrontend failed"
            else:
                print "getRawChannel failed"
        else:
            print "getResourceManager instance failed"
        return False

    def createConfig(self):
        self.positioner_tune = ConfigNothing()
        self.positioner_move = ConfigNothing()
        self.positioner_finemove = ConfigNothing()
        self.positioner_limits = ConfigNothing()
        self.positioner_goto0 = ConfigNothing()
        storepos = []
        for x in range(1, 255):
            storepos.append(str(x))
        self.positioner_storage = ConfigSelection(choices=storepos)

    def createSetup(self):
        self.list.append((_("Tune"), self.positioner_tune, "tune"))
        self.list.append(
            (_("Positioner movement"), self.positioner_move, "move"))
        self.list.append((_("Positioner fine movement"),
                          self.positioner_finemove, "finemove"))
        self.list.append((_("Set limits"), self.positioner_limits, "limits"))
        self.list.append(
            (_("Positioner storage"), self.positioner_storage, "storage"))
        self.list.append((_("Goto 0"), self.positioner_goto0, "goto0"))
        self["list"].l.setList(self.list)

    def go(self):
        pass

    def getCurrentConfigPath(self):
        return self["list"].getCurrent()[2]

    def up(self):
        if not self.isMoving:
            self["list"].instance.moveSelection(self["list"].instance.moveUp)
            self.updateColors(self.getCurrentConfigPath())

    def down(self):
        if not self.isMoving:
            self["list"].instance.moveSelection(self["list"].instance.moveDown)
            self.updateColors(self.getCurrentConfigPath())

    def left(self):
        self["list"].handleKey(KEY_LEFT)

    def right(self):
        self["list"].handleKey(KEY_RIGHT)

    def updateColors(self, entry):
        if entry == "tune":
            self.red.setText(_("Tune"))
            self.green.setText("")
            self.yellow.setText("")
            self.blue.setText("")
        elif entry == "move":
            if self.isMoving:
                self.red.setText(_("Stop"))
                self.green.setText(_("Stop"))
                self.yellow.setText(_("Stop"))
                self.blue.setText(_("Stop"))
            else:
                self.red.setText(_("Move west"))
                self.green.setText(_("Search west"))
                self.yellow.setText(_("Search east"))
                self.blue.setText(_("Move east"))
        elif entry == "finemove":
            self.red.setText("")
            self.green.setText(_("Step west"))
            self.yellow.setText(_("Step east"))
            self.blue.setText("")
        elif entry == "limits":
            self.red.setText(_("Limits off"))
            self.green.setText(_("Limit west"))
            self.yellow.setText(_("Limit east"))
            self.blue.setText(_("Limits on"))
        elif entry == "storage":
            self.red.setText("")
            self.green.setText(_("Store position"))
            self.yellow.setText(_("Goto position"))
            self.blue.setText("")
        elif entry == "goto0":
            self.red.setText(_("Goto 0"))
            self.green.setText("")
            self.yellow.setText("")
            self.blue.setText("")
        else:
            self.red.setText("")
            self.green.setText("")
            self.yellow.setText("")
            self.blue.setText("")

    def redKey(self):
        entry = self.getCurrentConfigPath()
        if entry == "move":
            if self.isMoving:
                self.diseqccommand("stop")
                self.isMoving = False
                self.stopOnLock = False
            else:
                self.diseqccommand("moveWest", 0)
                self.isMoving = True
            self.updateColors("move")
        elif entry == "limits":
            self.diseqccommand("limitOff")
        elif entry == "tune":
            fe_data = {}
            self.frontend.getFrontendData(fe_data)
            self.frontend.getTransponderData(fe_data, True)
            feparm = self.tuner.lastparm.getDVBS()
            fe_data["orbital_position"] = feparm.orbital_position
            self.session.openWithCallback(self.tune, TunerScreen, self.feid,
                                          fe_data)
        elif entry == "goto0":
            print "move to position 0"
            self.diseqccommand("moveTo", 0)

    def greenKey(self):
        entry = self.getCurrentConfigPath()
        if entry == "move":
            if self.isMoving:
                self.diseqccommand("stop")
                self.isMoving = False
                self.stopOnLock = False
            else:
                self.isMoving = True
                self.stopOnLock = True
                self.diseqccommand("moveWest", 0)
            self.updateColors("move")
        elif entry == "finemove":
            print "stepping west"
            self.diseqccommand("moveWest", 0xFF)  # one step
        elif entry == "storage":
            print "store at position", int(self.positioner_storage.value)
            self.diseqccommand("store", int(self.positioner_storage.value))

        elif entry == "limits":
            self.diseqccommand("limitWest")

    def yellowKey(self):
        entry = self.getCurrentConfigPath()
        if entry == "move":
            if self.isMoving:
                self.diseqccommand("stop")
                self.isMoving = False
                self.stopOnLock = False
            else:
                self.isMoving = True
                self.stopOnLock = True
                self.diseqccommand("moveEast", 0)
            self.updateColors("move")
        elif entry == "finemove":
            print "stepping east"
            self.diseqccommand("moveEast", 0xFF)  # one step
        elif entry == "storage":
            print "move to position", int(self.positioner_storage.value)
            self.diseqccommand("moveTo", int(self.positioner_storage.value))
        elif entry == "limits":
            self.diseqccommand("limitEast")

    def blueKey(self):
        entry = self.getCurrentConfigPath()
        if entry == "move":
            if self.isMoving:
                self.diseqccommand("stop")
                self.isMoving = False
                self.stopOnLock = False
            else:
                self.diseqccommand("moveEast", 0)
                self.isMoving = True
            self.updateColors("move")
            print "moving east"
        elif entry == "limits":
            self.diseqccommand("limitOn")

    def diseqccommand(self, cmd, param=0):
        self.diseqc.command(cmd, param)
        self.tuner.retune()

    def updateStatus(self):
        if self.frontend:
            self.frontend.getFrontendStatus(self.frontendStatus)
        self["snr_db"].update()
        self["snr_percentage"].update()
        self["ber_value"].update()
        self["snr_bar"].update()
        self["ber_bar"].update()
        self["lock_state"].update()
        transponderdata = ConvertToHumanReadable(
            self.tuner.getTransponderData(), "DVB-S")
        self["frequency_value"].setText(str(transponderdata.get("frequency")))
        self["symbolrate_value"].setText(
            str(transponderdata.get("symbol_rate")))
        self["fec_value"].setText(str(transponderdata.get("fec_inner")))
        if self.frontendStatus.get(
                "tuner_locked", 0) == 1 and self.isMoving and self.stopOnLock:
            self.diseqccommand("stop")
            self.isMoving = False
            self.stopOnLock = False
            self.updateColors(self.getCurrentConfigPath())
        self.statusTimer.start(50, True)

    def tune(self, transponder):
        if transponder is not None:
            self.tuner.tune(transponder)
예제 #39
0
class Satfinder(ScanSetup):
	def __init__(self, session, feid):
		self.initcomplete = False
		self.feid = feid
		self.oldref = None
		self.frontendData = None
		service = session and session.nav.getCurrentService()
		feinfo = service and service.frontendInfo()
		self.frontendData = feinfo and feinfo.getAll(True)
		del feinfo
		del service

		ScanSetup.__init__(self, session)
		self.setTitle(_("Satfinder"))

		self["introduction"].setText(_("Press OK to scan"))
		self["Frontend"] = FrontendStatus(frontend_source = lambda : self.frontend, update_interval = 100)

		self["actions"] = ActionMap(["SetupActions"],
		{
			"save": self.keyGoScan,
			"ok": self.keyGoScan,
			"cancel": self.keyCancel,
		}, -3)

		self.initcomplete = True
		self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
		self.onClose.append(self.__onClose)
		self.onShow.append(self.__onShow)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
				else:
					print "getFrontend failed"
			else:
				print "getRawChannel failed"
		else:
			print "getResourceManager instance failed"
		return False

	def __onShow(self):
		if self.oldref is not None:
			self.session.nav.stopService() # try to disable foreground service
		if not self.openFrontend():
			if self.session.pipshown: # try to disable pip
				self.session.pipshown = False
				del self.session.pip
				if not self.openFrontend():
					self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)

	def __onClose(self):
		self.session.nav.playService(self.oldref)

	def createSetup(self):
		self.typeOfTuningEntry = None
		self.satEntry = None

		self.list = []

		self.satEntry = getConfigListEntry(_('Satellite'), self.tuning_sat)
		self.list.append(self.satEntry)
		self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type)
		self.list.append(self.typeOfTuningEntry)

		nim = nimmanager.nim_slots[self.feid]

		self.systemEntry = None
		if self.tuning_type.getValue() == "manual_transponder":
			if nim.isCompatible("DVB-S2"):
				self.systemEntry = getConfigListEntry(_('System'), self.scan_sat.system)
				self.list.append(self.systemEntry)
			else:
				# downgrade to dvb-s, in case a -s2 config was active
				self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S
			self.list.append(getConfigListEntry(_('Frequency'), self.scan_sat.frequency))
			self.list.append(getConfigListEntry(_('Polarization'), self.scan_sat.polarization))
			self.list.append(getConfigListEntry(_('Symbol rate'), self.scan_sat.symbolrate))
			self.list.append(getConfigListEntry(_('Inversion'), self.scan_sat.inversion))
			if self.scan_sat.system.getValue() == eDVBFrontendParametersSatellite.System_DVB_S:
				self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec))
			elif self.scan_sat.system.getValue() == eDVBFrontendParametersSatellite.System_DVB_S2:
				self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
				self.modulationEntry = getConfigListEntry(_('Modulation'), self.scan_sat.modulation)
				self.list.append(self.modulationEntry)
				self.list.append(getConfigListEntry(_('Roll-off'), self.scan_sat.rolloff))
				self.list.append(getConfigListEntry(_('Pilot'), self.scan_sat.pilot))
		elif self.tuning_transponder and self.tuning_type.getValue() == "predefined_transponder":
			self.list.append(getConfigListEntry(_("Transponder"), self.tuning_transponder))
		self["config"].list = self.list
		self["config"].l.setList(self.list)

	def newConfig(self):
		cur = self["config"].getCurrent()
		if cur in (self.typeOfTuningEntry, self.systemEntry):
			self.createSetup()
		elif cur == self.satEntry:
			self.updateSats()
			self.createSetup()

	def sat_changed(self, config_element):
		self.newConfig()
		self.retune(config_element)

	def retune(self, configElement):
		returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
		satpos = int(self.tuning_sat.getValue())
		if self.tuning_type.getValue() == "manual_transponder":
			if self.scan_sat.system.getValue() == eDVBFrontendParametersSatellite.System_DVB_S2:
				fec = self.scan_sat.fec_s2.getValue()
			else:
				fec = self.scan_sat.fec.getValue()
			returnvalue = (
				self.scan_sat.frequency.getValue(),
				self.scan_sat.symbolrate.getValue(),
				self.scan_sat.polarization.getValue(),
				fec,
				self.scan_sat.inversion.getValue(),
				satpos,
				self.scan_sat.system.getValue(),
				self.scan_sat.modulation.getValue(),
				self.scan_sat.rolloff.getValue(),
				self.scan_sat.pilot.getValue())
			self.tune(returnvalue)
		elif self.tuning_type.getValue() == "predefined_transponder":
			tps = nimmanager.getTransponders(satpos)
			l = len(tps)
			if l > self.tuning_transponder.index:
				transponder = tps[self.tuning_transponder.index]
				returnvalue = (transponder[1] / 1000, transponder[2] / 1000,
					transponder[3], transponder[4], 2, satpos, transponder[5], transponder[6], transponder[8], transponder[9])
				self.tune(returnvalue)

	def createConfig(self, foo):
		self.tuning_transponder = None
		self.tuning_type = ConfigSelection(choices = [("manual_transponder", _("Manual transponder")), ("predefined_transponder", _("Predefined transponder"))])
		orbital_position = 192
		if self.frontendData and self.frontendData.has_key('orbital_position'):
			orbital_position = self.frontendData['orbital_position']
		self.tuning_sat = getConfigSatlist(orbital_position, nimmanager.getSatListForNim(self.feid))
		ScanSetup.createConfig(self, self.frontendData)

		self.updateSats()

		for x in (self.tuning_type, self.tuning_sat, self.scan_sat.frequency,
			self.scan_sat.inversion, self.scan_sat.symbolrate,
			self.scan_sat.polarization, self.scan_sat.fec, self.scan_sat.pilot,
			self.scan_sat.fec_s2, self.scan_sat.fec, self.scan_sat.modulation,
			self.scan_sat.rolloff, self.scan_sat.system):
			x.addNotifier(self.retune, initial_call = False)

	def updateSats(self):
		orb_pos = self.tuning_sat.orbital_position
		if orb_pos is not None:
			transponderlist = nimmanager.getTransponders(orb_pos)
			list = []
			default = None
			index = 0
			for x in transponderlist:
				if x[3] == 0:
					pol = "H"
				elif x[3] == 1:
					pol = "V"
				elif x[3] == 2:
					pol = "CL"
				elif x[3] == 3:
					pol = "CR"
				else:
					pol = "??"
				if x[4] == 0:
					fec = "FEC Auto"
				elif x[4] == 1:
					fec = "FEC 1/2"
				elif x[4] == 2:
					fec = "FEC 2/3"
				elif x[4] == 3:
					fec = "FEC 3/4"
				elif x[4] == 4:
					fec = "FEC 5/6"
				elif x[4] == 5:
					fec = "FEC 7/8"
				elif x[4] == 6:
					fec = "FEC 8/9"
				elif x[4] == 7:
					fec = "FEC 3/5"
				elif x[4] == 8:
					fec = "FEC 4/5"
				elif x[4] == 9:
					fec = "FEC 9/10"
				elif x[4] == 15:
					fec = "FEC None"
				else:
					fec = "FEC Unknown"
				e = "%d %s %d %s" % ((x[1] / 1000), pol, (x[2] / 1000), fec)

				if default is None:
					default = str(index)
				list.append((str(index), e))
				index += 1
			self.tuning_transponder = ConfigSelection(choices = list, default = default)
			self.tuning_transponder.addNotifier(self.retune, initial_call = False)

	def keyGoScan(self):
		self.frontend = None
		del self.raw_channel

		self.updateSatList()

		self.scan_satselection = [ self.tuning_sat ]
		self.satfinder = True

		self.scan_sat.frequency.setValue(self.transponder[0])
		self.scan_sat.symbolrate.setValue(self.transponder[1])
		self.scan_sat.polarization.setValue(self.transponder[2])
		if self.scan_sat.system.getValue() == eDVBFrontendParametersSatellite.System_DVB_S:
			self.scan_sat.fec.setValue(self.transponder[3])
		else:
			self.scan_sat.fec_s2.setValue(self.transponder[3])
		self.scan_sat.inversion.setValue(self.transponder[4])
		self.scan_sat.system.setValue(self.transponder[6])
		self.scan_sat.modulation.setValue(self.transponder[7])
		self.scan_sat.rolloff.setValue(self.transponder[8])
		self.scan_sat.pilot.setValue(self.transponder[9])

		self.keyGo()

	def restartPrevService(self, yesno):
		if yesno:
			if self.frontend:
				self.frontend = None
				del self.raw_channel
		else:
			self.oldref = None
		self.close(None)

	def keyCancel(self):
		if self.oldref:
			self.session.openWithCallback(self.restartPrevService, MessageBox, _("Zap back to service before satfinder?"), MessageBox.TYPE_YESNO)
		else:
			self.restartPrevService(False)

	def tune(self, transponder):
		if self.initcomplete:
			if transponder is not None:
				self.tuner.tune(transponder)
				self.transponder = transponder
예제 #40
0
class AutoDiseqc(Screen, ConfigListScreen):
    skin = """
		<screen position="c-250,c-100" size="500,250" title=" ">
			<widget source="statusbar" render="Label" position="10,5" zPosition="10" size="e-10,60" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
			<widget source="tunerstatusbar" render="Label" position="10,60" zPosition="10" size="e-10,30" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
			<widget name="config" position="10,100" size="e-10,100" scrollbarMode="showOnDemand" />
			<ePixmap pixmap="skin_default/buttons/red.png" position="c-140,e-45" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="c-140,e-45" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
		</screen>"""

    diseqc_ports = ["A", "B", "C", "D"]

    sat_frequencies = [
        # astra 192 zdf
        (
            11953,
            27500,
            eDVBFrontendParametersSatellite.Polarisation_Horizontal,
            eDVBFrontendParametersSatellite.FEC_3_4,
            eDVBFrontendParametersSatellite.Inversion_Off,
            192,
            eDVBFrontendParametersSatellite.System_DVB_S,
            eDVBFrontendParametersSatellite.Modulation_Auto,
            eDVBFrontendParametersSatellite.RollOff_auto,
            eDVBFrontendParametersSatellite.Pilot_Unknown,
            1079,
            1,
            "Astra 1 19.2e",
        ),
        # astra 235 astra ses
        (
            12168,
            27500,
            eDVBFrontendParametersSatellite.Polarisation_Vertical,
            eDVBFrontendParametersSatellite.FEC_3_4,
            eDVBFrontendParametersSatellite.Inversion_Off,
            235,
            eDVBFrontendParametersSatellite.System_DVB_S,
            eDVBFrontendParametersSatellite.Modulation_Auto,
            eDVBFrontendParametersSatellite.RollOff_auto,
            eDVBFrontendParametersSatellite.Pilot_Unknown,
            3224,
            3,
            "Astra 3 23.5e",
        ),
        # astra 282 bbc
        (
            10776,
            22000,
            eDVBFrontendParametersSatellite.Polarisation_Horizontal,
            eDVBFrontendParametersSatellite.FEC_Auto,
            eDVBFrontendParametersSatellite.Inversion_Unknown,
            282,
            eDVBFrontendParametersSatellite.System_DVB_S,
            eDVBFrontendParametersSatellite.Modulation_Auto,
            eDVBFrontendParametersSatellite.RollOff_auto,
            eDVBFrontendParametersSatellite.Pilot_Unknown,
            2045,
            2,
            "Astra 2 28.2e",
        ),
        # hotbird 130 rai
        (
            10992,
            27500,
            eDVBFrontendParametersSatellite.Polarisation_Vertical,
            eDVBFrontendParametersSatellite.FEC_2_3,
            eDVBFrontendParametersSatellite.Inversion_Off,
            130,
            eDVBFrontendParametersSatellite.System_DVB_S,
            eDVBFrontendParametersSatellite.Modulation_Auto,
            eDVBFrontendParametersSatellite.RollOff_auto,
            eDVBFrontendParametersSatellite.Pilot_Unknown,
            12400,
            318,
            "Hotbird 13.0e",
        ),
    ]

    SAT_TABLE_FREQUENCY = 0
    SAT_TABLE_SYMBOLRATE = 1
    SAT_TABLE_POLARISATION = 2
    SAT_TABLE_FEC = 3
    SAT_TABLE_INVERSION = 4
    SAT_TABLE_ORBPOS = 5
    SAT_TABLE_SYSTEM = 6
    SAT_TABLE_MODULATION = 7
    SAT_TABLE_ROLLOFF = 8
    SAT_TABLE_PILOT = 9
    SAT_TABLE_TSID = 10
    SAT_TABLE_ONID = 11
    SAT_TABLE_NAME = 12

    def __init__(self, session, feid, nr_of_ports, simple_tone, simple_sat_change):
        self.skin = AutoDiseqc.skin
        Screen.__init__(self, session)

        self["statusbar"] = StaticText(" ")
        self["tunerstatusbar"] = StaticText(" ")

        self.list = []
        ConfigListScreen.__init__(self, self.list, session=self.session)

        self["config"].list = self.list
        self["config"].l.setList(self.list)

        self["key_red"] = StaticText(_("Abort"))

        self.index = 0
        self.port_index = 0
        self.feid = feid
        self.nr_of_ports = nr_of_ports
        self.simple_tone = simple_tone
        self.simple_sat_change = simple_sat_change
        self.found_sats = []

        if not self.openFrontend():
            self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
            self.session.nav.stopService()
            if not self.openFrontend():
                if self.session.pipshown:
                    self.session.pipshown = False
                    del self.session.pip
                    if not self.openFrontend():
                        self.frontend = None

        self["actions"] = ActionMap(["SetupActions"], {"cancel": self.keyCancel}, -2)

        self.count = 0
        self.state = 0
        self.abort = False

        self.statusTimer = eTimer()
        self.statusTimer.callback.append(self.statusCallback)
        self.tunerStatusTimer = eTimer()
        self.tunerStatusTimer.callback.append(self.tunerStatusCallback)
        self.startStatusTimer()

    def keyCancel(self):
        self.abort = True

    def keyOK(self):
        return

    def keyLeft(self):
        return

    def keyRight(self):
        return

    def openFrontend(self):
        res_mgr = eDVBResourceManager.getInstance()
        if res_mgr:
            self.raw_channel = res_mgr.allocateRawChannel(self.feid)
            if self.raw_channel:
                self.frontend = self.raw_channel.getFrontend()
                if self.frontend:
                    return True
        return False

    def statusCallback(self):
        if self.state == 0:
            if self.port_index == 0:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcA.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 1:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcB.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 2:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcC.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 3:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcD.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])

            if self.nr_of_ports == 4:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b_c_d"
            elif self.nr_of_ports == 2:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b"
            else:
                config.Nims[self.feid].diseqcMode.value = "single"

            config.Nims[self.feid].configMode.value = "simple"
            config.Nims[self.feid].simpleDiSEqCSetVoltageTone = self.simple_tone
            config.Nims[self.feid].simpleDiSEqCOnlyOnSatChange = self.simple_sat_change

            self.saveAndReloadNimConfig()
            self.state += 1

        elif self.state == 1:
            InitNimManager(nimmanager)

            self.tuner = Tuner(self.frontend)
            self.tuner.tune(self.sat_frequencies[self.index])

            self["statusbar"].setText(
                _("Checking tuner %d\nDiSEqC port %s for %s")
                % (self.feid, self.diseqc_ports[self.port_index], self.sat_frequencies[self.index][self.SAT_TABLE_NAME])
            )
            self["tunerstatusbar"].setText(" ")

            self.count = 0
            self.state = 0

            self.startTunerStatusTimer()
            return

        self.startStatusTimer()

    def startStatusTimer(self):
        self.statusTimer.start(100, True)

    def setupSave(self):
        self.clearNimEntries()
        for x in self.found_sats:
            if x[0] == "A":
                config.Nims[self.feid].diseqcA.value = "%d" % (x[1])
            elif x[0] == "B":
                config.Nims[self.feid].diseqcB.value = "%d" % (x[1])
            elif x[0] == "C":
                config.Nims[self.feid].diseqcC.value = "%d" % (x[1])
            elif x[0] == "D":
                config.Nims[self.feid].diseqcD.value = "%d" % (x[1])
        self.saveAndReloadNimConfig()

    def setupClear(self):
        self.clearNimEntries()
        self.saveAndReloadNimConfig()

    def clearNimEntries(self):
        config.Nims[self.feid].diseqcA.value = "3601"
        config.Nims[self.feid].diseqcB.value = "3601"
        config.Nims[self.feid].diseqcC.value = "3601"
        config.Nims[self.feid].diseqcD.value = "3601"

    def saveAndReloadNimConfig(self):
        config.Nims[self.feid].save()
        configfile.save()
        configfile.load()
        nimmanager.sec.update()

    def tunerStatusCallback(self):
        dict = {}
        self.frontend.getFrontendStatus(dict)

        self["tunerstatusbar"].setText(_("Tuner status %s") % (dict["tuner_state"]))

        if dict["tuner_state"] == "LOCKED":
            self.raw_channel.requestTsidOnid(self.gotTsidOnid)

        if dict["tuner_state"] == "LOSTLOCK" or dict["tuner_state"] == "FAILED":
            self.tunerStopScan(False)
            return

        self.count += 1
        if self.count > 10:
            self.tunerStopScan(False)
        else:
            self.startTunerStatusTimer()

    def startTunerStatusTimer(self):
        self.tunerStatusTimer.start(1000, True)

    def gotTsidOnid(self, tsid, onid):
        self.tunerStatusTimer.stop()
        if (
            tsid == self.sat_frequencies[self.index][self.SAT_TABLE_TSID]
            and onid == self.sat_frequencies[self.index][self.SAT_TABLE_ONID]
        ):
            self.tunerStopScan(True)
        else:
            self.tunerStopScan(False)

    def tunerStopScan(self, result):
        if self.abort:
            self.setupClear()
            self.close(False)
            return
        if result:
            self.found_sats.append(
                (
                    self.diseqc_ports[self.port_index],
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS],
                    self.sat_frequencies[self.index][self.SAT_TABLE_NAME],
                )
            )
            self.index = 0
            self.port_index += 1
        else:
            self.index += 1
            if len(self.sat_frequencies) == self.index:
                self.index = 0
                self.port_index += 1

        if len(self.found_sats) > 0:
            self.list = []
            for x in self.found_sats:
                self.list.append(getConfigListEntry((_("DiSEqC port %s: %s") % (x[0], x[2]))))
            self["config"].l.setList(self.list)

        if self.nr_of_ports == self.port_index:
            self.state = 99
            self.setupSave()
            self.close(len(self.found_sats) > 0)
            return

        for x in self.found_sats:
            if x[1] == self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS]:
                self.tunerStopScan(False)
                return

        self.startStatusTimer()
예제 #41
0
	def prepareScanData(self, orb, pol, band, is_scan):
		self.is_runable = False
		self.orb_position = orb[0]
		self.sat_name = orb[1]
		self.feid = int(self.scan_nims.value)
		tab_hilow = {"high" : 1, "low" : 0}
		tab_pol = {
			"horizontal" : eDVBFrontendParametersSatellite.Polarisation_Horizontal,
			"vertical" : eDVBFrontendParametersSatellite.Polarisation_Vertical,
			"circular left" : eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
			"circular right" : eDVBFrontendParametersSatellite.Polarisation_CircularRight
		}

		returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

		self.frontend = None
		if not self.openFrontend():
			self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					self.session.pipshown = False
					del self.session.pip
					self.openFrontend()
		if self.frontend == None :
			self.session.open(MessageBox, _("Sorry, this tuner is in use."), MessageBox.TYPE_ERROR)
			return False
		self.tuner = Tuner(self.frontend)

		if self.is_c_band_scan :
			self.scan_sat.frequency.value = 3600
		else:
			if tab_hilow[band]:
				self.scan_sat.frequency.value = 12515
			else:
				self.scan_sat.frequency.value = 11015
		returnvalue = (self.scan_sat.frequency.value,
					 0,
					 tab_pol[pol],
					 0,
					 0,
					 orb[0],
					 eDVBFrontendParametersSatellite.System_DVB_S,
					 0,
					 0,
					 0)
		self.tuner.tune(returnvalue)

		if self.getNimSocket(self.feid) < 0:
			print "can't find i2c number!!"
			return

		c_band_loc_osc = 5150
		uni_lnb_loc_osc = {"high" : 10600, "low" : 9750}
		uni_lnb_cutoff = 11700
		if self.is_c_band_scan :
			temp_start_int_freq = c_band_loc_osc - self.blindscan_stop_frequency.value
			temp_end_int_freq = c_band_loc_osc - self.blindscan_start_frequency.value
			status_box_start_freq = c_band_loc_osc - temp_end_int_freq
			status_box_end_freq = c_band_loc_osc - temp_start_int_freq

		else:
			if tab_hilow[band] :
				if self.blindscan_start_frequency.value < uni_lnb_cutoff :
					temp_start_int_freq = uni_lnb_cutoff - uni_lnb_loc_osc[band]
				else:
					temp_start_int_freq = self.blindscan_start_frequency.value - uni_lnb_loc_osc[band]
				temp_end_int_freq = self.blindscan_stop_frequency.value - uni_lnb_loc_osc[band]
			else:
				if self.blindscan_stop_frequency.value > uni_lnb_cutoff :
					temp_end_int_freq = uni_lnb_cutoff - uni_lnb_loc_osc[band]
				else:
					temp_end_int_freq = self.blindscan_stop_frequency.value - uni_lnb_loc_osc[band]
				temp_start_int_freq = self.blindscan_start_frequency.value - uni_lnb_loc_osc[band]
			status_box_start_freq = temp_start_int_freq + uni_lnb_loc_osc[band]
			status_box_end_freq = temp_end_int_freq + uni_lnb_loc_osc[band]
			
		if getBoxType().startswith('venton'):
			cmd = "venton_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) 
		elif getBoxType().startswith('vu'):
			cmd = "vuplus_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) # commented out by Huevos cmd = "vuplus_blindscan %d %d %d %d %d %d %d %d" % (self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		elif getBoxType().startswith('et'):
			cmd = "avl_xtrend_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) # commented out by Huevos cmd = "avl_xtrend_blindscan %d %d %d %d %d %d %d %d" % (self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		elif getBoxType().startswith('odin'):
			cmd = "odin_blindscan %d %d %d %d %d %d %d" % (self.feid, temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band]) # odin_blindscan tuner_idx min_frequency max_frequency min_symbolrate max_symbolrate polarization(Vertical & Horizontal) hilow_band
		elif getBoxType().startswith('gb'):
			cmd = "gigablue_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) # commented out by Huevos cmd = "vuplus_blindscan %d %d %d %d %d %d %d %d" % (self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		print "prepared command : [%s]" % (cmd)

		self.thisRun = [] # used to check result corresponds with values used above
		self.thisRun.append(int(temp_start_int_freq))
		self.thisRun.append(int(temp_end_int_freq))
		self.thisRun.append(int(tab_hilow[band]))

		self.blindscan_container = eConsoleAppContainer()
		self.blindscan_container.appClosed.append(self.blindscanContainerClose)
		self.blindscan_container.dataAvail.append(self.blindscanContainerAvail)
		self.blindscan_container.execute(cmd)

		display_pol = pol # Display the correct polarisation in the MessageBox below
		if self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight :
			display_pol = _("circular right")
		elif self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularLeft :
			display_pol = _("circular left")
		elif  self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2 :
			if pol == "horizontal" :
				display_pol = _("circular left")
			else:
				display_pol = _("circular right")

		tmpstr = _("Looking for available transponders.\nThis will take a short while.\n\n   Current Status : %d/%d\n   Satellite : %s\n   Polarization : %s\n   Frequency range : %d - %d MHz\n   Symbol rates : %d - %d MHz") %(self.running_count, self.max_count, orb[1], display_pol, status_box_start_freq, status_box_end_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value)
		if is_scan :
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionClose, MessageBox, tmpstr, MessageBox.TYPE_INFO)
		else:
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionNone, MessageBox, tmpstr, MessageBox.TYPE_INFO)
예제 #42
0
class Blindscan(ConfigListScreen, Screen):
	skin="""
		<screen name="Blindscan" position="center,center" size="560,290" title="Blindscan">
			<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
			<widget name="config" position="5,50" size="550,200" scrollbarMode="showOnDemand" />
			<widget name="introduction" position="0,265" size="560,20" font="Regular;20" halign="center" />
		</screen>
		"""
	def __init__(self, session):
		Screen.__init__(self, session)
		self.setup_title = _("Blindscan")
		Screen.setTitle(self, _(self.setup_title))
		self.skinName = "Setup"
		self.current_play_service = self.session.nav.getCurrentlyPlayingServiceReference()

		self.onChangedEntry = [ ]
		self["HelpWindow"] = Pixmap()
		self["HelpWindow"].hide()
		self["VKeyIcon"] = Boolean(False)
		self["description"] = Label("")
		self['footnote'] = Label("")
		self["status"] = StaticText()

		# update sat list
		self.satList = []
		for slot in nimmanager.nim_slots:
			if slot.isCompatible("DVB-S"):
				self.satList.append(nimmanager.getSatListForNim(slot.slot))
			else:
				self.satList.append(None)

		# make config
		self.createConfig()

		self.list = []
		self.status = ""

		ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
		if self.scan_nims.value != None and self.scan_nims.value != "" :
			self["actions"] = ActionMap(["ColorActions", "SetupActions", 'DirectionActions'],
			{
				"red": self.keyCancel,
				"green": self.keyGo,
				"ok": self.keyGo,
				"cancel": self.keyCancel,
			}, -2)
			self["key_red"] = StaticText(_("Exit"))
			self["key_green"] = StaticText(_("Scan"))
			self["introduction"] = Label(_("Press Green/OK to start the scan"))
			self.createSetup()
		else :
			self["actions"] = ActionMap(["ColorActions", "SetupActions", 'DirectionActions'],
			{
				"red": self.keyCancel,
				"green": self.keyNone,
				"ok": self.keyNone,
				"cancel": self.keyCancel,
			}, -2)
			self["key_red"] = StaticText(_("Exit"))
			self["key_green"] = StaticText(" ")
			self["introduction"] = Label(_("Please setup your tuner configuration."))

		self.i2c_mapping_table = None
		self.makeNimSocket()

		self.changedEntry()

	# for summary:
	def changedEntry(self):
		for x in self.onChangedEntry:
			x()
	def getCurrentEntry(self):
		return self["config"].getCurrent() and self["config"].getCurrent()[0] or ""

	def getCurrentValue(self):
		return self["config"].getCurrent() and str(self["config"].getCurrent()[1].getText()) or ""

	def getCurrentDescription(self):
		return self["config"].getCurrent() and len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2] or ""

	def createSummary(self):
		from Screens.Setup import SetupSummary
		return SetupSummary

	def makeNimSocket(self):
		self.i2c_mapping_table = {0:2, 1:3, 2:1, 3:0}

	def getNimSocket(self, slot_number):
		if slot_number < 0 or slot_number > 3:
			return -1
		return self.i2c_mapping_table[slot_number]

	def keyNone(self):
		None

	def callbackNone(self, *retval):
		None

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
				else:
					print "getFrontend failed"
			else:
				print "getRawChannel failed"
		else:
			print "getResourceManager instance failed"
		return False

	def createConfig(self):
		self.feinfo = None
		frontendData = None
		defaultSat = {
			"orbpos": 192,
			"system": eDVBFrontendParametersSatellite.System_DVB_S,
			"frequency": 11836,
			"inversion": eDVBFrontendParametersSatellite.Inversion_Unknown,
			"symbolrate": 27500,
			"polarization": eDVBFrontendParametersSatellite.Polarisation_Horizontal,
			"fec": eDVBFrontendParametersSatellite.FEC_Auto,
			"fec_s2": eDVBFrontendParametersSatellite.FEC_9_10,
			"modulation": eDVBFrontendParametersSatellite.Modulation_QPSK
		}

		self.service = self.session.nav.getCurrentService()
		if self.service is not None:
			self.feinfo = self.service.frontendInfo()
			frontendData = self.feinfo and self.feinfo.getAll(True)
		if frontendData is not None:
			ttype = frontendData.get("tuner_type", "UNKNOWN")
			if ttype == "DVB-S":
				defaultSat["system"] = frontendData.get("system", eDVBFrontendParametersSatellite.System_DVB_S)
				defaultSat["frequency"] = frontendData.get("frequency", 0) / 1000
				defaultSat["inversion"] = frontendData.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown)
				defaultSat["symbolrate"] = frontendData.get("symbol_rate", 0) / 1000
				defaultSat["polarization"] = frontendData.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal)
				if defaultSat["system"] == eDVBFrontendParametersSatellite.System_DVB_S2:
					defaultSat["fec_s2"] = frontendData.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
					defaultSat["rolloff"] = frontendData.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35)
					defaultSat["pilot"] = frontendData.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown)
				else:
					defaultSat["fec"] = frontendData.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
				defaultSat["modulation"] = frontendData.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK)
				defaultSat["orbpos"] = frontendData.get("orbital_position", 0)
		del self.feinfo
		del self.service
		del frontendData

		self.scan_sat = ConfigSubsection()
		self.scan_networkScan = ConfigYesNo(default = False)

		#ConfigYesNo(default = True)
		self.blindscan_start_frequency = ConfigInteger(default = 10700, limits = (1, 99999))
		self.blindscan_stop_frequency = ConfigInteger(default = 12750, limits = (1, 99999))
		self.blindscan_start_symbol = ConfigInteger(default = 2, limits = (1, 99))
		self.blindscan_stop_symbol = ConfigInteger(default = 45, limits = (1, 99))
		self.scan_clearallservices = ConfigYesNo(default = False)
		self.scan_onlyfree = ConfigYesNo(default = False)
		self.dont_scan_known_tps = ConfigYesNo(default = False)
		self.filter_off_adjacent_satellites = ConfigSelection(default = 0, choices = [
			(0, _("no")),
			(1, _("up to 1 degree")),
			(2, _("up to 2 degrees")),
			(3, _("up to 3 degrees"))])
		self.search_type = ConfigSelection(default = 0, choices = [
			(0, _("scan for channels")),
			(1, _("save to XML file"))])


		# collect all nims which are *not* set to "nothing"
		nim_list = []
		for n in nimmanager.nim_slots:
			if n.config_mode == "nothing":
				continue
			if n.config_mode == "advanced" and len(nimmanager.getSatListForNim(n.slot)) < 1:
				continue
			if n.config_mode in ("loopthrough", "satposdepends"):
				root_id = nimmanager.sec.getRoot(n.slot_id, int(n.config.connectedTo.value))
				if n.type == nimmanager.nim_slots[root_id].type: # check if connected from a DVB-S to DVB-S2 Nim or vice versa
					continue
			if n.isCompatible("DVB-S"):
				nim_list.append((str(n.slot), n.friendly_full_description))
		self.scan_nims = ConfigSelection(choices = nim_list)

		# sat
		self.scan_sat.frequency = ConfigInteger(default = defaultSat["frequency"], limits = (1, 99999))
		self.scan_sat.polarization = ConfigSelection(default = eDVBFrontendParametersSatellite.Polarisation_CircularRight + 1, choices = [
			(eDVBFrontendParametersSatellite.Polarisation_CircularRight + 1, _("vertical and horizontal")),
			(eDVBFrontendParametersSatellite.Polarisation_Vertical, _("vertical")),
			(eDVBFrontendParametersSatellite.Polarisation_Horizontal, _("horizontal")),
			(eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2, _("circular right and circular left")),
			(eDVBFrontendParametersSatellite.Polarisation_CircularRight, _("circular right")),
			(eDVBFrontendParametersSatellite.Polarisation_CircularLeft, _("circular left"))])
		self.scan_scansat = {}
		for sat in nimmanager.satList:
			self.scan_scansat[sat[0]] = ConfigYesNo(default = False)

		self.scan_satselection = []
		for slot in nimmanager.nim_slots:
			if slot.isCompatible("DVB-S"):
				self.scan_satselection.append(getConfigSatlist(defaultSat["orbpos"], self.satList[slot.slot]))
		return True

	def getSelectedSatIndex(self, v):
		index    = 0
		none_cnt = 0
		for n in self.satList:
			if self.satList[index] == None:
				none_cnt = none_cnt + 1
			if index == int(v):
				return (index-none_cnt)
			index = index + 1
		return -1

	def createSetup(self):
		self.list = []
		self.multiscanlist = []
		index_to_scan = int(self.scan_nims.value)
		print "ID: ", index_to_scan

		self.tunerEntry = getConfigListEntry(_("Tuner"), self.scan_nims,_('Select a tuner that is configured for the satellite you wish to search'))
		self.list.append(self.tunerEntry)

		if self.scan_nims == [ ]:
			return

		self.systemEntry = None
		self.modulationEntry = None
		nim = nimmanager.nim_slots[index_to_scan]

		self.scan_networkScan.value = False
		if nim.isCompatible("DVB-S") :
			self.list.append(getConfigListEntry(_('Satellite'), self.scan_satselection[self.getSelectedSatIndex(index_to_scan)],_('Select the satellite you wish to search')))
			self.list.append(getConfigListEntry(_('Scan start frequency'), self.blindscan_start_frequency,_('Frequency values must be between 10700 and 12750 (or 3000 and 4200 in the case of C-band satellites)')))
			self.list.append(getConfigListEntry(_('Scan stop frequency'), self.blindscan_stop_frequency,_('Frequency values must be between 10700 and 12750 (or 3000 and 4200 in the case of C-band satellites)')))
			self.list.append(getConfigListEntry(_("Polarisation"), self.scan_sat.polarization,_('If you are not sure what polarisations the satellite you wish to search transmits, select "vertical and horizontal"')))
			self.list.append(getConfigListEntry(_('Scan start symbolrate'), self.blindscan_start_symbol,_('Symbol rate values are in megasymbols; enter a value between 1 and 44')))
			self.list.append(getConfigListEntry(_('Scan stop symbolrate'), self.blindscan_stop_symbol,_('Symbol rate values are in megasymbols; enter a value between 2 and 45')))
			self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices,_('If you select "yes" all channels on the satellite being search will be deleted before starting the current search')))
			self.list.append(getConfigListEntry(_("Only free scan"), self.scan_onlyfree,_('If you select "yes" the scan will only save channels that are not encrypted; "no" will find encrypted and non-encrypted channels')))
			self.list.append(getConfigListEntry(_("Only scan unknown transponders"), self.dont_scan_known_tps,_('If you select "yes" the scan will only search transponders not listed in satellites.xml')))
			self.list.append(getConfigListEntry(_("Filter out adjacent satellites"), self.filter_off_adjacent_satellites,_('When a neighbouring satellite is very strong this avoids searching transponders known to be coming from the neighbouring satellite')))
			self.list.append(getConfigListEntry(_("Search type"), self.search_type,_('"channel scan" searches for channels and saves them to your receiver; "save to XML file" does a transponder search and saves found transponders to an XML file in satellites.xml format')))
			self["config"].list = self.list
			self["config"].l.setList(self.list)

	def newConfig(self):
		cur = self["config"].getCurrent()
		print "cur is", cur
		if cur == self.tunerEntry or \
			cur == self.systemEntry or \
			(self.modulationEntry and self.systemEntry[1].value == eDVBFrontendParametersSatellite.System_DVB_S2 and cur == self.modulationEntry):
			self.createSetup()

	def checkSettings(self, orb):
		self.ku_band_lower_limit = 10700
		self.is_c_band_scan = False
		band = self.SatBandCheck(orb)
		if band :
			if band == 'C' :
				self.is_c_band_scan = True
		else:
			if self.blindscan_start_frequency.value < 4200 :
				self.is_c_band_scan = True
		if self.blindscan_start_symbol.value < 1 or self.blindscan_start_symbol.value > 44 :
			self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nStart symbol rate must be between 1MHz and 44MHz."), MessageBox.TYPE_ERROR)
			return False
		if self.blindscan_stop_symbol.value < 2 or self.blindscan_stop_symbol.value > 45 :
			self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nStop symbol rate must be between 2MHz and 45MHz."), MessageBox.TYPE_ERROR)
			return False
		if self.blindscan_start_symbol.value > self.blindscan_stop_symbol.value :
			self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nSymbol rate start value is larger than stop value."), MessageBox.TYPE_ERROR)
			return False
		if self.blindscan_start_frequency.value > self.blindscan_stop_frequency.value :
			self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nFrequency start value is larger than stop value."), MessageBox.TYPE_ERROR)
			return False
		if self.is_c_band_scan and band == 'C' :
			if self.blindscan_start_frequency.value < 3000 :
				self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nThat is a C-band satellite so frequency values \nneed to be between 3000MHz and 4200MHz."), MessageBox.TYPE_ERROR)
				return False
			if self.blindscan_stop_frequency.value > 4200 :
				self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nThat is a C-band satellite so frequency values \nneed to be between 3000MHz and 4200MHz."), MessageBox.TYPE_ERROR)
				return False
			return True
		if self.is_c_band_scan :
			if self.blindscan_start_frequency.value < 3000 :
				self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nStart frequency must be between 10700MHz and 12750MHz.\n(Or 3000MHz and 4200MHz in the case of c-band)."), MessageBox.TYPE_ERROR)
				return False
			if self.blindscan_stop_frequency.value > 4200 :
				self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nFor C-band searches stop frequency must be between 3000MHz and 4200MHz."), MessageBox.TYPE_ERROR)
				return False
			return True
		if band == 'Ku' :
			if self.blindscan_start_frequency.value < 10700 or self.blindscan_start_frequency.value > 12750 :
				self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nThat is a Ku-band satellite so frequency values \nneed to be between 10700MHz and 12750MHz."), MessageBox.TYPE_ERROR)
				return False
			if self.blindscan_stop_frequency.value < 10700 or self.blindscan_stop_frequency.value > 12750 :
				self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nThat is a Ku-band satellite so frequency values \nneed to be between 10700MHz and 12750MHz."), MessageBox.TYPE_ERROR)
				return False
		if self.blindscan_start_frequency.value < 10700 or self.blindscan_start_frequency.value > 12750 :
			self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nStart frequency must be between 10700MHz and 12750MHz.\n(Or 3000MHz and 4200MHz in the case of c-band)."), MessageBox.TYPE_ERROR)
			return False
		if self.blindscan_stop_frequency.value < 10700 or self.blindscan_stop_frequency.value > 12750 :
			self.session.open(MessageBox, _("Invalid parameters entered. Please correct and try again.\nStop frequency must be between 10700MHz and 12750MHz.\n(Or 3000MHz and 4200MHz in the case of c-band)."), MessageBox.TYPE_ERROR)
			return False
		return True

	def keyLeft(self):
		ConfigListScreen.keyLeft(self)
		self.newConfig()

	def keyRight(self):
		ConfigListScreen.keyRight(self)
		self.newConfig()

	def keyCancel(self):
		self.session.nav.playService(self.current_play_service)
		for x in self["config"].list:
			x[1].cancel()
		self.close()

	def keyGo(self):

		tab_pol = {
			eDVBFrontendParametersSatellite.Polarisation_Horizontal : "horizontal",
			eDVBFrontendParametersSatellite.Polarisation_Vertical : "vertical",
			eDVBFrontendParametersSatellite.Polarisation_CircularLeft : "circular left",
			eDVBFrontendParametersSatellite.Polarisation_CircularRight : "circular right",
			eDVBFrontendParametersSatellite.Polarisation_CircularRight + 1 : "horizontal and vertical",
			eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2 : "circular left and circular right"
		}

		self.tmp_tplist=[]
		tmp_pol = []
		tmp_band = []
		idx_selected_sat = int(self.getSelectedSatIndex(self.scan_nims.value))
		tmp_list=[self.satList[int(self.scan_nims.value)][self.scan_satselection[idx_selected_sat].index]]
		orb = tmp_list[0][0]

		if self.checkSettings(orb) == False:
			return

		uni_lnb_cutoff = 11700
		if self.blindscan_start_frequency.value < uni_lnb_cutoff and self.blindscan_stop_frequency.value > uni_lnb_cutoff :
			tmp_band=["low","high"]
		elif self.blindscan_start_frequency.value < uni_lnb_cutoff :
			tmp_band=["low"]
		else :
			tmp_band=["high"]

		if self.scan_sat.polarization.value >  eDVBFrontendParametersSatellite.Polarisation_CircularRight : # must be searching both polarisations, either V and H, or R and L
			tmp_pol=["vertical", "horizontal"]
		elif self.scan_sat.polarization.value ==  eDVBFrontendParametersSatellite.Polarisation_CircularRight :
			tmp_pol=["vertical"]
		elif self.scan_sat.polarization.value ==  eDVBFrontendParametersSatellite.Polarisation_CircularLeft :
			tmp_pol=["horizontal"]
		else:
			tmp_pol=[tab_pol[self.scan_sat.polarization.value]]

		self.doRun(tmp_list, tmp_pol, tmp_band)


	def doRun(self, tmp_list, tmp_pol, tmp_band):
		self.full_data = ""
		self.total_list=[]
		for x in tmp_list:
			for y in tmp_pol:
				for z in tmp_band:
					self.total_list.append([x,y,z])
					print "add scan item : ", x, ", ", y, ", ", z

		self.max_count = len(self.total_list)
		self.is_runable = True
		self.running_count = 0
		self.clockTimer = eTimer()
		self.clockTimer.callback.append(self.doClock)
		self.clockTimer.start(1000)

	def doClock(self):
		is_scan = False
		if self.is_runable :
			if self.running_count >= self.max_count:
				self.clockTimer.stop()
				del self.clockTimer
				self.clockTimer = None
				print "Done"
				return
			orb = self.total_list[self.running_count][0]
			pol = self.total_list[self.running_count][1]
			band = self.total_list[self.running_count][2]
			self.running_count = self.running_count + 1
			print "running status-[%d] : [%d][%s][%s]" %(self.running_count, orb[0], pol, band)
			if self.running_count == self.max_count:
				is_scan = True
			self.prepareScanData(orb, pol, band, is_scan)

	def prepareScanData(self, orb, pol, band, is_scan):
		self.is_runable = False
		self.orb_position = orb[0]
		self.sat_name = orb[1]
		self.feid = int(self.scan_nims.value)
		tab_hilow = {"high" : 1, "low" : 0}
		tab_pol = {
			"horizontal" : eDVBFrontendParametersSatellite.Polarisation_Horizontal,
			"vertical" : eDVBFrontendParametersSatellite.Polarisation_Vertical,
			"circular left" : eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
			"circular right" : eDVBFrontendParametersSatellite.Polarisation_CircularRight
		}

		returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

		self.frontend = None
		if not self.openFrontend():
			self.oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					self.session.pipshown = False
					del self.session.pip
					self.openFrontend()
		if self.frontend == None :
			self.session.open(MessageBox, _("Sorry, this tuner is in use."), MessageBox.TYPE_ERROR)
			return False
		self.tuner = Tuner(self.frontend)

		if self.is_c_band_scan :
			self.scan_sat.frequency.value = 3600
		else:
			if tab_hilow[band]:
				self.scan_sat.frequency.value = 12515
			else:
				self.scan_sat.frequency.value = 11015
		returnvalue = (self.scan_sat.frequency.value,
					 0,
					 tab_pol[pol],
					 0,
					 0,
					 orb[0],
					 eDVBFrontendParametersSatellite.System_DVB_S,
					 0,
					 0,
					 0)
		self.tuner.tune(returnvalue)

		if self.getNimSocket(self.feid) < 0:
			print "can't find i2c number!!"
			return

		c_band_loc_osc = 5150
		uni_lnb_loc_osc = {"high" : 10600, "low" : 9750}
		uni_lnb_cutoff = 11700
		if self.is_c_band_scan :
			temp_start_int_freq = c_band_loc_osc - self.blindscan_stop_frequency.value
			temp_end_int_freq = c_band_loc_osc - self.blindscan_start_frequency.value
			status_box_start_freq = c_band_loc_osc - temp_end_int_freq
			status_box_end_freq = c_band_loc_osc - temp_start_int_freq

		else:
			if tab_hilow[band] :
				if self.blindscan_start_frequency.value < uni_lnb_cutoff :
					temp_start_int_freq = uni_lnb_cutoff - uni_lnb_loc_osc[band]
				else:
					temp_start_int_freq = self.blindscan_start_frequency.value - uni_lnb_loc_osc[band]
				temp_end_int_freq = self.blindscan_stop_frequency.value - uni_lnb_loc_osc[band]
			else:
				if self.blindscan_stop_frequency.value > uni_lnb_cutoff :
					temp_end_int_freq = uni_lnb_cutoff - uni_lnb_loc_osc[band]
				else:
					temp_end_int_freq = self.blindscan_stop_frequency.value - uni_lnb_loc_osc[band]
				temp_start_int_freq = self.blindscan_start_frequency.value - uni_lnb_loc_osc[band]
			status_box_start_freq = temp_start_int_freq + uni_lnb_loc_osc[band]
			status_box_end_freq = temp_end_int_freq + uni_lnb_loc_osc[band]
			
		if getBoxType().startswith('venton'):
			cmd = "venton_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) 
		elif getBoxType().startswith('vu'):
			cmd = "vuplus_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) # commented out by Huevos cmd = "vuplus_blindscan %d %d %d %d %d %d %d %d" % (self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		elif getBoxType().startswith('et'):
			cmd = "avl_xtrend_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) # commented out by Huevos cmd = "avl_xtrend_blindscan %d %d %d %d %d %d %d %d" % (self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		elif getBoxType().startswith('odin'):
			cmd = "odin_blindscan %d %d %d %d %d %d %d" % (self.feid, temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band]) # odin_blindscan tuner_idx min_frequency max_frequency min_symbolrate max_symbolrate polarization(Vertical & Horizontal) hilow_band
		elif getBoxType().startswith('gb'):
			cmd = "gigablue_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) # commented out by Huevos cmd = "vuplus_blindscan %d %d %d %d %d %d %d %d" % (self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		print "prepared command : [%s]" % (cmd)

		self.thisRun = [] # used to check result corresponds with values used above
		self.thisRun.append(int(temp_start_int_freq))
		self.thisRun.append(int(temp_end_int_freq))
		self.thisRun.append(int(tab_hilow[band]))

		self.blindscan_container = eConsoleAppContainer()
		self.blindscan_container.appClosed.append(self.blindscanContainerClose)
		self.blindscan_container.dataAvail.append(self.blindscanContainerAvail)
		self.blindscan_container.execute(cmd)

		display_pol = pol # Display the correct polarisation in the MessageBox below
		if self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight :
			display_pol = _("circular right")
		elif self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularLeft :
			display_pol = _("circular left")
		elif  self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2 :
			if pol == "horizontal" :
				display_pol = _("circular left")
			else:
				display_pol = _("circular right")

		tmpstr = _("Looking for available transponders.\nThis will take a short while.\n\n   Current Status : %d/%d\n   Satellite : %s\n   Polarization : %s\n   Frequency range : %d - %d MHz\n   Symbol rates : %d - %d MHz") %(self.running_count, self.max_count, orb[1], display_pol, status_box_start_freq, status_box_end_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value)
		if is_scan :
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionClose, MessageBox, tmpstr, MessageBox.TYPE_INFO)
		else:
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionNone, MessageBox, tmpstr, MessageBox.TYPE_INFO)

	def blindscanContainerClose(self, retval):
		lines = self.full_data.split('\n')
		self.full_data = "" # Clear this string so we don't get duplicates on subsequent runs
		for line in lines:
			data = line.split()
			print "cnt :", len(data), ", data :", data
			if len(data) >= 10 and self.dataIsGood(data) :
				if data[0] == 'OK':
					parm = eDVBFrontendParametersSatellite()
					sys = { "DVB-S" : eDVBFrontendParametersSatellite.System_DVB_S,
						"DVB-S2" : eDVBFrontendParametersSatellite.System_DVB_S2}
					qam = { "QPSK" : parm.Modulation_QPSK,
						"8PSK" : parm.Modulation_8PSK}
					inv = { "INVERSION_OFF" : parm.Inversion_Off,
						"INVERSION_ON" : parm.Inversion_On,
						"INVERSION_AUTO" : parm.Inversion_Unknown}
					fec = { "FEC_AUTO" : parm.FEC_Auto,
						"FEC_1_2" : parm.FEC_1_2,
						"FEC_2_3" : parm.FEC_2_3,
						"FEC_3_4" : parm.FEC_3_4,
						"FEC_5_6": parm.FEC_5_6,
						"FEC_7_8" : parm.FEC_7_8,
						"FEC_8_9" : parm.FEC_8_9,
						"FEC_3_5" : parm.FEC_3_5,
						"FEC_9_10" : parm.FEC_9_10,
						"FEC_NONE" : parm.FEC_None}
					roll ={ "ROLLOFF_20" : parm.RollOff_alpha_0_20,
						"ROLLOFF_25" : parm.RollOff_alpha_0_25,
						"ROLLOFF_35" : parm.RollOff_alpha_0_35}
					pilot={ "PILOT_ON" : parm.Pilot_On,
						"PILOT_OFF" : parm.Pilot_Off}
					pol = {	"HORIZONTAL" : parm.Polarisation_Horizontal,
						"VERTICAL" : parm.Polarisation_Vertical}
					parm.orbital_position = self.orb_position
					parm.polarisation = pol[data[1]]
					parm.frequency = int(data[2])
					parm.symbol_rate = int(data[3])
					parm.system = sys[data[4]]
					parm.inversion = inv[data[5]]
					parm.pilot = pilot[data[6]]
					parm.fec = fec[data[7]]
					parm.modulation = qam[data[8]]
					parm.rolloff = roll[data[9]]
					self.tmp_tplist.append(parm)
		self.blindscan_session.close(True)

	def blindscanContainerAvail(self, str):
		print str
		#if str.startswith("OK"):
		self.full_data = self.full_data + str

	def blindscanSessionNone(self, *val):
		import time
		self.blindscan_container.sendCtrlC()
		self.blindscan_container = None
		time.sleep(2)

		if self.frontend:
			self.frontend = None
			del self.raw_channel

		if val[0] == False:
			self.tmp_tplist = []
			self.running_count = self.max_count

		self.is_runable = True


	def blindscanSessionClose(self, *val):
		self.blindscanSessionNone(val[0])

		if self.tmp_tplist != None and self.tmp_tplist != []:
			self.tmp_tplist = self.correctBugsCausedByDriver(self.tmp_tplist)

			# Sync with or remove transponders that exist in satellites.xml
			self.known_transponders = self.getKnownTransponders(self.orb_position)
			if self.dont_scan_known_tps.value :
				self.tmp_tplist = self.removeKnownTransponders(self.tmp_tplist, self.known_transponders)
			else:
				self.tmp_tplist = self.syncWithKnownTransponders(self.tmp_tplist, self.known_transponders)

			# Filter off transponders on neighbouring satellites
			if self.filter_off_adjacent_satellites.value :
				 self.tmp_tplist = self.filterOffAdjacentSatellites(self.tmp_tplist, self.orb_position, self.filter_off_adjacent_satellites.value)

			# Process transponders still in list
			if self.tmp_tplist != [] :
				for p in self.tmp_tplist:
					print "data : [%d][%d][%d][%d][%d][%d][%d][%d][%d][%d]" % (p.orbital_position, p.polarisation, p.frequency, p.symbol_rate, p.system, p.inversion, p.pilot, p.fec, p.modulation, p.modulation)

				if self.search_type.value == 0 : # Do a service scan
					self.startScan(self.tmp_tplist, self.feid)
				else: # Save transponder data to file. No service scan.
					self.tmp_tplist = sorted(self.tmp_tplist, key=lambda transponder: transponder.frequency)
					xml_location = self.createSatellitesXMLfile(self.tmp_tplist, XML_BLINDSCAN_DIR)
					msg = _("Search completed. %d transponders found.\n\nDetails saved in:\n%s")%(len(self.tmp_tplist), xml_location)
					self.session.openWithCallback(self.callbackNone, MessageBox, msg, MessageBox.TYPE_INFO, timeout=300)
			else:
				msg = _("No new transponders found! \n\nOnly transponders already listed in satellites.xml \nhave been found for those search parameters!")
				self.session.openWithCallback(self.callbackNone, MessageBox, msg, MessageBox.TYPE_INFO, timeout=60)

		else:
			msg = _("No transponders were found for those search parameters!")
			if val[0] == False:
				msg = _("The blindscan run was cancelled by the user.")
			self.session.openWithCallback(self.callbackNone, MessageBox, msg, MessageBox.TYPE_INFO, timeout=60)
			self.tmp_tplist = []

	def startScan(self, tlist, feid, networkid = 0):
		self.scan_session = None

		flags = 0
		if self.scan_clearallservices.value:
			flags |= eComponentScan.scanRemoveServices
		else:
			flags |= eComponentScan.scanDontRemoveUnscanned
		if self.scan_onlyfree.value:
			flags |= eComponentScan.scanOnlyFree
		self.session.open(ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])

	def getKnownTransponders(self, pos):
		tlist = []
		list = nimmanager.getTransponders(pos)
		for x in list:
			if x[0] == 0:
				parm = eDVBFrontendParametersSatellite()
				parm.frequency = x[1]
				parm.symbol_rate = x[2]
				parm.polarisation = x[3]
				parm.fec = x[4]
				parm.inversion = x[7]
				parm.orbital_position = pos
				parm.system = x[5]
				parm.modulation = x[6]
				parm.rolloff = x[8]
				parm.pilot = x[9]
				tlist.append(parm)
		return tlist

	def syncWithKnownTransponders(self, tplist, knowntp) :
		tolerance = 5
		multiplier = 1000
		x = 0
		for t in tplist :
			for k in knowntp :
				if (t.polarisation % 2) == (k.polarisation % 2) and \
					abs(t.frequency - k.frequency) < (tolerance*multiplier) and \
					abs(t.symbol_rate - k.symbol_rate) < (tolerance*multiplier) :
					tplist[x] = k
					break
			x += 1
		return tplist

	def removeKnownTransponders(self, tplist, knowntp) :
		new_tplist = []
		tolerance = 5
		multiplier = 1000
		x = 0
		isnt_known = True
		for t in tplist :
			for k in knowntp :
				if (t.polarisation % 2) == (k.polarisation % 2) and \
					abs(t.frequency - k.frequency) < (tolerance*multiplier) and \
					abs(t.symbol_rate - k.symbol_rate) < (tolerance*multiplier) :
					isnt_known = False
					break
			x += 1
			if isnt_known :
				new_tplist.append(t)
			else:
				isnt_known = True
		return new_tplist

	def filterOffAdjacentSatellites(self, tplist, pos, degrees) :
		neighbours = []
		tenths_of_degrees = degrees * 10
		for sat in nimmanager.satList :
			if sat[0] != pos and self.positionDiff(pos, sat[0]) <= tenths_of_degrees :
				neighbours.append(sat[0])
		for neighbour in neighbours :
			tplist = self.removeKnownTransponders(tplist, self.getKnownTransponders(neighbour))
		return tplist

	def correctBugsCausedByDriver(self, tplist) :
		if self.is_c_band_scan : # for some reason a c-band scan (with a Vu+) returns the transponder frequencies in Ku band format so they have to be converted back to c-band numbers before the subsequent service search
			x = 0
			for transponders in tplist :
				if tplist[x].frequency > (4200*1000) :
					tplist[x].frequency = (5150*1000) - (tplist[x].frequency - (9750*1000))
				x += 1

		x = 0
		for transponders in tplist :
			if tplist[x].system == 0 : # convert DVB-S transponders to auto fec as for some reason the tuner incorrectly returns 3/4 FEC for all transmissions
				tplist[x].fec = 0
			if self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight : # Return circular transponders to correct polarisation
				tplist[x].polarisation = eDVBFrontendParametersSatellite.Polarisation_CircularRight
			elif self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularLeft : # Return circular transponders to correct polarisation
				tplist[x].polarisation = eDVBFrontendParametersSatellite.Polarisation_CircularLeft
			elif self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2: # Return circular transponders to correct polarisation
				if tplist[x].polarisation == eDVBFrontendParametersSatellite.Polarisation_Horizontal : # Return circular transponders to correct polarisation
					tplist[x].polarisation = eDVBFrontendParametersSatellite.Polarisation_CircularLeft
				else:
					tplist[x].polarisation = eDVBFrontendParametersSatellite.Polarisation_CircularRight
			x += 1
		return tplist

	def positionDiff(self, pos1, pos2) :
		diff = pos1 - pos2
		return min(abs(diff % 3600), 3600 - abs(diff % 3600))

	def dataIsGood(self, data) : # check output of the binary for nonsense values
		good = False
		low_lo = 9750
		high_lo = 10600
		c_lo = 5150
		lower_freq = self.thisRun[0]
		upper_freq = self.thisRun[1]
		high_band = self.thisRun[2]
		data_freq = int(int(data[2])/1000)
		data_symbol = int(data[3])
		lower_symbol = (self.blindscan_start_symbol.value * 1000000) - 200000
		upper_symbol = (self.blindscan_stop_symbol.value * 1000000) + 200000

		if high_band :
			data_if_freq = data_freq - high_lo
		elif self.is_c_band_scan and data_freq > 2999 and data_freq < 4201 :
			data_if_freq = c_lo - data_freq
		else :
			data_if_freq = data_freq - low_lo

		if data_if_freq >= lower_freq and data_if_freq <= upper_freq :
			good = True

		if data_symbol < lower_symbol or data_symbol > upper_symbol :
			good = False

		if good == False :
			print "Data returned by the binary is not good...\n	Data: Frequency [%d], Symbol rate [%d]" % (int(data[2]), int(data[3]))

		return good

	def createSatellitesXMLfile(self, tp_list, save_xml_dir) :
		pos = self.orb_position
		if pos > 1800 :
			pos -= 3600
		if pos < 0 :
			pos_name = '%dW' % (abs(int(pos))/10)
		else :
			pos_name = '%dE' % (abs(int(pos))/10)
		location = '%s/blindscan_%s_%s.xml' %(save_xml_dir, pos_name, strftime("%d-%m-%Y_%H-%M-%S"))
		tuner = ['A', 'B', 'C']
		polarisation = ['horizontal', 'vertical', 'circular left', 'circular right', 'vertical and horizontal', 'circular right and circular left']
		adjacent = ['no', 'up to 1 degree', 'up to 2 degrees', 'up to 3 degrees']
		known_txp = 'no'
		if self.filter_off_adjacent_satellites.value :
			known_txp ='yes'
		xml = ['<?xml version="1.0" encoding="iso-8859-1"?>\n\n']
		xml.append('<!--\n')
		xml.append('	File created on %s\n' % (strftime("%A, %d of %B %Y, %H:%M:%S")))
		xml.append('	using %s receiver running Enigma2 image, version %s,\n' % (getBoxType(), about.getImageVersionString()))
		xml.append('	build %s, with the blindscan plugin updated by Huevos\n\n' % (about.getBuildVersionString()))
		xml.append('	Search parameters:\n')
		xml.append('		Tuner: %s\n' % (tuner[self.feid]))
		xml.append('		Satellite: %s\n' % (self.sat_name))
		xml.append('		Start frequency: %dMHz\n' % (self.blindscan_start_frequency.value))
		xml.append('		Stop frequency: %dMHz\n' % (self.blindscan_stop_frequency.value))
		xml.append('		Polarization: %s\n' % (polarisation[self.scan_sat.polarization.value]))
		xml.append('		Lower symbol rate: %d\n' % (self.blindscan_start_symbol.value * 1000))
		xml.append('		Upper symbol rate: %d\n' % (self.blindscan_stop_symbol.value * 1000))
		xml.append('		Only save unknown tranponders: %s\n' % (known_txp))
		xml.append('		Filter out adjacent satellites: %s\n' % (adjacent[self.filter_off_adjacent_satellites.value]))
		xml.append('-->\n\n')
		xml.append('<satellites>\n')
		xml.append('	<sat name="%s" flags="0" position="%s">\n' % (self.sat_name.replace('&', '&amp;'), self.orb_position))
		for tp in tp_list :
			xml.append('		<transponder frequency="%d" symbol_rate="%d" polarization="%d" fec_inner="%d" system="%d" modulation="%d"/>\n' % (tp.frequency, tp.symbol_rate, tp.polarisation, tp.fec, tp.system, tp.modulation))
		xml.append('	</sat>\n')
		xml.append('</satellites>')
		open(location, "w").writelines(xml)
		return location

	def SatBandCheck(self, pos) :
		freq = 0
		band = ''
		tp_list = self.getKnownTransponders(pos)
		if len(tp_list) :
			freq = int(tp_list[0].frequency)
		if freq :
			if freq < 4201000 and freq > 2999000 :
				band = 'C'
			elif freq < 12751000 and freq > 10700000 :
				band = 'Ku'
		print "SatBandCheck band = %s" % (band)
		return band
예제 #43
0
class Blindscan(ConfigListScreen, Screen):
    skin = """
		<screen position="center,center" size="560,390" title="Blindscan">
			<ePixmap pixmap="skin_default/buttons/red.png" position="40,10" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/green.png" position="210,10" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/blue.png" position="380,10" size="140,40" alphatest="on" />

			<widget source="key_red" render="Label" position="40,10" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1"/>
			<widget source="key_green" render="Label" position="210,10" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1"/>
			<widget source="key_blue" render="Label" position="380,10" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" foregroundColor="#ffffff" transparent="1"/>

			<widget name="config" position="5,70" size="550,280" scrollbarMode="showOnDemand" />
			<widget name="introduction" position="0,365" size="560,20" font="Regular;20" halign="center" />
		</screen>
		"""

    def __init__(self, session):
        Screen.__init__(self, session)

        self.current_play_service = self.session.nav.getCurrentlyPlayingServiceReference(
        )

        # update sat list
        self.satList = []
        for slot in nimmanager.nim_slots:
            if slot.isCompatible("DVB-S"):
                self.satList.append(nimmanager.getSatListForNim(slot.slot))
            else:
                self.satList.append(None)

        # make config
        self.createConfig()

        self.list = []
        self.status = ""

        ConfigListScreen.__init__(self, self.list)
        if self.scan_nims.value != None and self.scan_nims.value != "":
            self["actions"] = ActionMap(
                [
                    "OkCancelActions",
                    "ShortcutActions",
                    "WizardActions",
                    "ColorActions",
                    "SetupActions",
                ], {
                    "red": self.keyCancel,
                    "green": self.keyGo,
                    "blue": self.keyGoAll,
                    "ok": self.keyGo,
                    "cancel": self.keyCancel,
                }, -2)
            self["key_red"] = StaticText(_("Exit"))
            self["key_green"] = StaticText("Scan")
            self["key_blue"] = StaticText("Scan All")
            self["introduction"] = Label(_("Press Green/OK to start the scan"))
            self.createSetup()
        else:
            self["actions"] = ActionMap(
                [
                    "OkCancelActions",
                    "ShortcutActions",
                    "WizardActions",
                    "ColorActions",
                    "SetupActions",
                ], {
                    "red": self.keyCancel,
                    "green": self.keyNone,
                    "blue": self.keyNone,
                    "ok": self.keyNone,
                    "cancel": self.keyCancel,
                }, -2)
            self["key_red"] = StaticText(_("Exit"))
            self["key_green"] = StaticText(" ")
            self["key_blue"] = StaticText(" ")
            self["introduction"] = Label(
                _("Please setup your tuner configuration."))

        self.i2c_mapping_table = None
        self.nimSockets = self.ScanNimsocket()
        self.makeNimSocket()

    def ScanNimsocket(self):
        _nimSocket = {}
        fp = file('/proc/bus/nim_sockets')

        sNo, sName, sI2C = -1, "", -1
        for line in fp:
            line = line.strip()
            if line.startswith('NIM Socket'):
                sNo, sName, sI2C = -1, '', -1
                try:
                    sNo = line.split()[2][:-1]
                except:
                    sNo = -1
            elif line.startswith('I2C_Device:'):
                try:
                    sI2C = line.split()[1]
                except:
                    sI2C = -1
            elif line.startswith('Name:'):
                try:
                    sName = line.split()[3][4:-1]
                except:
                    sName = ""
            if sNo >= 0 and sName != "":
                if sI2C != -1:
                    _nimSocket[sNo] = [sName, sI2C]
                else:
                    _nimSocket[sNo] = [sName]
        fp.close()
        print "parsed nimsocket :", _nimSocket
        return _nimSocket

    def makeNimSocket(self, nimname=""):
        is_exist_i2c = False
        self.i2c_mapping_table = {0: 2, 1: 3, 2: 1, 3: 0}
        if self.nimSockets is not None:
            for XX in self.nimSockets.keys():
                nimsocket = self.nimSockets[XX]
                if len(nimsocket) > 1:
                    try:
                        self.i2c_mapping_table[int(XX)] = int(nimsocket[1])
                    except:
                        continue
                    is_exist_i2c = True
        print "i2c_mapping_table :", self.i2c_mapping_table, ", is_exist_i2c :", is_exist_i2c
        if is_exist_i2c: return

        if nimname == "AVL6222":
            model = file('/proc/stb/info/vumodel').read().strip()
            if model == "uno":
                self.i2c_mapping_table = {0: 3, 1: 3, 2: 1, 3: 0}
            elif model == "duo2":
                nimdata = self.nimSockets['0']
                try:
                    if nimdata[0] == "AVL6222":
                        self.i2c_mapping_table = {0: 2, 1: 2, 2: 4, 3: 4}
                    else:
                        self.i2c_mapping_table = {0: 2, 1: 4, 2: 4, 3: 0}
                except:
                    self.i2c_mapping_table = {0: 2, 1: 4, 2: 4, 3: 0}
            else:
                self.i2c_mapping_table = {0: 2, 1: 4, 2: 0, 3: 0}
        else:
            self.i2c_mapping_table = {0: 2, 1: 3, 2: 1, 3: 0}

    def getNimSocket(self, slot_number):
        if slot_number < 0 or slot_number > 3:
            return -1
        return self.i2c_mapping_table[slot_number]

    def keyNone(self):
        None

    def callbackNone(self, *retval):
        None

    def openFrontend(self):
        res_mgr = eDVBResourceManager.getInstance()
        if res_mgr:
            self.raw_channel = res_mgr.allocateRawChannel(self.feid)
            if self.raw_channel:
                self.frontend = self.raw_channel.getFrontend()
                if self.frontend:
                    return True
                else:
                    print "getFrontend failed"
            else:
                print "getRawChannel failed"
        else:
            print "getResourceManager instance failed"
        return False

    def createConfig(self):
        self.feinfo = None
        frontendData = None
        defaultSat = {
            "orbpos": 192,
            "system": eDVBFrontendParametersSatellite.System_DVB_S,
            "frequency": 11836,
            "inversion": eDVBFrontendParametersSatellite.Inversion_Unknown,
            "symbolrate": 27500,
            "polarization":
            eDVBFrontendParametersSatellite.Polarisation_Horizontal,
            "fec": eDVBFrontendParametersSatellite.FEC_Auto,
            "fec_s2": eDVBFrontendParametersSatellite.FEC_9_10,
            "modulation": eDVBFrontendParametersSatellite.Modulation_QPSK
        }

        self.service = self.session.nav.getCurrentService()
        if self.service is not None:
            self.feinfo = self.service.frontendInfo()
            frontendData = self.feinfo and self.feinfo.getAll(True)
        if frontendData is not None:
            ttype = frontendData.get("tuner_type", "UNKNOWN")
            if ttype == "DVB-S":
                defaultSat["system"] = frontendData.get(
                    "system", eDVBFrontendParametersSatellite.System_DVB_S)
                defaultSat["frequency"] = frontendData.get("frequency",
                                                           0) / 1000
                defaultSat["inversion"] = frontendData.get(
                    "inversion",
                    eDVBFrontendParametersSatellite.Inversion_Unknown)
                defaultSat["symbolrate"] = frontendData.get("symbol_rate",
                                                            0) / 1000
                defaultSat["polarization"] = frontendData.get(
                    "polarization",
                    eDVBFrontendParametersSatellite.Polarisation_Horizontal)
                if defaultSat[
                        "system"] == eDVBFrontendParametersSatellite.System_DVB_S2:
                    defaultSat["fec_s2"] = frontendData.get(
                        "fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
                    defaultSat["rolloff"] = frontendData.get(
                        "rolloff",
                        eDVBFrontendParametersSatellite.RollOff_alpha_0_35)
                    defaultSat["pilot"] = frontendData.get(
                        "pilot", eDVBFrontendParametersSatellite.Pilot_Unknown)
                else:
                    defaultSat["fec"] = frontendData.get(
                        "fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
                defaultSat["modulation"] = frontendData.get(
                    "modulation",
                    eDVBFrontendParametersSatellite.Modulation_QPSK)
                defaultSat["orbpos"] = frontendData.get("orbital_position", 0)
        del self.feinfo
        del self.service
        del frontendData

        self.scan_sat = ConfigSubsection()
        self.scan_networkScan = ConfigYesNo(default=False)

        # blindscan add
        self.blindscan_hi = ConfigSelection(default="hi_low",
                                            choices=[("low", _("low")),
                                                     ("high", _("high")),
                                                     ("hi_low", _("hi_low"))])

        #ConfigYesNo(default = True)
        self.blindscan_start_frequency = ConfigInteger(default=950 * 1000000)
        self.blindscan_stop_frequency = ConfigInteger(default=2150 * 1000000)
        self.blindscan_start_symbol = ConfigInteger(default=2 * 1000000)
        self.blindscan_stop_symbol = ConfigInteger(default=45 * 1000000)
        self.scan_clearallservices = ConfigYesNo(default=False)
        self.scan_onlyfree = ConfigYesNo(default=False)

        # collect all nims which are *not* set to "nothing"
        nim_list = []
        for n in nimmanager.nim_slots:
            if n.config_mode == "nothing":
                continue
            if n.config_mode == "advanced" and len(
                    nimmanager.getSatListForNim(n.slot)) < 1:
                continue
            if n.config_mode in ("loopthrough", "satposdepends"):
                root_id = nimmanager.sec.getRoot(
                    n.slot_id, int(n.config.connectedTo.value))
                if n.type == nimmanager.nim_slots[
                        root_id].type:  # check if connected from a DVB-S to DVB-S2 Nim or vice versa
                    continue
            if n.isCompatible("DVB-S"):
                nim_list.append((str(n.slot), n.friendly_full_description))
        self.scan_nims = ConfigSelection(choices=nim_list)

        # sat
        self.scan_sat.frequency = ConfigInteger(
            default=defaultSat["frequency"], limits=(1, 99999))
        #self.scan_sat.polarization = ConfigSelection(default = defaultSat["polarization"], choices = [
        self.scan_sat.polarization = ConfigSelection(
            default=eDVBFrontendParametersSatellite.Polarisation_CircularRight
            + 1,
            choices=[
                (eDVBFrontendParametersSatellite.Polarisation_CircularRight +
                 1, _("horizontal_vertical")),
                (eDVBFrontendParametersSatellite.Polarisation_Horizontal,
                 _("horizontal")),
                (eDVBFrontendParametersSatellite.Polarisation_Vertical,
                 _("vertical")),
                (eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
                 _("circular left")),
                (eDVBFrontendParametersSatellite.Polarisation_CircularRight,
                 _("circular right"))
            ])
        self.scan_scansat = {}
        for sat in nimmanager.satList:
            self.scan_scansat[sat[0]] = ConfigYesNo(default=False)

        self.scan_satselection = []
        for slot in nimmanager.nim_slots:
            if slot.isCompatible("DVB-S"):
                self.scan_satselection.append(
                    getConfigSatlist(defaultSat["orbpos"],
                                     self.satList[slot.slot]))
        return True

    def getSelectedSatIndex(self, v):
        index = 0
        none_cnt = 0
        for n in self.satList:
            if self.satList[index] == None:
                none_cnt = none_cnt + 1
            if index == int(v):
                return (index - none_cnt)
            index = index + 1
        return -1

    def createSetup(self):
        self.list = []
        self.multiscanlist = []
        index_to_scan = int(self.scan_nims.value)
        print "ID: ", index_to_scan

        self.tunerEntry = getConfigListEntry(_("Tuner"), self.scan_nims)
        self.list.append(self.tunerEntry)

        if self.scan_nims == []:
            return

        self.systemEntry = None
        self.modulationEntry = None
        nim = nimmanager.nim_slots[index_to_scan]

        self.scan_networkScan.value = False
        if nim.isCompatible("DVB-S"):
            self.list.append(
                getConfigListEntry(
                    _('Satellite'), self.scan_satselection[
                        self.getSelectedSatIndex(index_to_scan)]))
            self.list.append(
                getConfigListEntry(_('Scan start frequency'),
                                   self.blindscan_start_frequency))
            self.list.append(
                getConfigListEntry(_('Scan stop frequency'),
                                   self.blindscan_stop_frequency))
            self.list.append(
                getConfigListEntry(_("Polarity"), self.scan_sat.polarization))
            self.list.append(
                getConfigListEntry(_("Scan band"), self.blindscan_hi))
            self.list.append(
                getConfigListEntry(_('Scan start symbolrate'),
                                   self.blindscan_start_symbol))
            self.list.append(
                getConfigListEntry(_('Scan stop symbolrate'),
                                   self.blindscan_stop_symbol))
            self.list.append(
                getConfigListEntry(_("Clear before scan"),
                                   self.scan_clearallservices))
            self.list.append(
                getConfigListEntry(_("Only Free scan"), self.scan_onlyfree))
            self["config"].list = self.list
            self["config"].l.setList(self.list)

    def newConfig(self):
        cur = self["config"].getCurrent()
        print "cur is", cur
        if cur == self.tunerEntry or \
         cur == self.systemEntry or \
         (self.modulationEntry and self.systemEntry[1].value == eDVBFrontendParametersSatellite.System_DVB_S2 and cur == self.modulationEntry):
            self.createSetup()

    def checkSettings(self):
        if self.blindscan_start_frequency.value < 950 * 1000000 or self.blindscan_start_frequency.value > 2150 * 1000000:
            self.session.open(
                MessageBox,
                _("Please check again.\nStart frequency must be between 950 and 2150."
                  ), MessageBox.TYPE_ERROR)
            return False
        if self.blindscan_stop_frequency.value < 950 * 1000000 or self.blindscan_stop_frequency.value > 2150 * 1000000:
            self.session.open(
                MessageBox,
                _("Please check again.\nStop frequency must be between 950 and 2150."
                  ), MessageBox.TYPE_ERROR)
            return False
        if self.blindscan_start_frequency.value > self.blindscan_stop_frequency.value:
            self.session.open(
                MessageBox,
                _("Please check again.\nFrequency : start value is larger than stop value."
                  ), MessageBox.TYPE_ERROR)
            return False
        if self.blindscan_start_symbol.value < 2 * 1000000 or self.blindscan_start_symbol.value > 45 * 1000000:
            self.session.open(
                MessageBox,
                _("Please check again.\nStart symbolrate must be between 2MHz and 45MHz."
                  ), MessageBox.TYPE_ERROR)
            return False
        if self.blindscan_stop_symbol.value < 2 * 1000000 or self.blindscan_stop_symbol.value > 45 * 1000000:
            self.session.open(
                MessageBox,
                _("Please check again.\nStop symbolrate must be between 2MHz and 45MHz."
                  ), MessageBox.TYPE_ERROR)
            return False
        if self.blindscan_start_symbol.value > self.blindscan_stop_symbol.value:
            self.session.open(
                MessageBox,
                _("Please check again.\nSymbolrate : start value is larger than stop value."
                  ), MessageBox.TYPE_ERROR)
            return False
        return True

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()

    def keyCancel(self):
        self.session.nav.playService(self.current_play_service)
        for x in self["config"].list:
            x[1].cancel()
        self.close()

    def keyGo(self):
        if self.checkSettings() == False:
            return

        tab_pol = {
            eDVBFrontendParametersSatellite.Polarisation_Horizontal:
            "horizontal",
            eDVBFrontendParametersSatellite.Polarisation_Vertical:
            "vertical",
            eDVBFrontendParametersSatellite.Polarisation_CircularLeft:
            "circular left",
            eDVBFrontendParametersSatellite.Polarisation_CircularRight:
            "circular right",
            eDVBFrontendParametersSatellite.Polarisation_CircularRight + 1:
            "horizontal_vertical"
        }

        self.tmp_tplist = []
        tmp_pol = []
        tmp_band = []
        idx_selected_sat = int(self.getSelectedSatIndex(self.scan_nims.value))
        tmp_list = [
            self.satList[int(self.scan_nims.value)][
                self.scan_satselection[idx_selected_sat].index]
        ]

        if self.blindscan_hi.value == "hi_low":
            tmp_band = ["low", "high"]
        else:
            tmp_band = [self.blindscan_hi.value]

        if self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight + 1:
            tmp_pol = ["horizontal", "vertical"]
        else:
            tmp_pol = [tab_pol[self.scan_sat.polarization.value]]

        self.doRun(tmp_list, tmp_pol, tmp_band)

    def keyGoAll(self):
        if self.checkSettings() == False:
            return
        self.tmp_tplist = []
        tmp_list = []
        tmp_band = ["low", "high"]
        tmp_pol = ["horizontal", "vertical"]

        for slot in nimmanager.nim_slots:
            device_name = "/dev/dvb/adapter0/frontend%d" % (slot.slot)
            if slot.isCompatible("DVB-S") and int(
                    self.scan_nims.value) == slot.slot:
                for s in self.satList[slot.slot]:
                    tmp_list.append(s)
        self.doRun(tmp_list, tmp_pol, tmp_band)

    def doRun(self, tmp_list, tmp_pol, tmp_band):
        def GetCommand(nimIdx):
            _nimSocket = self.nimSockets
            try:
                sName = _nimSocket[str(nimIdx)][0]
                sType = _supportNimType[sName]
                return "vuplus_%(TYPE)sblindscan" % {'TYPE': sType}, sName
            except:
                pass
            return "vuplus_blindscan", ""

        self.binName, nimName = GetCommand(self.scan_nims.value)

        self.makeNimSocket(nimName)
        if self.binName is None:
            self.session.open(
                MessageBox,
                "Blindscan is not supported in " + nimName + " tuner.",
                MessageBox.TYPE_ERROR)
            print nimName + " is not support blindscan."
            return

        self.full_data = ""
        self.total_list = []
        for x in tmp_list:
            for y in tmp_pol:
                for z in tmp_band:
                    self.total_list.append([x, y, z])
                    print "add scan item : ", x, ", ", y, ", ", z

        self.max_count = len(self.total_list)
        self.is_runable = True
        self.running_count = 0
        self.clockTimer = eTimer()
        self.clockTimer.callback.append(self.doClock)
        self.clockTimer.start(1000)

    def doClock(self):
        is_scan = False
        if self.is_runable:
            if self.running_count >= self.max_count:
                self.clockTimer.stop()
                del self.clockTimer
                self.clockTimer = None
                print "Done"
                return
            orb = self.total_list[self.running_count][0]
            pol = self.total_list[self.running_count][1]
            band = self.total_list[self.running_count][2]
            self.running_count = self.running_count + 1
            print "running status-[%d] : [%d][%s][%s]" % (self.running_count,
                                                          orb[0], pol, band)
            if self.running_count == self.max_count:
                is_scan = True
            self.prepareScanData(orb, pol, band, is_scan)

    def prepareScanData(self, orb, pol, band, is_scan):
        self.is_runable = False
        self.orb_position = orb[0]
        self.feid = int(self.scan_nims.value)
        tab_hilow = {"high": 1, "low": 0}
        tab_pol = {
            "horizontal":
            eDVBFrontendParametersSatellite.Polarisation_Horizontal,
            "vertical":
            eDVBFrontendParametersSatellite.Polarisation_Vertical,
            "circular left":
            eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
            "circular right":
            eDVBFrontendParametersSatellite.Polarisation_CircularRight
        }

        returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

        if not self.openFrontend():
            self.oldref = self.session.nav.getCurrentlyPlayingServiceReference(
            )
            self.session.nav.stopService()
            if not self.openFrontend():
                if self.session.pipshown:
                    self.session.pipshown = False
                    del self.session.pip
                    if not self.openFrontend():
                        self.frontend = None
        self.tuner = Tuner(self.frontend)

        if tab_hilow[band]:
            self.scan_sat.frequency.value = 12515
        else:
            self.scan_sat.frequency.value = 11015
        returnvalue = (self.scan_sat.frequency.value, 0, tab_pol[pol], 0, 0,
                       orb[0], eDVBFrontendParametersSatellite.System_DVB_S, 0,
                       0, 0)
        self.tuner.tune(returnvalue)

        if self.getNimSocket(self.feid) < 0:
            print "can't find i2c number!!"
            return
        try:
            cmd = "%s %d %d %d %d %d %d %d %d" % (
                self.binName, self.blindscan_start_frequency.value / 1000000,
                self.blindscan_stop_frequency.value / 1000000,
                self.blindscan_start_symbol.value / 1000000,
                self.blindscan_stop_symbol.value / 1000000, tab_pol[pol],
                tab_hilow[band], self.feid, self.getNimSocket(self.feid))
        except:
            return
        print "prepared command : [%s]" % (cmd)
        self.blindscan_container = eConsoleAppContainer()
        self.blindscan_container.appClosed.append(self.blindscanContainerClose)
        self.blindscan_container.dataAvail.append(self.blindscanContainerAvail)
        self.blindscan_container.execute(cmd)

        tmpstr = "Look for available transponders.\nThis works will take several minutes.\n\n   - Current Status : %d/%d\n   - Orbital Positions : %s\n   - Polarization : %s\n   - Bandwidth : %s" % (
            self.running_count, self.max_count, orb[1], pol, band)
        if is_scan:
            self.blindscan_session = self.session.openWithCallback(
                self.blindscanSessionClose, MessageBox, _(tmpstr),
                MessageBox.TYPE_INFO)
        else:
            self.blindscan_session = self.session.openWithCallback(
                self.blindscanSessionNone, MessageBox, _(tmpstr),
                MessageBox.TYPE_INFO)

    def blindscanContainerClose(self, retval):
        lines = self.full_data.split('\n')
        for line in lines:
            data = line.split()
            print "cnt :", len(data), ", data :", data
            if len(data) >= 10:
                if data[0] == 'OK':
                    parm = eDVBFrontendParametersSatellite()
                    sys = {
                        "DVB-S": eDVBFrontendParametersSatellite.System_DVB_S,
                        "DVB-S2": eDVBFrontendParametersSatellite.System_DVB_S2
                    }
                    qam = {
                        "QPSK": parm.Modulation_QPSK,
                        "8PSK": parm.Modulation_8PSK
                    }
                    inv = {
                        "INVERSION_OFF": parm.Inversion_Off,
                        "INVERSION_ON": parm.Inversion_On,
                        "INVERSION_AUTO": parm.Inversion_Unknown
                    }
                    fec = {
                        "FEC_AUTO": parm.FEC_Auto,
                        "FEC_1_2": parm.FEC_1_2,
                        "FEC_2_3": parm.FEC_2_3,
                        "FEC_3_4": parm.FEC_3_4,
                        "FEC_5_6": parm.FEC_5_6,
                        "FEC_7_8": parm.FEC_7_8,
                        "FEC_8_9": parm.FEC_8_9,
                        "FEC_3_5": parm.FEC_3_5,
                        "FEC_9_10": parm.FEC_9_10,
                        "FEC_NONE": parm.FEC_None
                    }
                    roll = {
                        "ROLLOFF_20": parm.RollOff_alpha_0_20,
                        "ROLLOFF_25": parm.RollOff_alpha_0_25,
                        "ROLLOFF_35": parm.RollOff_alpha_0_35
                    }
                    pilot = {
                        "PILOT_ON": parm.Pilot_On,
                        "PILOT_OFF": parm.Pilot_Off
                    }
                    pol = {
                        "HORIZONTAL": parm.Polarisation_Horizontal,
                        "VERTICAL": parm.Polarisation_Vertical
                    }
                    try:
                        parm.orbital_position = self.orb_position
                        parm.polarisation = pol[data[1]]
                        parm.frequency = int(data[2])
                        parm.symbol_rate = int(data[3])
                        parm.system = sys[data[4]]
                        parm.inversion = inv[data[5]]
                        parm.pilot = pilot[data[6]]
                        parm.fec = fec[data[7]]
                        parm.modulation = qam[data[8]]
                        parm.rolloff = roll[data[9]]
                        self.tmp_tplist.append(parm)
                    except:
                        pass
        self.blindscan_session.close(True)

    def blindscanContainerAvail(self, str):
        print str
        #if str.startswith("OK"):
        self.full_data = self.full_data + str

    def blindscanSessionNone(self, *val):
        import time
        self.blindscan_container.sendCtrlC()
        self.blindscan_container = None
        time.sleep(2)

        if self.frontend:
            self.frontend = None
            del self.raw_channel

        if val[0] == False:
            self.tmp_tplist = []
            self.running_count = self.max_count

        self.is_runable = True

    def blindscanSessionClose(self, *val):
        self.blindscanSessionNone(val[0])

        if self.tmp_tplist != None and self.tmp_tplist != []:
            for p in self.tmp_tplist:
                print "data : [%d][%d][%d][%d][%d][%d][%d][%d][%d][%d]" % (
                    p.orbital_position, p.polarisation, p.frequency,
                    p.symbol_rate, p.system, p.inversion, p.pilot, p.fec,
                    p.modulation, p.modulation)

            self.startScan(self.tmp_tplist, self.feid)
        else:
            msg = "No found transponders!!\nPlease check the satellite connection, or scan other search condition."
            if val[0] == False:
                msg = "Blindscan was canceled by the user."
            self.session.openWithCallback(self.callbackNone,
                                          MessageBox,
                                          _(msg),
                                          MessageBox.TYPE_INFO,
                                          timeout=10)
            self.tmp_tplist = []

    def startScan(self, tlist, feid, networkid=0):
        self.scan_session = None

        flags = 0
        if self.scan_clearallservices.value:
            flags |= eComponentScan.scanRemoveServices
        else:
            flags |= eComponentScan.scanDontRemoveUnscanned
        if self.scan_onlyfree.value:
            flags |= eComponentScan.scanOnlyFree
        self.session.open(ServiceScan, [{
            "transponders": tlist,
            "feid": feid,
            "flags": flags,
            "networkid": networkid
        }])
예제 #44
0
class AutoDiseqc(Screen, ConfigListScreen):
    skin = """
		<screen position="c-250,c-100" size="500,250" title=" ">
			<widget source="statusbar" render="Label" position="10,5" zPosition="10" size="e-10,60" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
			<widget source="tunerstatusbar" render="Label" position="10,60" zPosition="10" size="e-10,30" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
			<widget name="config" position="10,100" size="e-10,100" scrollbarMode="showOnDemand" />
			<ePixmap pixmap="skin_default/buttons/red.png" position="c-140,e-45" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="c-140,e-45" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
		</screen>"""

    diseqc_ports = ["A", "B", "C", "D"]

    sat_frequencies = [
     # astra 192 zdf
     ( 11953, 27500, \
     eDVBFrontendParametersSatellite.Polarisation_Horizontal, eDVBFrontendParametersSatellite.FEC_3_4, \
     eDVBFrontendParametersSatellite.Inversion_Off, 192, \
     eDVBFrontendParametersSatellite.System_DVB_S, eDVBFrontendParametersSatellite.Modulation_Auto, \
     eDVBFrontendParametersSatellite.RollOff_auto, eDVBFrontendParametersSatellite.Pilot_Unknown, \
     1079, 1, "Astra 1 19.2e"),

     # astra 235 astra ses
     ( 12168, 27500, \
     eDVBFrontendParametersSatellite.Polarisation_Vertical, eDVBFrontendParametersSatellite.FEC_3_4, \
     eDVBFrontendParametersSatellite.Inversion_Off, 235, \
     eDVBFrontendParametersSatellite.System_DVB_S, eDVBFrontendParametersSatellite.Modulation_Auto, \
     eDVBFrontendParametersSatellite.RollOff_auto, eDVBFrontendParametersSatellite.Pilot_Unknown, \
     3224, 3, "Astra 3 23.5e"),

     # astra 282 bbc
     ( 10773, 22000, \
     eDVBFrontendParametersSatellite.Polarisation_Horizontal, eDVBFrontendParametersSatellite.FEC_5_6, \
     eDVBFrontendParametersSatellite.Inversion_Off, 282, \
     eDVBFrontendParametersSatellite.System_DVB_S, eDVBFrontendParametersSatellite.Modulation_Auto, \
     eDVBFrontendParametersSatellite.RollOff_auto, eDVBFrontendParametersSatellite.Pilot_Unknown, \
     2045, 2, "Astra 2 28.2e"),

     # hotbird 130 rai
     ( 10992, 27500, \
     eDVBFrontendParametersSatellite.Polarisation_Vertical, eDVBFrontendParametersSatellite.FEC_2_3, \
     eDVBFrontendParametersSatellite.Inversion_Off, 130, \
     eDVBFrontendParametersSatellite.System_DVB_S, eDVBFrontendParametersSatellite.Modulation_Auto, \
     eDVBFrontendParametersSatellite.RollOff_auto, eDVBFrontendParametersSatellite.Pilot_Unknown, \
     12400, 318, "Hotbird 13.0e"),
    ]

    SAT_TABLE_FREQUENCY = 0
    SAT_TABLE_SYMBOLRATE = 1
    SAT_TABLE_POLARISATION = 2
    SAT_TABLE_FEC = 3
    SAT_TABLE_INVERSION = 4
    SAT_TABLE_ORBPOS = 5
    SAT_TABLE_SYSTEM = 6
    SAT_TABLE_MODULATION = 7
    SAT_TABLE_ROLLOFF = 8
    SAT_TABLE_PILOT = 9
    SAT_TABLE_TSID = 10
    SAT_TABLE_ONID = 11
    SAT_TABLE_NAME = 12

    def __init__(self, session, feid, nr_of_ports, simple_tone,
                 simple_sat_change):
        self.skin = AutoDiseqc.skin
        Screen.__init__(self, session)

        self["statusbar"] = StaticText(" ")
        self["tunerstatusbar"] = StaticText(" ")

        self.list = []
        ConfigListScreen.__init__(self, self.list, session=self.session)

        self["config"].list = self.list
        self["config"].l.setList(self.list)

        self["key_red"] = StaticText(_("Abort"))

        self.index = 0
        self.port_index = 0
        self.feid = feid
        self.nr_of_ports = nr_of_ports
        self.simple_tone = simple_tone
        self.simple_sat_change = simple_sat_change
        self.found_sats = []

        if not self.openFrontend():
            self.oldref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
            self.session.nav.stopService()
            if not self.openFrontend():
                if self.session.pipshown:
                    if hasattr(self.session, 'infobar'):
                        if self.session.infobar.servicelist and self.session.infobar.servicelist.dopipzap:
                            self.session.infobar.servicelist.togglePipzap()
                    if hasattr(self.session, 'pip'):
                        del self.session.pip
                    self.session.pipshown = False
                if not self.openFrontend():
                    self.frontend = None
                    self.raw_channel = None

        if self.raw_channel:
            self.raw_channel.receivedTsidOnid.get().append(self.gotTsidOnid)

        self["actions"] = ActionMap(["SetupActions"], {
            "cancel": self.keyCancel,
        }, -2)

        self.count = 0
        self.state = 0
        self.abort = False

        self.statusTimer = eTimer()
        self.statusTimer.callback.append(self.statusCallback)
        self.tunerStatusTimer = eTimer()
        self.tunerStatusTimer.callback.append(self.tunerStatusCallback)
        self.startStatusTimer()
        self.onClose.append(self.__onClose)

    def __onClose(self):
        if self.raw_channel:
            self.raw_channel.receivedTsidOnid.get().remove(self.gotTsidOnid)

    def keyCancel(self):
        self.abort = True

    def keyOK(self):
        return

    def keyLeft(self):
        return

    def keyRight(self):
        return

    def openFrontend(self):
        res_mgr = eDVBResourceManager.getInstance()
        if res_mgr:
            self.raw_channel = res_mgr.allocateRawChannel(self.feid)
            if self.raw_channel:
                self.frontend = self.raw_channel.getFrontend()
                if self.frontend:
                    return True
        return False

    def statusCallback(self):
        if self.state == 0:
            if self.port_index == 0:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcA.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 1:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcB.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 2:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcC.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 3:
                self.clearNimEntries()
                config.Nims[self.feid].diseqcD.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])

            if self.nr_of_ports == 4:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b_c_d"
            elif self.nr_of_ports == 2:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b"
            else:
                config.Nims[self.feid].diseqcMode.value = "single"

            config.Nims[self.feid].configMode.value = "simple"
            config.Nims[
                self.feid].simpleDiSEqCSetVoltageTone = self.simple_tone
            config.Nims[
                self.feid].simpleDiSEqCOnlyOnSatChange = self.simple_sat_change

            self.saveAndReloadNimConfig()
            self.state += 1

        elif self.state == 1:
            InitNimManager(nimmanager)

            self.tuner = Tuner(self.frontend)
            if self.raw_channel:
                self.raw_channel.requestTsidOnid()
            self.tuner.tune(self.sat_frequencies[self.index])

            self["statusbar"].setText(
                _("Checking tuner %s\nDiSEqC port %s for %s") %
                (chr(self.feid + 65), self.diseqc_ports[self.port_index],
                 self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
            self["tunerstatusbar"].setText(" ")

            self.count = 0
            self.state = 0

            self.startTunerStatusTimer()
            return

        self.startStatusTimer()

    def startStatusTimer(self):
        self.statusTimer.start(100, True)

    def setupSave(self):
        self.clearNimEntries()
        for x in self.found_sats:
            if x[0] == "A":
                config.Nims[self.feid].diseqcA.value = "%d" % (x[1])
            elif x[0] == "B":
                config.Nims[self.feid].diseqcB.value = "%d" % (x[1])
            elif x[0] == "C":
                config.Nims[self.feid].diseqcC.value = "%d" % (x[1])
            elif x[0] == "D":
                config.Nims[self.feid].diseqcD.value = "%d" % (x[1])
        self.saveAndReloadNimConfig()

    def setupClear(self):
        self.clearNimEntries()
        self.saveAndReloadNimConfig()

    def clearNimEntries(self):
        config.Nims[self.feid].diseqcA.value = "3601"
        config.Nims[self.feid].diseqcB.value = "3601"
        config.Nims[self.feid].diseqcC.value = "3601"
        config.Nims[self.feid].diseqcD.value = "3601"

    def saveAndReloadNimConfig(self):
        config.Nims[self.feid].save()
        configfile.save()
        configfile.load()
        nimmanager.sec.update()

    def tunerStatusCallback(self):
        dict = {}
        if self.frontend:
            self.frontend.getFrontendStatus(dict)
        else:
            self.tunerStopScan(False)
            return
        self["tunerstatusbar"].setText(
            _("Tuner status %s") % (dict["tuner_state"]))

        if dict["tuner_state"] == "LOSTLOCK" or dict["tuner_state"] == "FAILED":
            self.tunerStopScan(False)
            return

        self.count += 1
        if self.count > 10:
            self.tunerStopScan(False)
        else:
            self.startTunerStatusTimer()

    def startTunerStatusTimer(self):
        self.tunerStatusTimer.start(1000, True)

    def gotTsidOnid(self, tsid, onid):
        self.tunerStatusTimer.stop()
        if tsid == self.sat_frequencies[self.index][
                self.SAT_TABLE_TSID] and onid == self.sat_frequencies[
                    self.index][self.SAT_TABLE_ONID]:
            self.tunerStopScan(True)
        else:
            self.tunerStopScan(False)

    def tunerStopScan(self, result):
        if self.abort:
            self.setupClear()
            self.close(False)
            return
        if result:
            self.found_sats.append(
                (self.diseqc_ports[self.port_index],
                 self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS],
                 self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
            self.index = 0
            self.port_index += 1
        else:
            self.index += 1
            if len(self.sat_frequencies) == self.index:
                self.index = 0
                self.port_index += 1

        if len(self.found_sats) > 0:
            self.list = []
            for x in self.found_sats:
                self.list.append(
                    getConfigListEntry(
                        (_("DiSEqC port %s: %s") % (x[0], x[2]))))
            self["config"].l.setList(self.list)

        if self.nr_of_ports == self.port_index:
            self.state = 99
            self.setupSave()
            self.close(len(self.found_sats) > 0)
            return

        for x in self.found_sats:
            if x[1] == self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS]:
                self.tunerStopScan(False)
                return

        self.startStatusTimer()
예제 #45
0
class Blindscan(ConfigListScreen, Screen):
	skin="""
		<screen position="center,center" size="640,560" title="Blind scan">
			<widget name="rotorstatus" position="5,5" size="550,25" font="Regular;20" foregroundColor="#00ffc000" />
			<widget name="config" position="5,30" size="630,310" scrollbarMode="showOnDemand" />
			<ePixmap pixmap="skin_default/div-h.png" position="0,340" zPosition="1" size="640,2" />
			<widget name="description" position="5,345" size="630,125" font="Regular;19" foregroundColor="#00ffc000" halign="center" />
			<ePixmap pixmap="skin_default/div-h.png" position="0,475" zPosition="1" size="640,2" />
			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/SystemPlugins/Blindscan/images/red.png" position="10,520" size="200,2" alphatest="on" />
			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/SystemPlugins/Blindscan/images/yellow.png" position="220,520" size="200,2" alphatest="on" />
			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/SystemPlugins/Blindscan/images/green.png" position="430,520" size="200,2" alphatest="on" />
			<widget name="red" position="10,490" zPosition="2" size="200,30" font="Regular; 19" halign="center" valign="center" backgroundColor="background" foregroundColor="white" transparent="1" />
			<widget name="yellow" position="220,490" zPosition="2" size="200,30" font="Regular; 19" halign="center" valign="center" backgroundColor="background" foregroundColor="white" transparent="1" />
			<widget name="green" position="430,490" zPosition="2" size="200,30" font="Regular; 19" halign="center" valign="center" backgroundColor="background" foregroundColor="white" transparent="1" />
			<widget name="introduction" position="5,535" size="630,25" font="Regular;20" foregroundColor="#1f771f" halign="center" />
		</screen>
		"""
	def __init__(self, session):
		Screen.__init__(self, session)
		self.setup_title = _("Blind scan for internal DVB-S2 tuners")
		Screen.setTitle(self, _(self.setup_title))
		self.skinName = "Blindscan"
		try:
			self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		except:
			self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.onChangedEntry = [ ]
		self["description"] = Label("")
		self["rotorstatus"] = Label("")
		self.getCurrentTuner = None
		self.orb_pos = 0
		# update sat list
		self.satList = []
		for slot in nimmanager.nim_slots:
			if slot.isCompatible("DVB-S"):
				self.satList.append(nimmanager.getSatListForNim(slot.slot))
			else:
				self.satList.append(None)
		self.statusTimer = eTimer()
		self.statusTimer.callback.append(self.setDishOrbosValue)
		# make config
		self.createConfig()
		self.list = []

		ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
		if self.scan_nims.value != None and self.scan_nims.value != "" :
			self["actions"] = ActionMap(["ColorActions", "SetupActions", 'DirectionActions'],
			{
				"red": self.keyCancel,
				"green": self.keyGo,
				"yellow": self.keyFile,
				"ok": self.keyGo,
				"cancel": self.keyCancel,
			}, -2)
			self["red"] = Label(_("Exit"))
			self["yellow"] = Label("")
			self["green"] = Label(_("Scan"))
			self["introduction"] = Label(_("Press Green/OK to start the scan"))
			self.createSetup()
		else :
			self["actions"] = ActionMap(["ColorActions", "SetupActions", 'DirectionActions'],
			{
				"red": self.keyCancel,
				"green": self.keyNone,
				"yellow": self.keyNone,
				"ok": self.keyNone,
				"cancel": self.keyCancel,
			}, -2)
			self["red"] = Label(_("Exit"))
			self["yellow"] = Label("")
			self["green"] = Label(" ")
			self["introduction"] = Label(_("Please setup your tuner configuration."))

		self.i2c_mapping_table = None
		self.nimSockets = self.ScanNimsocket()
		self.makeNimSocket()
		self["config"].onSelectionChanged.append(self.textHelp)
		if XML_FILE is not None and os.path.exists(XML_FILE):
			self["yellow"].setText(_("Open xml file"))
		self.changedEntry()

	# for summary:
	def changedEntry(self):
		for x in self.onChangedEntry:
			x()
	def getCurrentEntry(self):
		return self["config"].getCurrent() and self["config"].getCurrent()[0] or ""

	def getCurrentValue(self):
		return self["config"].getCurrent() and str(self["config"].getCurrent()[1].getText()) or ""

	def textHelp(self):
		self["description"].setText(self.getCurrentDescription())

	def getCurrentDescription(self):
		return self["config"].getCurrent() and len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2] or ""

	def createSummary(self):
		from Screens.Setup import SetupSummary
		return SetupSummary

	def ScanNimsocket(self):
		_nimSocket = {}
		try:
			fp = open('/proc/bus/nim_sockets')
		except:
			return _nimSocket
		for line in fp:
			line = line.strip()
			if line.startswith('NIM Socket'):
				sNo, sName, sI2C = -1, '', -1
				try:    sNo = line.split()[2][:-1]
				except:	sNo = -1
			elif line.startswith('I2C_Device:'):
				try:    sI2C = line.split()[1]
				except: sI2C = -1
			elif line.startswith('Name:'):
				splitLines = line.split()
				try:
					if splitLines[1].startswith('BCM'):
						sName = splitLines[1]
					else:
						sName = splitLines[3][4:-1]
				except: sName = ""
			if sNo >= 0 and sName != "":
				if sName.startswith('BCM'):
					sI2C = sNo
				if sI2C != -1:
					_nimSocket[sNo] = [sName, sI2C]
				else:	_nimSocket[sNo] = [sName]
		fp.close()
		print "parsed nimsocket :", _nimSocket
		return _nimSocket

	def makeNimSocket(self, nimname=""):
		is_exist_i2c = False
		self.i2c_mapping_table = {0:2, 1:3, 2:1, 3:0}
		if self.nimSockets is not None:
			for XX in self.nimSockets.keys():
				nimsocket = self.nimSockets[XX]
				if len(nimsocket) > 1:
					try:	self.i2c_mapping_table[int(XX)] = int(nimsocket[1])
					except: continue
					is_exist_i2c = True
		print "i2c_mapping_table :", self.i2c_mapping_table, ", is_exist_i2c :", is_exist_i2c
		if is_exist_i2c: return

		if nimname == "AVL6222":
			try:
				l = open('/proc/stb/info/vumodel')
				model = l.read().strip()
				l.close()
			except:
				model = ""
			if model == "uno":
				self.i2c_mapping_table = {0:3, 1:3, 2:1, 3:0}
			elif model == "duo2":
				nimdata = self.nimSockets['0']
				try:
					if nimdata[0] == "AVL6222":
						self.i2c_mapping_table = {0:2, 1:2, 2:4, 3:4}
					else:	self.i2c_mapping_table = {0:2, 1:4, 2:4, 3:0}
				except: self.i2c_mapping_table = {0:2, 1:4, 2:4, 3:0}
			else:	self.i2c_mapping_table = {0:2, 1:4, 2:0, 3:0}
		else:	self.i2c_mapping_table = {0:2, 1:3, 2:1, 3:0}

	def getNimSocket(self, slot_number):
		if slot_number < 0 or slot_number > 3:
			return -1
		return self.i2c_mapping_table[slot_number]

	def keyNone(self):
		None

	def callbackNone(self, *retval):
		None

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
				else:
					print "getFrontend failed"
			else:
				print "getRawChannel failed"
		else:
			print "getResourceManager instance failed"
		return False

	def prepareFrontend(self):
		self.frontend = None
		if hasattr(self, 'raw_channel'):
			del self.raw_channel
		if not self.openFrontend():
			oldref = self.session.nav.getCurrentlyPlayingServiceReference()
			stop_current_service = True
			if oldref and self.getCurrentTuner is not None:
				if self.getCurrentTuner < 4 and self.feid != self.getCurrentTuner:
					stop_current_service = False
			if stop_current_service:
				self.session.nav.stopService()
				self.getCurrentTuner = None
			if not self.openFrontend():
				if self.session.pipshown:
					if hasattr(self.session, 'infobar'):
						slist = self.session.infobar.servicelist
						if slist and slist.dopipzap:
							slist.togglePipzap()
					self.session.pipshown = False
					if hasattr(self.session, 'pip'):
						del self.session.pip
					self.openFrontend()
		if self.frontend == None :
			text = _("Sorry, this tuner is in use.")
			if self.session.nav.getRecordings():
				text += "\n"
				text += _("Maybe the reason that recording is currently running.")
			self.session.open(MessageBox, text, MessageBox.TYPE_ERROR)
			return False
		self.tuner = Tuner(self.frontend)
		return True

	def createConfig(self):
		self.feinfo = None
		frontendData = None
		defaultSat = {
			"orbpos": 192,
			"system": eDVBFrontendParametersSatellite.System_DVB_S,
			"frequency": 11836,
			"inversion": eDVBFrontendParametersSatellite.Inversion_Unknown,
			"symbolrate": 27500,
			"polarization": eDVBFrontendParametersSatellite.Polarisation_Horizontal,
			"fec": eDVBFrontendParametersSatellite.FEC_Auto,
			"fec_s2": eDVBFrontendParametersSatellite.FEC_9_10,
			"modulation": eDVBFrontendParametersSatellite.Modulation_QPSK
		}

		self.service = self.session.nav.getCurrentService()
		if self.service is not None:
			self.feinfo = self.service.frontendInfo()
			frontendData = self.feinfo and self.feinfo.getAll(True)
		if frontendData is not None:
			ttype = frontendData.get("tuner_type", "UNKNOWN")
			if ttype == "DVB-S":
				defaultSat["system"] = frontendData.get("system", eDVBFrontendParametersSatellite.System_DVB_S)
				defaultSat["frequency"] = frontendData.get("frequency", 0) / 1000
				defaultSat["inversion"] = frontendData.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown)
				defaultSat["symbolrate"] = frontendData.get("symbol_rate", 0) / 1000
				defaultSat["polarization"] = frontendData.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal)
				if defaultSat["system"] == eDVBFrontendParametersSatellite.System_DVB_S2:
					defaultSat["fec_s2"] = frontendData.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
					defaultSat["rolloff"] = frontendData.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35)
					defaultSat["pilot"] = frontendData.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown)
				else:
					defaultSat["fec"] = frontendData.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
				defaultSat["modulation"] = frontendData.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK)
				defaultSat["orbpos"] = frontendData.get("orbital_position", 0)
			if ttype != "UNKNOWN":
				self.getCurrentTuner = frontendData.get("tuner_number", None)
		del self.feinfo
		del self.service
		del frontendData

		self.scan_sat = ConfigSubsection()
		self.scan_networkScan = ConfigYesNo(default = False)

		self.blindscan_Ku_band_start_frequency = ConfigInteger(default = 10700, limits = (10700, 12749))
		self.blindscan_Ku_band_stop_frequency = ConfigInteger(default = 12750, limits = (10701, 12750))
		self.blindscan_C_band_start_frequency = ConfigInteger(default = 3600, limits = (3000, 4199))
		self.blindscan_C_band_stop_frequency = ConfigInteger(default = 4200, limits = (3001, 4200))
		self.blindscan_start_symbol = ConfigInteger(default = 2, limits = (1, 44))
		self.blindscan_stop_symbol = ConfigInteger(default = 45, limits = (2, 45))
		self.scan_clearallservices = ConfigSelection(default = "no", choices = [("no", _("no")), ("yes", _("yes")), ("yes_hold_feeds", _("yes (keep feeds)"))])
		self.scan_onlyfree = ConfigYesNo(default = False)
		self.dont_scan_known_tps = ConfigYesNo(default = False)
		self.filter_off_adjacent_satellites = ConfigSelection(default = 0, choices = [
			(0, _("no")),
			(1, _("up to 1 degree")),
			(2, _("up to 2 degrees")),
			(3, _("up to 3 degrees"))])
		self.search_type = ConfigSelection(default = 0, choices = [
			(0, _("scan for channels")),
			(1, _("save to XML file"))])


		# collect all nims which are *not* set to "nothing"
		nim_list = []
		for n in nimmanager.nim_slots:
			if n.config_mode == "nothing":
				continue
			if n.config_mode == "advanced" and len(nimmanager.getSatListForNim(n.slot)) < 1:
				continue
			if n.config_mode in ("loopthrough", "satposdepends"):
				root_id = nimmanager.sec.getRoot(n.slot_id, int(n.config.connectedTo.value))
				if n.type == nimmanager.nim_slots[root_id].type: # check if connected from a DVB-S to DVB-S2 Nim or vice versa
					continue
			if n.isCompatible("DVB-S"):
				nim_list.append((str(n.slot), n.friendly_full_description))
		self.scan_nims = ConfigSelection(choices = nim_list)

		# sat
		self.scan_sat.frequency = ConfigInteger(default = defaultSat["frequency"], limits = (1, 99999))
		self.scan_sat.polarization = ConfigSelection(default = eDVBFrontendParametersSatellite.Polarisation_CircularRight + 1, choices = [
			(eDVBFrontendParametersSatellite.Polarisation_CircularRight + 1, _("vertical and horizontal")),
			(eDVBFrontendParametersSatellite.Polarisation_Vertical, _("vertical")),
			(eDVBFrontendParametersSatellite.Polarisation_Horizontal, _("horizontal")),
			(eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2, _("circular right and circular left")),
			(eDVBFrontendParametersSatellite.Polarisation_CircularRight, _("circular right")),
			(eDVBFrontendParametersSatellite.Polarisation_CircularLeft, _("circular left"))])

		self.scan_satselection = []
		for slot in nimmanager.nim_slots:
			if slot.isCompatible("DVB-S"):
				self.scan_satselection.append(getConfigSatlist(defaultSat["orbpos"], self.satList[slot.slot]))
		self.frontend = None # set for later use
		return True

	def getSelectedSatIndex(self, v):
		index    = 0
		none_cnt = 0
		for n in self.satList:
			if self.satList[index] == None:
				none_cnt = none_cnt + 1
			if index == int(v):
				return (index-none_cnt)
			index = index + 1
		return -1

	def createSetup(self):
		self.list = []
		self.multiscanlist = []
		index_to_scan = int(self.scan_nims.value)
		print "ID: ", index_to_scan
		warning_text = _("\nWARNING! Blind scan may make the tuner malfunction on a VU+ and ET receiver. A reboot afterwards may be required to return to proper tuner function.")
		self.tunerEntry = getConfigListEntry(_("Tuner"), self.scan_nims,(_("Select a tuner that is configured for the satellite you wish to search") + warning_text))
		self.list.append(self.tunerEntry)

		if self.scan_nims == [ ]:
			return
		nim = nimmanager.nim_slots[index_to_scan]

		self.scan_networkScan.value = False
		if nim.isCompatible("DVB-S") : 
			self.satelliteEntry = getConfigListEntry(_('Satellite'), self.scan_satselection[self.getSelectedSatIndex(index_to_scan)],_('Select the satellite you wish to search'))
			self.searchtypeEntry = getConfigListEntry(_("Search type"), self.search_type,_('"channel scan" searches for channels and saves them to your receiver; "save to XML file" does a transponder search and saves found transponders to an XML file in satellites.xml format'))
			self.list.append(self.satelliteEntry)
			self.SatBandCheck()
			if self.is_c_band_scan :
				self.list.append(getConfigListEntry(_('Scan start frequency'), self.blindscan_C_band_start_frequency,_('Frequency values must be between 3000 MHz and 4199 MHz (C-band)')))
				self.list.append(getConfigListEntry(_('Scan stop frequency'), self.blindscan_C_band_stop_frequency,_('Frequency values must be between 3001 MHz and 4200 MHz (C-band)')))
			else:
				self.list.append(getConfigListEntry(_('Scan start frequency'), self.blindscan_Ku_band_start_frequency,_('Frequency values must be between 10700 MHz and 12749 MHz')))
				self.list.append(getConfigListEntry(_('Scan stop frequency'), self.blindscan_Ku_band_stop_frequency,_('Frequency values must be between 10701 MHz and 12750 MHz')))
			polarisation_text = _("The suggested polarisation for this satellite is '%s'") % self.suggestedPolarisation
			self.list.append(getConfigListEntry(_("Polarisation"), self.scan_sat.polarization, polarisation_text))
			self.list.append(getConfigListEntry(_('Scan start symbolrate'), self.blindscan_start_symbol,_('Symbol rate values are in megasymbols; enter a value between 1 and 44')))
			self.list.append(getConfigListEntry(_('Scan stop symbolrate'), self.blindscan_stop_symbol,_('Symbol rate values are in megasymbols; enter a value between 2 and 45')))
			self.list.append(getConfigListEntry(_("Only scan unknown transponders"), self.dont_scan_known_tps,_('If you select "yes" the scan will only search transponders not listed in satellites.xml')))
			self.list.append(getConfigListEntry(_("Filter out adjacent satellites"), self.filter_off_adjacent_satellites,_('When a neighbouring satellite is very strong this avoids searching transponders known to be coming from the neighbouring satellite')))
			self.list.append(self.searchtypeEntry)
			if self.search_type.value == 0:
				self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices,_('If you select "yes" all channels on the satellite being search will be deleted before starting the current search, yes (keep feeds) means the same but hold all feed services/transponders.')))
				self.list.append(getConfigListEntry(_("Only free scan"), self.scan_onlyfree,_('If you select "yes" the scan will only save channels that are not encrypted; "no" will find encrypted and non-encrypted channels')))
			self["config"].list = self.list
			self["config"].l.setList(self.list)
			self.startDishMovingIfRotorSat()

	def newConfig(self):
		cur = self["config"].getCurrent()
		print "cur is", cur
		if cur is not None and (cur == self.tunerEntry or cur == self.satelliteEntry or cur == self.searchtypeEntry):
			self.createSetup()

	def keyLeft(self):
		ConfigListScreen.keyLeft(self)
		self.newConfig()

	def keyRight(self):
		ConfigListScreen.keyRight(self)
		self.newConfig()

	def keyCancel(self):
		if hasattr(self, 'raw_channel'):
			del self.raw_channel
		self.session.nav.playService(self.session.postScanService)
		for x in self["config"].list:
			x[1].cancel()
		self.close()

	def keyGo(self):

		tab_pol = {
			eDVBFrontendParametersSatellite.Polarisation_Horizontal : "horizontal",
			eDVBFrontendParametersSatellite.Polarisation_Vertical : "vertical",
			eDVBFrontendParametersSatellite.Polarisation_CircularLeft : "circular left",
			eDVBFrontendParametersSatellite.Polarisation_CircularRight : "circular right",
			eDVBFrontendParametersSatellite.Polarisation_CircularRight + 1 : "horizontal and vertical",
			eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2 : "circular left and circular right"
		}

		self.tmp_tplist=[]
		tmp_pol = []
		tmp_band = []
		idx_selected_sat = int(self.getSelectedSatIndex(self.scan_nims.value))
		tmp_list=[self.satList[int(self.scan_nims.value)][self.scan_satselection[idx_selected_sat].index]]

		if self.is_c_band_scan :
			self.blindscan_start_frequency = self.blindscan_C_band_start_frequency
			self.blindscan_stop_frequency = self.blindscan_C_band_stop_frequency
		else :
			self.blindscan_start_frequency = self.blindscan_Ku_band_start_frequency
			self.blindscan_stop_frequency = self.blindscan_Ku_band_stop_frequency
		
		# swap start and stop values if entered the wrong way round
		if self.blindscan_start_frequency.value > self.blindscan_stop_frequency.value :
			temp = self.blindscan_stop_frequency.value 
			self.blindscan_stop_frequency.value = self.blindscan_start_frequency.value
			self.blindscan_start_frequency.value = temp
			del temp

		# swap start and stop values if entered the wrong way round
		if self.blindscan_start_symbol.value > self.blindscan_stop_symbol.value :
			temp = self.blindscan_stop_symbol.value 
			self.blindscan_stop_symbol.value = self.blindscan_start_symbol.value
			self.blindscan_start_symbol.value = temp
			del temp

		uni_lnb_cutoff = 11700
		if self.blindscan_start_frequency.value < uni_lnb_cutoff and self.blindscan_stop_frequency.value > uni_lnb_cutoff :
			tmp_band=["low","high"]
		elif self.blindscan_start_frequency.value < uni_lnb_cutoff :
			tmp_band=["low"]
		else :
			tmp_band=["high"]

		if self.scan_sat.polarization.value >  eDVBFrontendParametersSatellite.Polarisation_CircularRight : # must be searching both polarisations, either V and H, or R and L
			tmp_pol=["vertical", "horizontal"]
		elif self.scan_sat.polarization.value ==  eDVBFrontendParametersSatellite.Polarisation_CircularRight :
			tmp_pol=["vertical"]
		elif self.scan_sat.polarization.value ==  eDVBFrontendParametersSatellite.Polarisation_CircularLeft :
			tmp_pol=["horizontal"]
		else:
			tmp_pol=[tab_pol[self.scan_sat.polarization.value]]

		self.doRun(tmp_list, tmp_pol, tmp_band)


	def doRun(self, tmp_list, tmp_pol, tmp_band):
		def GetCommand(nimIdx):
			_nimSocket = self.nimSockets
			try:
				sName = _nimSocket[str(nimIdx)][0]
				sType = _supportNimType[sName]
				return "vuplus_%(TYPE)sblindscan"%{'TYPE':sType}, sName
			except: pass
			return "vuplus_blindscan", ""
		if boxtype.startswith('vu'):
			self.binName,nimName =  GetCommand(self.scan_nims.value)

			self.makeNimSocket(nimName)
			if self.binName is None:
				self.session.open(MessageBox, _("Blindscan is not supported in ") + nimName + _(" tuner."), MessageBox.TYPE_ERROR)
				print nimName + " does not support blindscan."
				return

		self.full_data = ""
		self.total_list=[]
		for x in tmp_list:
			for y in tmp_pol:
				for z in tmp_band:
					self.total_list.append([x,y,z])
					print "add scan item : ", x, ", ", y, ", ", z

		self.max_count = len(self.total_list)
		self.is_runable = True
		self.running_count = 0
		self.clockTimer = eTimer()
		self.clockTimer.callback.append(self.doClock)
		self.clockTimer.start(1000)

	def doClock(self):
		is_scan = False
		if self.is_runable :
			if self.running_count >= self.max_count:
				self.clockTimer.stop()
				del self.clockTimer
				self.clockTimer = None
				print "Done"
				return
			orb = self.total_list[self.running_count][0]
			pol = self.total_list[self.running_count][1]
			band = self.total_list[self.running_count][2]
			self.running_count = self.running_count + 1
			print "running status-[%d] : [%d][%s][%s]" %(self.running_count, orb[0], pol, band)
			if self.running_count == self.max_count:
				is_scan = True
			self.prepareScanData(orb, pol, band, is_scan)

	def prepareScanData(self, orb, pol, band, is_scan):
		self.is_runable = False
		self.orb_position = orb[0]
		self.sat_name = orb[1]
		self.feid = int(self.scan_nims.value)
		tab_hilow = {"high" : 1, "low" : 0}
		tab_pol = {
			"horizontal" : eDVBFrontendParametersSatellite.Polarisation_Horizontal,
			"vertical" : eDVBFrontendParametersSatellite.Polarisation_Vertical,
			"circular left" : eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
			"circular right" : eDVBFrontendParametersSatellite.Polarisation_CircularRight
		}

		returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

		if not self.prepareFrontend():
			return False

		if self.is_c_band_scan :
			self.scan_sat.frequency.value = 3600
		else:
			if tab_hilow[band]:
				self.scan_sat.frequency.value = 12515
			else:
				self.scan_sat.frequency.value = 11015
		returnvalue = (self.scan_sat.frequency.value,
					 0,
					 tab_pol[pol],
					 0,
					 0,
					 orb[0],
					 eDVBFrontendParametersSatellite.System_DVB_S,
					 0,
					 0,
					 0)
		self.tuner.tune(returnvalue)

		if self.getNimSocket(self.feid) < 0:
			print "can't find i2c number!!"
			return

		c_band_loc_osc = 5150
		uni_lnb_loc_osc = {"high" : 10600, "low" : 9750}
		uni_lnb_cutoff = 11700
		if self.is_c_band_scan :
			temp_start_int_freq = c_band_loc_osc - self.blindscan_stop_frequency.value
			temp_end_int_freq = c_band_loc_osc - self.blindscan_start_frequency.value
			status_box_start_freq = c_band_loc_osc - temp_end_int_freq
			status_box_end_freq = c_band_loc_osc - temp_start_int_freq

		else:
			if tab_hilow[band] :
				if self.blindscan_start_frequency.value < uni_lnb_cutoff :
					temp_start_int_freq = uni_lnb_cutoff - uni_lnb_loc_osc[band]
				else:
					temp_start_int_freq = self.blindscan_start_frequency.value - uni_lnb_loc_osc[band]
				temp_end_int_freq = self.blindscan_stop_frequency.value - uni_lnb_loc_osc[band]
			else:
				if self.blindscan_stop_frequency.value > uni_lnb_cutoff :
					temp_end_int_freq = uni_lnb_cutoff - uni_lnb_loc_osc[band]
				else:
					temp_end_int_freq = self.blindscan_stop_frequency.value - uni_lnb_loc_osc[band]
				temp_start_int_freq = self.blindscan_start_frequency.value - uni_lnb_loc_osc[band]
			status_box_start_freq = temp_start_int_freq + uni_lnb_loc_osc[band]
			status_box_end_freq = temp_end_int_freq + uni_lnb_loc_osc[band]

		if boxtype.startswith('vu'):
			try:
                               cmd = "%s %d %d %d %d %d %d %d %d" % (self.binName, temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
			except: return
		elif boxtype.startswith('et'):
                       cmd = "avl_xtrend_blindscan %d %d %d %d %d %d %d %d" % (temp_start_int_freq, temp_end_int_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid)) # commented out by Huevos cmd = "avl_xtrend_blindscan %d %d %d %d %d %d %d %d" % (self.blindscan_start_frequency.value/1000000, self.blindscan_stop_frequency.value/1000000, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value, tab_pol[pol], tab_hilow[band], self.feid, self.getNimSocket(self.feid))
		print "prepared command : [%s]" % (cmd)

		self.thisRun = [] # used to check result corresponds with values used above
		self.thisRun.append(int(temp_start_int_freq))
		self.thisRun.append(int(temp_end_int_freq))
		self.thisRun.append(int(tab_hilow[band]))

		self.blindscan_container = eConsoleAppContainer()
		self.blindscan_container.appClosed.append(self.blindscanContainerClose)
		self.blindscan_container.dataAvail.append(self.blindscanContainerAvail)
		self.blindscan_container.execute(cmd)

		display_pol = pol # Display the correct polarisation in the MessageBox below
		if self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight :
			display_pol = _("circular right")
		elif self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularLeft :
			display_pol = _("circular left")
		elif  self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2 :
			if pol == "horizontal" :
				display_pol = _("circular left")
			else:
				display_pol = _("circular right")
		if display_pol == "horizontal":
			display_pol = _("horizontal")
		if display_pol == "vertical":
			display_pol = _("vertical")

		tmpstr = _("Looking for available transponders.\nThis will take a short while.\n\n   Current Status : %d/%d\n   Satellite : %s\n   Polarization : %s\n   Frequency range : %d - %d MHz\n   Symbol rates : %d - %d MHz") %(self.running_count, self.max_count, orb[1], display_pol, status_box_start_freq, status_box_end_freq, self.blindscan_start_symbol.value, self.blindscan_stop_symbol.value)
		if is_scan :
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionClose, MessageBox, tmpstr, MessageBox.TYPE_INFO)
		else:
			self.blindscan_session = self.session.openWithCallback(self.blindscanSessionNone, MessageBox, tmpstr, MessageBox.TYPE_INFO)

	def blindscanContainerClose(self, retval):
		lines = self.full_data.split('\n')
		self.full_data = "" # Clear this string so we don't get duplicates on subsequent runs
		for line in lines:
			data = line.split()
			print "cnt :", len(data), ", data :", data
			if len(data) >= 10 and self.dataIsGood(data) :
				if data[0] == 'OK':
					parm = eDVBFrontendParametersSatellite()
					sys = { "DVB-S" : eDVBFrontendParametersSatellite.System_DVB_S,
						"DVB-S2" : eDVBFrontendParametersSatellite.System_DVB_S2}
					qam = { "QPSK" : parm.Modulation_QPSK,
						"8PSK" : parm.Modulation_8PSK}
					inv = { "INVERSION_OFF" : parm.Inversion_Off,
						"INVERSION_ON" : parm.Inversion_On,
						"INVERSION_AUTO" : parm.Inversion_Unknown}
					fec = { "FEC_AUTO" : parm.FEC_Auto,
						"FEC_1_2" : parm.FEC_1_2,
						"FEC_2_3" : parm.FEC_2_3,
						"FEC_3_4" : parm.FEC_3_4,
						"FEC_5_6": parm.FEC_5_6,
						"FEC_7_8" : parm.FEC_7_8,
						"FEC_8_9" : parm.FEC_8_9,
						"FEC_3_5" : parm.FEC_3_5,
						"FEC_9_10" : parm.FEC_9_10,
						"FEC_NONE" : parm.FEC_None}
					roll ={ "ROLLOFF_20" : parm.RollOff_alpha_0_20,
						"ROLLOFF_25" : parm.RollOff_alpha_0_25,
						"ROLLOFF_35" : parm.RollOff_alpha_0_35}
					pilot={ "PILOT_ON" : parm.Pilot_On,
						"PILOT_OFF" : parm.Pilot_Off, 
						"PILOT_AUTO" : parm.Pilot_Unknown}
					pol = {	"HORIZONTAL" : parm.Polarisation_Horizontal,
						"VERTICAL" : parm.Polarisation_Vertical}
					parm.orbital_position = self.orb_position
					parm.polarisation = pol[data[1]]
					parm.frequency = int(data[2])
					parm.symbol_rate = int(data[3])
					parm.system = sys[data[4]]
					parm.inversion = inv[data[5]]
					parm.pilot = pilot[data[6]]
					parm.fec = fec[data[7]]
					parm.modulation = qam[data[8]]
					parm.rolloff = roll[data[9]]
					self.tmp_tplist.append(parm)
		self.blindscan_session.close(True)

	def blindscanContainerAvail(self, str):
		print str
		#if str.startswith("OK"):
		self.full_data = self.full_data + str

	def blindscanSessionNone(self, *val):
		import time
		self.blindscan_container.sendCtrlC()
		self.blindscan_container = None
		time.sleep(2)

		self.releaseFrontend()

		if val[0] == False:
			self.tmp_tplist = []
			self.running_count = self.max_count

		self.is_runable = True


	def blindscanSessionClose(self, *val):
		global XML_FILE
		self["yellow"].setText("")
		XML_FILE = None
		self.blindscanSessionNone(val[0])

		if self.tmp_tplist != None and self.tmp_tplist != []:
			self.tmp_tplist = self.correctBugsCausedByDriver(self.tmp_tplist)

			# Sync with or remove transponders that exist in satellites.xml
			self.known_transponders = self.getKnownTransponders(self.orb_position)
			if self.dont_scan_known_tps.value :
				self.tmp_tplist = self.removeKnownTransponders(self.tmp_tplist, self.known_transponders)
			else:
				self.tmp_tplist = self.syncWithKnownTransponders(self.tmp_tplist, self.known_transponders)

			# Filter off transponders on neighbouring satellites
			if self.filter_off_adjacent_satellites.value :
				 self.tmp_tplist = self.filterOffAdjacentSatellites(self.tmp_tplist, self.orb_position, self.filter_off_adjacent_satellites.value)

			# Process transponders still in list
			if self.tmp_tplist != [] :
				for p in self.tmp_tplist:
					print "data : [%d][%d][%d][%d][%d][%d][%d][%d][%d][%d]" % (p.orbital_position, p.polarisation, p.frequency, p.symbol_rate, p.system, p.inversion, p.pilot, p.fec, p.modulation, p.modulation)

				if self.search_type.value == 0 : # Do a service scan
					self.startScan(self.tmp_tplist, self.feid)
				else: # Save transponder data to file. No service scan.
					self.tmp_tplist = sorted(self.tmp_tplist, key=lambda transponder: transponder.frequency)
					xml_location = self.createSatellitesXMLfile(self.tmp_tplist, XML_BLINDSCAN_DIR)
					msg = _("Search completed. %d transponders found.\n\nDetails saved in:\n%s")%(len(self.tmp_tplist), xml_location)
					self.session.openWithCallback(self.callbackNone, MessageBox, msg, MessageBox.TYPE_INFO, timeout=300)
			else:
				msg = _("No new transponders found! \n\nOnly transponders already listed in satellites.xml \nhave been found for those search parameters!")
				self.session.openWithCallback(self.callbackNone, MessageBox, msg, MessageBox.TYPE_INFO, timeout=60)

		else:
			msg = _("No transponders were found for those search parameters!")
			if val[0] == False:
				msg = _("The blindscan run was cancelled by the user.")
			self.session.openWithCallback(self.callbackNone, MessageBox, msg, MessageBox.TYPE_INFO, timeout=60)
			self.tmp_tplist = []

	def startScan(self, tlist, feid, networkid = 0):
		self.scan_session = None

		flags = 0
		tmp = self.scan_clearallservices.value
		if tmp == "no":
			flags |= eComponentScan.scanDontRemoveUnscanned
		elif tmp == "yes":
			flags |= eComponentScan.scanRemoveServices
		elif tmp == "yes_hold_feeds":
			flags |= eComponentScan.scanRemoveServices
			flags |= eComponentScan.scanDontRemoveFeeds
		if self.scan_onlyfree.value:
			flags |= eComponentScan.scanOnlyFree
		self.session.openWithCallback(self.startScanCallback, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])

	def getKnownTransponders(self, pos):
		tlist = []
		list = nimmanager.getTransponders(pos)
		for x in list:
			if x[0] == 0:
				parm = eDVBFrontendParametersSatellite()
				parm.frequency = x[1]
				parm.symbol_rate = x[2]
				parm.polarisation = x[3]
				parm.fec = x[4]
				parm.inversion = x[7]
				parm.orbital_position = pos
				parm.system = x[5]
				parm.modulation = x[6]
				parm.rolloff = x[8]
				parm.pilot = x[9]
				tlist.append(parm)
		return tlist

	def syncWithKnownTransponders(self, tplist, knowntp) :
		tolerance = 5
		multiplier = 1000
		x = 0
		for t in tplist :
			for k in knowntp :
				if (t.polarisation % 2) == (k.polarisation % 2) and \
					abs(t.frequency - k.frequency) < (tolerance*multiplier) and \
					abs(t.symbol_rate - k.symbol_rate) < (tolerance*multiplier) :
					tplist[x] = k
					break
			x += 1
		return tplist

	def removeKnownTransponders(self, tplist, knowntp) :
		new_tplist = []
		tolerance = 5
		multiplier = 1000
		x = 0
		isnt_known = True
		for t in tplist :
			for k in knowntp :
				if (t.polarisation % 2) == (k.polarisation % 2) and \
					abs(t.frequency - k.frequency) < (tolerance*multiplier) and \
					abs(t.symbol_rate - k.symbol_rate) < (tolerance*multiplier) :
					isnt_known = False
					break
			x += 1
			if isnt_known :
				new_tplist.append(t)
			else:
				isnt_known = True
		return new_tplist

	def filterOffAdjacentSatellites(self, tplist, pos, degrees) :
		neighbours = []
		tenths_of_degrees = degrees * 10
		for sat in nimmanager.satList :
			if sat[0] != pos and self.positionDiff(pos, sat[0]) <= tenths_of_degrees :
				neighbours.append(sat[0])
		for neighbour in neighbours :
			tplist = self.removeKnownTransponders(tplist, self.getKnownTransponders(neighbour))
		return tplist

	def correctBugsCausedByDriver(self, tplist) :
		if self.is_c_band_scan : # for some reason a c-band scan (with a Vu+) returns the transponder frequencies in Ku band format so they have to be converted back to c-band numbers before the subsequent service search
			x = 0
			for transponders in tplist :
				if tplist[x].frequency > (4200*1000) :
					tplist[x].frequency = (5150*1000) - (tplist[x].frequency - (9750*1000))
				x += 1

		x = 0
		for transponders in tplist :
			if tplist[x].system == 0 : # convert DVB-S transponders to auto fec as for some reason the tuner incorrectly returns 3/4 FEC for all transmissions
				tplist[x].fec = 0
			if self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight : # Return circular transponders to correct polarisation
				tplist[x].polarisation = eDVBFrontendParametersSatellite.Polarisation_CircularRight
			elif self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularLeft : # Return circular transponders to correct polarisation
				tplist[x].polarisation = eDVBFrontendParametersSatellite.Polarisation_CircularLeft
			elif self.scan_sat.polarization.value == eDVBFrontendParametersSatellite.Polarisation_CircularRight + 2: # Return circular transponders to correct polarisation
				if tplist[x].polarisation == eDVBFrontendParametersSatellite.Polarisation_Horizontal : # Return circular transponders to correct polarisation
					tplist[x].polarisation = eDVBFrontendParametersSatellite.Polarisation_CircularLeft
				else:
					tplist[x].polarisation = eDVBFrontendParametersSatellite.Polarisation_CircularRight
			x += 1
		return tplist

	def positionDiff(self, pos1, pos2) :
		diff = pos1 - pos2
		return min(abs(diff % 3600), 3600 - abs(diff % 3600))

	def dataIsGood(self, data) : # check output of the binary for nonsense values
		good = False
		low_lo = 9750
		high_lo = 10600
		c_lo = 5150
		lower_freq = self.thisRun[0]
		upper_freq = self.thisRun[1]
		high_band = self.thisRun[2]
		data_freq = int(int(data[2])/1000)
		data_symbol = int(data[3])
		lower_symbol = (self.blindscan_start_symbol.value * 1000000) - 200000
		upper_symbol = (self.blindscan_stop_symbol.value * 1000000) + 200000

		if high_band :
			data_if_freq = data_freq - high_lo
		elif self.is_c_band_scan and data_freq > 2999 and data_freq < 4201 :
			data_if_freq = c_lo - data_freq
		else :
			data_if_freq = data_freq - low_lo

		if data_if_freq >= lower_freq and data_if_freq <= upper_freq :
			good = True

		if data_symbol < lower_symbol or data_symbol > upper_symbol :
			good = False

		if good == False :
			print "Data returned by the binary is not good...\n	Data: Frequency [%d], Symbol rate [%d]" % (int(data[2]), int(data[3]))

		return good

	def createSatellitesXMLfile(self, tp_list, save_xml_dir) :
		pos = self.orb_position
		if pos > 1800 :
			pos -= 3600
		if pos < 0 :
			pos_name = '%dW' % (abs(int(pos))/10)
		else :
			pos_name = '%dE' % (abs(int(pos))/10)
		location = '%s/blindscan_%s_%s.xml' %(save_xml_dir, pos_name, strftime("%d-%m-%Y_%H-%M-%S"))
		tuner = nimmanager.nim_slots[self.feid].friendly_full_description
		polarisation = ['horizontal', 'vertical', 'circular left', 'circular right', 'vertical and horizontal', 'circular right and circular left']
		adjacent = ['no', 'up to 1 degree', 'up to 2 degrees', 'up to 3 degrees']
		known_txp = 'no'
		if self.filter_off_adjacent_satellites.value :
			known_txp ='yes'
		xml = ['<?xml version="1.0" encoding="iso-8859-1"?>\n\n']
		xml.append('<!--\n')
		xml.append('	File created on %s\n' % (strftime("%A, %d of %B %Y, %H:%M:%S")))
		try:
			xml.append('	using %s receiver running Enigma2 image, version %s,\n' % (boxtype, about.getEnigmaVersionString()))
			xml.append('	image %s, with the blindscan plugin updated by Huevos\n\n' % (about.getImageTypeString()))
		except:
			xml.append('	using %s receiver running Enigma2 image, with the blindscan plugin updated by Huevos\n\n' % (boxtype))
		xml.append('	Search parameters:\n')
		xml.append('		%s\n' % (tuner))
		xml.append('		Satellite: %s\n' % (self.sat_name))
		xml.append('		Start frequency: %dMHz\n' % (self.blindscan_start_frequency.value))
		xml.append('		Stop frequency: %dMHz\n' % (self.blindscan_stop_frequency.value))
		xml.append('		Polarization: %s\n' % (polarisation[self.scan_sat.polarization.value]))
		xml.append('		Lower symbol rate: %d\n' % (self.blindscan_start_symbol.value * 1000))
		xml.append('		Upper symbol rate: %d\n' % (self.blindscan_stop_symbol.value * 1000))
		xml.append('		Only save unknown tranponders: %s\n' % (known_txp))
		xml.append('		Filter out adjacent satellites: %s\n' % (adjacent[self.filter_off_adjacent_satellites.value]))
		xml.append('-->\n\n')
		xml.append('<satellites>\n')
		xml.append('	<sat name="%s" flags="0" position="%s">\n' % (self.sat_name.replace('&', '&amp;'), self.orb_position))
		for tp in tp_list :
			xml.append('		<transponder frequency="%d" symbol_rate="%d" polarization="%d" fec_inner="%d" system="%d" modulation="%d"/>\n' % (tp.frequency, tp.symbol_rate, tp.polarisation, tp.fec, tp.system, tp.modulation))
		xml.append('	</sat>\n')
		xml.append('</satellites>')
		open(location, "w").writelines(xml)
		global XML_FILE
		self["yellow"].setText(_("Open xml file"))
		XML_FILE = location
		return location

	def keyFile(self):
		if XML_FILE is not None and os.path.exists(XML_FILE):
			self.session.open(Console,_(XML_FILE),["cat %s" % XML_FILE])

	def SatBandCheck(self) :
		pos = self.getOrbPos()
		freq = 0
		band = 'Unknown'
		self.is_c_band_scan = False
		self.suggestedPolarisation = _("vertical & horizontal")
		# check in satellites.xml to work out band
		tp_list = self.getKnownTransponders(pos)
		if len(tp_list) :
			freq = int(tp_list[0].frequency)
			if int(tp_list[0].polarisation) > 1 : # for hints text
				self.suggestedPolarisation = _("circular right & circular left")
		if freq :
			if freq < 4201000 and freq > 2999000 :
				band = 'C'
				self.is_c_band_scan = True
			elif freq < 12751000 and freq > 10700000 :
				band = 'Ku'
		# if satellites.xml didn't contain any entries for this satellite check 
		# LNB type instead. Assumes the tuner is configured correctly for C-band.
		if band == "Unknown" and self.isCbandLNB(pos): 
			band = 'C'
			self.is_c_band_scan = True 
		print "SatBandCheck band = %s" % (band)
		
	def isCbandLNB(self, cur_orb_pos):
		nim = nimmanager.nim_slots[int(self.scan_nims.value)]
		if nim.config.configMode.getValue() == "advanced":
			currSat = nim.config.advanced.sat[cur_orb_pos]
			lnbnum = int(currSat.lnb.getValue())
			currLnb = nim.config.advanced.lnb[lnbnum]
			lof = currLnb.lof.getValue()
			print "LNB type: ", lof
			if lof == "c_band":
				return True
		return False

	def getOrbPos(self):
		idx_selected_sat = int(self.getSelectedSatIndex(self.scan_nims.value))
		tmp_list=[self.satList[int(self.scan_nims.value)][self.scan_satselection[idx_selected_sat].index]]
		orb = tmp_list[0][0]
		print "orb = ", orb
		return orb
		
	def startScanCallback(self, answer):
		if answer:
			if hasattr(self, 'raw_channel'):
				del self.raw_channel
			self.session.nav.playService(self.session.postScanService)
			self.close(True)
		
	def startDishMovingIfRotorSat(self):
		self["rotorstatus"].setText("")
		orb_pos = self.getOrbPos()
		self.orb_pos = 0
		self.feid = int(self.scan_nims.value)
		rotorSatsForNim = nimmanager.getRotorSatListForNim(self.feid)
		if len(rotorSatsForNim) < 1:
			self.releaseFrontend() # stop dish if moving due to previous call
			return False
		rotorSat = False
		for sat in rotorSatsForNim:
			if sat[0] == orb_pos:
				rotorSat = True
				break
		if not rotorSat:
			self.releaseFrontend() # stop dish if moving due to previous call
			return False
		tps = nimmanager.getTransponders(orb_pos)
		if len(tps) < 1:
			return False
		if Lastrotorposition is not None and config.misc.lastrotorposition.value != 9999:
			text = _("Rotor: ") + self.OrbToStr(config.misc.lastrotorposition.value)
			self["rotorstatus"].setText(text)
		# freq, sr, pol, fec, inv, orb, sys, mod, roll, pilot 
		transponder = (tps[0][1] / 1000, tps[0][2] / 1000, tps[0][3], tps[0][4], 2, orb_pos, tps[0][5], tps[0][6], tps[0][8], tps[0][9])
		if not self.prepareFrontend():
			return False
		self.tuner.tune(transponder)
		self.orb_pos = orb_pos
		if Lastrotorposition is not None and config.misc.lastrotorposition.value != 9999:
			self.statusTimer.stop()
			self.startStatusTimer()
		return True

	def OrbToStr(self, orbpos):
		if orbpos > 1800:
			orbpos = 3600 - orbpos
			return "%d.%d\xc2\xb0 W" % (orbpos/10, orbpos%10)
		return "%d.%d\xc2\xb0 E" % (orbpos/10, orbpos%10)

	def setDishOrbosValue(self):
		if self.getRotorMovingState():
			if self.orb_pos != 0 and self.orb_pos != config.misc.lastrotorposition.value:
				config.misc.lastrotorposition.value = self.orb_pos
				config.misc.lastrotorposition.save()
			text = _("Moving to ") + self.OrbToStr(self.orb_pos)
			self.startStatusTimer()
		else:
			text = _("Rotor: ") + self.OrbToStr(config.misc.lastrotorposition.value)
		self["rotorstatus"].setText(text)

	def startStatusTimer(self):
		self.statusTimer.start(1000)

	def getRotorMovingState(self):
		return eDVBSatelliteEquipmentControl.getInstance().isRotorMoving()

	def releaseFrontend(self):
		if self.frontend:
			self.frontend = None
			del self.raw_channel
예제 #46
0
class Satfinder(ScanSetup, ServiceScan):
	def __init__(self, session):
		self.initcomplete = False
		service = session and session.nav.getCurrentService()
		feinfo = service and service.frontendInfo()
		self.frontendData = feinfo and feinfo.getAll(True)
		del feinfo
		del service

		self.systemEntry = None
		self.systemEntryATSC = None
		self.satfinderTunerEntry = None
		self.satEntry = None
		self.frequencyEntry = None
		self.polarizationEntry = None
		self.symbolrateEntry = None
		self.inversionEntry = None
		self.rolloffEntry = None
		self.pilotEntry = None
		self.fecEntry = None
		self.transponder = None
		self.is_id_boolEntry = None
		self.t2mi_plp_id_boolEntry = None

		ScanSetup.__init__(self, session)
		self.setTitle(_("Signal Finder"))
		self["introduction"].setText(_("Press OK to scan"))
		self["Frontend"] = FrontendStatus(frontend_source=lambda: self.frontend, update_interval=100)

		self["actions"] = ActionMap(["SetupActions", "ColorActions"],
		{
			"save": self.keyGoScan,
			"ok": self.keyGoScan,
			"cancel": self.keyCancel,
		}, -3)

		self.initcomplete = True
		self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.onClose.append(self.__onClose)
		self.onShow.append(self.prepareFrontend)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			fe_id = int(self.scan_nims.value)
			self.raw_channel = res_mgr.allocateRawChannel(fe_id)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
		return False

	def prepareFrontend(self):
		self.frontend = None
		try:
			if not self.openFrontend():
				self.session.nav.stopService()
				if not self.openFrontend():
					if self.session.pipshown:
						from Screens.InfoBar import InfoBar
						InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
						if not self.openFrontend():
							self.frontend = None # in normal case this should not happen
			self.tuner = Tuner(self.frontend)
			self.createSetup()
			self.retune()
		except:
			pass

	def __onClose(self):
		self.session.nav.playService(self.session.postScanService)

	def newConfig(self):
#		self.transponder = None
		cur = self["config"].getCurrent()
		print("cur ", cur)

		if cur == self.tunerEntry:
			self.feid = int(self.scan_nims.value)
			self.prepareFrontend()
			if self.frontend == None and self.session.nav.RecordTimer.isRecording():
				slot = nimmanager.nim_slots[self.feid]
				msg = _("%s not available.") % slot.getSlotName()
				msg += _("\nRecording in progress.")
				self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR)
		elif cur == self.is_id_boolEntry:
			if self.is_id_boolEntry[1].value:
				self.scan_sat.is_id.value = 0 if self.is_id_memory < 0 else self.is_id_memory
				self.scan_sat.pls_mode.value = self.pls_mode_memory
				self.scan_sat.pls_code.value = self.pls_code_memory
			else:
				self.is_id_memory = self.scan_sat.is_id.value
				self.pls_mode_memory = self.scan_sat.pls_mode.value
				self.pls_code_memory = self.scan_sat.pls_code.value
				self.scan_sat.is_id.value = eDVBFrontendParametersSatellite.No_Stream_Id_Filter
				self.scan_sat.pls_mode.value = eDVBFrontendParametersSatellite.PLS_Gold
				self.scan_sat.pls_code.value = eDVBFrontendParametersSatellite.PLS_Default_Gold_Code
			self.createSetup()
			self.retune()
		elif cur == self.t2mi_plp_id_boolEntry:
			if self.t2mi_plp_id_boolEntry[1].value:
				self.scan_sat.t2mi_plp_id.value = 0 if self.t2mi_plp_id_memory < 0 else self.t2mi_plp_id_memory
				self.scan_sat.t2mi_pid.value = self.t2mi_pid_memory
			else:
				self.t2mi_plp_id_memory = self.scan_sat.t2mi_plp_id.value
				self.t2mi_pid_memory = self.scan_sat.t2mi_pid.value
				self.scan_sat.t2mi_plp_id.value = eDVBFrontendParametersSatellite.No_T2MI_PLP_Id
				self.scan_sat.t2mi_pid.value = eDVBFrontendParametersSatellite.T2MI_Default_Pid
			self.createSetup()
			self.retune()
		else:
			ScanSetup.newConfig(self)
		if cur[1].value == "single_transponder":
			self.retune()

	def createSetup(self):
		ScanSetup.createSetup(self)

#manipulate "config", remove "self.scan_networkScan", "self.scan_clearallservices" and "self.scan_onlyfree"
		tlist = self["config"].getList()
		for x in (self.scan_networkScan, self.scan_clearallservices, self.scan_onlyfree):
			for y in tlist:
				if x == y[1]:
					tlist.remove(y)
		self["config"].list = tlist
		self["config"].l.setList(tlist)

#manipulate choices, we need only "single_transponder","predefined_transponder"
		for scan_type in (self.scan_type, self.scan_typecable, self.scan_typeterrestrial, self.scan_typeatsc):
			slist = scan_type.choices.choices
			dlist = []
			for x in slist:
				if x[0] in ("single_transponder", "predefined_transponder"):
					dlist.append(x)
			scan_type.choices.choices = dlist

	def TunerTypeChanged(self):
		fe_id = int(self.scan_nims.value)
		multiType = config.Nims[fe_id].multiType
		system = multiType.getText()
		if (system in ('DVB-S', 'DVB-S2') and config.Nims[fe_id].dvbs.configMode.value == "nothing") or \
			(system in ('DVB-T', 'DVB-T2') and config.Nims[fe_id].dvbt.configMode.value == "nothing") or \
			(system in ('DVB-C') and config.Nims[fe_id].dvbc.configMode.value == "nothing") or \
			(system in ('ATSC') and config.Nims[fe_id].atsc.configMode.value == "nothing"):
			return
		slot = nimmanager.nim_slots[fe_id]
		print("dvb_api_version ", iDVBFrontend.dvb_api_version)
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)

		if slot.isMultiType():
			eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, "dummy", False) #to force a clear of m_delsys_whitelist
			types = slot.getMultiTypeList()
			import six
			for FeType in six.itervalues(types):
				if FeType in ("DVB-S", "DVB-S2", "DVB-S2X") and config.Nims[slot.slot].dvbs.configMode.value == "nothing":
					continue
				elif FeType in ("DVB-T", "DVB-T2") and config.Nims[slot.slot].dvbt.configMode.value == "nothing":
					continue
				elif FeType in ("DVB-C", "DVB-C2") and config.Nims[slot.slot].dvbc.configMode.value == "nothing":
					continue
				elif FeType in ("ATSC") and config.Nims[slot.slot].atsc.configMode.value == "nothing":
					continue
				eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, FeType, True)
		else:
			eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, slot.getType())


#			if not path.exists("/proc/stb/frontend/%d/mode" % fe_id) and iDVBFrontend.dvb_api_version >= 5:
		print("api >=5 and new style tuner driver")
		if self.frontend:
			if system == 'DVB-C':
				ret = self.frontend.changeType(iDVBFrontend.feCable)
			elif system in ('DVB-T', 'DVB-T2'):
				ret = self.frontend.changeType(iDVBFrontend.feTerrestrial)
			elif system in ('DVB-S', 'DVB-S2'):
				ret = self.frontend.changeType(iDVBFrontend.feSatellite)
			elif system == 'ATSC':
				ret = self.frontend.changeType(iDVBFrontend.feATSC)
			else:
				ret = False
			if not ret:
				print("%d: tunerTypeChange to '%s' failed" % (fe_id, system))
			else:
				print("new system ", system)
		else:
			print("%d: tunerTypeChange to '%s' failed (BUSY)" % (fe_id, multiType.getText()))
		self.retune()

	def createConfig(self):
		ScanSetup.createConfig(self)
		for x in (
			self.scan_sat.frequency,
			self.scan_satselection[int(self.scan_nims.value)],
			self.scan_sat.symbolrate,
			self.scan_sat.is_id,
			self.scan_sat.pls_mode,
			self.scan_sat.pls_code,
			self.scan_sat.t2mi_plp_id,
			self.scan_sat.t2mi_pid,
			self.scan_ter.channel,
			self.scan_ter.frequency,
			self.scan_ter.inversion,
			self.scan_ter.bandwidth, self.scan_ter.fechigh, self.scan_ter.feclow,
			self.scan_ter.modulation, self.scan_ter.transmission,
			self.scan_ter.guard, self.scan_ter.hierarchy,
			self.scan_ter.plp_id,
			self.scan_cab.frequency, self.scan_cab.inversion, self.scan_cab.symbolrate,
			self.scan_cab.modulation, self.scan_cab.fec,
			self.scan_ats.frequency, self.scan_ats.modulation, self.scan_ats.inversion,
			self.scan_ats.system,

			):
			if x is not None:
				x.clearNotifiers()
				x.addNotifier(self.TriggeredByConfigElement, initial_call=False)

	def TriggeredByConfigElement(self, configElement):
		self.retune()

	def retune(self):
		nim = nimmanager.nim_slots[int(self.scan_nims.value)]
		if nim.isCompatible("DVB-S") and nim.config.dvbs.configMode.value != "nothing":
			return self.retuneSat()
		if nim.isCompatible("DVB-T") and nim.config.dvbt.configMode.value != "nothing":
			return self.retuneTerr()
		if nim.isCompatible("DVB-C") and nim.config.dvbc.configMode.value != "nothing":
			return self.retuneCab()
		if nim.isCompatible("ATSC") and nim.config.atsc.configMode.value != "nothing":
			return self.retuneATSC()
		self.frontend = None
		self.raw_channel = None
		print("error: tuner not enabled/supported", nim.getType())

	def retuneCab(self):
		if self.initcomplete:
			if self.scan_typecable.value == "single_transponder":
				transponder = (
					self.scan_cab.frequency.value[0] * 1000 + self.scan_cab.frequency.value[1],
					self.scan_cab.symbolrate.value * 1000,
					self.scan_cab.modulation.value,
					self.scan_cab.fec.value,
					self.scan_cab.inversion.value
				)
				self.tuner.tuneCab(transponder)
				self.transponder = transponder
			elif self.scan_typecable.value == "predefined_transponder":
				if self.CableTransponders is not None:
					tps = nimmanager.getTranspondersCable(int(self.scan_nims.value))
					if len(tps) > self.CableTransponders.index:
						tp = tps[self.CableTransponders.index]
						# tp = 0 transponder type, 1 freq, 2 sym, 3 mod, 4 fec, 5 inv, 6 sys
						transponder = (tp[1], tp[2], tp[3], tp[4], tp[5])
						self.tuner.tuneCab(transponder)
						self.transponder = transponder

	def retuneTerr(self):
		if self.initcomplete:
			if self.scan_input_as.value == "channel":
				frequency = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)
				if frequency:
					frequency = int(frequency)
				else:  # FIXME channel2frequency return None because of channel not found
					print("[Satfinder] retuneTerr DVB-T channel '%s' out of scope" % str(self.scan_ter.channel.value))
					return
			else:
				frequency = self.scan_ter.frequency.floatint * 1000
			if self.scan_typeterrestrial.value == "single_transponder":
				transponder = [
					2, #TERRESTRIAL
					frequency,
					self.scan_ter.bandwidth.value,
					self.scan_ter.modulation.value,
					self.scan_ter.fechigh.value,
					self.scan_ter.feclow.value,
					self.scan_ter.guard.value,
					self.scan_ter.transmission.value,
					self.scan_ter.hierarchy.value,
					self.scan_ter.inversion.value,
					self.scan_ter.system.value,
					self.scan_ter.plp_id.value]
				self.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])
				self.transponder = transponder
			elif self.scan_typeterrestrial.value == "predefined_transponder":
				if self.TerrestrialTransponders is not None:
					region = nimmanager.getTerrestrialDescription(int(self.scan_nims.value))
					tps = nimmanager.getTranspondersTerrestrial(region)
					if len(tps) > self.TerrestrialTransponders.index:
						transponder = tps[self.TerrestrialTransponders.index]
						# frequency 1, inversion 9, bandwidth 2, fechigh 4, feclow 5, modulation 3, transmission 7, guard 6, hierarchy 8, system 10, plp_id 11
						self.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])
						self.transponder = transponder

	def retuneSat(self):
		fe_id = int(self.scan_nims.value)
		nimsats = self.satList[fe_id]
		selsatidx = self.scan_satselection[fe_id].index
		if len(nimsats):
			orbpos = nimsats[selsatidx][0]
			if self.initcomplete:
				if self.scan_type.value == "single_transponder":
					if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
						fec = self.scan_sat.fec_s2.value
					else:
						fec = self.scan_sat.fec.value

					transponder = (
						self.scan_sat.frequency.value,
						self.scan_sat.symbolrate.value,
						self.scan_sat.polarization.value,
						fec,
						self.scan_sat.inversion.value,
						orbpos,
						self.scan_sat.system.value,
						self.scan_sat.modulation.value,
						self.scan_sat.rolloff.value,
						self.scan_sat.pilot.value,
						self.scan_sat.is_id.value,
						self.scan_sat.pls_mode.value,
						self.scan_sat.pls_code.value,
						self.scan_sat.t2mi_plp_id.value,
						self.scan_sat.t2mi_pid.value)
					self.tuner.tune(transponder)
					self.transponder = transponder
				elif self.scan_type.value == "predefined_transponder":
					tps = nimmanager.getTransponders(orbpos)
					if len(tps) > self.preDefTransponders.index:
						tp = tps[self.preDefTransponders.index]
						transponder = (tp[1] // 1000, tp[2] // 1000,
							tp[3], tp[4], 2, orbpos, tp[5], tp[6], tp[8], tp[9], tp[10], tp[11], tp[12], tp[13], tp[14])
						self.tuner.tune(transponder)
						self.transponder = transponder

	def retuneATSC(self):
		if self.initcomplete:
			if self.scan_typeatsc.value == "single_transponder":
				transponder = (
					self.scan_ats.frequency.floatint * 1000,
					self.scan_ats.modulation.value,
					self.scan_ats.inversion.value,
					self.scan_ats.system.value,
				)
				if self.initcomplete:
					self.tuner.tuneATSC(transponder)
				self.transponder = transponder
			elif self.scan_typeatsc.value == "predefined_transponder":
				tps = nimmanager.getTranspondersATSC(int(self.scan_nims.value))
				if tps and len(tps) > self.ATSCTransponders.index:
					tp = tps[self.ATSCTransponders.index]
					transponder = (tp[1], tp[2], tp[3], tp[4])
					if self.initcomplete:
						self.tuner.tuneATSC(transponder)
					self.transponder = transponder

	def keyGoScan(self):
		if self.transponder is None:
			print("error: no transponder data")
			return
		fe_id = int(self.scan_nims.value)
		nim = nimmanager.nim_slots[fe_id]
		self.frontend = None
		if self.raw_channel:
			self.raw_channel = None
		tlist = []
		if nim.isCompatible("DVB-S"):
			nimsats = self.satList[fe_id]
			selsatidx = self.scan_satselection[fe_id].index
			if len(nimsats):
				orbpos = nimsats[selsatidx][0]
				self.addSatTransponder(tlist,
					self.transponder[0], # frequency
					self.transponder[1], # sr
					self.transponder[2], # pol
					self.transponder[3], # fec
					self.transponder[4], # inversion
					orbpos,
					self.transponder[6], # system
					self.transponder[7], # modulation
					self.transponder[8], # rolloff
					self.transponder[9], # pilot
					self.transponder[10],# input stream id
					self.transponder[11],# pls mode
					self.transponder[12], # pls code
					self.transponder[13], # t2mi_plp_id
					self.transponder[14] # t2mi_pid
				)
		elif nim.isCompatible("DVB-T"):
			parm = buildTerTransponder(
				self.transponder[1],  # frequency
				self.transponder[9],  # inversion
				self.transponder[2],  # bandwidth
				self.transponder[4],  # fechigh
				self.transponder[5],  # feclow
				self.transponder[3],  # modulation
				self.transponder[7],  # transmission
				self.transponder[6],  # guard
				self.transponder[8],  # hierarchy
				self.transponder[10], # system
				self.transponder[11]  # plp_id
			)
			tlist.append(parm)
		elif nim.isCompatible("DVB-C"):
			self.addCabTransponder(tlist,
				self.transponder[0], # frequency
				self.transponder[1], # sr
				self.transponder[2], # modulation
				self.transponder[3], # fec_inner
				self.transponder[4]  # inversion
			)
		elif nim.isCompatible("ATSC"):
			self.addATSCTransponder(tlist,
				self.transponder[0], # frequency
				self.transponder[1], # modulation
				self.transponder[2], # inversion
				self.transponder[3]  # system
			)
		else:
			print("error: tuner not enabled/supported", nim.getType())
		self.startScan(tlist, fe_id)

	def startScan(self, tlist, feid):
		flags = 0
		networkid = 0
		self.session.openWithCallback(self.startScanCallback, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])

	def startScanCallback(self, answer=None):
		if answer:
			self.doCloseRecursive()

	def keyCancel(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			self.raw_channel = None
		self.close(False)

	def doCloseRecursive(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			self.raw_channel = None
		self.close(True)
예제 #47
0
파일: plugin.py 프로젝트: popazerty/12
class PositionerSetup(Screen):
	skin = """
		<screen position="100,100" size="560,400" title="Positioner setup..." >
			<widget name="list" position="100,0" size="350,155" />

			<widget name="red" position="0,155" size="140,80" backgroundColor="red" halign="center" valign="center" font="Regular;21" />
			<widget name="green" position="140,155" size="140,80" backgroundColor="green" halign="center" valign="center" font="Regular;21" />
			<widget name="yellow" position="280,155" size="140,80" backgroundColor="yellow" halign="center" valign="center" font="Regular;21" />
			<widget name="blue" position="420,155" size="140,80" backgroundColor="blue" halign="center" valign="center" font="Regular;21" />

			<widget name="snr_db" position="60,245" size="150,22" halign="center" valign="center" font="Regular;21" />
			<eLabel text="SNR:" position="0,270" size="60,22" font="Regular;21" />
			<eLabel text="BER:" position="0,295" size="60,22" font="Regular;21" />
			<eLabel text="Lock:" position="0,320" size="60,22" font="Regular;21" />
			<widget name="snr_percentage" position="220,270" size="60,22" font="Regular;21" />
			<widget name="ber_value" position="220,295" size="60,22" font="Regular;21" />
			<widget name="lock_state" position="60,320" size="150,22" font="Regular;21" />
			<widget name="snr_bar" position="60,270" size="150,22" />
			<widget name="ber_bar" position="60,295" size="150,22" />

			<eLabel text="Frequency:" position="300,245" size="120,22" font="Regular;21" />
			<eLabel text="Symbolrate:" position="300,270" size="120,22" font="Regular;21" />
			<eLabel text="FEC:" position="300,295" size="120,22" font="Regular;21" />
			<widget name="frequency_value" position="420,245" size="120,22" font="Regular;21" />
			<widget name="symbolrate_value" position="420,270" size="120,22" font="Regular;21" />
			<widget name="fec_value" position="420,295" size="120,22" font="Regular;21" />
		</screen>"""
	def __init__(self, session, feid):
		self.skin = PositionerSetup.skin
		Screen.__init__(self, session)
		self.feid = feid
		self.oldref = None

		cur = { }
		if not self.openFrontend():
			self.oldref = session.nav.getCurrentlyPlayingServiceReference()
			service = session.nav.getCurrentService()
			feInfo = service and service.frontendInfo()
			if feInfo:
				cur = feInfo.getTransponderData(True)
			del feInfo
			del service
			session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if session.pipshown: # try to disable pip
					service = self.session.pip.pipservice
					feInfo = service and service.frontendInfo()
					if feInfo:
						cur = feInfo.getTransponderData()
					del feInfo
					del service
					session.pipshown = False
					session.deleteDialog(session.pip)
					del session.pip
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen

		self.frontendStatus = { }
		self.diseqc = Diseqc(self.frontend)
		self.tuner = Tuner(self.frontend, True) #True means we dont like that the normal sec stuff sends commands to the rotor!

		tp = ( cur.get("frequency", 0) / 1000,
			cur.get("symbol_rate", 0) / 1000,
			cur.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal),
			cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto),
			cur.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown),
			cur.get("orbital_position", 0),
			cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S),
			cur.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK),
			cur.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
			cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown))

		self.tuner.tune(tp)
		self.createConfig()

		self.isMoving = False
		self.stopOnLock = False

		self.red = Label("")
		self["red"] = self.red
		self.green = Label("")
		self["green"] = self.green
		self.yellow = Label("")
		self["yellow"] = self.yellow
		self.blue = Label("")
		self["blue"] = self.blue

		self.list = []
		self["list"] = ConfigList(self.list)
		self.createSetup()

		self["snr_db"] = TunerInfo(TunerInfo.SNR_DB, statusDict = self.frontendStatus)
		self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE, statusDict = self.frontendStatus)
		self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE, statusDict = self.frontendStatus)
		self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR, statusDict = self.frontendStatus)
		self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR, statusDict = self.frontendStatus)
		self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE, statusDict = self.frontendStatus)

		self["frequency_value"] = Label("")
		self["symbolrate_value"] = Label("")
		self["fec_value"] = Label("")

		self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ColorActions"],
		{
			"ok": self.go,
			"cancel": self.keyCancel,
			"up": self.up,
			"down": self.down,
			"left": self.left,
			"right": self.right,
			"red": self.redKey,
			"green": self.greenKey,
			"yellow": self.yellowKey,
			"blue": self.blueKey,
		}, -1)

		self.updateColors("tune")

		self.statusTimer = eTimer()
		self.statusTimer_conn = self.statusTimer.timeout.connect(self.updateStatus)
		self.statusTimer.start(50, True)
		self.onClose.append(self.__onClose)

	def __onClose(self):
		self.session.nav.playService(self.oldref)

	def restartPrevService(self, yesno):
		if yesno:
			if self.frontend:
				self.frontend = None
				del self.raw_channel
		else:
			self.oldref=None
		self.close(None)

	def keyCancel(self):
		if self.oldref:
			self.session.openWithCallback(self.restartPrevService, MessageBox, _("Zap back to service before positioner setup?"), MessageBox.TYPE_YESNO)
		else:
			self.restartPrevService(False)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
				else:
					print "getFrontend failed"
			else:
				print "getRawChannel failed"
		else:
			print "getResourceManager instance failed"
		return False

	def createConfig(self):
		self.positioner_tune = ConfigNothing()
		self.positioner_move = ConfigNothing()
		self.positioner_finemove = ConfigNothing()
		self.positioner_limits = ConfigNothing()
		self.positioner_goto0 = ConfigNothing()
		storepos = []
		for x in range(1,255):
			storepos.append(str(x))
		self.positioner_storage = ConfigSelection(choices = storepos)

	def createSetup(self):
		self.list.append((_("Tune"), self.positioner_tune, "tune"))
		self.list.append((_("Positioner movement"), self.positioner_move, "move"))
		self.list.append((_("Positioner fine movement"), self.positioner_finemove, "finemove"))
		self.list.append((_("Set limits"), self.positioner_limits, "limits"))
		self.list.append((_("Positioner storage"), self.positioner_storage, "storage"))
		self.list.append((_("Goto 0"), self.positioner_goto0, "goto0"))
		self["list"].l.setList(self.list)

	def go(self):
		pass

	def getCurrentConfigPath(self):
		return self["list"].getCurrent()[2]

	def up(self):
		if not self.isMoving:
			self["list"].instance.moveSelection(self["list"].instance.moveUp)
			self.updateColors(self.getCurrentConfigPath())

	def down(self):
		if not self.isMoving:
			self["list"].instance.moveSelection(self["list"].instance.moveDown)
			self.updateColors(self.getCurrentConfigPath())

	def left(self):
		self["list"].handleKey(KEY_LEFT)

	def right(self):
		self["list"].handleKey(KEY_RIGHT)

	def updateColors(self, entry):
		if entry == "tune":
			self.red.setText(_("Tune"))
			self.green.setText("")
			self.yellow.setText("")
			self.blue.setText("")
		elif entry == "move":
			if self.isMoving:
				self.red.setText(_("Stop"))
				self.green.setText(_("Stop"))
				self.yellow.setText(_("Stop"))
				self.blue.setText(_("Stop"))
			else:
				self.red.setText(_("Move west"))
				self.green.setText(_("Search west"))
				self.yellow.setText(_("Search east"))
				self.blue.setText(_("Move east"))
		elif entry == "finemove":
			self.red.setText("")
			self.green.setText(_("Step west"))
			self.yellow.setText(_("Step east"))
			self.blue.setText("")
		elif entry == "limits":
			self.red.setText(_("Limits off"))
			self.green.setText(_("Limit west"))
			self.yellow.setText(_("Limit east"))
			self.blue.setText(_("Limits on"))
		elif entry == "storage":
			self.red.setText("")
			self.green.setText(_("Store position"))
			self.yellow.setText(_("Goto position"))
			self.blue.setText("")
		elif entry == "goto0":
			self.red.setText(_("Goto 0"))
			self.green.setText("")
			self.yellow.setText("")
			self.blue.setText("")
		else:
			self.red.setText("")
			self.green.setText("")
			self.yellow.setText("")
			self.blue.setText("")

	def redKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.diseqccommand("stop")
				self.isMoving = False
				self.stopOnLock = False
			else:
				self.diseqccommand("moveWest", 0)
				self.isMoving = True
			self.updateColors("move")
		elif entry == "limits":
			self.diseqccommand("limitOff")
		elif entry == "tune":
			fe_data = { }
			self.frontend.getFrontendData(fe_data)
			self.frontend.getTransponderData(fe_data, True)
			feparm = self.tuner.lastparm.getDVBS()
			fe_data["orbital_position"] = feparm.orbital_position
			self.session.openWithCallback(self.tune, TunerScreen, self.feid, fe_data)
		elif entry == "goto0":
			print "move to position 0"
			self.diseqccommand("moveTo", 0)

	def greenKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.diseqccommand("stop")
				self.isMoving = False
				self.stopOnLock = False
			else:
				self.isMoving = True
				self.stopOnLock = True
				self.diseqccommand("moveWest", 0)
			self.updateColors("move")
		elif entry == "finemove":
			print "stepping west"
			self.diseqccommand("moveWest", 0xFF) # one step
		elif entry == "storage":
			print "store at position", int(self.positioner_storage.value)
			self.diseqccommand("store", int(self.positioner_storage.value))

		elif entry == "limits":
			self.diseqccommand("limitWest")

	def yellowKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.diseqccommand("stop")
				self.isMoving = False
				self.stopOnLock = False
			else:
				self.isMoving = True
				self.stopOnLock = True
				self.diseqccommand("moveEast", 0)
			self.updateColors("move")
		elif entry == "finemove":
			print "stepping east"
			self.diseqccommand("moveEast", 0xFF) # one step
		elif entry == "storage":
			print "move to position", int(self.positioner_storage.value)
			self.diseqccommand("moveTo", int(self.positioner_storage.value))
		elif entry == "limits":
			self.diseqccommand("limitEast")

	def blueKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.diseqccommand("stop")
				self.isMoving = False
				self.stopOnLock = False
			else:
				self.diseqccommand("moveEast", 0)
				self.isMoving = True
			self.updateColors("move")
			print "moving east"
		elif entry == "limits":
			self.diseqccommand("limitOn")

	def diseqccommand(self, cmd, param = 0):
		self.diseqc.command(cmd, param)
		self.tuner.retune()

	def updateStatus(self):
		if self.frontend:
			self.frontendStatus.clear()
			self.frontend.getFrontendStatus(self.frontendStatus)
		self["snr_db"].update()
		self["snr_percentage"].update()
		self["ber_value"].update()
		self["snr_bar"].update()
		self["ber_bar"].update()
		self["lock_state"].update()
		transponderdata = ConvertToHumanReadable(self.tuner.getTransponderData(), "DVB-S")
		self["frequency_value"].setText(str(transponderdata.get("frequency")))
		self["symbolrate_value"].setText(str(transponderdata.get("symbol_rate")))
		self["fec_value"].setText(str(transponderdata.get("fec_inner")))
		if self.frontendStatus.get("tuner_locked", 0) == 1 and self.isMoving and self.stopOnLock:
			self.diseqccommand("stop")
			self.isMoving = False
			self.stopOnLock = False
			self.updateColors(self.getCurrentConfigPath())
		self.statusTimer.start(50, True)

	def tune(self, transponder):
		if transponder is not None:
			self.tuner.tune(transponder)
예제 #48
0
파일: plugin.py 프로젝트: popazerty/12
	def __init__(self, session, feid):
		self.skin = PositionerSetup.skin
		Screen.__init__(self, session)
		self.feid = feid
		self.oldref = None

		cur = { }
		if not self.openFrontend():
			self.oldref = session.nav.getCurrentlyPlayingServiceReference()
			service = session.nav.getCurrentService()
			feInfo = service and service.frontendInfo()
			if feInfo:
				cur = feInfo.getTransponderData(True)
			del feInfo
			del service
			session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if session.pipshown: # try to disable pip
					service = self.session.pip.pipservice
					feInfo = service and service.frontendInfo()
					if feInfo:
						cur = feInfo.getTransponderData()
					del feInfo
					del service
					session.pipshown = False
					session.deleteDialog(session.pip)
					del session.pip
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen

		self.frontendStatus = { }
		self.diseqc = Diseqc(self.frontend)
		self.tuner = Tuner(self.frontend, True) #True means we dont like that the normal sec stuff sends commands to the rotor!

		tp = ( cur.get("frequency", 0) / 1000,
			cur.get("symbol_rate", 0) / 1000,
			cur.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal),
			cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto),
			cur.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown),
			cur.get("orbital_position", 0),
			cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S),
			cur.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK),
			cur.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
			cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown))

		self.tuner.tune(tp)
		self.createConfig()

		self.isMoving = False
		self.stopOnLock = False

		self.red = Label("")
		self["red"] = self.red
		self.green = Label("")
		self["green"] = self.green
		self.yellow = Label("")
		self["yellow"] = self.yellow
		self.blue = Label("")
		self["blue"] = self.blue

		self.list = []
		self["list"] = ConfigList(self.list)
		self.createSetup()

		self["snr_db"] = TunerInfo(TunerInfo.SNR_DB, statusDict = self.frontendStatus)
		self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE, statusDict = self.frontendStatus)
		self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE, statusDict = self.frontendStatus)
		self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR, statusDict = self.frontendStatus)
		self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR, statusDict = self.frontendStatus)
		self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE, statusDict = self.frontendStatus)

		self["frequency_value"] = Label("")
		self["symbolrate_value"] = Label("")
		self["fec_value"] = Label("")

		self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ColorActions"],
		{
			"ok": self.go,
			"cancel": self.keyCancel,
			"up": self.up,
			"down": self.down,
			"left": self.left,
			"right": self.right,
			"red": self.redKey,
			"green": self.greenKey,
			"yellow": self.yellowKey,
			"blue": self.blueKey,
		}, -1)

		self.updateColors("tune")

		self.statusTimer = eTimer()
		self.statusTimer_conn = self.statusTimer.timeout.connect(self.updateStatus)
		self.statusTimer.start(50, True)
		self.onClose.append(self.__onClose)
예제 #49
0
class Satfinder(ScanSetup, ServiceScan):
    def __init__(self, session):
        self.initcomplete = False
        self.frontendData = None
        service = session and session.nav.getCurrentService()
        feinfo = service and service.frontendInfo()
        self.frontendData = feinfo and feinfo.getAll(True)
        del feinfo
        del service

        ScanSetup.__init__(self, session)
        self.setTitle(_("Satfinder"))
        self["introduction"].setText(_("Press OK to scan"))
        self["Frontend"] = FrontendStatus(
            frontend_source=lambda: self.frontend, update_interval=100)

        self["actions"] = ActionMap(
            ["SetupActions"], {
                "save": self.keyGoScan,
                "ok": self.keyGoScan,
                "cancel": self.keyCancel,
            }, -3)

        self.initcomplete = True
        self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceOrGroup(
        )
        self.onClose.append(self.__onClose)
        self.onShow.append(self.prepareFrontend)

    def openFrontend(self):
        res_mgr = eDVBResourceManager.getInstance()
        if res_mgr:
            self.raw_channel = res_mgr.allocateRawChannel(self.feid)
            if self.raw_channel:
                self.frontend = self.raw_channel.getFrontend()
                if self.frontend:
                    return True
        return False

    def prepareFrontend(self):
        self.frontend = None
        if not self.openFrontend():
            self.session.nav.stopService()
            if not self.openFrontend():
                if self.session.pipshown:
                    from Screens.InfoBar import InfoBar
                    InfoBar.instance and hasattr(
                        InfoBar.instance,
                        "showPiP") and InfoBar.instance.showPiP()
                    if not self.openFrontend():
                        self.frontend = None  # in normal case this should not happen
        self.tuner = Tuner(self.frontend)
        self.retune(None)

    def __onClose(self):
        self.session.nav.playService(self.session.postScanService)

    def createSetup(self):
        self.list = []
        self.satfinderTunerEntry = getConfigListEntry(_("Tuner"),
                                                      self.satfinder_scan_nims)
        self.list.append(self.satfinderTunerEntry)
        self.tuning_sat = self.scan_satselection[self.getSelectedSatIndex(
            self.feid)]
        self.satEntry = getConfigListEntry(_('Satellite'), self.tuning_sat)
        self.list.append(self.satEntry)
        self.updatePreDefTransponders()
        self.typeOfTuningEntry = getConfigListEntry(_('Tune'),
                                                    self.tuning_type)
        self.list.append(self.typeOfTuningEntry)

        nim = nimmanager.nim_slots[self.feid]

        if self.tuning_type.value == "manual_transponder":
            if nim.isCompatible("DVB-S2"):
                self.systemEntry = getConfigListEntry(_('System'),
                                                      self.scan_sat.system)
                self.list.append(self.systemEntry)
            else:
                # downgrade to dvb-s, in case a -s2 config was active
                self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S
            self.list.append(
                getConfigListEntry(_('Frequency'), self.scan_sat.frequency))
            self.list.append(
                getConfigListEntry(_('Polarization'),
                                   self.scan_sat.polarization))
            self.list.append(
                getConfigListEntry(_('Symbol rate'), self.scan_sat.symbolrate))
            self.list.append(
                getConfigListEntry(_('Inversion'), self.scan_sat.inversion))
            if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
                self.list.append(
                    getConfigListEntry(_("FEC"), self.scan_sat.fec))
            elif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
                self.list.append(
                    getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
                self.modulationEntry = getConfigListEntry(
                    _('Modulation'), self.scan_sat.modulation)
                self.list.append(self.modulationEntry)
                self.list.append(
                    getConfigListEntry(_('Roll-off'), self.scan_sat.rolloff))
                self.list.append(
                    getConfigListEntry(_('Pilot'), self.scan_sat.pilot))
        elif self.preDefTransponders and self.tuning_type.value == "predefined_transponder":
            self.list.append(
                getConfigListEntry(_("Transponder"), self.preDefTransponders))
        self["config"].list = self.list
        self["config"].l.setList(self.list)
        self.retune(None)

    def newConfig(self):
        cur = self["config"].getCurrent()
        if cur in (self.typeOfTuningEntry, self.systemEntry):
            self.createSetup()
        elif cur == self.satfinderTunerEntry:
            self.feid = int(self.satfinder_scan_nims.value)
            self.prepareFrontend()
            self.createSetup()
        elif cur == self.satEntry:
            self.createSetup()

    def retune(self, configElement):
        returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        if not self.tuning_sat.value:
            return
        satpos = int(self.tuning_sat.value)
        if self.tuning_type.value == "manual_transponder":
            if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
                fec = self.scan_sat.fec_s2.value
            else:
                fec = self.scan_sat.fec.value
            returnvalue = (self.scan_sat.frequency.value,
                           self.scan_sat.symbolrate.value,
                           self.scan_sat.polarization.value, fec,
                           self.scan_sat.inversion.value, satpos,
                           self.scan_sat.system.value,
                           self.scan_sat.modulation.value,
                           self.scan_sat.rolloff.value,
                           self.scan_sat.pilot.value)
            self.tune(returnvalue)
        elif self.tuning_type.value == "predefined_transponder":
            tps = nimmanager.getTransponders(satpos)
            l = len(tps)
            if l > self.preDefTransponders.index:
                transponder = tps[self.preDefTransponders.index]
                returnvalue = (transponder[1] / 1000, transponder[2] / 1000,
                               transponder[3], transponder[4], 2, satpos,
                               transponder[5], transponder[6], transponder[8],
                               transponder[9])
                self.tune(returnvalue)

    def createConfig(self, foo):
        self.preDefTransponders = None
        self.tuning_type = ConfigSelection(
            choices=[("manual_transponder", _("User defined transponder")
                      ), ("predefined_transponder",
                          _("Predefined transponder"))])
        self.orbital_position = 192
        if self.frontendData and self.frontendData.has_key('orbital_position'):
            self.orbital_position = self.frontendData['orbital_position']
        ScanSetup.createConfig(self, self.frontendData)

        for x in (self.tuning_type, self.scan_sat.frequency,
                  self.scan_sat.inversion, self.scan_sat.symbolrate,
                  self.scan_sat.polarization, self.scan_sat.fec,
                  self.scan_sat.pilot, self.scan_sat.fec_s2, self.scan_sat.fec,
                  self.scan_sat.modulation, self.scan_sat.rolloff,
                  self.scan_sat.system):
            x.addNotifier(self.retune, initial_call=False)

        satfinder_nim_list = []
        for n in nimmanager.nim_slots:
            if not n.isCompatible("DVB-S"):
                continue
            if n.config_mode in ("loopthrough", "satposdepends", "nothing"):
                continue
            if n.config_mode == "advanced" and len(
                    nimmanager.getSatListForNim(n.slot)) < 1:
                continue
            satfinder_nim_list.append(
                (str(n.slot), n.friendly_full_description))
        self.satfinder_scan_nims = ConfigSelection(choices=satfinder_nim_list)
        self.feid = int(self.satfinder_scan_nims.value)

        self.satList = []
        self.scan_satselection = []
        for slot in nimmanager.nim_slots:
            if slot.isCompatible("DVB-S"):
                self.satList.append(nimmanager.getSatListForNim(slot.slot))
                self.scan_satselection.append(
                    getConfigSatlist(self.orbital_position,
                                     self.satList[slot.slot]))
            else:
                self.satList.append(None)

    def getSelectedSatIndex(self, v):
        index = 0
        none_cnt = 0
        for n in self.satList:
            if self.satList[index] == None:
                none_cnt = none_cnt + 1
            if index == int(v):
                return (index - none_cnt)
            index = index + 1
        return -1

    def updatePreDefTransponders(self):
        ScanSetup.predefinedTranspondersList(self,
                                             self.tuning_sat.orbital_position)
        if self.preDefTransponders:
            self.preDefTransponders.addNotifier(self.retune,
                                                initial_call=False)

    def keyGoScan(self):
        self.frontend = None
        del self.raw_channel
        tlist = []
        self.addSatTransponder(
            tlist,
            self.transponder[0],  # frequency
            self.transponder[1],  # sr
            self.transponder[2],  # pol
            self.transponder[3],  # fec
            self.transponder[4],  # inversion
            self.tuning_sat.orbital_position,
            self.transponder[6],  # system
            self.transponder[7],  # modulation
            self.transponder[8],  # rolloff
            self.transponder[9]  # pilot
        )
        self.startScan(tlist, self.feid)

    def startScan(self, tlist, feid):
        flags = 0
        networkid = 0
        self.session.openWithCallback(self.startScanCallback, ServiceScan,
                                      [{
                                          "transponders": tlist,
                                          "feid": feid,
                                          "flags": flags,
                                          "networkid": networkid
                                      }])

    def startScanCallback(self, answer):
        if answer:
            self.doCloseRecursive()

    def keyCancel(self):
        if self.session.postScanService and self.frontend:
            self.frontend = None
            del self.raw_channel
        self.close(False)

    def doCloseRecursive(self):
        if self.session.postScanService and self.frontend:
            self.frontend = None
            del self.raw_channel
        self.close(True)

    def tune(self, transponder):
        if self.initcomplete:
            if transponder is not None:
                self.tuner.tune(transponder)
                self.transponder = transponder
예제 #50
0
class AutoDiseqc(Screen, ConfigListScreen):
    diseqc_ports = ["A", "B", "C", "D"]

    sat_frequencies = [
        # Astra 28.2E EPG background audio
        (11778, 27500, eDVBFrontendParametersSatellite.Polarisation_Vertical,
         eDVBFrontendParametersSatellite.FEC_2_3,
         eDVBFrontendParametersSatellite.Inversion_Off, 282,
         eDVBFrontendParametersSatellite.System_DVB_S,
         eDVBFrontendParametersSatellite.Modulation_Auto,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 2004, 2,
         "Astra 2 28.2e"),

        # Astra 23.5E Astra SES
        (12168, 27500, eDVBFrontendParametersSatellite.Polarisation_Vertical,
         eDVBFrontendParametersSatellite.FEC_3_4,
         eDVBFrontendParametersSatellite.Inversion_Off, 235,
         eDVBFrontendParametersSatellite.System_DVB_S,
         eDVBFrontendParametersSatellite.Modulation_Auto,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 3224, 3,
         "Astra 3 23.5e"),

        # Astra 19.2E ZDF
        (11953, 27500, eDVBFrontendParametersSatellite.Polarisation_Horizontal,
         eDVBFrontendParametersSatellite.FEC_3_4,
         eDVBFrontendParametersSatellite.Inversion_Off, 192,
         eDVBFrontendParametersSatellite.System_DVB_S,
         eDVBFrontendParametersSatellite.Modulation_Auto,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 1079, 1,
         "Astra 1 19.2e"),

        # Hotbird 13.0E Rai 1
        (10992, 27500, eDVBFrontendParametersSatellite.Polarisation_Vertical,
         eDVBFrontendParametersSatellite.FEC_2_3,
         eDVBFrontendParametersSatellite.Inversion_Off, 130,
         eDVBFrontendParametersSatellite.System_DVB_S,
         eDVBFrontendParametersSatellite.Modulation_Auto,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 12400, 318,
         "Hotbird 13.0e"),

        # Eutelsat 9.0E CCTV Europe
        (11996, 27500, eDVBFrontendParametersSatellite.Polarisation_Vertical,
         eDVBFrontendParametersSatellite.FEC_3_4,
         eDVBFrontendParametersSatellite.Inversion_Off, 90,
         eDVBFrontendParametersSatellite.System_DVB_S,
         eDVBFrontendParametersSatellite.Modulation_Auto,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 6400, 156,
         "Eutelsat 9B 9.0e"),

        # Thor 0.8W Sky News
        (12418, 28000, eDVBFrontendParametersSatellite.Polarisation_Vertical,
         eDVBFrontendParametersSatellite.FEC_7_8,
         eDVBFrontendParametersSatellite.Inversion_Off, 3592,
         eDVBFrontendParametersSatellite.System_DVB_S,
         eDVBFrontendParametersSatellite.Modulation_Auto,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 20, 70,
         "Thor 5/6/7 0.8w"),

        # Eutelsat 5.0W Fransat
        (11054, 29950, eDVBFrontendParametersSatellite.Polarisation_Vertical,
         eDVBFrontendParametersSatellite.FEC_3_4,
         eDVBFrontendParametersSatellite.Inversion_Off, 3550,
         eDVBFrontendParametersSatellite.System_DVB_S2,
         eDVBFrontendParametersSatellite.Modulation_8PSK,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 20500, 1375,
         "Eutelsat A/B 5.0w"),

        # Hispasat 30.0W TSA
        (10890, 27500, eDVBFrontendParametersSatellite.Polarisation_Vertical,
         eDVBFrontendParametersSatellite.FEC_3_4,
         eDVBFrontendParametersSatellite.Inversion_Off, 3300,
         eDVBFrontendParametersSatellite.System_DVB_S,
         eDVBFrontendParametersSatellite.Modulation_Auto,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 15, 2,
         "Hispasat 30.0w"),
    ]

    circular_sat_frequencies = [
        # Express AMU1 36.0E NHK World Japan
        (12341, 27500,
         eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
         eDVBFrontendParametersSatellite.FEC_3_4,
         eDVBFrontendParametersSatellite.Inversion_Off, 360,
         eDVBFrontendParametersSatellite.System_DVB_S,
         eDVBFrontendParametersSatellite.Modulation_Auto,
         eDVBFrontendParametersSatellite.RollOff_auto,
         eDVBFrontendParametersSatellite.Pilot_Unknown,
         eDVBFrontendParametersSatellite.No_Stream_Id_Filter,
         eDVBFrontendParametersSatellite.PLS_Gold,
         eDVBFrontendParametersSatellite.PLS_Default_Gold_Code,
         eDVBFrontendParametersSatellite.No_T2MI_PLP_Id,
         eDVBFrontendParametersSatellite.T2MI_Default_Pid, 11, 112,
         "Express AMU1 36.0e"),
    ]

    SAT_TABLE_FREQUENCY = 0
    SAT_TABLE_SYMBOLRATE = 1
    SAT_TABLE_POLARISATION = 2
    SAT_TABLE_FEC = 3
    SAT_TABLE_INVERSION = 4
    SAT_TABLE_ORBPOS = 5
    SAT_TABLE_SYSTEM = 6
    SAT_TABLE_MODULATION = 7
    SAT_TABLE_ROLLOFF = 8
    SAT_TABLE_PILOT = 9
    SAT_TABLE_IS_ID = 10
    SAT_TABLE_PLS_MODE = 11
    SAT_TABLE_PLS_CODE = 12
    SAT_TABLE_T2MI_PLP_ID = 13
    SAT_TABLE_T2MI_PID = 14
    SAT_TABLE_TSID = 15
    SAT_TABLE_ONID = 16
    SAT_TABLE_NAME = 17

    def __init__(self, session, feid, nr_of_ports, simple_tone,
                 simple_sat_change):
        Screen.__init__(self, session)

        self["statusbar"] = StaticText(" ")
        self["tunerstatusbar"] = StaticText(" ")

        self.list = []
        ConfigListScreen.__init__(self, self.list, session=self.session)

        self["config"].list = self.list
        self["config"].l.setList(self.list)

        self["key_red"] = StaticText(_("Abort"))

        self.index = 0
        self.port_index = 0
        self.feid = feid
        self.nr_of_ports = nr_of_ports
        self.simple_tone = simple_tone
        self.simple_sat_change = simple_sat_change
        self.found_sats = []
        self.circular_setup = False
        sat_found = False
        for x in self.sat_frequencies:
            if x[self.SAT_TABLE_ORBPOS] == 360:
                sat_found = True
        if self.nr_of_ports == 1:
            if not sat_found:
                self.sat_frequencies += self.circular_sat_frequencies
        elif sat_found:
            self.sat_frequencies.remove(x)

        if not self.openFrontend():
            self.oldref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
            self.session.nav.stopService()
            if not self.openFrontend():
                if self.session.pipshown:
                    if hasattr(self.session, 'infobar'):
                        if self.session.infobar.servicelist and self.session.infobar.servicelist.dopipzap:
                            self.session.infobar.servicelist.togglePipzap()
                    if hasattr(self.session, 'pip'):
                        del self.session.pip
                    self.session.pipshown = False
                if not self.openFrontend():
                    self.frontend = None
                    self.raw_channel = None

        if self.raw_channel:
            self.raw_channel.receivedTsidOnid.get().append(self.gotTsidOnid)

        self["actions"] = ActionMap(["SetupActions"], {
            "cancel": self.keyCancel,
        }, -2)

        self.count = 0
        self.state = 0
        self.abort = False

        self.diseqc = [
            config.Nims[self.feid].diseqcA.value,
            config.Nims[self.feid].diseqcB.value,
            config.Nims[self.feid].diseqcC.value,
            config.Nims[self.feid].diseqcD.value,
        ]

        self.statusTimer = eTimer()
        self.statusTimer.callback.append(self.statusCallback)
        self.tunerStatusTimer = eTimer()
        self.tunerStatusTimer.callback.append(self.tunerStatusCallback)
        self.startStatusTimer()
        self.onClose.append(self.__onClose)

    def __onClose(self):
        if self.raw_channel:
            self.raw_channel.receivedTsidOnid.get().remove(self.gotTsidOnid)

    def keyCancel(self):
        self.abort = True

    def keyOK(self):
        return

    def keyLeft(self):
        return

    def keyRight(self):
        return

    def openFrontend(self):
        res_mgr = eDVBResourceManager.getInstance()
        if res_mgr:
            self.raw_channel = res_mgr.allocateRawChannel(self.feid)
            if self.raw_channel:
                self.frontend = self.raw_channel.getFrontend()
                if self.frontend:
                    return True
        return False

    def statusCallback(self):
        if self.state == 0:
            if self.port_index == 0 and self.diseqc[0] == "3600":
                self.clearNimEntries()
                config.Nims[self.feid].diseqcA.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 1 and self.diseqc[1] == "3600":
                self.clearNimEntries()
                config.Nims[self.feid].diseqcB.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 2 and self.diseqc[2] == "3600":
                self.clearNimEntries()
                config.Nims[self.feid].diseqcC.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
            elif self.port_index == 3 and self.diseqc[3] == "3600":
                self.clearNimEntries()
                config.Nims[self.feid].diseqcD.value = "%d" % (
                    self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])

            if self.nr_of_ports == 4:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b_c_d"
            elif self.nr_of_ports == 2:
                config.Nims[self.feid].diseqcMode.value = "diseqc_a_b"
            else:
                config.Nims[self.feid].diseqcMode.value = "single"
                if self.sat_frequencies[self.index][
                        self.SAT_TABLE_ORBPOS] == 360 and not self.found_sats:
                    config.Nims[
                        self.feid].simpleDiSEqCSetCircularLNB.value = True
                    self.circular_setup = True

            config.Nims[self.feid].configMode.value = "simple"
            config.Nims[
                self.feid].simpleDiSEqCSetVoltageTone = self.simple_tone
            config.Nims[
                self.feid].simpleDiSEqCOnlyOnSatChange = self.simple_sat_change

            self.saveAndReloadNimConfig()
            self.state += 1

        elif self.state == 1:
            if self.diseqc[self.port_index] != "3600":
                self.statusTimer.stop()
                self.count = 0
                self.state = 0
                self.index = len(self.sat_frequencies) - 1
                self.tunerStopScan(False)
                return

            if self.circular_setup:
                if self.raw_channel:
                    self.raw_channel.receivedTsidOnid.get().remove(
                        self.gotTsidOnid)
                del self.frontend
                del self.raw_channel
                if not self.openFrontend():
                    self.frontend = None
                    self.raw_channel = None
                if self.raw_channel:
                    self.raw_channel.receivedTsidOnid.get().append(
                        self.gotTsidOnid)

            InitNimManager(nimmanager)

            self.tuner = Tuner(self.frontend)
            if self.raw_channel:
                self.raw_channel.requestTsidOnid()
            self.tuner.tune(self.sat_frequencies[self.index])

            self["statusbar"].setText(
                _("Checking tuner %s\nDiSEqC port %s for %s") %
                (chr(self.feid + 65), self.diseqc_ports[self.port_index],
                 self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
            self["tunerstatusbar"].setText(" ")

            self.count = 0
            self.state = 0

            self.startTunerStatusTimer()
            return

        self.startStatusTimer()

    def startStatusTimer(self):
        self.statusTimer.start(100, True)

    def setupSave(self):
        self.clearNimEntries()
        for x in self.found_sats:
            if x[0] == "A":
                config.Nims[self.feid].diseqcA.value = "%d" % (x[1])
            elif x[0] == "B":
                config.Nims[self.feid].diseqcB.value = "%d" % (x[1])
            elif x[0] == "C":
                config.Nims[self.feid].diseqcC.value = "%d" % (x[1])
            elif x[0] == "D":
                config.Nims[self.feid].diseqcD.value = "%d" % (x[1])
        self.saveAndReloadNimConfig()

    def setupClear(self):
        self.clearNimEntries()
        self.saveAndReloadNimConfig()

    def clearNimEntries(self):
        config.Nims[self.feid].diseqcA.value = "3601" if self.diseqc[
            0] == "3600" else self.diseqc[0]
        config.Nims[self.feid].diseqcB.value = "3601" if self.diseqc[
            1] == "3600" else self.diseqc[1]
        config.Nims[self.feid].diseqcC.value = "3601" if self.diseqc[
            2] == "3600" else self.diseqc[2]
        config.Nims[self.feid].diseqcD.value = "3601" if self.diseqc[
            3] == "3600" else self.diseqc[3]

    def saveAndReloadNimConfig(self):
        config.Nims[self.feid].save()
        configfile.save()
        configfile.load()
        nimmanager.sec.update()

    def tunerStatusCallback(self):
        dict = {}
        if self.frontend:
            self.frontend.getFrontendStatus(dict)
        else:
            self.tunerStopScan(False)
            return

        if dict["tuner_state"] == "TUNING":
            self["tunerstatusbar"].setText(
                _("Tuner status:") + " " + _("TUNING"))
        elif dict["tuner_state"] == "LOCKED":
            self["tunerstatusbar"].setText(
                _("Tuner status:") + " " + _("ACQUIRING TSID/ONID"))
        elif dict["tuner_state"] == "IDLE":
            self["tunerstatusbar"].setText(
                _("Tuner status:") + " " + _("IDLE"))
        elif dict["tuner_state"] == "UNKNOWN":
            self["tunerstatusbar"].setText(
                _("Tuner status:") + " " + _("UNKNOWN"))
        elif dict["tuner_state"] == "LOSTLOCK" or dict[
                "tuner_state"] == "FAILED":
            self["tunerstatusbar"].setText(
                _("Tuner status:") + " " + _("FAILED"))
            self.tunerStopScan(False)
            return

        self.count += 1
        if self.count > 10:
            self.tunerStopScan(False)
        else:
            self.startTunerStatusTimer()

    def startTunerStatusTimer(self):
        self.tunerStatusTimer.start(2000, True)

    def gotTsidOnid(self, tsid, onid):
        self.tunerStatusTimer.stop()
        if tsid == self.sat_frequencies[self.index][
                self.SAT_TABLE_TSID] and onid == self.sat_frequencies[
                    self.index][self.SAT_TABLE_ONID]:
            self.tunerStopScan(True)
        else:
            self.tunerStopScan(False)

    def tunerStopScan(self, result):
        if self.abort:
            self.setupClear()
            self.close(False)
            return
        if result:
            self.found_sats.append(
                (self.diseqc_ports[self.port_index],
                 self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS],
                 self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
            self.index = 0
            self.port_index += 1
        else:
            self.index += 1
            if len(self.sat_frequencies) == self.index:
                self.index = 0
                self.port_index += 1

        if len(self.found_sats) > 0:
            self.list = []
            for x in self.found_sats:
                self.list.append(
                    getConfigListEntry(
                        (_("DiSEqC port %s: %s") % (x[0], x[2]))))
            self["config"].l.setList(self.list)

        if self.nr_of_ports == self.port_index:
            self.state = 99
            self.setupSave()
            self.close(len(self.found_sats) > 0)
            return

        for x in self.found_sats:
            if x[1] == self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS]:
                self.tunerStopScan(False)
                return

        self.startStatusTimer()
예제 #51
0
파일: plugin.py 프로젝트: kingvuplus/b-p
class Satfinder(ScanSetup, ServiceScan):
	def __init__(self, session):
		self.initcomplete = False
		service = session and session.nav.getCurrentService()
		feinfo = service and service.frontendInfo()
		self.frontendData = feinfo and feinfo.getAll(True)
		del feinfo
		del service

		self.typeOfTuningEntry = None
		self.systemEntry = None
		self.satfinderTunerEntry = None
		self.satEntry = None
		self.typeOfInputEntry = None

		ScanSetup.__init__(self, session)
		self.setTitle(_("Satfinder"))
		self["introduction"].setText(_("Press OK to scan"))
		self["Frontend"] = FrontendStatus(frontend_source = lambda : self.frontend, update_interval = 100)

		self["actions"] = ActionMap(["SetupActions", "ColorActions"],
		{
			"save": self.keyGoScan,
			"ok": self.keyGoScan,
			"cancel": self.keyCancel,
		}, -3)

		self.initcomplete = True
		self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.onClose.append(self.__onClose)
		self.onShow.append(self.prepareFrontend)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
		return False

	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)

	def __onClose(self):
		self.session.nav.playService(self.session.postScanService)

	def newConfig(self):
		cur = self["config"].getCurrent()
		if cur in (self.typeOfTuningEntry, self.systemEntry, self.typeOfInputEntry):
			self.createSetup()
		elif cur == self.satfinderTunerEntry:
			self.feid = int(self.satfinder_scan_nims.value)
			self.createSetup()
			self.prepareFrontend()
			if self.frontend == None:
				msg = _("Tuner not available.")
				if self.session.nav.RecordTimer.isRecording():
					msg += _("\nRecording in progress.")
				self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR)
		elif cur == self.satEntry:
			self.createSetup()
		else:
			self.retune(None)

	def createSetup(self):
		self.list = []
		self.satfinderTunerEntry = getConfigListEntry(_("Tuner"), self.satfinder_scan_nims)
		self.list.append(self.satfinderTunerEntry)
		if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"):
			self.tuning_sat = self.scan_satselection[self.getSelectedSatIndex(self.feid)]
			self.satEntry = getConfigListEntry(_('Satellite'), self.tuning_sat)
			self.list.append(self.satEntry)
			self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type)
			if len(nimmanager.getTransponders(int(self.tuning_sat.value))) < 1: # Only offer 'predefined transponder' if some transponders exist
				self.tuning_type.value = "single_transponder"
			else:
				self.list.append(self.typeOfTuningEntry)

			nim = nimmanager.nim_slots[self.feid]

			if self.tuning_type.value == "single_transponder":
				if nim.isCompatible("DVB-S2"):
					self.systemEntry = getConfigListEntry(_('System'), self.scan_sat.system)
					self.list.append(self.systemEntry)
				else:
					# downgrade to dvb-s, in case a -s2 config was active
					self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S
				self.list.append(getConfigListEntry(_('Frequency'), self.scan_sat.frequency))
				self.list.append(getConfigListEntry(_('Polarization'), self.scan_sat.polarization))
				self.list.append(getConfigListEntry(_('Symbol rate'), self.scan_sat.symbolrate))
				self.list.append(getConfigListEntry(_('Inversion'), self.scan_sat.inversion))
				if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
					self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec))
				elif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
					self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
					self.modulationEntry = getConfigListEntry(_('Modulation'), self.scan_sat.modulation)
					self.list.append(self.modulationEntry)
					self.list.append(getConfigListEntry(_('Roll-off'), self.scan_sat.rolloff))
					self.list.append(getConfigListEntry(_('Pilot'), self.scan_sat.pilot))
			elif self.tuning_type.value == "predefined_transponder":
				self.updatePreDefTransponders()
				self.list.append(getConfigListEntry(_("Transponder"), self.preDefTransponders))
		elif nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-C"):
			self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type)
			if config.Nims[self.feid].cable.scan_type.value != "provider" or len(nimmanager.getTranspondersCable(int(self.satfinder_scan_nims.value))) < 1: # only show 'predefined transponder' if in provider mode and transponders exist
				self.tuning_type.value = "single_transponder"
			else:
				self.list.append(self.typeOfTuningEntry)
			if self.tuning_type.value == "single_transponder":
				self.list.append(getConfigListEntry(_("Frequency"), self.scan_cab.frequency))
				self.list.append(getConfigListEntry(_("Inversion"), self.scan_cab.inversion))
				self.list.append(getConfigListEntry(_("Symbol rate"), self.scan_cab.symbolrate))
				self.list.append(getConfigListEntry(_("Modulation"), self.scan_cab.modulation))
				self.list.append(getConfigListEntry(_("FEC"), self.scan_cab.fec))
			elif self.tuning_type.value == "predefined_transponder":
				self.scan_nims.value = self.satfinder_scan_nims.value
				self.predefinedCabTranspondersList()
				self.list.append(getConfigListEntry(_('Transponder'), self.CableTransponders))
		elif nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T"):
			self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type)
			region = nimmanager.getTerrestrialDescription(int(self.satfinder_scan_nims.value))
			if len(nimmanager.getTranspondersTerrestrial(region)) < 1: # Only offer 'predefined transponder' if some transponders exist
				self.tuning_type.value = "single_transponder"
			else:
				self.list.append(self.typeOfTuningEntry)
			if self.tuning_type.value == "single_transponder":
				if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T2"):
					self.systemEntryTerr = getConfigListEntry(_('System'), self.scan_ter.system)
					self.list.append(self.systemEntryTerr)
				else:
					self.scan_ter.system.value = eDVBFrontendParametersTerrestrial.System_DVB_T
				self.typeOfInputEntry = getConfigListEntry(_("Use frequency or channel"), self.scan_input_as)
				if self.ter_channel_input:
					self.list.append(self.typeOfInputEntry)
				else:
					self.scan_input_as.value = self.scan_input_as.choices[0]
				if self.ter_channel_input and self.scan_input_as.value == "channel":
					channel = getChannelNumber(self.scan_ter.frequency.value*1000, self.ter_tnumber)
					if channel:
						self.scan_ter.channel.value = int(channel.replace("+","").replace("-",""))
					self.list.append(getConfigListEntry(_("Channel"), self.scan_ter.channel))
				else:
					prev_val = self.scan_ter.frequency.value
					self.scan_ter.frequency.value = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)/1000
					if self.scan_ter.frequency.value == 474000:
						self.scan_ter.frequency.value = prev_val
					self.list.append(getConfigListEntry(_("Frequency"), self.scan_ter.frequency))
				self.list.append(getConfigListEntry(_("Inversion"), self.scan_ter.inversion))
				self.list.append(getConfigListEntry(_("Bandwidth"), self.scan_ter.bandwidth))
				self.list.append(getConfigListEntry(_("Code rate HP"), self.scan_ter.fechigh))
				self.list.append(getConfigListEntry(_("Code rate LP"), self.scan_ter.feclow))
				self.list.append(getConfigListEntry(_("Modulation"), self.scan_ter.modulation))
				self.list.append(getConfigListEntry(_("Transmission mode"), self.scan_ter.transmission))
				self.list.append(getConfigListEntry(_("Guard interval"), self.scan_ter.guard))
				self.list.append(getConfigListEntry(_("Hierarchy info"), self.scan_ter.hierarchy))
				if self.scan_ter.system.value == eDVBFrontendParametersTerrestrial.System_DVB_T2:
					self.list.append(getConfigListEntry(_('PLP ID'), self.scan_ter.plp_id))
			elif self.tuning_type.value == "predefined_transponder":
				self.scan_nims.value = self.satfinder_scan_nims.value
				self.predefinedTerrTranspondersList()
				self.list.append(getConfigListEntry(_('Transponder'), self.TerrestrialTransponders))
		self.retune(None)
		self["config"].list = self.list
		self["config"].l.setList(self.list)

	def createConfig(self, foo):
		self.tuning_type = ConfigSelection(default = "predefined_transponder", choices = [("single_transponder", _("User defined transponder")), ("predefined_transponder", _("Predefined transponder"))])
		self.orbital_position = 192
		if self.frontendData and self.frontendData.has_key('orbital_position'):
			self.orbital_position = self.frontendData['orbital_position']
		ScanSetup.createConfig(self, self.frontendData)

		for x in (self.scan_sat.frequency,
			self.scan_sat.inversion, self.scan_sat.symbolrate,
			self.scan_sat.polarization, self.scan_sat.fec, self.scan_sat.pilot,
			self.scan_sat.fec_s2, self.scan_sat.fec, self.scan_sat.modulation,
			self.scan_sat.rolloff, self.scan_sat.system,
			self.scan_ter.channel, self.scan_ter.frequency, self.scan_ter.inversion,
			self.scan_ter.bandwidth, self.scan_ter.fechigh, self.scan_ter.feclow,
			self.scan_ter.modulation, self.scan_ter.transmission,
			self.scan_ter.guard, self.scan_ter.hierarchy, self.scan_ter.plp_id,
			self.scan_cab.frequency, self.scan_cab.inversion, self.scan_cab.symbolrate,
			self.scan_cab.modulation, self.scan_cab.fec):
			x.addNotifier(self.retune, initial_call = False)

		satfinder_nim_list = []
		for n in nimmanager.nim_slots:
			if not (n.isCompatible("DVB-S") or n.isCompatible("DVB-T") or n.isCompatible("DVB-C")):
				continue
			if n.config_mode  in ("loopthrough", "satposdepends", "nothing"):
				continue
			if n.isCompatible("DVB-S") and n.config_mode == "advanced" and len(nimmanager.getSatListForNim(n.slot)) < 1:
				continue
			satfinder_nim_list.append((str(n.slot), n.friendly_full_description))
		self.satfinder_scan_nims = ConfigSelection(choices = satfinder_nim_list)
		if self.frontendData is not None and len(satfinder_nim_list) > 0: # open the plugin with the currently active NIM as default
			self.satfinder_scan_nims.setValue(str(self.frontendData.get("tuner_number", satfinder_nim_list[0][0])))

		self.feid = int(self.satfinder_scan_nims.value)

		self.satList = []
		self.scan_satselection = []
		for slot in nimmanager.nim_slots:
			if slot.isCompatible("DVB-S"):
				self.satList.append(nimmanager.getSatListForNim(slot.slot))
				self.scan_satselection.append(getConfigSatlist(self.orbital_position, self.satList[slot.slot]))
			else:
				self.satList.append(None)

		if self.frontendData:
			ttype = self.frontendData.get("tuner_type", "UNKNOWN")
			if ttype == "DVB-S" and self.predefinedTranspondersList(self.getSelectedSatIndex(self.feid)) is None and len(nimmanager.getTransponders(self.getSelectedSatIndex(self.feid))) > 0:
				self.tuning_type.value = "single_transponder"
			elif ttype == "DVB-T" and self.predefinedTerrTranspondersList() is None and len(nimmanager.getTranspondersTerrestrial(nimmanager.getTerrestrialDescription(self.feid))) > 0:
				self.tuning_type.value = "single_transponder"
			elif ttype == "DVB-C" and self.predefinedCabTranspondersList() is None and len(nimmanager.getTranspondersCable(self.feid)) > 0:
				self.tuning_type.value = "single_transponder"

	def getSelectedSatIndex(self, v):
		index    = 0
		none_cnt = 0
		for n in self.satList:
			if self.satList[index] is None:
				none_cnt += 1
			if index == int(v):
				return index-none_cnt
			index += 1
		return -1

	def updatePreDefTransponders(self):
		ScanSetup.predefinedTranspondersList(self, self.tuning_sat.orbital_position)

	def retuneCab(self, configElement):
		if not nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-C"):
			return
		if self.initcomplete:
			if self.tuning_type.value == "single_transponder":
				transponder = (
					self.scan_cab.frequency.value*1000,
					self.scan_cab.symbolrate.value*1000,
					self.scan_cab.modulation.value,
					self.scan_cab.fec.value,
					self.scan_cab.inversion.value
				)
				if self.initcomplete:
					self.tuner.tuneCab(transponder)
				self.transponder = transponder
			elif self.tuning_type.value == "predefined_transponder":
				tps = nimmanager.getTranspondersCable(int(self.satfinder_scan_nims.value))
				if len(tps) > self.CableTransponders.index :
					tp = tps[self.CableTransponders.index]
					# tp = 0 transponder type, 1 freq, 2 sym, 3 mod, 4 fec, 5 inv, 6 sys
					transponder = (tp[1], tp[2], tp[3], tp[4], tp[5])
					if self.initcomplete:
						self.tuner.tuneCab(transponder)
					self.transponder = transponder

	def retuneTerr(self, configElement):
		if not nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T"):
			return self.retuneCab(configElement)
		if self.initcomplete:
			if self.scan_input_as.value == "channel":
				frequency = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)
			else:
				frequency = self.scan_ter.frequency.value * 1000
			if self.tuning_type.value == "single_transponder":
				transponder = [
					2, #TERRESTRIAL
					frequency,
					self.scan_ter.bandwidth.value,
					self.scan_ter.modulation.value,
					self.scan_ter.fechigh.value,
					self.scan_ter.feclow.value,
					self.scan_ter.guard.value,
					self.scan_ter.transmission.value,
					self.scan_ter.hierarchy.value,
					self.scan_ter.inversion.value,
					self.scan_ter.system.value,
					self.scan_ter.plp_id.value]
				if self.initcomplete:
					self.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])
				self.transponder = transponder
			elif self.tuning_type.value == "predefined_transponder":
				region = nimmanager.getTerrestrialDescription(int(self.satfinder_scan_nims.value))
				tps = nimmanager.getTranspondersTerrestrial(region)
				if len(tps) > self.TerrestrialTransponders.index :
					transponder = tps[self.TerrestrialTransponders.index]
					# frequency 1, inversion 9, bandwidth 2, fechigh 4, feclow 5, modulation 3, transmission 7, guard 6, hierarchy 8, system 10, plp_id 11
					if self.initcomplete:
						self.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])
					self.transponder = transponder

	def retune(self, configElement): # satellite
		if not nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"):
			return self.retuneTerr(configElement)
		if not self.tuning_sat.value:
			return
		satpos = int(self.tuning_sat.value)
		if self.tuning_type.value == "single_transponder":
			if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
				fec = self.scan_sat.fec_s2.value
			else:
				fec = self.scan_sat.fec.value
			transponder = (
				self.scan_sat.frequency.value,
				self.scan_sat.symbolrate.value,
				self.scan_sat.polarization.value,
				fec,
				self.scan_sat.inversion.value,
				satpos,
				self.scan_sat.system.value,
				self.scan_sat.modulation.value,
				self.scan_sat.rolloff.value,
				self.scan_sat.pilot.value)
			if self.initcomplete:
				self.tuner.tune(transponder)
			self.transponder = transponder
		elif self.tuning_type.value == "predefined_transponder":
			tps = nimmanager.getTransponders(satpos)
			if len(tps) > self.preDefTransponders.index:
				tp = tps[self.preDefTransponders.index]
				transponder = (tp[1] / 1000, tp[2] / 1000,
					tp[3], tp[4], 2, satpos, tp[5], tp[6], tp[8], tp[9])
				if self.initcomplete:
					self.tuner.tune(transponder)
				self.transponder = transponder

	def keyGoScan(self):
		self.frontend = None
		if self.raw_channel:
			del(self.raw_channel)
		tlist = []
		if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"):
			self.addSatTransponder(tlist,
				self.transponder[0], # frequency
				self.transponder[1], # sr
				self.transponder[2], # pol
				self.transponder[3], # fec
				self.transponder[4], # inversion
				self.tuning_sat.orbital_position,
				self.transponder[6], # system
				self.transponder[7], # modulation
				self.transponder[8], # rolloff
				self.transponder[9]  # pilot
			)
		elif nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T"):
			parm = buildTerTransponder(
				self.transponder[1],  # frequency
				self.transponder[9],  # inversion
				self.transponder[2],  # bandwidth
				self.transponder[4],  # fechigh
				self.transponder[5],  # feclow
				self.transponder[3],  # modulation
				self.transponder[7],  # transmission
				self.transponder[6],  # guard
				self.transponder[8],  # hierarchy
				self.transponder[10], # system
				self.transponder[11]  # plp_id
			)
			tlist.append(parm)
		else: # DVB-C
			self.addCabTransponder(tlist,
				self.transponder[0], # frequency
				self.transponder[1], # sr
				self.transponder[2], # modulation
				self.transponder[3], # fec_inner
				self.transponder[4]  # inversion
			)
		self.startScan(tlist, self.feid)

	def startScan(self, tlist, feid):
		flags = 0
		networkid = 0
		self.session.openWithCallback(self.startScanCallback, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])

	def startScanCallback(self, answer=None):
		if answer:
			self.doCloseRecursive()

	def keyCancel(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			del self.raw_channel
		self.close(False)

	def doCloseRecursive(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			del self.raw_channel
		self.close(True)
예제 #52
0
    def __init__(self, session, feid):
        self.skin = PositionerSetup.skin
        Screen.__init__(self, session)
        self.feid = feid
        self.oldref = None

        cur = {}
        if not self.openFrontend():
            self.oldref = session.nav.getCurrentlyPlayingServiceReference()
            service = session.nav.getCurrentService()
            feInfo = service and service.frontendInfo()
            if feInfo:
                cur = feInfo.getTransponderData(True)
            del feInfo
            del service
            session.nav.stopService()  # try to disable foreground service
            if not self.openFrontend():
                if session.pipshown:  # try to disable pip
                    service = self.session.pip.pipservice
                    feInfo = service and service.frontendInfo()
                    if feInfo:
                        cur = feInfo.getTransponderData()
                    del feInfo
                    del service
                    session.pipshown = False
                    del session.pip
                    if not self.openFrontend():
                        self.frontend = None  # in normal case this should not happen

        self.frontendStatus = {}
        self.diseqc = Diseqc(self.frontend)
        self.tuner = Tuner(self.frontend)

        tp = (cur.get("frequency", 0) / 1000, cur.get("symbol_rate", 0) / 1000,
              cur.get("polarization",
                      eDVBFrontendParametersSatellite.Polarisation_Horizontal),
              cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto),
              cur.get("inversion",
                      eDVBFrontendParametersSatellite.Inversion_Unknown),
              cur.get("orbital_position", 0),
              cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S),
              cur.get("modulation",
                      eDVBFrontendParametersSatellite.Modulation_QPSK),
              cur.get("rolloff",
                      eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
              cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown))

        self.tuner.tune(tp)
        self.createConfig()

        self.isMoving = False
        self.stopOnLock = False

        self.red = Label("")
        self["red"] = self.red
        self.green = Label("")
        self["green"] = self.green
        self.yellow = Label("")
        self["yellow"] = self.yellow
        self.blue = Label("")
        self["blue"] = self.blue

        self.list = []
        self["list"] = ConfigList(self.list)
        self.createSetup()

        self["snr_db"] = TunerInfo(TunerInfo.SNR_DB,
                                   statusDict=self.frontendStatus)
        self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE,
                                           statusDict=self.frontendStatus)
        self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE,
                                      statusDict=self.frontendStatus)
        self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR,
                                    statusDict=self.frontendStatus)
        self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR,
                                    statusDict=self.frontendStatus)
        self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE,
                                       statusDict=self.frontendStatus)

        self["frequency_value"] = Label("")
        self["symbolrate_value"] = Label("")
        self["fec_value"] = Label("")

        self["actions"] = ActionMap(
            ["DirectionActions", "OkCancelActions", "ColorActions"], {
                "ok": self.go,
                "cancel": self.keyCancel,
                "up": self.up,
                "down": self.down,
                "left": self.left,
                "right": self.right,
                "red": self.redKey,
                "green": self.greenKey,
                "yellow": self.yellowKey,
                "blue": self.blueKey,
            }, -1)

        self.updateColors("tune")

        self.statusTimer = eTimer()
        self.statusTimer.callback.append(self.updateStatus)
        self.statusTimer.start(50, True)
        self.onClose.append(self.__onClose)
예제 #53
0
파일: plugin.py 프로젝트: OpenSH4/enigma2
class Satfinder(ScanSetup, ServiceScan):
	def __init__(self, session):
		self.initcomplete = False
		self.frontendData = None
		service = session and session.nav.getCurrentService()
		feinfo = service and service.frontendInfo()
		self.frontendData = feinfo and feinfo.getAll(True)
		del feinfo
		del service
		
		self.typeOfTuningEntry = None
		self.systemEntry = None
		self.satfinderTunerEntry = None
		self.satEntry = None

		ScanSetup.__init__(self, session)
		self.setTitle(_("Satfinder"))
		self["introduction"].setText(_("Press OK to scan"))
		self["Frontend"] = FrontendStatus(frontend_source = lambda : self.frontend, update_interval = 100)

		self["actions"] = ActionMap(["SetupActions"],
		{
			"save": self.keyGoScan,
			"ok": self.keyGoScan,
			"cancel": self.keyCancel,
		}, -3)

		self.initcomplete = True
		self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.onClose.append(self.__onClose)
		self.onShow.append(self.prepareFrontend)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
		return False

	def prepareFrontend(self):
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown: # try to disable pip
					if hasattr(self.session, 'infobar'):
						if self.session.infobar.servicelist.dopipzap:
							self.session.infobar.servicelist.togglePipzap()
					if hasattr(self.session, 'pip'):
						del self.session.pip
					self.session.pipshown = False
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)
		self.retune(None)

	def __onClose(self):
		self.session.nav.playService(self.session.postScanService)

	def createSetup(self):
		self.list = []
		self.satfinderTunerEntry = getConfigListEntry(_("Tuner"), self.satfinder_scan_nims)
		self.list.append(self.satfinderTunerEntry)
		self.tuning_sat = self.scan_satselection[self.getSelectedSatIndex(self.feid)]
		self.satEntry = getConfigListEntry(_('Satellite'), self.tuning_sat)
		self.list.append(self.satEntry)
		self.updatePreDefTransponders()
		self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type)
		self.list.append(self.typeOfTuningEntry)

		nim = nimmanager.nim_slots[self.feid]

		if self.tuning_type.value == "manual_transponder":
			if nim.isCompatible("DVB-S2"):
				self.systemEntry = getConfigListEntry(_('System'), self.scan_sat.system)
				self.list.append(self.systemEntry)
			else:
				# downgrade to dvb-s, in case a -s2 config was active
				self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S
			self.list.append(getConfigListEntry(_('Frequency'), self.scan_sat.frequency))
			self.list.append(getConfigListEntry(_('Polarization'), self.scan_sat.polarization))
			self.list.append(getConfigListEntry(_('Symbol rate'), self.scan_sat.symbolrate))
			self.list.append(getConfigListEntry(_('Inversion'), self.scan_sat.inversion))
			if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
				self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec))
			elif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
				self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
				self.modulationEntry = getConfigListEntry(_('Modulation'), self.scan_sat.modulation)
				self.list.append(self.modulationEntry)
				self.list.append(getConfigListEntry(_('Roll-off'), self.scan_sat.rolloff))
				self.list.append(getConfigListEntry(_('Pilot'), self.scan_sat.pilot))
		elif self.preDefTransponders and self.tuning_type.value == "predefined_transponder":
			self.list.append(getConfigListEntry(_("Transponder"), self.preDefTransponders))
		self["config"].list = self.list
		self["config"].l.setList(self.list)
		self.retune(None)

	def newConfig(self):
		cur = self["config"].getCurrent()
		if cur in (self.typeOfTuningEntry, self.systemEntry):
			self.createSetup()
		elif cur == self.satfinderTunerEntry:
			self.feid = int(self.satfinder_scan_nims.value)
			self.prepareFrontend()
			self.createSetup()
			if self.frontend == None:
				msg = _("Sorry that tuner is not available.")
				if self.session.nav.RecordTimer.isRecording():
					msg += _("\nA recording is in progress.")
				self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR)
		elif cur == self.satEntry:
			self.createSetup()

	def retune(self, configElement):
		returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
		if not self.tuning_sat.value:
			return
		satpos = int(self.tuning_sat.value)
		if self.tuning_type.value == "manual_transponder":
			if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
				fec = self.scan_sat.fec_s2.value
			else:
				fec = self.scan_sat.fec.value
			returnvalue = (
				self.scan_sat.frequency.value,
				self.scan_sat.symbolrate.value,
				self.scan_sat.polarization.value,
				fec,
				self.scan_sat.inversion.value,
				satpos,
				self.scan_sat.system.value,
				self.scan_sat.modulation.value,
				self.scan_sat.rolloff.value,
				self.scan_sat.pilot.value)
			self.tune(returnvalue)
		elif self.tuning_type.value == "predefined_transponder":
			tps = nimmanager.getTransponders(satpos)
			l = len(tps)
			if l > self.preDefTransponders.index:
				transponder = tps[self.preDefTransponders.index]
				returnvalue = (transponder[1] / 1000, transponder[2] / 1000,
					transponder[3], transponder[4], 2, satpos, transponder[5], transponder[6], transponder[8], transponder[9])
				self.tune(returnvalue)

	def createConfig(self, foo):
		self.preDefTransponders = None
		self.tuning_type = ConfigSelection(choices = [("manual_transponder", _("User defined transponder")), ("predefined_transponder", _("Predefined transponder"))], default = "predefined_transponder")
		self.orbital_position = 192
		if self.frontendData and self.frontendData.has_key('orbital_position'):
			self.orbital_position = self.frontendData['orbital_position']
		ScanSetup.createConfig(self, self.frontendData)

		for x in (self.tuning_type, self.scan_sat.frequency,
			self.scan_sat.inversion, self.scan_sat.symbolrate,
			self.scan_sat.polarization, self.scan_sat.fec, self.scan_sat.pilot,
			self.scan_sat.fec_s2, self.scan_sat.fec, self.scan_sat.modulation,
			self.scan_sat.rolloff, self.scan_sat.system):
			x.addNotifier(self.retune, initial_call = False)

		satfinder_nim_list = []
		for n in nimmanager.nim_slots:
			if not n.isCompatible("DVB-S"):
				continue
			if n.config_mode  in ("loopthrough", "satposdepends", "nothing"):
				continue
			if n.config_mode == "advanced" and len(nimmanager.getSatListForNim(n.slot)) < 1:
				continue
			satfinder_nim_list.append((str(n.slot), n.friendly_full_description))
		self.satfinder_scan_nims = ConfigSelection(choices = satfinder_nim_list)
		self.feid = int(self.satfinder_scan_nims.value)

		self.satList = []
		self.scan_satselection = []
		for slot in nimmanager.nim_slots:
			if slot.isCompatible("DVB-S"):
				self.satList.append(nimmanager.getSatListForNim(slot.slot))
				self.scan_satselection.append(getConfigSatlist(self.orbital_position, self.satList[slot.slot]))
			else:
				self.satList.append(None)

	def getSelectedSatIndex(self, v):
		index    = 0
		none_cnt = 0
		for n in self.satList:
			if self.satList[index] is None:
				none_cnt += 1
			if index == int(v):
				return index-none_cnt
			index += 1
		return -1

	def updatePreDefTransponders(self):
		ScanSetup.predefinedTranspondersList(self, self.tuning_sat.orbital_position)
		if self.preDefTransponders:
			self.preDefTransponders.addNotifier(self.retune, initial_call=False)

	def keyGoScan(self):
		self.frontend = None
		del self.raw_channel
		tlist = []
		self.addSatTransponder(tlist,
			self.transponder[0], # frequency
			self.transponder[1], # sr
			self.transponder[2], # pol
			self.transponder[3], # fec
			self.transponder[4], # inversion
			self.tuning_sat.orbital_position,
			self.transponder[6], # system
			self.transponder[7], # modulation
			self.transponder[8], # rolloff
			self.transponder[9]  # pilot
		)
		self.startScan(tlist, self.feid)

	def startScan(self, tlist, feid):
		flags = 0
		networkid = 0
		self.session.openWithCallback(self.startScanCallback, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])

	def startScanCallback(self, answer=None):
		if answer:
			self.doCloseRecursive()

	def keyCancel(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			del self.raw_channel
		self.close(False)

	def doCloseRecursive(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			del self.raw_channel
		self.close(True)

	def tune(self, transponder):
		if self.initcomplete:
			if transponder is not None:
				self.tuner.tune(transponder)
				self.transponder = transponder
예제 #54
0
파일: AutoDiseqc.py 프로젝트: momi133/pure2
class AutoDiseqc(Screen, ConfigListScreen):
	diseqc_ports = [
		"A", "B", "C", "D"
	]

	sat_frequencies = [
		# astra 192 zdf
		(
			11953,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Horizontal,
			eDVBFrontendParametersSatellite.FEC_3_4,
			eDVBFrontendParametersSatellite.Inversion_Off,
			192,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			-1,
			0,
			1,
			1079,
			1,
			"Astra 1 19.2e"),

		# astra 235 astra ses
		(
			12168,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Vertical,
			eDVBFrontendParametersSatellite.FEC_3_4,
			eDVBFrontendParametersSatellite.Inversion_Off,
			235,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			-1,
			0,
			1,
			3224,
			3,
			"Astra 3 23.5e"),

		# astra 282 EPG background audio
		(
			11778,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Vertical,
			eDVBFrontendParametersSatellite.FEC_2_3,
			eDVBFrontendParametersSatellite.Inversion_Off,
			282,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			-1,
			0,
			1,
			2004,
			2,
			"Astra 2 28.2e"),

		# hotbird 130 rai
		(
			10992,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Vertical,
			eDVBFrontendParametersSatellite.FEC_2_3,
			eDVBFrontendParametersSatellite.Inversion_Off,
			130,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,		
			-1,
			0,
			1,
			12400,
			318,
			"Hotbird 13.0e"),

		# eutelsat 160 hrt
 		(
 			10721,
 			27500,
 			eDVBFrontendParametersSatellite.Polarisation_Horizontal,
 			eDVBFrontendParametersSatellite.FEC_3_4,
 			eDVBFrontendParametersSatellite.Inversion_Off,
 			160,
 			eDVBFrontendParametersSatellite.System_DVB_S,
 			eDVBFrontendParametersSatellite.Modulation_Auto,
 			eDVBFrontendParametersSatellite.RollOff_auto,
 			eDVBFrontendParametersSatellite.Pilot_Unknown,		
 			-1,
 			0,
 			1,
 			20100,
 			366,
 			"Eutelsat 16A 16.0e"),

		# thor  3592 CT24
		(
			12072,
			28000,
			eDVBFrontendParametersSatellite.Polarisation_Vertical,
			eDVBFrontendParametersSatellite.FEC_7_8,
			eDVBFrontendParametersSatellite.Inversion_Off,
			3592,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			-1,
			0,
			1,
			706,
			1536,
			"Thor 5/6/7 0.8w"),

		# hispasat 300 tsa
		(
			10890,
			27500,
			eDVBFrontendParametersSatellite.Polarisation_Vertical,
			eDVBFrontendParametersSatellite.FEC_3_4,
			eDVBFrontendParametersSatellite.Inversion_Off,
			3300,
			eDVBFrontendParametersSatellite.System_DVB_S,
			eDVBFrontendParametersSatellite.Modulation_Auto,
			eDVBFrontendParametersSatellite.RollOff_auto,
			eDVBFrontendParametersSatellite.Pilot_Unknown,
			-1,
			0,
			0,
			1388,
			1388,
			"Hispasat 30.0w"),
	]

	SAT_TABLE_FREQUENCY = 0
	SAT_TABLE_SYMBOLRATE = 1
	SAT_TABLE_POLARISATION = 2
	SAT_TABLE_FEC = 3
	SAT_TABLE_INVERSION = 4
	SAT_TABLE_ORBPOS = 5
	SAT_TABLE_SYSTEM = 6
	SAT_TABLE_MODULATION = 7
	SAT_TABLE_ROLLOFF = 8
	SAT_TABLE_PILOT = 9
	SAT_TABLE_ISID = 10
	SAT_TABLE_PLSMODE = 11
	SAT_TABLE_PLSCODE = 12
	SAT_TABLE_TSID = 13
	SAT_TABLE_ONID = 14
	SAT_TABLE_NAME = 15

	def __init__(self, session, feid, nr_of_ports, simple_tone, simple_sat_change):
		Screen.__init__(self, session)

		self["statusbar"] = StaticText(" ")
		self["tunerstatusbar"] = StaticText(" ")

		self.list = []
		ConfigListScreen.__init__(self, self.list, session = self.session)

		self["config"].list = self.list
		self["config"].l.setList(self.list)

		self["key_red"] = StaticText(_("Abort"))

		self.session.pipshown = False
		self.index = 0
		self.port_index = 0
		self.feid = feid
		self.nr_of_ports = nr_of_ports
		self.simple_tone = simple_tone
		self.simple_sat_change = simple_sat_change
		self.found_sats = []

		if not self.openFrontend():
			self.oldref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					if hasattr(self.session, 'infobar'):
						if self.session.infobar.servicelist and self.session.infobar.servicelist.dopipzap:
							self.session.infobar.servicelist.togglePipzap()
					if hasattr(self.session, 'pip'):
						del self.session.pip
					self.session.pipshown = False
				if not self.openFrontend():
					self.frontend = None
					self.raw_channel = None

		if self.raw_channel:
			self.raw_channel.receivedTsidOnid.get().append(self.gotTsidOnid)

		self["actions"] = ActionMap(["SetupActions"],
		{
			"cancel": self.keyCancel,
		}, -2)

		self.count = 0
		self.state = 0
		self.abort = False

		self.statusTimer = eTimer()
		self.statusTimer.callback.append(self.statusCallback)
		self.tunerStatusTimer = eTimer()
		self.tunerStatusTimer.callback.append(self.tunerStatusCallback)
		self.startStatusTimer()
		self.onClose.append(self.__onClose)

	def __onClose(self):
		if self.raw_channel:
			self.raw_channel.receivedTsidOnid.get().remove(self.gotTsidOnid)

	def keyCancel(self):
		self.abort = True

	def keyOK(self):
		return

	def keyLeft(self):
		return

	def keyRight(self):
		return

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
		return False

	def statusCallback(self):
		if self.state == 0:
			if self.port_index == 0:
				self.clearNimEntries()
				config.Nims[self.feid].dvbs.diseqcA.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
			elif self.port_index == 1:
				self.clearNimEntries()
				config.Nims[self.feid].dvbs.diseqcB.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
			elif self.port_index == 2:
				self.clearNimEntries()
				config.Nims[self.feid].dvbs.diseqcC.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])
			elif self.port_index == 3:
				self.clearNimEntries()
				config.Nims[self.feid].dvbs.diseqcD.value = "%d" % (self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS])

			if self.nr_of_ports == 4:
				config.Nims[self.feid].dvbs.diseqcMode.value = "diseqc_a_b_c_d"
			elif self.nr_of_ports == 2:
				config.Nims[self.feid].dvbs.diseqcMode.value = "diseqc_a_b"
			else:
				config.Nims[self.feid].dvbs.diseqcMode.value = "single"

			config.Nims[self.feid].dvbs.configMode.value = "simple"
			config.Nims[self.feid].dvbs.simpleDiSEqCSetVoltageTone = self.simple_tone
			config.Nims[self.feid].dvbs.simpleDiSEqCOnlyOnSatChange = self.simple_sat_change

			self.saveAndReloadNimConfig()
			self.state += 1

		elif self.state == 1:
			InitNimManager(nimmanager)

			self.tuner = Tuner(self.frontend)
			if self.raw_channel:
				self.raw_channel.requestTsidOnid()
			self.tuner.tune(self.sat_frequencies[self.index])

			self["statusbar"].setText(_("Checking tuner %d\nDiSEqC port %s for %s") % (self.feid, self.diseqc_ports[self.port_index], self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
			self["tunerstatusbar"].setText(" ")

			self.count = 0
			self.state = 0

			self.startTunerStatusTimer()
			return

		self.startStatusTimer()

	def startStatusTimer(self):
		self.statusTimer.start(100, True)

	def setupSave(self):
		self.clearNimEntries()
		for x in self.found_sats:
			if x[0] == "A":
				config.Nims[self.feid].dvbs.diseqcA.value = "%d" % (x[1])
			elif x[0] == "B":
				config.Nims[self.feid].dvbs.diseqcB.value = "%d" % (x[1])
			elif x[0] == "C":
				config.Nims[self.feid].dvbs.diseqcC.value = "%d" % (x[1])
			elif x[0] == "D":
				config.Nims[self.feid].dvbs.diseqcD.value = "%d" % (x[1])
		self.saveAndReloadNimConfig()

	def setupClear(self):
		self.clearNimEntries()
		self.saveAndReloadNimConfig()

	def clearNimEntries(self):
		config.Nims[self.feid].dvbs.diseqcA.value = "3601"
		config.Nims[self.feid].dvbs.diseqcB.value = "3601"
		config.Nims[self.feid].dvbs.diseqcC.value = "3601"
		config.Nims[self.feid].dvbs.diseqcD.value = "3601"

	def saveAndReloadNimConfig(self):
		config.Nims[self.feid].save()
		configfile.save()
		configfile.load()
		nimmanager.sec.update()

	def tunerStatusCallback(self):
		dict = {}
		if self.frontend:
			self.frontend.getFrontendStatus(dict)
		else:
			self.tunerStopScan(False)
			return
		if dict["tuner_state"] == "TUNING":
                        self["tunerstatusbar"].setText(_("Tuner status TUNING"))

		elif dict["tuner_state"] == "FAILED":
                        self["tunerstatusbar"].setText(_("Tuner status FAILED"))

		elif dict["tuner_state"] == "LOSTLOCK":
                        self["tunerstatusbar"].setText(_("Tuner status LOSTLOCK"))

		elif dict["tuner_state"] == "LOCKED":
                        self["tunerstatusbar"].setText(_("Tuner status LOCKED"))

		elif dict["tuner_state"] == "IDLE":
                        self["tunerstatusbar"].setText(_("Tuner status IDLE"))

		elif dict["tuner_state"] == "UNKNOWN":
                        self["tunerstatusbar"].setText(_("Tuner status UNKNOWN"))
			
		if dict["tuner_state"] == "LOSTLOCK" or dict["tuner_state"] == "FAILED":
			self.tunerStopScan(False)
			return

		self.count += 1
		if self.count > 10:
			self.tunerStopScan(False)
		else:
			self.startTunerStatusTimer()

	def startTunerStatusTimer(self):
		self.tunerStatusTimer.start(1000, True)

	def gotTsidOnid(self, tsid, onid):
		self.tunerStatusTimer.stop()
		if tsid == self.sat_frequencies[self.index][self.SAT_TABLE_TSID] and onid == self.sat_frequencies[self.index][self.SAT_TABLE_ONID]:
			self.tunerStopScan(True)
		else:
			self.tunerStopScan(False)

	def tunerStopScan(self, result):
		if self.abort:
			self.setupClear()
			self.close(False)
			return
		if result:
			self.found_sats.append((self.diseqc_ports[self.port_index], self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS], self.sat_frequencies[self.index][self.SAT_TABLE_NAME]))
			self.index = 0
			self.port_index += 1
		else:
			self.index += 1
			if len(self.sat_frequencies) == self.index:
				self.index = 0
				self.port_index += 1

		if len(self.found_sats) > 0:
			self.list = []
			for x in self.found_sats:
				self.list.append(getConfigListEntry((_("DiSEqC port %s: %s") % (x[0], x[2]))))
			self["config"].l.setList(self.list)

		if self.nr_of_ports == self.port_index:
			self.state = 99
			self.setupSave()
			self.close(len(self.found_sats) > 0)
			return

		for x in self.found_sats:
			if x[1] == self.sat_frequencies[self.index][self.SAT_TABLE_ORBPOS]:
				self.tunerStopScan(False)
				return

		self.startStatusTimer()
예제 #55
0
class SimpleSatScan(ConfigListScreen, Screen):
    skin = """
	<screen position="center,center" size="520,480" title="Simple Satellite Scan">
		<!-- little tune status -->
		<eLabel name="pos" text="Current position:" position="10,10" size="210,20" font="Regular;19" halign="right" transparent="1" />
		<widget name="status" position="230,10" size="260,20" font="Console;19" valign="center" foregroundColor="#f8f711" transparent="1" />
		<!-- dB -->
		<!--widget source="Frontend" render="Label" position="190,10" zPosition="2" size="260,20" font="Regular;19" foregroundColor="#02f408" halign="center" valign="center" transparent="1"-->
		<widget source="Frontend" render="Label" position="190,35" zPosition="2" size="260,20" font="Regular;19" halign="center" valign="center" transparent="1">
			<convert type="FrontendInfo">SNRdB</convert>
		</widget>
		<!-- SNR -->
		<eLabel name="snr" text="SNR:" position="120,35" size="60,22" font="Regular;21" halign="right" transparent="1" />
		<widget source="Frontend" render="Progress" position="190,35" size="260,20" pixmap="skin_default/bar_snr.png" borderWidth="2" borderColor="#cccccc">
			<convert type="FrontendInfo">SNR</convert>
		</widget>
		<widget source="Frontend" render="Label" position="460,35" size="60,22" font="Regular;21">
			<convert type="FrontendInfo">SNR</convert>
		</widget>
		<!-- Lock -->
		<eLabel name="lock" text="LOCK:" position="10,35" size="60,22" font="Regular;21" halign="right" transparent="1" />
		<widget source="Frontend" render="Pixmap" pixmap="skin_default/icons/lock_on.png" position="80,32" zPosition="1" size="38,31" alphatest="on">
			<convert type="FrontendInfo">LOCK</convert>
			<convert type="ConditionalShowHide" />
		</widget>
		<widget source="Frontend" render="Pixmap" pixmap="skin_default/icons/lock_off.png" position="80,32" zPosition="1" size="38,31" alphatest="on">
			<convert type="FrontendInfo">LOCK</convert>
			<convert type="ConditionalShowHide">Invert</convert>
		</widget>
		<!-- AGC -->
		<eLabel name="agc" text="AGC:" position="120,60" size="60,22" font="Regular;21" halign="right" transparent="1" />
		<widget source="Frontend" render="Progress" position="190,60" size="260,20" pixmap="skin_default/bar_snr.png" borderWidth="2" borderColor="#cccccc">
			<convert type="FrontendInfo">AGC</convert>
		</widget>
		<widget source="Frontend" render="Label" position="460,60" size="60,22" font="Regular;21">
			<convert type="FrontendInfo">AGC</convert>
		</widget>
		<!-- BER -->
		<eLabel name="ber" text="BER:" position="120,85" size="60,22" font="Regular;21" halign="right" transparent="1" />
		<widget source="Frontend" render="Progress" position="190,85" size="260,20" pixmap="skin_default/bar_ber.png" borderWidth="2" borderColor="#cccccc">
			<convert type="FrontendInfo">BER</convert>
		</widget>
		<widget source="Frontend" render="Label" position="460,85" size="60,22" font="Regular;21">
			<convert type="FrontendInfo">BER</convert>
		</widget>
		<!-- config -->
		<widget name="config" position="10,120" size="500,320" scrollbarMode="showOnDemand" transparent="1" />
		<widget name="introduction" position="10,450" size="500,25" font="Regular;20" halign="center" valign="center" />
	</screen>"""

    def __init__(self, session):
        self.skin = SimpleSatScan.skin
        Screen.__init__(self, session)

        self.initcomplete = False
        self.frontend = None
        self.prev_ref = False
        self.oldref = None
        self.updateSatList()
        self.service = session.nav.getCurrentService()
        self.feinfo = None
        frontendData = None
        if self.service is not None:
            self.feinfo = self.service.frontendInfo()
            frontendData = self.feinfo and self.feinfo.getAll(True)

        self.createConfig(frontendData)

        del self.feinfo
        del self.service

        self["actions"] = NumberActionMap(["SetupActions"], {
            "ok": self.keyGo,
            "cancel": self.keyCancel,
        }, -2)

        self.list = []
        self.tpslist = []
        self.tpslist_idx = 0
        self.tuneTimer = eTimer()
        self.tuneTimer.callback.append(self.updateTuneStatus)

        ConfigListScreen.__init__(self, self.list)
        if not self.scan_nims.value == "":
            self.createSetup()
            self.feid = int(self.scan_nims.value)
            orbpos = "??"
            if len(self.satList) > self.feid and len(
                    self.scan_satselection) > self.feid and len(
                        self.satList[self.feid]):
                orbpos = self.OrbToStr(self.satList[self.feid][
                    self.scan_satselection[self.feid].index][0])
            self["status"] = Label(
                orbpos + ": " + str(self.scan_sat.frequency.value) + " " +
                self.PolToStr(self.scan_sat.polarization.value))
            self["introduction"] = Label(_("Press OK to start the scan"))
        else:
            self["introduction"] = Label(
                _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."
                  ))
            self["status"] = Label("")
            self.feid = None

        self.initFrontend()
        self.initcomplete = self.feid != None

    def openFrontend(self):
        res_mgr = eDVBResourceManager.getInstance()
        if res_mgr:
            self.raw_channel = res_mgr.allocateRawChannel(self.feid)
            if self.raw_channel:
                self.frontend = self.raw_channel.getFrontend()
                if self.frontend:
                    return True
        return False

    def initFrontend(self):
        if self.oldref is None:
            self.oldref = self.session.nav.getCurrentlyPlayingServiceReference(
            )
        if not self.openFrontend():
            self.prev_ref = True
            self.session.nav.stopService()  # try to disable foreground service
            if not self.openFrontend():
                if self.session.pipshown:  # try to disable pip
                    self.session.pipshown = False
                    del self.session.pip
                    if not self.openFrontend():
                        self.frontend = None  # in normal case this should not happen
        try:
            self.tuner = Tuner(self.frontend)
            self["Frontend"] = FrontendStatus(
                frontend_source=lambda: self.frontend, update_interval=100)
        except:
            pass

    def deInitFrontend(self):
        if self.frontend:
            self.frontend = None
            del self.raw_channel

    def updateTuneStatus(self):
        if not self.frontend: return
        stop = False
        dict = {}
        self.frontend.getFrontendStatus(dict)
        if dict["tuner_state"] == "TUNING":
            self.tuneTimer.start(100, True)
        else:
            if dict["tuner_state"] == "LOSTLOCK" or dict[
                    "tuner_state"] == "FAILED":
                self.tpslist_idx += 1
                if self.tpslist_idx >= len(self.tpslist):
                    stop = True
                    self["status"].setText("search failed!")
                    self.tpslist_idx = 0
            elif dict["tuner_state"] == "LOCKED":
                stop = True

            if not stop:
                self["status"].setText(
                    self.OrbToStr(self.tpslist[self.tpslist_idx][5]) + ": " +
                    str(self.tpslist[self.tpslist_idx][0]) + " " +
                    self.PolToStr(self.tpslist[self.tpslist_idx][2]))
                self.tune(self.tpslist[self.tpslist_idx])
                self.tuneTimer.start(100, True)

    def tune(self, transponder):
        if self.initcomplete:
            if transponder is not None and self.tuner is not None:
                self.tuner.tune(transponder)

    def retune(self, configElement):
        self.tuneTimer.stop()
        if self.scan_nims == []: return
        if self.scan_nims.value == "": return
        self.tpslist_idx = 0
        tpslist = []
        status_text = ""
        multi_tune = False
        index_to_scan = int(self.scan_nims.value)
        if len(self.satList) <= index_to_scan: return
        if len(self.scan_satselection) <= index_to_scan: return

        nim = nimmanager.nim_slots[index_to_scan]
        if not nim.isCompatible("DVB-S"): return

        nimsats = self.satList[index_to_scan]
        selsatidx = self.scan_satselection[index_to_scan].index
        if self.scan_type.value == "single_transponder":
            if len(nimsats):
                orbpos = nimsats[selsatidx][0]
                if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
                    fec = self.scan_sat.fec.value
                else:
                    fec = self.scan_sat.fec_s2.value
                tpslist.append(
                    (self.scan_sat.frequency.value,
                     self.scan_sat.symbolrate.value,
                     self.scan_sat.polarization.value, fec,
                     self.scan_sat.inversion.value, orbpos,
                     self.scan_sat.system.value,
                     self.scan_sat.modulation.value,
                     self.scan_sat.rolloff.value, self.scan_sat.pilot.value))
        elif self.scan_type.value == "predefined_transponder":
            if len(nimsats):
                orbpos = nimsats[selsatidx][0]
                index = self.scan_transponders.index
                if configElement and configElement._value == str(orbpos):
                    index = 0
                tps = nimmanager.getTransponders(orbpos)
                if len(tps) > index:
                    x = tps[index]
                    tpslist.append((x[1] / 1000, x[2] / 1000, x[3], x[4], x[7],
                                    orbpos, x[5], x[6], x[8], x[9]))
                #else:
                #	status_text = "tpslist for %d empty! %d" % (sat[0], index)
        elif self.scan_type.value == "single_satellite":
            if len(nimsats):
                multi_tune = True
                orbpos = nimsats[selsatidx][0]
                tps = nimmanager.getTransponders(orbpos)
                for x in tps:
                    if x[0] == 0:  #SAT
                        tpslist.append((x[1] / 1000, x[2] / 1000, x[3], x[4],
                                        x[7], orbpos, x[5], x[6], x[8], x[9]))
        elif self.scan_type.value == "multisat":
            if len(self.multiscanlist):
                for sat in self.multiscanlist:
                    if sat[1].value or len(tpslist) == 0:
                        if len(tpslist):
                            del tpslist[:]
                        tps = nimmanager.getTransponders(sat[0])
                        for x in tps:
                            if x[0] == 0:  #SAT
                                tpslist.append(
                                    (x[1] / 1000, x[2] / 1000, x[3], x[4],
                                     x[7], sat[0], x[5], x[6], x[8], x[9]))
                        if sat[1].value:
                            multi_tune = True
                            break
            else:
                status_text = "multiscanlist empty!"
                SatList = nimmanager.getSatListForNim(index_to_scan)
                for sat in SatList:
                    tps = nimmanager.getTransponders(sat[0])
                    for x in tps:
                        if x[0] == 0:  #SAT
                            tpslist.append(
                                (x[1] / 1000, x[2] / 1000, x[3], x[4], x[7],
                                 sat[0], x[5], x[6], x[8], x[9]))
                    if len(tpslist): break

        self.tpslist = tpslist
        if len(self.tpslist):
            status_text = self.OrbToStr(
                self.tpslist[self.tpslist_idx][5]) + ": " + str(
                    self.tpslist[self.tpslist_idx][0]) + " " + self.PolToStr(
                        self.tpslist[self.tpslist_idx][2])
            self.tune(self.tpslist[self.tpslist_idx])
            if multi_tune:
                self.tuneTimer.start(100, True)
        self["status"].setText(status_text)

    def OrbToStr(self, orbpos=-1):
        if orbpos == -1 or orbpos > 3600: return "??"
        if orbpos > 1800:
            return "%d.%dW" % ((3600 - orbpos) / 10, (3600 - orbpos) % 10)
        else:
            return "%d.%dE" % (orbpos / 10, orbpos % 10)

    def PolToStr(self, pol):
        return (pol == 0 and "H") or (pol == 1 and "V") or (
            pol == 2 and "L") or (pol == 3 and "R") or "??"

    def FecToStr(self, fec):
        return (fec == 0 and "Auto") or (fec == 1 and "1/2") or (fec == 2 and "2/3") or (fec == 3 and "3/4") or \
         (fec == 4 and "5/6") or (fec == 5 and "7/8") or (fec == 6 and "8/9") or (fec == 7 and "3/5") or \
         (fec == 8 and "4/5") or (fec == 9 and "9/10") or (fec == 15 and "None") or "Unknown"

    def updateTranspondersList(self, orbpos):
        if orbpos is not None:
            index = 0
            list = []
            tps = nimmanager.getTransponders(orbpos)
            for x in tps:
                if x[0] == 0:  #SAT
                    s = str(x[1] / 1000) + " " + self.PolToStr(
                        x[3]) + " / " + str(
                            x[2] / 1000) + " / " + self.FecToStr(x[4])
                    list.append((str(index), s))
                    index += 1
            self.scan_transponders = ConfigSelection(choices=list, default="0")
            self.scan_transponders.addNotifier(self.retune, initial_call=False)

    def updateSatList(self):
        self.satList = []
        for slot in nimmanager.nim_slots:
            if slot.isCompatible("DVB-S"):
                self.satList.append(nimmanager.getSatListForNim(slot.slot))
            #else:
            #	self.satList.append(None)

    def createSetup(self):
        self.tuneTimer.stop()
        self.list = []
        self.multiscanlist = []
        index_to_scan = int(self.scan_nims.value)

        self.tunerEntry = getConfigListEntry(_("Tuner"), self.scan_nims)
        self.list.append(self.tunerEntry)

        if self.scan_nims == []:
            return

        self.typeOfScanEntry = None
        self.systemEntry = None
        self.satelliteEntry = None
        self.modulationEntry = None
        self.scan_networkScan.value = False
        nim = nimmanager.nim_slots[index_to_scan]
        if nim.isCompatible("DVB-S"):
            self.typeOfScanEntry = getConfigListEntry(_("Type of scan"),
                                                      self.scan_type)
            self.list.append(self.typeOfScanEntry)

            if self.scan_type.value == "single_transponder":
                self.updateSatList()
                sat = self.satList[index_to_scan][
                    self.scan_satselection[index_to_scan].index]
                self.updateTranspondersList(sat[0])
                if nim.isCompatible("DVB-S2"):
                    self.systemEntry = getConfigListEntry(
                        _('System'), self.scan_sat.system)
                    self.list.append(self.systemEntry)
                else:
                    self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S
                self.list.append(
                    getConfigListEntry(_('Satellite'),
                                       self.scan_satselection[index_to_scan]))
                self.list.append(
                    getConfigListEntry(_('Frequency'),
                                       self.scan_sat.frequency))
                self.list.append(
                    getConfigListEntry(_('Inversion'),
                                       self.scan_sat.inversion))
                self.list.append(
                    getConfigListEntry(_('Symbol Rate'),
                                       self.scan_sat.symbolrate))
                self.list.append(
                    getConfigListEntry(_("Polarity"),
                                       self.scan_sat.polarization))
                if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
                    self.list.append(
                        getConfigListEntry(_("FEC"), self.scan_sat.fec))
                elif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
                    self.list.append(
                        getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
                    self.modulationEntry = getConfigListEntry(
                        _('Modulation'), self.scan_sat.modulation)
                    self.list.append(self.modulationEntry)
                    self.list.append(
                        getConfigListEntry(_('Rolloff'),
                                           self.scan_sat.rolloff))
                    self.list.append(
                        getConfigListEntry(_('Pilot'), self.scan_sat.pilot))
            elif self.scan_type.value == "predefined_transponder":
                self.updateSatList()
                self.satelliteEntry = getConfigListEntry(
                    _('Satellite'), self.scan_satselection[index_to_scan])
                self.list.append(self.satelliteEntry)
                sat = self.satList[index_to_scan][
                    self.scan_satselection[index_to_scan].index]
                self.updateTranspondersList(sat[0])
                self.list.append(
                    getConfigListEntry(_('Transponder'),
                                       self.scan_transponders))
            elif self.scan_type.value == "single_satellite":
                self.updateSatList()
                sat = self.satList[index_to_scan][
                    self.scan_satselection[index_to_scan].index]
                self.updateTranspondersList(sat[0])
                print self.scan_satselection[index_to_scan]
                self.list.append(
                    getConfigListEntry(_("Satellite"),
                                       self.scan_satselection[index_to_scan]))
                self.scan_networkScan.value = True
            elif self.scan_type.value == "multisat":
                tlist = []
                SatList = nimmanager.getSatListForNim(index_to_scan)
                for x in SatList:
                    if self.Satexists(tlist, x[0]) == 0:
                        tlist.append(x[0])
                        sat = ConfigEnableDisable(
                            default=self.scan_type.value.find("_yes") != -1
                            and True or False)
                        configEntry = getConfigListEntry(
                            nimmanager.getSatDescription(x[0]), sat)
                        self.list.append(configEntry)
                        self.multiscanlist.append((x[0], sat))
                        sat.addNotifier(self.retune, initial_call=False)
                self.scan_networkScan.value = True

        self.list.append(
            getConfigListEntry(_("Network scan"), self.scan_networkScan))
        self.list.append(
            getConfigListEntry(_("Clear before scan"),
                               self.scan_clearallservices))
        self.list.append(
            getConfigListEntry(_("Only Free scan"), self.scan_onlyfree))
        self["config"].list = self.list
        self["config"].l.setList(self.list)

    def Satexists(self, tlist, pos):
        for x in tlist:
            if x == pos:
                return 1
        return 0

    def newConfig(self):
        cur = self["config"].getCurrent()
        if cur == self.typeOfScanEntry or \
         cur == self.tunerEntry or \
         cur == self.systemEntry or \
         cur == self.satelliteEntry or \
         (self.modulationEntry and self.systemEntry[1].value == eDVBFrontendParametersSatellite.System_DVB_S2 and cur == self.modulationEntry):
            self.createSetup()

    def createConfig(self, frontendData):
        defaultSat = {
            "orbpos": 192,
            "system": eDVBFrontendParametersSatellite.System_DVB_S,
            "frequency": 11836,
            "inversion": eDVBFrontendParametersSatellite.Inversion_Unknown,
            "symbolrate": 27500,
            "polarization":
            eDVBFrontendParametersSatellite.Polarisation_Horizontal,
            "fec": eDVBFrontendParametersSatellite.FEC_Auto,
            "fec_s2": eDVBFrontendParametersSatellite.FEC_9_10,
            "modulation": eDVBFrontendParametersSatellite.Modulation_QPSK
        }

        if frontendData is not None:
            ttype = frontendData.get("tuner_type", "UNKNOWN")
            if ttype == "DVB-S":
                defaultSat["system"] = frontendData.get(
                    "system", eDVBFrontendParametersSatellite.System_DVB_S)
                defaultSat["frequency"] = frontendData.get("frequency",
                                                           0) / 1000
                defaultSat["inversion"] = frontendData.get(
                    "inversion",
                    eDVBFrontendParametersSatellite.Inversion_Unknown)
                defaultSat["symbolrate"] = frontendData.get("symbol_rate",
                                                            0) / 1000
                defaultSat["polarization"] = frontendData.get(
                    "polarization",
                    eDVBFrontendParametersSatellite.Polarisation_Horizontal)
                if defaultSat[
                        "system"] == eDVBFrontendParametersSatellite.System_DVB_S2:
                    defaultSat["fec_s2"] = frontendData.get(
                        "fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
                    defaultSat["rolloff"] = frontendData.get(
                        "rolloff",
                        eDVBFrontendParametersSatellite.RollOff_alpha_0_35)
                    defaultSat["pilot"] = frontendData.get(
                        "pilot", eDVBFrontendParametersSatellite.Pilot_Unknown)
                else:
                    defaultSat["fec"] = frontendData.get(
                        "fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
                defaultSat["modulation"] = frontendData.get(
                    "modulation",
                    eDVBFrontendParametersSatellite.Modulation_QPSK)
                defaultSat["orbpos"] = frontendData.get("orbital_position", 0)

        self.scan_sat = ConfigSubsection()

        self.scan_type = ConfigSelection(
            default="single_transponder",
            choices=[("single_transponder", _("Single transponder")),
                     ("predefined_transponder", _("Predefined transponder")),
                     ("single_satellite", _("Single satellite")),
                     ("multisat", _("Multisat"))])
        self.scan_transponders = None
        self.scan_clearallservices = ConfigSelection(
            default="no",
            choices=[("no", _("no")), ("yes", _("yes")),
                     ("yes_hold_feeds", _("yes (keep feeds)"))])
        self.scan_onlyfree = ConfigYesNo(default=False)
        self.scan_networkScan = ConfigYesNo(default=False)

        nim_list = []
        for n in nimmanager.nim_slots:
            if n.config_mode == "nothing":
                continue
            if n.config_mode == "advanced" and len(
                    nimmanager.getSatListForNim(n.slot)) < 1:
                continue
            if n.config_mode in ("loopthrough", "satposdepends"):
                root_id = nimmanager.sec.getRoot(
                    n.slot_id, int(n.config.connectedTo.value))
                if n.type == nimmanager.nim_slots[root_id].type:
                    continue
            if n.isCompatible("DVB-S"):
                nim_list.append((str(n.slot), n.friendly_full_description))

        self.scan_nims = ConfigSelection(choices=nim_list)

        self.scan_sat.system = ConfigSelection(
            default=defaultSat["system"],
            choices=[
                (eDVBFrontendParametersSatellite.System_DVB_S, _("DVB-S")),
                (eDVBFrontendParametersSatellite.System_DVB_S2, _("DVB-S2"))
            ])
        self.scan_sat.frequency = ConfigInteger(
            default=defaultSat["frequency"], limits=(1, 99999))
        self.scan_sat.inversion = ConfigSelection(
            default=defaultSat["inversion"],
            choices=[(eDVBFrontendParametersSatellite.Inversion_Off, _("off")),
                     (eDVBFrontendParametersSatellite.Inversion_On, _("on")),
                     (eDVBFrontendParametersSatellite.Inversion_Unknown,
                      _("Auto"))])
        self.scan_sat.symbolrate = ConfigInteger(
            default=defaultSat["symbolrate"], limits=(1, 99999))
        self.scan_sat.polarization = ConfigSelection(
            default=defaultSat["polarization"],
            choices=[
                (eDVBFrontendParametersSatellite.Polarisation_Horizontal,
                 _("horizontal")),
                (eDVBFrontendParametersSatellite.Polarisation_Vertical,
                 _("vertical")),
                (eDVBFrontendParametersSatellite.Polarisation_CircularLeft,
                 _("circular left")),
                (eDVBFrontendParametersSatellite.Polarisation_CircularRight,
                 _("circular right"))
            ])
        self.scan_sat.fec = ConfigSelection(
            default=defaultSat["fec"],
            choices=[(eDVBFrontendParametersSatellite.FEC_Auto, _("Auto")),
                     (eDVBFrontendParametersSatellite.FEC_1_2, "1/2"),
                     (eDVBFrontendParametersSatellite.FEC_2_3, "2/3"),
                     (eDVBFrontendParametersSatellite.FEC_3_4, "3/4"),
                     (eDVBFrontendParametersSatellite.FEC_5_6, "5/6"),
                     (eDVBFrontendParametersSatellite.FEC_7_8, "7/8"),
                     (eDVBFrontendParametersSatellite.FEC_None, _("None"))])
        self.scan_sat.fec_s2 = ConfigSelection(
            default=defaultSat["fec_s2"],
            choices=[(eDVBFrontendParametersSatellite.FEC_1_2, "1/2"),
                     (eDVBFrontendParametersSatellite.FEC_2_3, "2/3"),
                     (eDVBFrontendParametersSatellite.FEC_3_4, "3/4"),
                     (eDVBFrontendParametersSatellite.FEC_3_5, "3/5"),
                     (eDVBFrontendParametersSatellite.FEC_4_5, "4/5"),
                     (eDVBFrontendParametersSatellite.FEC_5_6, "5/6"),
                     (eDVBFrontendParametersSatellite.FEC_7_8, "7/8"),
                     (eDVBFrontendParametersSatellite.FEC_8_9, "8/9"),
                     (eDVBFrontendParametersSatellite.FEC_9_10, "9/10")])
        self.scan_sat.modulation = ConfigSelection(
            default=defaultSat["modulation"],
            choices=[(eDVBFrontendParametersSatellite.Modulation_QPSK, "QPSK"),
                     (eDVBFrontendParametersSatellite.Modulation_8PSK, "8PSK")
                     ])
        self.scan_sat.rolloff = ConfigSelection(
            default=defaultSat.get(
                "rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
            choices=[
                (eDVBFrontendParametersSatellite.RollOff_alpha_0_35, "0.35"),
                (eDVBFrontendParametersSatellite.RollOff_alpha_0_25, "0.25"),
                (eDVBFrontendParametersSatellite.RollOff_alpha_0_20, "0.20")
            ])
        self.scan_sat.pilot = ConfigSelection(
            default=defaultSat.get(
                "pilot", eDVBFrontendParametersSatellite.Pilot_Unknown),
            choices=[(eDVBFrontendParametersSatellite.Pilot_Off, _("off")),
                     (eDVBFrontendParametersSatellite.Pilot_On, _("on")),
                     (eDVBFrontendParametersSatellite.Pilot_Unknown, _("Auto"))
                     ])

        self.scan_scansat = {}
        for sat in nimmanager.satList:
            self.scan_scansat[sat[0]] = ConfigYesNo(default=False)

        self.scan_satselection = []
        for slot in nimmanager.nim_slots:
            if slot.isCompatible("DVB-S"):
                x = getConfigSatlist(defaultSat["orbpos"],
                                     self.satList[slot.slot])
                x.addNotifier(self.retune, initial_call=False)
                self.scan_satselection.append(x)
            else:
                self.scan_satselection.append(None)

        for x in (self.scan_nims, self.scan_type, self.scan_sat.frequency,
                  self.scan_sat.inversion, self.scan_sat.symbolrate,
                  self.scan_sat.polarization, self.scan_sat.fec,
                  self.scan_sat.pilot, self.scan_sat.fec_s2, self.scan_sat.fec,
                  self.scan_sat.modulation, self.scan_sat.rolloff,
                  self.scan_sat.system):
            x.addNotifier(self.retune, initial_call=False)

        return True

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()

    def addSatTransponder(self, tlist, frequency, symbol_rate, polarisation,
                          fec, inversion, orbital_position, system, modulation,
                          rolloff, pilot):
        print "Add Sat: frequ: " + str(frequency) + " symbol: " + str(
            symbol_rate) + " pol: " + str(polarisation) + " fec: " + str(
                fec) + " inversion: " + str(inversion) + " modulation: " + str(
                    modulation) + " system: " + str(system) + " rolloff" + str(
                        rolloff) + " pilot" + str(pilot)
        print "orbpos: " + str(orbital_position)
        parm = eDVBFrontendParametersSatellite()
        parm.modulation = modulation
        parm.system = system
        parm.frequency = frequency * 1000
        parm.symbol_rate = symbol_rate * 1000
        parm.polarisation = polarisation
        parm.fec = fec
        parm.inversion = inversion
        parm.orbital_position = orbital_position
        parm.rolloff = rolloff
        parm.pilot = pilot
        tlist.append(parm)

    def getInitialTransponderList(self, tlist, pos):
        list = nimmanager.getTransponders(pos)
        for x in list:
            if x[0] == 0:  #SAT
                parm = eDVBFrontendParametersSatellite()
                parm.frequency = x[1]
                parm.symbol_rate = x[2]
                parm.polarisation = x[3]
                parm.fec = x[4]
                parm.inversion = x[7]
                parm.orbital_position = pos
                parm.system = x[5]
                parm.modulation = x[6]
                parm.rolloff = x[8]
                parm.pilot = x[9]
                tlist.append(parm)

    def keyGo(self):
        if self.scan_nims.value == "":
            return
        self.tuneTimer.stop()
        self.deInitFrontend()
        index_to_scan = int(self.scan_nims.value)
        self.feid = index_to_scan
        tlist = []
        flags = None
        startScan = True
        removeAll = True
        self.prev_ref = True
        if self.scan_nims == []:
            self.session.open(
                MessageBox,
                _("No tuner is enabled!\nPlease setup your tuner settings before you start a service scan."
                  ), MessageBox.TYPE_ERROR)
            return

        nim = nimmanager.nim_slots[index_to_scan]
        if not nim.isCompatible("DVB-S"): return
        #if self.scan_type.value == "single_transponder":
        if self.scan_type.value.find("_transponder") != -1:
            assert len(self.satList) > index_to_scan
            assert len(self.scan_satselection) > index_to_scan

            nimsats = self.satList[index_to_scan]
            selsatidx = self.scan_satselection[index_to_scan].index

            if len(nimsats):
                orbpos = nimsats[selsatidx][0]
                if self.scan_type.value == "single_transponder":
                    if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
                        fec = self.scan_sat.fec.value
                    else:
                        fec = self.scan_sat.fec_s2.value
                    self.addSatTransponder(tlist,
                                           self.scan_sat.frequency.value,
                                           self.scan_sat.symbolrate.value,
                                           self.scan_sat.polarization.value,
                                           fec, self.scan_sat.inversion.value,
                                           orbpos, self.scan_sat.system.value,
                                           self.scan_sat.modulation.value,
                                           self.scan_sat.rolloff.value,
                                           self.scan_sat.pilot.value)
                elif self.scan_type.value == "predefined_transponder":
                    tps = nimmanager.getTransponders(orbpos)
                    if len(tps) > self.scan_transponders.index:
                        x = tps[self.scan_transponders.index]
                        self.addSatTransponder(tlist, x[1] / 1000, x[2] / 1000,
                                               x[3], x[4], x[7], orbpos, x[5],
                                               x[6], x[8], x[9])
            removeAll = False
        elif self.scan_type.value == "single_satellite":
            sat = self.satList[index_to_scan][
                self.scan_satselection[index_to_scan].index]
            self.getInitialTransponderList(tlist, sat[0])
        elif self.scan_type.value.find("multisat") != -1:
            SatList = nimmanager.getSatListForNim(index_to_scan)
            for x in self.multiscanlist:
                if x[1].value:
                    print "   " + str(x[0])
                    self.getInitialTransponderList(tlist, x[0])

        flags = self.scan_networkScan.value and eComponentScan.scanNetworkSearch or 0

        tmp = self.scan_clearallservices.value
        if tmp == "yes":
            flags |= eComponentScan.scanRemoveServices
        elif tmp == "yes_hold_feeds":
            flags |= eComponentScan.scanRemoveServices
            flags |= eComponentScan.scanDontRemoveFeeds

        if tmp != "no" and not removeAll:
            flags |= eComponentScan.scanDontRemoveUnscanned

        if self.scan_onlyfree.value:
            flags |= eComponentScan.scanOnlyFree

        for x in self["config"].list:
            x[1].save()

        if startScan:
            self.startScan(tlist, flags, index_to_scan)

    def keyCancel(self):
        for x in self["config"].list:
            x[1].cancel()
        if self.oldref and self.prev_ref:
            self.session.openWithCallback(
                self.restartPrevService,
                MessageBox,
                _("Zap back to service before a service scan?"),
                MessageBox.TYPE_YESNO,
                timeout=5)
        else:
            self.close()

    def restartPrevService(self, answer):
        if answer:
            self.tuneTimer.stop()
            self.deInitFrontend()
            if self.oldref:
                self.session.nav.playService(self.oldref)
        self.close()

    def startScan(self, tlist, flags, feid):
        if len(tlist):
            self.session.openWithCallback(self.serviceScanFinished,
                                          ServiceScan, [{
                                              "transponders": tlist,
                                              "feid": feid,
                                              "flags": flags
                                          }])
        else:
            self.session.open(
                MessageBox,
                _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."
                  ), MessageBox.TYPE_ERROR)
            self.keyCancel()

    def serviceScanFinished(self):
        self.session.openWithCallback(
            self.restartSimpleSatScan,
            MessageBox,
            _("Do you want to scan another transponder/satellite?"),
            MessageBox.TYPE_YESNO,
            timeout=10)

    def restartSimpleSatScan(self, answer):
        if answer:
            # reinit FrontendStatus...
            self.frontend = None
            self.initFrontend()
            self.retune(None)
        else:
            self.keyCancel()
예제 #56
0
class Satfinder(ScanSetup):
    def openFrontend(self):
        res_mgr = eDVBResourceManager.getInstance()
        if res_mgr:
            self.raw_channel = res_mgr.allocateRawChannel(self.feid)
            if self.raw_channel:
                self.frontend = self.raw_channel.getFrontend()
                if self.frontend:
                    return True
                else:
                    print "getFrontend failed"
            else:
                print "getRawChannel failed"
        else:
            print "getResourceManager instance failed"
        return False

    def __init__(self, session, feid):
        self.initcomplete = False
        self.feid = feid
        self.oldref = None

        if not self.openFrontend():
            self.oldref = session.nav.getCurrentlyPlayingServiceReference()
            session.nav.stopService()  # try to disable foreground service
            if not self.openFrontend():
                if session.pipshown:  # try to disable pip
                    session.pipshown = False
                    del session.pip
                    if not self.openFrontend():
                        self.frontend = None  # in normal case this should not happen

        ScanSetup.__init__(self, session)
        self.tuner = Tuner(self.frontend)
        self["introduction"].setText("")
        self["Frontend"] = FrontendStatus(
            frontend_source=lambda: self.frontend, update_interval=100)
        self.initcomplete = True
        self.onClose.append(self.__onClose)

    def __onClose(self):
        self.session.nav.playService(self.oldref)

    def createSetup(self):
        self.typeOfTuningEntry = None
        self.satEntry = None

        self.list = []

        self.typeOfTuningEntry = getConfigListEntry(_('Tune'),
                                                    self.tuning_type)
        self.list.append(self.typeOfTuningEntry)
        self.satEntry = getConfigListEntry(_('Satellite'), self.tuning_sat)
        self.list.append(self.satEntry)

        nim = nimmanager.nim_slots[self.feid]

        self.systemEntry = None
        if self.tuning_type.value == "manual_transponder":
            if nim.isCompatible("DVB-S2"):
                self.systemEntry = getConfigListEntry(_('System'),
                                                      self.scan_sat.system)
                self.list.append(self.systemEntry)
            else:
                # downgrade to dvb-s, in case a -s2 config was active
                self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S
            self.list.append(
                getConfigListEntry(_('Frequency'), self.scan_sat.frequency))
            self.list.append(
                getConfigListEntry(_('Inversion'), self.scan_sat.inversion))
            self.list.append(
                getConfigListEntry(_('Symbol Rate'), self.scan_sat.symbolrate))
            self.list.append(
                getConfigListEntry(_("Polarity"), self.scan_sat.polarization))
            if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
                self.list.append(
                    getConfigListEntry(_("FEC"), self.scan_sat.fec))
            elif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
                self.list.append(
                    getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
                self.modulationEntry = getConfigListEntry(
                    _('Modulation'), self.scan_sat.modulation)
                self.list.append(self.modulationEntry)
                self.list.append(
                    getConfigListEntry(_('Rolloff'), self.scan_sat.rolloff))
                self.list.append(
                    getConfigListEntry(_('Pilot'), self.scan_sat.pilot))
        elif self.tuning_transponder and self.tuning_type.value == "predefined_transponder":
            self.list.append(
                getConfigListEntry(_("Transponder"), self.tuning_transponder))
        self["config"].list = self.list
        self["config"].l.setList(self.list)

    def newConfig(self):
        cur = self["config"].getCurrent()
        if cur in (self.typeOfTuningEntry, self.systemEntry):
            self.createSetup()
        elif cur == self.satEntry:
            self.updateSats()
            self.createSetup()

    def sat_changed(self, config_element):
        self.newConfig()
        self.retune(config_element)

    def retune(self, configElement):
        returnvalue = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        satpos = int(self.tuning_sat.value)
        if self.tuning_type.value == "manual_transponder":
            if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
                fec = self.scan_sat.fec_s2.value
            else:
                fec = self.scan_sat.fec.value
            returnvalue = (self.scan_sat.frequency.value,
                           self.scan_sat.symbolrate.value,
                           self.scan_sat.polarization.value, fec,
                           self.scan_sat.inversion.value, satpos,
                           self.scan_sat.system.value,
                           self.scan_sat.modulation.value,
                           self.scan_sat.rolloff.value,
                           self.scan_sat.pilot.value)
            self.tune(returnvalue)
        elif self.tuning_type.value == "predefined_transponder":
            tps = nimmanager.getTransponders(satpos)
            l = len(tps)
            if l > self.tuning_transponder.index:
                transponder = tps[self.tuning_transponder.index]
                returnvalue = (transponder[1] / 1000, transponder[2] / 1000,
                               transponder[3], transponder[4], 2, satpos,
                               transponder[5], transponder[6], transponder[8],
                               transponder[9])
                self.tune(returnvalue)

    def createConfig(self, foo):
        self.tuning_transponder = None
        self.tuning_type = ConfigSelection(
            choices=[("manual_transponder", _("Manual transponder")
                      ), ("predefined_transponder",
                          _("Predefined transponder"))])
        self.tuning_sat = getConfigSatlist(
            192, nimmanager.getSatListForNim(self.feid))
        ScanSetup.createConfig(self, None)

        self.updateSats()

        for x in (self.tuning_type, self.tuning_sat, self.scan_sat.frequency,
                  self.scan_sat.inversion, self.scan_sat.symbolrate,
                  self.scan_sat.polarization, self.scan_sat.fec,
                  self.scan_sat.pilot, self.scan_sat.fec_s2, self.scan_sat.fec,
                  self.scan_sat.modulation, self.scan_sat.rolloff,
                  self.scan_sat.system):
            x.addNotifier(self.retune, initial_call=False)

    def updateSats(self):
        orb_pos = self.tuning_sat.orbital_position
        if orb_pos is not None:
            transponderlist = nimmanager.getTransponders(orb_pos)
            list = []
            default = None
            index = 0
            for x in transponderlist:
                if x[3] == 0:
                    pol = "H"
                elif x[3] == 1:
                    pol = "V"
                elif x[3] == 2:
                    pol = "CL"
                elif x[3] == 3:
                    pol = "CR"
                else:
                    pol = "??"
                if x[4] == 0:
                    fec = "FEC Auto"
                elif x[4] == 1:
                    fec = "FEC 1/2"
                elif x[4] == 2:
                    fec = "FEC 2/3"
                elif x[4] == 3:
                    fec = "FEC 3/4"
                elif x[4] == 4:
                    fec = "FEC 5/6"
                elif x[4] == 5:
                    fec = "FEC 7/8"
                elif x[4] == 6:
                    fec = "FEC 8/9"
                elif x[4] == 7:
                    fec = "FEC 3/5"
                elif x[4] == 8:
                    fec = "FEC 4/5"
                elif x[4] == 9:
                    fec = "FEC 9/10"
                elif x[4] == 15:
                    fec = "FEC None"
                else:
                    fec = "FEC Unknown"
                e = str(x[1]) + "," + str(x[2]) + "," + pol + "," + fec
                if default is None:
                    default = str(index)
                list.append((str(index), e))
                index += 1
            self.tuning_transponder = ConfigSelection(choices=list,
                                                      default=default)
            self.tuning_transponder.addNotifier(self.retune,
                                                initial_call=False)

    def keyGo(self):
        self.retune(self.tuning_type)

    def restartPrevService(self, yesno):
        if yesno:
            if self.frontend:
                self.frontend = None
                del self.raw_channel
        else:
            self.oldref = None
        self.close(None)

    def keyCancel(self):
        if self.oldref:
            self.session.openWithCallback(
                self.restartPrevService, MessageBox,
                _("Zap back to service before satfinder?"),
                MessageBox.TYPE_YESNO)
        else:
            self.restartPrevService(False)

    def tune(self, transponder):
        if self.initcomplete:
            if transponder is not None:
                self.tuner.tune(transponder)
예제 #57
0
파일: plugin.py 프로젝트: Open-Plus/opgui
class Satfinder(ScanSetup, ServiceScan):
	def __init__(self, session):
		self.initcomplete = False
		service = session and session.nav.getCurrentService()
		feinfo = service and service.frontendInfo()
		self.frontendData = feinfo and feinfo.getAll(True)
		del feinfo
		del service


		self.systemEntry = None
		self.systemEntryATSC = None
		self.satfinderTunerEntry = None
		self.satEntry = None
		self.frequencyEntry = None
		self.polarizationEntry = None
		self.symbolrateEntry = None
		self.inversionEntry = None
		self.rolloffEntry = None
		self.pilotEntry = None
		self.fecEntry = None
		self.transponder = None

		ScanSetup.__init__(self, session)
		self.setTitle(_("Signal Finder"))
		self["introduction"].setText(_("Press OK to scan"))
		self["Frontend"] = FrontendStatus(frontend_source = lambda : self.frontend, update_interval = 100)

		self["actions"] = ActionMap(["SetupActions", "ColorActions"],
		{
			"save": self.keyGoScan,
			"ok": self.keyGoScan,
			"cancel": self.keyCancel,
		}, -3)

		self.initcomplete = True
		self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.onClose.append(self.__onClose)
		self.onShow.append(self.prepareFrontend)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			fe_id = int(self.scan_nims.value)
			self.raw_channel = res_mgr.allocateRawChannel(fe_id)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
		return False

	def prepareFrontend(self):
		self.frontend = None
		try:
			if not self.openFrontend():
				self.session.nav.stopService()
				if not self.openFrontend():
					if self.session.pipshown:
						from Screens.InfoBar import InfoBar
						InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
						if not self.openFrontend():
							self.frontend = None # in normal case this should not happen
			self.tuner = Tuner(self.frontend)
			self.createSetup()
			self.retune()
		except:
			pass

	def __onClose(self):
		self.session.nav.playService(self.session.postScanService)

	def newConfig(self):
#		self.transponder = None
		cur = self["config"].getCurrent()
		print"cur ", cur

		if cur == self.tunerEntry:
			self.feid = int(self.scan_nims.value)
			self.prepareFrontend()
			if self.frontend == None and self.session.nav.RecordTimer.isRecording():
				slot = nimmanager.nim_slots[self.feid]
				msg = _("%s not available.") % slot.getSlotName()
				msg += _("\nRecording in progress.")
				self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR)
		else:
			ScanSetup.newConfig(self)
		if cur[1].value == "single_transponder":
			self.retune()


	def createSetup(self):
		ScanSetup.createSetup(self)

#manipulate "config", remove "self.scan_networkScan", "self.scan_clearallservices" and "self.scan_onlyfree"
		tlist = self["config"].getList()
		for x in (self.scan_networkScan, self.scan_clearallservices, self.scan_onlyfree):
			for y in tlist:
				if x == y[1]:
					tlist.remove(y)
		self["config"].list = tlist
		self["config"].l.setList(tlist)

#manipulate choices, we need only "single_transponder","predefined_transponder"
		for scan_type in (self.scan_type, self.scan_typecable, self.scan_typeterrestrial, self.scan_typeatsc):
			slist = scan_type.choices.choices
			dlist = []
			for x in slist:
				if x[0] in ("single_transponder","predefined_transponder"):
					dlist.append(x)
			scan_type.choices.choices = dlist

	def TunerTypeChanged(self):
		fe_id = int(self.scan_nims.value)
		multiType = config.Nims[fe_id].multiType
		system = multiType.getText()
		if (system in ('DVB-S','DVB-S2') and config.Nims[fe_id].dvbs.configMode.value == "nothing") or \
			(system in ('DVB-T','DVB-T2') and config.Nims[fe_id].dvbt.configMode.value == "nothing") or \
			(system in ('DVB-C') and config.Nims[fe_id].dvbc.configMode.value == "nothing") or \
			(system in ('ATSC') and config.Nims[fe_id].atsc.configMode.value == "nothing") :
			return
		slot = nimmanager.nim_slots[fe_id]
		print "dvb_api_version ",iDVBFrontend.dvb_api_version
		self.frontend = None
		if not self.openFrontend():
			self.session.nav.stopService()
			if not self.openFrontend():
				if self.session.pipshown:
					from Screens.InfoBar import InfoBar
					InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen
		self.tuner = Tuner(self.frontend)

		if slot.isMultiType():
			eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, "dummy", False) #to force a clear of m_delsys_whitelist
			types = slot.getMultiTypeList()
			for FeType in types.itervalues():
				if FeType in ("DVB-S", "DVB-S2", "DVB-S2X") and config.Nims[slot.slot].dvbs.configMode.value == "nothing":
					continue
				elif FeType in ("DVB-T", "DVB-T2") and config.Nims[slot.slot].dvbt.configMode.value == "nothing":
					continue
				elif FeType in ("DVB-C", "DVB-C2") and config.Nims[slot.slot].dvbc.configMode.value == "nothing":
					continue
				elif FeType in ("ATSC") and config.Nims[slot.slot].atsc.configMode.value == "nothing":
					continue
				eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, FeType, True)
		else:
			eDVBResourceManager.getInstance().setFrontendType(slot.frontend_id, slot.getType())


#			if not path.exists("/proc/stb/frontend/%d/mode" % fe_id) and iDVBFrontend.dvb_api_version >= 5:
		print "api >=5 and new style tuner driver"
		if self.frontend:
			if system == 'DVB-C':
				ret = self.frontend.changeType(iDVBFrontend.feCable)
			elif system in ('DVB-T','DVB-T2'):
				ret = self.frontend.changeType(iDVBFrontend.feTerrestrial)
			elif system in ('DVB-S','DVB-S2'):
				ret = self.frontend.changeType(iDVBFrontend.feSatellite)
			elif system == 'ATSC':
				ret = self.frontend.changeType(iDVBFrontend.feATSC)
			else:
				ret = False
			if not ret:
				print "%d: tunerTypeChange to '%s' failed" %(fe_id, system)
			else:
				print "new system ",system
		else:
			print "%d: tunerTypeChange to '%s' failed (BUSY)" %(fe_id, multiType.getText())
		self.retune()

	def createConfig(self):
		ScanSetup.createConfig(self)
		for x in (
			self.scan_sat.frequency,
			self.scan_satselection[int(self.scan_nims.value)],
			self.scan_sat.symbolrate,
			self.scan_sat.is_id,
			self.scan_sat.pls_mode,
			self.scan_sat.pls_code,

			self.scan_ter.channel,
			self.scan_ter.frequency,
			self.scan_ter.inversion,
			self.scan_ter.bandwidth, self.scan_ter.fechigh, self.scan_ter.feclow,
			self.scan_ter.modulation, self.scan_ter.transmission,
			self.scan_ter.guard, self.scan_ter.hierarchy,
			self.scan_ter.plp_id,
			self.scan_cab.frequency, self.scan_cab.inversion, self.scan_cab.symbolrate,
			self.scan_cab.modulation, self.scan_cab.fec,
			self.scan_ats.frequency, self.scan_ats.modulation, self.scan_ats.inversion,
			self.scan_ats.system,

			):
			if x is not None:
				x.clearNotifiers()
				x.addNotifier(self.TriggeredByConfigElement, initial_call = False)

	def TriggeredByConfigElement(self, configElement):
		self.retune()

	def retune(self):
		nim = nimmanager.nim_slots[int(self.scan_nims.value)]
		if nim.isCompatible("DVB-S") and nim.config.dvbs.configMode.value != "nothing":
			return self.retuneSat()
		if nim.isCompatible("DVB-T") and nim.config.dvbt.configMode.value != "nothing":
			return self.retuneTerr()
		if nim.isCompatible("DVB-C") and nim.config.dvbc.configMode.value != "nothing":
			return self.retuneCab()
		if nim.isCompatible("ATSC") and nim.config.atsc.configMode.value != "nothing":
			return self.retuneATSC()
		self.frontend = None
		self.raw_channel = None
		print "error: tuner not enabled/supported", nim.getType()

	def retuneCab(self):
		if self.initcomplete:
			if self.scan_typecable.value == "single_transponder":
				transponder = (
					self.scan_cab.frequency.value*1000,
					self.scan_cab.symbolrate.value*1000,
					self.scan_cab.modulation.value,
					self.scan_cab.fec.value,
					self.scan_cab.inversion.value
				)
				self.tuner.tuneCab(transponder)
				self.transponder = transponder
			elif self.scan_typecable.value == "predefined_transponder":
				if self.CableTransponders is not None:
					tps = nimmanager.getTranspondersCable(int(self.scan_nims.value))
					if len(tps) > self.CableTransponders.index :
						tp = tps[self.CableTransponders.index]
						# tp = 0 transponder type, 1 freq, 2 sym, 3 mod, 4 fec, 5 inv, 6 sys
						transponder = (tp[1], tp[2], tp[3], tp[4], tp[5])
						self.tuner.tuneCab(transponder)
						self.transponder = transponder

	def retuneTerr(self):
		if self.initcomplete:
			if self.scan_input_as.value == "channel":
				frequency = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)
			else:
				frequency = self.scan_ter.frequency.value * 1000
			if self.scan_typeterrestrial.value == "single_transponder":
				transponder = [
					2, #TERRESTRIAL
					frequency,
					self.scan_ter.bandwidth.value,
					self.scan_ter.modulation.value,
					self.scan_ter.fechigh.value,
					self.scan_ter.feclow.value,
					self.scan_ter.guard.value,
					self.scan_ter.transmission.value,
					self.scan_ter.hierarchy.value,
					self.scan_ter.inversion.value,
					self.scan_ter.system.value,
					self.scan_ter.plp_id.value]
				self.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])
				self.transponder = transponder
			elif self.scan_typeterrestrial.value == "predefined_transponder":
				if self.TerrestrialTransponders is not None:
					region = nimmanager.getTerrestrialDescription(int(self.scan_nims.value))
					tps = nimmanager.getTranspondersTerrestrial(region)
					if len(tps) > self.TerrestrialTransponders.index :
						transponder = tps[self.TerrestrialTransponders.index]
						# frequency 1, inversion 9, bandwidth 2, fechigh 4, feclow 5, modulation 3, transmission 7, guard 6, hierarchy 8, system 10, plp_id 11
						self.tuner.tuneTerr(transponder[1], transponder[9], transponder[2], transponder[4], transponder[5], transponder[3], transponder[7], transponder[6], transponder[8], transponder[10], transponder[11])
						self.transponder = transponder

	def retuneSat(self):
		fe_id = int(self.scan_nims.value)
		nimsats = self.satList[fe_id]
		selsatidx = self.scan_satselection[fe_id].index
		if len(nimsats):
			orbpos = nimsats[selsatidx][0]
			if self.initcomplete:
				if self.scan_type.value == "single_transponder":
					if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
						fec = self.scan_sat.fec_s2.value
					else:
						fec = self.scan_sat.fec.value
					transponder = (
						self.scan_sat.frequency.value,
						self.scan_sat.symbolrate.value,
						self.scan_sat.polarization.value,
						fec,
						self.scan_sat.inversion.value,
						orbpos,
						self.scan_sat.system.value,
						self.scan_sat.modulation.value,
						self.scan_sat.rolloff.value,
						self.scan_sat.pilot.value,
						self.scan_sat.is_id.value,
						self.scan_sat.pls_mode.value,
						self.scan_sat.pls_code.value)
					self.tuner.tune(transponder)
					self.transponder = transponder
				elif self.scan_type.value == "predefined_transponder":
					tps = nimmanager.getTransponders(orbpos)
					if len(tps) > self.preDefTransponders.index:
						tp = tps[self.preDefTransponders.index]
						transponder = (tp[1] / 1000, tp[2] / 1000,
							tp[3], tp[4], 2, orbpos, tp[5], tp[6], tp[8], tp[9], tp[10], tp[11], tp[12])
						self.tuner.tune(transponder)
						self.transponder = transponder

	def retuneATSC(self):
		if self.initcomplete:
			if self.scan_typeatsc.value == "single_transponder":
				transponder = (
					self.scan_ats.frequency.value*1000,
					self.scan_ats.modulation.value,
					self.scan_ats.inversion.value,
					self.scan_ats.system.value,
				)
				if self.initcomplete:
					self.tuner.tuneATSC(transponder)
				self.transponder = transponder
			elif self.scan_typeatsc.value == "predefined_transponder":
				tps = nimmanager.getTranspondersATSC(int(self.scan_nims.value))
				if tps and len(tps) > self.ATSCTransponders.index:
					tp = tps[self.ATSCTransponders.index]
					transponder = (tp[1], tp[2], tp[3], tp[4])
					if self.initcomplete:
						self.tuner.tuneATSC(transponder)
					self.transponder = transponder

	def keyGoScan(self):
		if self.transponder is None:
			print "error: no transponder data"
			return
		fe_id = int(self.scan_nims.value)
		nim = nimmanager.nim_slots[fe_id]
		self.frontend = None
		if self.raw_channel:
			self.raw_channel = None
		tlist = []
		if nim.isCompatible("DVB-S"):
			nimsats = self.satList[fe_id]
			selsatidx = self.scan_satselection[fe_id].index
			if len(nimsats):
				orbpos = nimsats[selsatidx][0]
				self.addSatTransponder(tlist,
					self.transponder[0], # frequency
					self.transponder[1], # sr
					self.transponder[2], # pol
					self.transponder[3], # fec
					self.transponder[4], # inversion
					orbpos,
					self.transponder[6], # system
					self.transponder[7], # modulation
					self.transponder[8], # rolloff
					self.transponder[9], # pilot
					self.transponder[10],# input stream id
					self.transponder[11],# pls mode
					self.transponder[12] # pls code
				)
		elif nim.isCompatible("DVB-T"):
			parm = buildTerTransponder(
				self.transponder[1],  # frequency
				self.transponder[9],  # inversion
				self.transponder[2],  # bandwidth
				self.transponder[4],  # fechigh
				self.transponder[5],  # feclow
				self.transponder[3],  # modulation
				self.transponder[7],  # transmission
				self.transponder[6],  # guard
				self.transponder[8],  # hierarchy
				self.transponder[10], # system
				self.transponder[11]  # plp_id
			)
			tlist.append(parm)
		elif nim.isCompatible("DVB-C"):
			self.addCabTransponder(tlist,
				self.transponder[0], # frequency
				self.transponder[1], # sr
				self.transponder[2], # modulation
				self.transponder[3], # fec_inner
				self.transponder[4]  # inversion
			)
		elif nim.isCompatible("ATSC"):
			self.addATSCTransponder(tlist,
				self.transponder[0], # frequency
				self.transponder[1], # modulation
				self.transponder[2], # inversion
				self.transponder[3]  # system
			)
		else:
			print "error: tuner not enabled/supported", nim.getType()
		self.startScan(tlist, fe_id)

	def startScan(self, tlist, feid):
		flags = 0
		networkid = 0
		self.session.openWithCallback(self.startScanCallback, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])

	def startScanCallback(self, answer=None):
		if answer:
			self.doCloseRecursive()

	def keyCancel(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			self.raw_channel = None
		self.close(False)

	def doCloseRecursive(self):
		if self.session.postScanService and self.frontend:
			self.frontend = None
			self.raw_channel = None
		self.close(True)