Пример #1
0
    def doTune(self):
        from Screens.Standby import inStandby
        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            transponder = self.providers[self.currentAction]["transponder"]
        else:
            bouquet_key = None
            providers_tmp = config.autobouquetsmaker.providers.value.split("|")
            for provider_tmp in providers_tmp:
                provider_config = ProviderConfig(provider_tmp)
                provider_key = provider_config.getProvider()
                if self.currentAction != provider_key:
                    continue
                bouquet_key = provider_config.getArea()

            if not bouquet_key:
                print >> log, "[AutoBouquetsMaker] No area found"
                self.showError(_('No area found'))
                return

            transponder = self.providers[
                self.currentAction]["bouquets"][bouquet_key]

        nimList = []
        for nim in nimmanager.nim_slots:
            if (nim.config_mode not in
                ("loopthrough", "satposdepends", "nothing")) and (
                    (self.providers[self.currentAction]["streamtype"] == "dvbs"
                     and nim.isCompatible("DVB-S")) or
                    (self.providers[self.currentAction]["streamtype"] == "dvbc"
                     and nim.isCompatible("DVB-C")) or
                    (self.providers[self.currentAction]["streamtype"] == "dvbt"
                     and nim.isCompatible("DVB-T"))):
                nimList.append(nim.slot)
        if len(nimList) == 0:
            print >> log, "[AutoBouquetsMaker] No NIMs found"
            self.showError(_('No NIMs found'))
            return

        resmanager = eDVBResourceManager.getInstance()
        if not resmanager:
            print >> log, "[AutoBouquetsMaker] Cannot retrieve Resource Manager instance"
            self.showError(_('Cannot retrieve Resource Manager instance'))
            return

        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            print >> log, "[AutoBouquetsMaker] Search NIM for orbital position %d" % transponder[
                "orbital_position"]
        else:
            print >> log, "[AutoBouquetsMaker] Search NIM"

        # stop pip if running
        if self.session.pipshown:
            self.session.pipshown = False
            del self.session.pip
            print >> log, "[AutoBouquetsMaker] Stopping PIP."

        # stop currently playing service if it is using a tuner in ("loopthrough", "satposdepends")
        currentlyPlayingNIM = None
        currentService = self.session and self.session.nav.getCurrentService()
        frontendInfo = currentService and currentService.frontendInfo()
        frontendData = frontendInfo and frontendInfo.getAll(True)
        if frontendData is not None:
            currentlyPlayingNIM = frontendData.get("tuner_number", None)
            if self.providers[self.currentAction][
                    "streamtype"] == "dvbs" and currentlyPlayingNIM is not None:
                nimConfigMode = nimmanager.nim_slots[
                    currentlyPlayingNIM].config_mode
                if nimConfigMode in ("loopthrough", "satposdepends"):
                    self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference(
                    )
                    self.session.nav.stopService()
                    currentlyPlayingNIM = None
                    print >> log, "[AutoBouquetsMaker] The active service was using a %s tuner, so had to be stopped (slot id %s)." % (
                        nimConfigMode, currentlyPlayingNIM)
        del frontendInfo
        del currentService

        current_slotid = -1
        if self.rawchannel:
            del (self.rawchannel)

        self.frontend = None
        self.rawchannel = None

        nimList.reverse()  # start from the last
        for slotid in nimList:
            if self.providers[self.currentAction]["streamtype"] == "dvbs":
                sats = nimmanager.getSatListForNim(slotid)
                for sat in sats:
                    if sat[0] == transponder["orbital_position"]:
                        if current_slotid == -1:  # mark the first valid slotid in case of no other one is free
                            current_slotid = slotid

                        self.rawchannel = resmanager.allocateRawChannel(slotid)
                        if self.rawchannel:
                            print >> log, "[AutoBouquetsMaker] Nim found on slot id %d with sat %s" % (
                                slotid, sat[1])
                            current_slotid = slotid
                            break
            else:
                if current_slotid == -1:  # mark the first valid slotid in case of no other one is free
                    current_slotid = slotid
                self.rawchannel = resmanager.allocateRawChannel(slotid)
                if self.rawchannel:
                    print >> log, "[AutoBouquetsMaker] Nim found on slot id %d" % (
                        slotid)
                    current_slotid = slotid
                    break

            if self.rawchannel:
                break

        if current_slotid == -1:
            print >> log, "[AutoBouquetsMaker] No valid NIM found"
            self.showError(_('No valid NIM found'))
            return

        if not self.rawchannel:
            # if we are here the only possible option is to close the active service
            if currentlyPlayingNIM in nimList:
                slotid = currentlyPlayingNIM
                if self.providers[self.currentAction]["streamtype"] == "dvbs":
                    sats = nimmanager.getSatListForNim(currentlyPlayingNIM)
                    for sat in sats:
                        if sat[0] == transponder["orbital_position"]:
                            print >> log, "[AutoBouquetsMaker] Nim found on slot id %d but it's busy. Stopping active service" % currentlyPlayingNIM
                            self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference(
                            )
                            self.session.nav.stopService()
                            self.rawchannel = resmanager.allocateRawChannel(
                                slotid)
                            break
                else:
                    print >> log, "[AutoBouquetsMaker] Nim found on slot id %d but it's busy. Stopping active service" % currentlyPlayingNIM
                    self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference(
                    )
                    self.session.nav.stopService()
                    self.rawchannel = resmanager.allocateRawChannel(slotid)

            if not self.rawchannel:
                if self.session.nav.RecordTimer.isRecording():
                    print >> log, "[AutoBouquetsMaker] Cannot free NIM because a record is in progress"
                    self.showError(
                        _('Cannot free NIM because a recording is in progress')
                    )
                    return
                else:
                    print >> log, "[AutoBouquetsMaker] Cannot get the NIM"
                    self.showError(_('Cannot get the NIM'))
                    return

        # set extended timeout for rotors
        if self.providers[self.currentAction][
                "streamtype"] == "dvbs" and self.isRotorSat(
                    slotid, transponder["orbital_position"]):
            self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_ROTOR
            print >> log, "[AutoBouquetsMaker] Motorised dish. Will wait up to %i seconds for tuner lock." % (
                self.LOCK_TIMEOUT / 10)
        else:
            self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_FIXED
            print >> log, "[AutoBouquetsMaker] Fixed dish. Will wait up to %i seconds for tuner lock." % (
                self.LOCK_TIMEOUT / 10)

        self.frontend = self.rawchannel.getFrontend()
        if not self.frontend:
            print >> log, "[AutoBouquetsMaker] Cannot get frontend"
            self.showError(_('Cannot get frontend'))
            return

        demuxer_id = self.rawchannel.reserveDemux()
        if demuxer_id < 0:
            print >> log, "[AutoBouquetsMaker] Cannot allocate the demuxer"
            self.showError(_('Cannot allocate the demuxer'))
            return

        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            params = eDVBFrontendParametersSatellite()
            params.frequency = transponder["frequency"]
            params.symbol_rate = transponder["symbol_rate"]
            params.polarisation = transponder["polarization"]
            params.fec = transponder["fec_inner"]
            params.inversion = transponder["inversion"]
            params.orbital_position = transponder["orbital_position"]
            params.system = transponder["system"]
            params.modulation = transponder["modulation"]
            params.rolloff = transponder["roll_off"]
            params.pilot = transponder["pilot"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBS(params, False)

        elif self.providers[self.currentAction]["streamtype"] == "dvbt":
            params = eDVBFrontendParametersTerrestrial()
            params.frequency = transponder["frequency"]
            params.bandwidth = transponder["bandwidth"]
            params.code_rate_hp = transponder["code_rate_hp"]
            params.code_rate_lp = transponder["code_rate_lp"]
            params.inversion = transponder["inversion"]
            params.system = transponder["system"]
            params.modulation = transponder["modulation"]
            params.transmission_mode = transponder["transmission_mode"]
            params.guard_interval = transponder["guard_interval"]
            params.hierarchy = transponder["hierarchy"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBT(params)

        elif self.providers[self.currentAction]["streamtype"] == "dvbc":
            params = eDVBFrontendParametersCable()
            params.frequency = transponder["frequency"]
            params.symbol_rate = transponder["symbol_rate"]
            params.fec_inner = transponder["fec_inner"]
            params.inversion = transponder["inversion"]
            params.modulation = transponder["modulation"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBC(params)

        self.rawchannel.requestTsidOnid()
        self.frontend.tune(params_fe)
        self.manager.setAdapter(0)  # FIX: use the correct device
        self.manager.setDemuxer(demuxer_id)
        self.manager.setFrontend(current_slotid)

        self.lockcounter = 0
        self.locktimer = eTimer()
        self.locktimer.callback.append(self.checkTunerLock)
        self.locktimer.start(100, 1)
Пример #2
0
    def favourites(self, path, services, providers, providerConfigs,
                   bouquetsOrder):
        custom_dir = os.path.dirname(__file__) + "/../custom"
        provider_key = "favourites"
        customised = {"video": {}, "radio": {}}
        name = ""
        prefix = ""
        sections = {}
        bouquets = {"main": 1, "sections": 1}
        area_key = ""
        bouquets_to_hide = []
        bouquetsToHide = []
        swaprules = []
        placement = 0
        hacks = ""

        # Read favourites file
        dom = self.parseXML(custom_dir + "/favourites.xml")
        if dom is None:
            print >> log, "[ABM-Tools][favourites] No favorite.xml file"
        elif dom.documentElement.nodeType == dom.documentElement.ELEMENT_NODE and dom.documentElement.tagName == "favourites":
            print >> log, "[ABM-Tools][favourites] Reading favorite.xml file"
            for node in dom.documentElement.childNodes:
                if node.nodeType != node.ELEMENT_NODE:
                    continue

                if node.tagName == "name":
                    node.normalize()
                    if len(
                            node.childNodes
                    ) == 1 and node.childNodes[0].nodeType == node.TEXT_NODE:
                        name = node.childNodes[0].data.encode("utf-8")

                elif node.tagName == "sections":
                    sections = {}
                    for node2 in node.childNodes:
                        if node2.nodeType == node2.ELEMENT_NODE and node2.tagName == "section":
                            number = -1
                            for i in range(0, node2.attributes.length):
                                if node2.attributes.item(i).name == "number":
                                    number = int(
                                        node2.attributes.item(i).value)
                                if number == -1:
                                    continue

                                node2.normalize()
                                if len(node2.childNodes
                                       ) == 1 and node2.childNodes[
                                           0].nodeType == node2.TEXT_NODE:
                                    sections[number] = node2.childNodes[
                                        0].data.encode("utf-8")

                elif node.tagName == "inserts":
                    for node2 in node.childNodes:
                        if node2.nodeType == node2.ELEMENT_NODE and node2.tagName == "insert":
                            provider = ''
                            source = ''
                            target = ''
                            for i in range(0, node2.attributes.length):
                                if node2.attributes.item(i).name == "provider":
                                    provider = node2.attributes.item(
                                        i).value.encode("utf-8")
                                elif node2.attributes.item(i).name == "source":
                                    source = int(
                                        node2.attributes.item(i).value)
                                elif node2.attributes.item(i).name == "target":
                                    target = int(
                                        node2.attributes.item(i).value)
                            if provider and source and target and provider in services and source in services[
                                    provider]["video"]:
                                customised["video"][target] = services[
                                    provider]["video"][source]

                elif node.tagName == "bouquets":
                    for node2 in node.childNodes:
                        if node2.nodeType == node2.ELEMENT_NODE and node2.tagName == "main":
                            node2.normalize()
                            if len(node2.childNodes) == 1 and node2.childNodes[
                                    0].nodeType == node2.TEXT_NODE and node2.childNodes[
                                        0].data.encode("utf-8") != "1":
                                bouquets["main"] = 0
                        elif node2.nodeType == node2.ELEMENT_NODE and node2.tagName == "sections":
                            node2.normalize()
                            if len(node2.childNodes) == 1 and node2.childNodes[
                                    0].nodeType == node2.TEXT_NODE and node2.childNodes[
                                        0].data.encode("utf-8") != "1":
                                bouquets["sections"] = 0

                elif node.tagName == "placement":
                    node.normalize()
                    if len(
                            node.childNodes
                    ) == 1 and node.childNodes[0].nodeType == node.TEXT_NODE:
                        placement = min(
                            int(node.childNodes[0].data) - 1,
                            len(bouquetsOrder))
                        if placement < 0:
                            placement = 0

                elif node.tagName == "hacks":
                    node.normalize()
                    for i in range(0, len(node.childNodes)):
                        if node.childNodes[
                                i].nodeType == node.CDATA_SECTION_NODE:
                            hacks = node.childNodes[i].data.encode(
                                "utf-8").strip()

            if len(hacks) > 0:
                exec(hacks)

            if len(customised["video"]) > 0:
                providers[provider_key] = {}
                providers[provider_key]["name"] = name
                providers[provider_key]["bouquets"] = area_key
                providers[provider_key]["protocol"] = 'nolcn'
                providers[provider_key]["swapchannels"] = []
                providers[provider_key]["sections"] = sections
                if config.autobouquetsmaker.addprefix.value:
                    prefix = name
                services[provider_key] = customised
                bouquetsOrder.insert(placement, provider_key)

                from providerconfig import ProviderConfig
                providerConfigs[provider_key] = ProviderConfig("%s::0:" %
                                                               provider_key)
                if bouquets["main"] == 1:
                    providerConfigs[provider_key].setMakeNormalMain()
                if bouquets["sections"] == 1:
                    providerConfigs[provider_key].setMakeSections()
                from bouquetswriter import BouquetsWriter
                BouquetsWriter().buildBouquets(path,
                                               providerConfigs[provider_key],
                                               services[provider_key],
                                               sections, provider_key,
                                               swaprules, bouquets_to_hide,
                                               prefix)
            else:
                print >> log, "[ABM-Tools][favourites] Favourites list is zero length."
Пример #3
0
    def go(self):
        from Screens.Standby import inStandby
        self.manager = Manager()
        self.manager.setPath("/etc/enigma2")
        self.manager.setAddPrefix(config.autobouquetsmaker.addprefix.value)

        self.selectedProviders = {}
        self.actionsList = []

        providers_tmp = config.autobouquetsmaker.providers.value.split("|")

        for provider_tmp in providers_tmp:
            provider_config = ProviderConfig(provider_tmp)
            if provider_config.isValid() and Providers().providerFileExists(
                    provider_config.getProvider()):
                self.actionsList.append(provider_config.getProvider())
                self.selectedProviders[
                    provider_config.getProvider()] = provider_config

        if config.autobouquetsmaker.keepallbouquets.getValue():
            bouquets = Manager().getBouquetsList()
            bouquets_tv = []
            bouquets_radio = []
            for bouquet in bouquets["tv"]:
                if bouquet["filename"][:12] == "autobouquet." or bouquet[
                        "filename"][:len(self.ABM_BOUQUET_PREFIX
                                         )] == self.ABM_BOUQUET_PREFIX:
                    continue
                if len(bouquet["filename"]) > 0:
                    bouquets_tv.append(bouquet["filename"])
            for bouquet in bouquets["radio"]:
                if bouquet["filename"][:12] == "autobouquet." or bouquet[
                        "filename"][:len(self.ABM_BOUQUET_PREFIX
                                         )] == self.ABM_BOUQUET_PREFIX:
                    continue
                if len(bouquet["filename"]) > 0:
                    bouquets_radio.append(bouquet["filename"])
            self.manager.setBouquetsToKeep(bouquets_tv, bouquets_radio)
        else:
            bouquets = config.autobouquetsmaker.keepbouquets.value.split("|")
            bouquets_tv = []
            bouquets_radio = []
            for bouquet in bouquets:
                if bouquet.endswith(".tv"):
                    bouquets_tv.append(bouquet)
                elif bouquet.endswith(".radio"):
                    bouquets_radio.append(bouquet)
            self.manager.setBouquetsToKeep(bouquets_tv, bouquets_radio)

        bouquetsToHide = {}
        bouquets = config.autobouquetsmaker.hidesections.value.split("|")
        for bouquet in bouquets:
            tmp = bouquet.split(":")
            if len(tmp) != 2:
                continue

            if tmp[0].strip() not in bouquetsToHide:
                bouquetsToHide[tmp[0].strip()] = []

            bouquetsToHide[tmp[0].strip()].append(int(tmp[1].strip()))
        self.manager.setBouquetsToHide(bouquetsToHide)

        self.manager.load()

        self.progresscount = (len(self.actionsList) * 2) + 3
        self.progresscurrent = 1

        if not inStandby:
            self["progress"].setRange((0, self.progresscount))
            self["progress"].setValue(self.progresscurrent)

        self.timer = eTimer()
        self.timer.callback.append(self.doActions)
        self.timer.start(100, 1)
Пример #4
0
    def go(self):
        from Screens.Standby import inStandby

        self.manager = Manager()
        self.manager.setPath("/etc/enigma2")
        self.manager.setAddPrefix(config.autobouquetsmaker.addprefix.value)

        self.selectedProviders = {}
        self.actionsList = []

        providers_tmp = config.autobouquetsmaker.providers.value.split("|")

        for provider_tmp in providers_tmp:
            provider_config = ProviderConfig(provider_tmp)
            if provider_config.isValid() and Providers().providerFileExists(provider_config.getProvider()):
                self.actionsList.append(provider_config.getProvider())
                self.selectedProviders[provider_config.getProvider()] = provider_config

        if config.autobouquetsmaker.keepallbouquets.getValue():
            bouquets = Manager().getBouquetsList()
            bouquets_tv = []
            bouquets_radio = []
            for bouquet in bouquets["tv"]:
                if (
                    bouquet["filename"][:12] == "autobouquet."
                    or bouquet["filename"][: len(self.ABM_BOUQUET_PREFIX)] == self.ABM_BOUQUET_PREFIX
                ):
                    continue
                if len(bouquet["filename"]) > 0:
                    bouquets_tv.append(bouquet["filename"])
            for bouquet in bouquets["radio"]:
                if (
                    bouquet["filename"][:12] == "autobouquet."
                    or bouquet["filename"][: len(self.ABM_BOUQUET_PREFIX)] == self.ABM_BOUQUET_PREFIX
                ):
                    continue
                if len(bouquet["filename"]) > 0:
                    bouquets_radio.append(bouquet["filename"])
            self.manager.setBouquetsToKeep(bouquets_tv, bouquets_radio)
        else:
            bouquets = config.autobouquetsmaker.keepbouquets.value.split("|")
            bouquets_tv = []
            bouquets_radio = []
            for bouquet in bouquets:
                if bouquet.endswith(".tv"):
                    bouquets_tv.append(bouquet)
                elif bouquet.endswith(".radio"):
                    bouquets_radio.append(bouquet)
            self.manager.setBouquetsToKeep(bouquets_tv, bouquets_radio)

        bouquetsToHide = {}
        bouquets = config.autobouquetsmaker.hidesections.value.split("|")
        for bouquet in bouquets:
            tmp = bouquet.split(":")
            if len(tmp) != 2:
                continue

            if tmp[0].strip() not in bouquetsToHide:
                bouquetsToHide[tmp[0].strip()] = []

            bouquetsToHide[tmp[0].strip()].append(int(tmp[1].strip()))
        self.manager.setBouquetsToHide(bouquetsToHide)

        self.manager.load()

        self.progresscount = (len(self.actionsList) * 2) + 3
        self.progresscurrent = 1

        if not inStandby:
            self["progress"].setRange((0, self.progresscount))
            self["progress"].setValue(self.progresscurrent)

        self.timer = eTimer()
        self.timer.callback.append(self.doActions)
        self.timer.start(100, 1)
Пример #5
0
    def doTune(self):
        from Screens.Standby import inStandby

        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            transponder = self.providers[self.currentAction]["transponder"]
        else:
            bouquet_key = None
            providers_tmp = config.autobouquetsmaker.providers.value.split("|")
            for provider_tmp in providers_tmp:
                provider_config = ProviderConfig(provider_tmp)
                provider_key = provider_config.getProvider()
                if self.currentAction != provider_key:
                    continue
                bouquet_key = provider_config.getArea()

            if not bouquet_key:
                print >> log, "[AutoBouquetsMaker] No area found"
                self.showError(_("No area found"))
                return

            transponder = self.providers[self.currentAction]["bouquets"][bouquet_key]

        nimList = []
        for nim in nimmanager.nim_slots:
            if (nim.config_mode not in ("loopthrough", "satposdepends", "nothing")) and (
                (self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.isCompatible("DVB-S"))
                or (self.providers[self.currentAction]["streamtype"] == "dvbc" and nim.isCompatible("DVB-C"))
                or (self.providers[self.currentAction]["streamtype"] == "dvbt" and nim.isCompatible("DVB-T"))
            ):
                nimList.append(nim.slot)
        if len(nimList) == 0:
            print >> log, "[AutoBouquetsMaker] No NIMs found"
            self.showError(_("No NIMs found"))
            return

        resmanager = eDVBResourceManager.getInstance()
        if not resmanager:
            print >> log, "[AutoBouquetsMaker] Cannot retrieve Resource Manager instance"
            self.showError(_("Cannot retrieve Resource Manager instance"))
            return

        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            print >> log, "[AutoBouquetsMaker] Search NIM for orbital position %d" % transponder["orbital_position"]
        else:
            print >> log, "[AutoBouquetsMaker] Search NIM"

            # stop pip if running
        if self.session.pipshown:
            self.session.pipshown = False
            del self.session.pip
            print >> log, "[AutoBouquetsMaker] Stopping PIP."

            # stop currently playing service if it is using a tuner in ("loopthrough", "satposdepends")
        currentlyPlayingNIM = None
        currentService = self.session and self.session.nav.getCurrentService()
        frontendInfo = currentService and currentService.frontendInfo()
        frontendData = frontendInfo and frontendInfo.getAll(True)
        if frontendData is not None:
            currentlyPlayingNIM = frontendData.get("tuner_number", None)
            if self.providers[self.currentAction]["streamtype"] == "dvbs" and currentlyPlayingNIM is not None:
                nimConfigMode = nimmanager.nim_slots[currentlyPlayingNIM].config_mode
                if nimConfigMode in ("loopthrough", "satposdepends"):
                    self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference()
                    self.session.nav.stopService()
                    currentlyPlayingNIM = None
                    print >> log, "[AutoBouquetsMaker] The active service was using a %s tuner, so had to be stopped (slot id %s)." % (
                        nimConfigMode,
                        currentlyPlayingNIM,
                    )
        del frontendInfo
        del currentService

        current_slotid = -1
        if self.rawchannel:
            del (self.rawchannel)

        self.frontend = None
        self.rawchannel = None

        nimList.reverse()  # start from the last
        for slotid in nimList:
            if self.providers[self.currentAction]["streamtype"] == "dvbs":
                sats = nimmanager.getSatListForNim(slotid)
                for sat in sats:
                    if sat[0] == transponder["orbital_position"]:
                        if current_slotid == -1:  # mark the first valid slotid in case of no other one is free
                            current_slotid = slotid

                        self.rawchannel = resmanager.allocateRawChannel(slotid)
                        if self.rawchannel:
                            print >> log, "[AutoBouquetsMaker] Nim found on slot id %d with sat %s" % (slotid, sat[1])
                            current_slotid = slotid
                            break
            else:
                if current_slotid == -1:  # mark the first valid slotid in case of no other one is free
                    current_slotid = slotid
                self.rawchannel = resmanager.allocateRawChannel(slotid)
                if self.rawchannel:
                    print >> log, "[AutoBouquetsMaker] Nim found on slot id %d" % (slotid)
                    current_slotid = slotid
                    break

            if self.rawchannel:
                break

        if current_slotid == -1:
            print >> log, "[AutoBouquetsMaker] No valid NIM found"
            self.showError(_("No valid NIM found"))
            return

        if not self.rawchannel:
            # if we are here the only possible option is to close the active service
            if currentlyPlayingNIM in nimList:
                slotid = currentlyPlayingNIM
                if self.providers[self.currentAction]["streamtype"] == "dvbs":
                    sats = nimmanager.getSatListForNim(currentlyPlayingNIM)
                    for sat in sats:
                        if sat[0] == transponder["orbital_position"]:
                            print >> log, "[AutoBouquetsMaker] Nim found on slot id %d but it's busy. Stopping active service" % currentlyPlayingNIM
                            self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference()
                            self.session.nav.stopService()
                            self.rawchannel = resmanager.allocateRawChannel(slotid)
                            break
                else:
                    print >> log, "[AutoBouquetsMaker] Nim found on slot id %d but it's busy. Stopping active service" % currentlyPlayingNIM
                    self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference()
                    self.session.nav.stopService()
                    self.rawchannel = resmanager.allocateRawChannel(slotid)

            if not self.rawchannel:
                if self.session.nav.RecordTimer.isRecording():
                    print >> log, "[AutoBouquetsMaker] Cannot free NIM because a record is in progress"
                    self.showError(_("Cannot free NIM because a recording is in progress"))
                    return
                else:
                    print >> log, "[AutoBouquetsMaker] Cannot get the NIM"
                    self.showError(_("Cannot get the NIM"))
                    return

                    # set extended timeout for rotors
        if self.providers[self.currentAction]["streamtype"] == "dvbs" and self.isRotorSat(
            slotid, transponder["orbital_position"]
        ):
            self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_ROTOR
            print >> log, "[AutoBouquetsMaker] Motorised dish. Will wait up to %i seconds for tuner lock." % (
                self.LOCK_TIMEOUT / 10
            )
        else:
            self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_FIXED
            print >> log, "[AutoBouquetsMaker] Fixed dish. Will wait up to %i seconds for tuner lock." % (
                self.LOCK_TIMEOUT / 10
            )

        self.frontend = self.rawchannel.getFrontend()
        if not self.frontend:
            print >> log, "[AutoBouquetsMaker] Cannot get frontend"
            self.showError(_("Cannot get frontend"))
            return

        demuxer_id = self.rawchannel.reserveDemux()
        if demuxer_id < 0:
            print >> log, "[AutoBouquetsMaker] Cannot allocate the demuxer"
            self.showError(_("Cannot allocate the demuxer"))
            return

        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            params = eDVBFrontendParametersSatellite()
            params.frequency = transponder["frequency"]
            params.symbol_rate = transponder["symbol_rate"]
            params.polarisation = transponder["polarization"]
            params.fec = transponder["fec_inner"]
            params.inversion = transponder["inversion"]
            params.orbital_position = transponder["orbital_position"]
            params.system = transponder["system"]
            params.modulation = transponder["modulation"]
            params.rolloff = transponder["roll_off"]
            params.pilot = transponder["pilot"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBS(params, False)

        elif self.providers[self.currentAction]["streamtype"] == "dvbt":
            params = eDVBFrontendParametersTerrestrial()
            params.frequency = transponder["frequency"]
            params.bandwidth = transponder["bandwidth"]
            params.code_rate_hp = transponder["code_rate_hp"]
            params.code_rate_lp = transponder["code_rate_lp"]
            params.inversion = transponder["inversion"]
            params.system = transponder["system"]
            params.modulation = transponder["modulation"]
            params.transmission_mode = transponder["transmission_mode"]
            params.guard_interval = transponder["guard_interval"]
            params.hierarchy = transponder["hierarchy"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBT(params)

        elif self.providers[self.currentAction]["streamtype"] == "dvbc":
            params = eDVBFrontendParametersCable()
            params.frequency = transponder["frequency"]
            params.symbol_rate = transponder["symbol_rate"]
            params.fec_inner = transponder["fec_inner"]
            params.inversion = transponder["inversion"]
            params.modulation = transponder["modulation"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBC(params)

        self.rawchannel.requestTsidOnid()
        self.frontend.tune(params_fe)
        self.manager.setAdapter(0)  # FIX: use the correct device
        self.manager.setDemuxer(demuxer_id)
        self.manager.setFrontend(current_slotid)

        self.lockcounter = 0
        self.locktimer = eTimer()
        self.locktimer.callback.append(self.checkTunerLock)
        self.locktimer.start(100, 1)
Пример #6
0
	def doTune(self):
		from Screens.Standby import inStandby
		if self.providers[self.currentAction]["streamtype"] == "dvbs":
			transponder = self.providers[self.currentAction]["transponder"]
		else:
			bouquet_key = None
			providers_tmp = config.autobouquetsmaker.providers.value.split("|")
			for provider_tmp in providers_tmp:
				provider_config = ProviderConfig(provider_tmp)
				provider_key = provider_config.getProvider()
				if self.currentAction != provider_key:
					continue
				bouquet_key = provider_config.getArea()

			if not bouquet_key:
				print>>log, "[AutoBouquetsMaker] No area found"
				self.showError(_('No area found'))
				return
			
			transponder = self.providers[self.currentAction]["bouquets"][bouquet_key]

		nimList = []
		for nim in nimmanager.nim_slots:
			if (self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.isCompatible("DVB-S") and nim.config_mode not in ("loopthrough")) or (self.providers[self.currentAction]["streamtype"] == "dvbc" and nim.isCompatible("DVB-C")) or (self.providers[self.currentAction]["streamtype"] == "dvbt" and nim.isCompatible("DVB-T")):
				nimList.append(nim.slot)
		if len(nimList) == 0:
			print>>log, "[AutoBouquetsMaker] No NIMs found"
			self.showError(_('No NIMs found'))
			return

		resmanager = eDVBResourceManager.getInstance()
		if not resmanager:
			print>>log, "[AutoBouquetsMaker] Cannot retrieve Resource Manager instance"
			self.showError(_('Cannot retrieve Resource Manager instance'))
			return

		if self.providers[self.currentAction]["streamtype"] == "dvbs":
			print>>log, "[AutoBouquetsMaker] Search NIM for orbital position %d" % transponder["orbital_position"]
		else:
			print>>log, "[AutoBouquetsMaker] Search NIM"

		current_slotid = -1
		if self.rawchannel:
			del(self.rawchannel)

		self.frontend = None
		self.rawchannel = None

		nimList.reverse() # start from the last
		for slotid in nimList:
			if self.providers[self.currentAction]["streamtype"] == "dvbs":
				sats = nimmanager.getSatListForNim(slotid)
				for sat in sats:
					if sat[0] == transponder["orbital_position"]:
						if current_slotid == -1:	# mark the first valid slotid in case of no other one is free
							current_slotid = slotid

						self.rawchannel = resmanager.allocateRawChannel(slotid)
						if self.rawchannel:
							print>>log, "[AutoBouquetsMaker] Nim found on slot id %d with sat %s" % (slotid, sat[1])
							current_slotid = slotid
							break
			else:
				if current_slotid == -1:	# mark the first valid slotid in case of no other one is free
					current_slotid = slotid
				self.rawchannel = resmanager.allocateRawChannel(slotid)
				if self.rawchannel:
 					print>>log, "[AutoBouquetsMaker] Nim found on slot id %d" % (slotid)
					current_slotid = slotid
					break


			if self.rawchannel:
				break

		if current_slotid == -1:
			print>>log, "[AutoBouquetsMaker] No valid NIM found"
			self.showError(_('No valid NIM found'))
			return

		if not self.rawchannel:
			print>>log, "[AutoBouquetsMaker] Nim found on slot id %d but it's busy. Stop current service" % current_slotid
			if self.session.nav.RecordTimer.isRecording():
				print>>log, "[AutoBouquetsMaker] Cannot free NIM because a record is in progress"
				self.showError(_('Cannot free NIM because a record is in progress'))
				return

			self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference()
			self.session.nav.stopService()
			if self.session.pipshown:
				self.session.pipshown = False

			self.rawchannel = resmanager.allocateRawChannel(current_slotid)
			if not self.rawchannel:
				print>>log, "[AutoBouquetsMaker] Cannot get the NIM"
				self.showError(_('Cannot get the NIM'))
				return

		self.frontend = self.rawchannel.getFrontend()
		if not self.frontend:
			print>>log, "[AutoBouquetsMaker] Cannot get frontend"
			self.showError(_('Cannot get frontend'))
			return

		demuxer_id = self.rawchannel.reserveDemux()
		if demuxer_id < 0:
			print>>log, "[AutoBouquetsMaker] Cannot allocate the demuxer"
			self.showError(_('Cannot allocate the demuxer'))
			return

		if self.providers[self.currentAction]["streamtype"] == "dvbs":
			params = eDVBFrontendParametersSatellite()
			params.frequency = transponder["frequency"]
			params.symbol_rate = transponder["symbol_rate"]
			params.polarisation = transponder["polarization"]
			params.fec = transponder["fec_inner"]
			params.inversion = transponder["inversion"]
			params.orbital_position = transponder["orbital_position"]
			params.system = transponder["system"]
			params.modulation = transponder["modulation"]
			params.rolloff = transponder["roll_off"]
			params.pilot = transponder["pilot"]
			params_fe = eDVBFrontendParameters()
			params_fe.setDVBS(params, False)

		elif self.providers[self.currentAction]["streamtype"] == "dvbt":
			params = eDVBFrontendParametersTerrestrial()
			params.frequency = transponder["frequency"]
			params.bandwidth = transponder["bandwidth"]
			params.code_rate_hp = transponder["code_rate_hp"]
			params.code_rate_lp = transponder["code_rate_lp"]
			params.inversion = transponder["inversion"]
			params.system = transponder["system"]
			params.modulation = transponder["modulation"]
			params.transmission_mode = transponder["transmission_mode"]
			params.guard_interval = transponder["guard_interval"]
			params.hierarchy = transponder["hierarchy"]
			params_fe = eDVBFrontendParameters()
			params_fe.setDVBT(params)

		elif self.providers[self.currentAction]["streamtype"] == "dvbc":
			params = eDVBFrontendParametersCable()
			params.frequency = transponder["frequency"]
			params.symbol_rate = transponder["symbol_rate"]
			params.fec_inner = transponder["fec_inner"]
			params.inversion = transponder["inversion"]
			params.modulation = transponder["modulation"]
			params_fe = eDVBFrontendParameters()
			params_fe.setDVBC(params)

		self.rawchannel.requestTsidOnid()
		self.frontend.tune(params_fe)
		self.manager.setAdapter(0)	# FIX: use the correct device
		self.manager.setDemuxer(demuxer_id)
		self.manager.setFrontend(current_slotid)

		self.lockcounter = 0
		self.locktimer = eTimer()
		self.locktimer.callback.append(self.checkTunerLock)
		self.locktimer.start(100, 1)
Пример #7
0
    def doTune(self):
        from Screens.Standby import inStandby
        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            transponder = self.providers[self.currentAction]["transponder"]
        else:
            bouquet_key = None
            providers_tmp = config.autobouquetsmaker.providers.value.split("|")
            for provider_tmp in providers_tmp:
                provider_config = ProviderConfig(provider_tmp)
                provider_key = provider_config.getProvider()
                if self.currentAction != provider_key:
                    continue
                bouquet_key = provider_config.getArea()

            if not bouquet_key:
                print >> log, "[AutoBouquetsMaker] No area found"
                self.showError(_('No area found'))
                return

            transponder = self.providers[
                self.currentAction]["bouquets"][bouquet_key]

        nimList = []
        for nim in nimmanager.nim_slots:
            if (self.providers[self.currentAction]["streamtype"] == "dvbs"
                    and nim.isCompatible("DVB-S")
                    and nim.config_mode not in ("loopthrough")) or (
                        self.providers[self.currentAction]["streamtype"]
                        == "dvbc" and nim.isCompatible("DVB-C")) or (
                            self.providers[self.currentAction]["streamtype"]
                            == "dvbt" and nim.isCompatible("DVB-T")):
                nimList.append(nim.slot)
        if len(nimList) == 0:
            print >> log, "[AutoBouquetsMaker] No NIMs found"
            self.showError(_('No NIMs found'))
            return

        resmanager = eDVBResourceManager.getInstance()
        if not resmanager:
            print >> log, "[AutoBouquetsMaker] Cannot retrieve Resource Manager instance"
            self.showError(_('Cannot retrieve Resource Manager instance'))
            return

        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            print >> log, "[AutoBouquetsMaker] Search NIM for orbital position %d" % transponder[
                "orbital_position"]
        else:
            print >> log, "[AutoBouquetsMaker] Search NIM"

        current_slotid = -1
        if self.rawchannel:
            del (self.rawchannel)

        self.frontend = None
        self.rawchannel = None

        nimList.reverse()  # start from the last
        for slotid in nimList:
            if self.providers[self.currentAction]["streamtype"] == "dvbs":
                sats = nimmanager.getSatListForNim(slotid)
                for sat in sats:
                    if sat[0] == transponder["orbital_position"]:
                        if current_slotid == -1:  # mark the first valid slotid in case of no other one is free
                            current_slotid = slotid

                        self.rawchannel = resmanager.allocateRawChannel(slotid)
                        if self.rawchannel:
                            print >> log, "[AutoBouquetsMaker] Nim found on slot id %d with sat %s" % (
                                slotid, sat[1])
                            current_slotid = slotid
                            break
            else:
                if current_slotid == -1:  # mark the first valid slotid in case of no other one is free
                    current_slotid = slotid
                self.rawchannel = resmanager.allocateRawChannel(slotid)
                if self.rawchannel:
                    print >> log, "[AutoBouquetsMaker] Nim found on slot id %d" % (
                        slotid)
                    current_slotid = slotid
                    break

            if self.rawchannel:
                break

        if current_slotid == -1:
            print >> log, "[AutoBouquetsMaker] No valid NIM found"
            self.showError(_('No valid NIM found'))
            return

        if not self.rawchannel:
            print >> log, "[AutoBouquetsMaker] Nim found on slot id %d but it's busy. Stop current service" % current_slotid
            if self.session.nav.RecordTimer.isRecording():
                print >> log, "[AutoBouquetsMaker] Cannot free NIM because a record is in progress"
                self.showError(
                    _('Cannot free NIM because a record is in progress'))
                return

            self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference(
            )
            self.session.nav.stopService()
            if self.session.pipshown:
                self.session.pipshown = False

            self.rawchannel = resmanager.allocateRawChannel(current_slotid)
            if not self.rawchannel:
                print >> log, "[AutoBouquetsMaker] Cannot get the NIM"
                self.showError(_('Cannot get the NIM'))
                return

        self.frontend = self.rawchannel.getFrontend()
        if not self.frontend:
            print >> log, "[AutoBouquetsMaker] Cannot get frontend"
            self.showError(_('Cannot get frontend'))
            return

        demuxer_id = self.rawchannel.reserveDemux()
        if demuxer_id < 0:
            print >> log, "[AutoBouquetsMaker] Cannot allocate the demuxer"
            self.showError(_('Cannot allocate the demuxer'))
            return

        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            params = eDVBFrontendParametersSatellite()
            params.frequency = transponder["frequency"]
            params.symbol_rate = transponder["symbol_rate"]
            params.polarisation = transponder["polarization"]
            params.fec = transponder["fec_inner"]
            params.inversion = transponder["inversion"]
            params.orbital_position = transponder["orbital_position"]
            params.system = transponder["system"]
            params.modulation = transponder["modulation"]
            params.rolloff = transponder["roll_off"]
            params.pilot = transponder["pilot"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBS(params, False)

        elif self.providers[self.currentAction]["streamtype"] == "dvbt":
            params = eDVBFrontendParametersTerrestrial()
            params.frequency = transponder["frequency"]
            params.bandwidth = transponder["bandwidth"]
            params.code_rate_hp = transponder["code_rate_hp"]
            params.code_rate_lp = transponder["code_rate_lp"]
            params.inversion = transponder["inversion"]
            params.system = transponder["system"]
            params.modulation = transponder["modulation"]
            params.transmission_mode = transponder["transmission_mode"]
            params.guard_interval = transponder["guard_interval"]
            params.hierarchy = transponder["hierarchy"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBT(params)

        elif self.providers[self.currentAction]["streamtype"] == "dvbc":
            params = eDVBFrontendParametersCable()
            params.frequency = transponder["frequency"]
            params.symbol_rate = transponder["symbol_rate"]
            params.fec_inner = transponder["fec_inner"]
            params.inversion = transponder["inversion"]
            params.modulation = transponder["modulation"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBC(params)

        self.rawchannel.requestTsidOnid()
        self.frontend.tune(params_fe)
        self.manager.setAdapter(0)  # FIX: use the correct device
        self.manager.setDemuxer(demuxer_id)
        self.manager.setFrontend(current_slotid)

        self.lockcounter = 0
        self.locktimer = eTimer()
        self.locktimer.callback.append(self.checkTunerLock)
        self.locktimer.start(100, 1)
Пример #8
0
	def doTune(self):
		print>>log, "[ABM-main][doTune] searching for tuner for %s" % self.providers[self.currentAction]["name"]
		from Screens.Standby import inStandby
		if self.providers[self.currentAction]["streamtype"] == "dvbs":
			transponder = self.providers[self.currentAction]["transponder"]
		else:
			bouquet_key = None
			providers_tmp = self.abm_settings_str.split("|")
			for provider_tmp in providers_tmp:
				provider_config = ProviderConfig(provider_tmp)
				provider_key = provider_config.getProvider()
				if self.currentAction != provider_key:
					continue
				bouquet_key = provider_config.getArea()

			if not bouquet_key:
				print>>log, "[ABM-main][doTune] No area found"
				self.showError(_('No area found'))
				return

			transponder = self.providers[self.currentAction]["bouquets"][bouquet_key]

		nimList = []
		for nim in nimmanager.nim_slots:
			if self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.isCompatible("DVB-S"):
				try:
					if nim.isFBCTuner() and not nim.isFBCRoot():
						continue # do not load FBC links, only root tuners
				except:
					pass
			try: # OpenPLi Hot Switch compatible image
				if (nim.config_mode not in ("loopthrough", "satposdepends", "nothing")) and \
					{"dvbs": "DVB-S", "dvbc": "DVB-C", "dvbt": "DVB-T"}.get(self.providers[self.currentAction]["streamtype"], "UNKNOWN") in [x[:5] for x in nim.getTunerTypesEnabled()]:
					nimList.append(nim.slot)
			except AttributeError:
				try:
					if (nim.config_mode not in ("loopthrough", "satposdepends", "nothing")) and \
						((self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.isCompatible("DVB-S")) or \
						(self.providers[self.currentAction]["streamtype"] == "dvbc" and (nim.isCompatible("DVB-C") or (nim.isCompatible("DVB-S") and nim.canBeCompatible("DVB-C")))) or \
						(self.providers[self.currentAction]["streamtype"] == "dvbt" and (nim.isCompatible("DVB-T") or (nim.isCompatible("DVB-S") and nim.canBeCompatible("DVB-T"))))):
						nimList.append(nim.slot)
				except AttributeError: # OpenATV > 5.3
					if (self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.canBeCompatible("DVB-S") and nim.config_mode_dvbs not in ("loopthrough", "satposdepends", "nothing")) or \
						(self.providers[self.currentAction]["streamtype"] == "dvbc" and nim.canBeCompatible("DVB-C") and nim.config_mode_dvbc != "nothing") or \
						(self.providers[self.currentAction]["streamtype"] == "dvbt" and nim.canBeCompatible("DVB-T") and nim.config_mode_dvbt != "nothing"):
						nimList.append(nim.slot)

		if len(nimList) == 0:
			print>>log, "[ABM-main][doTune] No NIMs found"
			self.showError(_('No NIMs found for ') + self.providers[self.currentAction]["name"])
			return

		resmanager = eDVBResourceManager.getInstance()
		if not resmanager:
			print>>log, "[ABM-main][doTune] Cannot retrieve Resource Manager instance"
			self.showError(_('Cannot retrieve Resource Manager instance'))
			return

		if self.providers[self.currentAction]["streamtype"] == "dvbs":
			print>>log, "[ABM-main][doTune] Search NIM for orbital position %d" % transponder["orbital_position"]
		else:
			print>>log, "[ABM-main][doTune] Search NIM"

		# stop pip if running
		if self.session.pipshown:
			self.session.pipshown = False
			del self.session.pip
			print>>log, "[ABM-main][doTune] Stopping PIP."

		# stop currently playing service if it is using a tuner in ("loopthrough", "satposdepends")
		currentlyPlayingNIM = None
		currentService = self.session and self.session.nav.getCurrentService()
		frontendInfo = currentService and currentService.frontendInfo()
		frontendData = frontendInfo and frontendInfo.getAll(True)
		if frontendData is not None:
			currentlyPlayingNIM = frontendData.get("tuner_number", None)
			if self.providers[self.currentAction]["streamtype"] == "dvbs" and currentlyPlayingNIM is not None and nimmanager.nim_slots[currentlyPlayingNIM].isCompatible("DVB-S"):
				try:
					nimConfigMode = nimmanager.nim_slots[currentlyPlayingNIM].config_mode
				except AttributeError: # OpenATV > 5.3
					nimConfigMode = nimmanager.nim_slots[currentlyPlayingNIM].config_mode_dvbs
				if nimConfigMode in ("loopthrough", "satposdepends"):
					self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference()
					self.session.nav.stopService()
					currentlyPlayingNIM = None
					print>>log, "[ABM-main][doTune] The active service was using a %s tuner, so had to be stopped (slot id %s)." % (nimConfigMode, currentlyPlayingNIM)
		del frontendInfo
		del currentService

		current_slotid = -1
		if self.rawchannel:
			del(self.rawchannel)

		self.frontend = None
		self.rawchannel = None

		nimList.reverse() # start from the last
		for slotid in nimList:
			if self.providers[self.currentAction]["streamtype"] == "dvbs":
				sats = nimmanager.getSatListForNim(slotid)
				for sat in sats:
					if sat[0] == transponder["orbital_position"]:
						if current_slotid == -1:	# mark the first valid slotid in case of no other one is free
							current_slotid = slotid

						self.rawchannel = resmanager.allocateRawChannel(slotid)
						if self.rawchannel:
							print>>log, "[ABM-main][doTune] Nim found on slot id %d with sat %s" % (slotid, sat[1])
							current_slotid = slotid
						break
			else:
				if current_slotid == -1:	# mark the first valid slotid in case of no other one is free
					current_slotid = slotid
				self.rawchannel = resmanager.allocateRawChannel(slotid)
				if self.rawchannel:
 					print>>log, "[ABM-main][doTune] Nim found on slot id %d" % (slotid)
					current_slotid = slotid
					break

			if self.rawchannel:
				break

		if current_slotid == -1:
			print>>log, "[ABM-main][doTune] No valid NIM found"
			self.showError(_('No valid NIM found for ') + self.providers[self.currentAction]["name"])
			return

		if not self.rawchannel:
			# if we are here the only possible option is to close the active service
			if currentlyPlayingNIM in nimList:
				slotid = currentlyPlayingNIM
				if self.providers[self.currentAction]["streamtype"] == "dvbs":
					sats = nimmanager.getSatListForNim(slotid)
					for sat in sats:
						if sat[0] == transponder["orbital_position"]:
							print>>log, "[ABM-main][doTune] Nim found on slot id %d but it's busy. Stopping active service" % slotid
							self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference()
							self.session.nav.stopService()
							self.rawchannel = resmanager.allocateRawChannel(slotid)
							if self.rawchannel:
								print>>log, "[ABM-main][doTune] The active service was stopped, and the NIM is now free to use."
								current_slotid = slotid
							break
				else:
					print>>log, "[ABM-main][doTune] Nim found on slot id %d but it's busy. Stopping active service" % slotid
					self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference()
					self.session.nav.stopService()
					self.rawchannel = resmanager.allocateRawChannel(slotid)
					if self.rawchannel:
						print>>log, "[ABM-main][doTune] The active service was stopped, and the NIM is now free to use."
						current_slotid = slotid

			if not self.rawchannel:
				if self.session.nav.RecordTimer.isRecording():
					print>>log, "[ABM-main][doTune] Cannot free NIM because a recording is in progress"
					self.showError(_('Cannot free NIM because a recording is in progress'))
					return
				else:
					print>>log, "[ABM-main][doTune] Cannot get the NIM"
					self.showError(_('Cannot get the NIM'))
					return

		# set extended timeout for rotors
		self.motorised = False
		if self.providers[self.currentAction]["streamtype"] == "dvbs" and self.isRotorSat(current_slotid, transponder["orbital_position"]):
			self.motorised = True
			self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_ROTOR
			print>>log, "[ABM-main][doTune] Motorised dish. Will wait up to %i seconds for tuner lock." % (self.LOCK_TIMEOUT/10)
		else:
			self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_FIXED
			print>>log, "[ABM-main][doTune] Fixed dish. Will wait up to %i seconds for tuner lock." % (self.LOCK_TIMEOUT/10)

		self.frontend = self.rawchannel.getFrontend()
		if not self.frontend:
			print>>log, "[ABM-main][doTune] Cannot get frontend"
			self.showError(_('Cannot get frontend'))
			return

		demuxer_id = self.rawchannel.reserveDemux()
		if demuxer_id < 0:
			print>>log, "[ABM-main][doTune] Cannot allocate the demuxer."
			self.showError(_('Cannot allocate the demuxer.'))
			return

		if self.providers[self.currentAction]["streamtype"] == "dvbs":
			params = eDVBFrontendParametersSatellite()
			params.frequency = transponder["frequency"]
			params.symbol_rate = transponder["symbol_rate"]
			params.polarisation = transponder["polarization"]
			params.fec = transponder["fec_inner"]
			params.inversion = transponder["inversion"]
			params.orbital_position = transponder["orbital_position"]
			params.system = transponder["system"]
			params.modulation = transponder["modulation"]
			params.rolloff = transponder["roll_off"]
			params.pilot = transponder["pilot"]
			try: # if distro is MIS capable
				params.pls_mode = eDVBFrontendParametersSatellite.PLS_Root
				params.is_id = -1
				params.pls_code = 1
			except:
				pass
			params_fe = eDVBFrontendParameters()
			params_fe.setDVBS(params, False)

		elif self.providers[self.currentAction]["streamtype"] == "dvbt":
			params = eDVBFrontendParametersTerrestrial()
			params.frequency = transponder["frequency"]
			params.bandwidth = transponder["bandwidth"]
			params.code_rate_hp = transponder["code_rate_hp"]
			params.code_rate_lp = transponder["code_rate_lp"]
			params.inversion = transponder["inversion"]
			params.system = transponder["system"]
			params.modulation = transponder["modulation"]
			params.transmission_mode = transponder["transmission_mode"]
			params.guard_interval = transponder["guard_interval"]
			params.hierarchy = transponder["hierarchy"]
			params_fe = eDVBFrontendParameters()
			params_fe.setDVBT(params)

		elif self.providers[self.currentAction]["streamtype"] == "dvbc":
			params = eDVBFrontendParametersCable()
			params.frequency = transponder["frequency"]
			params.symbol_rate = transponder["symbol_rate"]
			params.fec_inner = transponder["fec_inner"]
			params.inversion = transponder["inversion"]
			params.modulation = transponder["modulation"]
			params_fe = eDVBFrontendParameters()
			params_fe.setDVBC(params)

		try:
			self.rawchannel.requestTsidOnid()
		except (TypeError):
			# for compatibility with some third party images
			self.rawchannel.requestTsidOnid(self.gotTsidOnid)

		self.frontend.tune(params_fe)
		self.manager.setAdapter(0)	# FIX: use the correct device
		self.manager.setDemuxer(demuxer_id)
		self.manager.setFrontend(current_slotid)

		self.current_slotid = current_slotid
		self.lockcounter = 0
		self.locktimer = eTimer()
		self.locktimer.callback.append(self.checkTunerLock)
		self.locktimer.start(100, 1)
Пример #9
0
    def doTune(self):
        print >> log, "[ABM-main][doTune] searching for tuner for %s" % self.providers[
            self.currentAction]["name"]
        from Screens.Standby import inStandby
        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            transponder = self.providers[self.currentAction]["transponder"]
        else:
            bouquet_key = None
            providers_tmp = self.abm_settings_str.split("|")
            for provider_tmp in providers_tmp:
                provider_config = ProviderConfig(provider_tmp)
                provider_key = provider_config.getProvider()
                if self.currentAction != provider_key:
                    continue
                bouquet_key = provider_config.getArea()

            if not bouquet_key:
                print >> log, "[ABM-main][doTune] No area found"
                self.showError(_('No area found'))
                return

            transponder = self.providers[
                self.currentAction]["bouquets"][bouquet_key]

        self.transponder = transponder

        nimList = []
        tunerSelectionAlgorithm = "UNKNOWN"  # for debug
        for nim in nimmanager.nim_slots:
            if self.providers[self.currentAction][
                    "streamtype"] == "dvbs" and nim.isCompatible("DVB-S"):
                try:
                    if nim.isFBCLink():
                        continue  # do not load FBC links, only root tuners
                except:
                    pass
            try:  # OpenPLi Hot Switch compatible image
                if (nim.config_mode not in ("loopthrough", "satposdepends", "nothing")) and \
                 {"dvbs": "DVB-S", "dvbc": "DVB-C", "dvbt": "DVB-T"}.get(self.providers[self.currentAction]["streamtype"], "UNKNOWN") in [x[:5] for x in nim.getTunerTypesEnabled()]:
                    if self.validNIM(nim.slot):
                        nimList.append(nim.slot)
                    tunerSelectionAlgorithm = "OpenPLi Hot Switch compatible"
            except AttributeError:
                try:
                    if (nim.config_mode not in ("loopthrough", "satposdepends", "nothing")) and \
                     ((self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.isCompatible("DVB-S")) or \
                     (self.providers[self.currentAction]["streamtype"] == "dvbc" and (nim.isCompatible("DVB-C") or (nim.isCompatible("DVB-S") and nim.canBeCompatible("DVB-C")))) or \
                     (self.providers[self.currentAction]["streamtype"] == "dvbt" and (nim.isCompatible("DVB-T") or (nim.isCompatible("DVB-S") and nim.canBeCompatible("DVB-T"))))):
                        if self.validNIM(nim.slot):
                            nimList.append(nim.slot)
                        tunerSelectionAlgorithm = "Conventional"
                except AttributeError:  # OpenATV > 5.3
                    if (self.providers[self.currentAction]["streamtype"] == "dvbs" and nim.canBeCompatible("DVB-S") and nim.config_mode_dvbs not in ("loopthrough", "satposdepends", "nothing")) or \
                     (self.providers[self.currentAction]["streamtype"] == "dvbc" and nim.canBeCompatible("DVB-C") and nim.config_mode_dvbc != "nothing") or \
                     (self.providers[self.currentAction]["streamtype"] == "dvbt" and nim.canBeCompatible("DVB-T") and nim.config_mode_dvbt != "nothing"):
                        if self.validNIM(nim.slot):
                            nimList.append(nim.slot)
                        tunerSelectionAlgorithm = "OpenATV > 5.3"

        print >> log, "[ABM-main][doTune] tuner selection algorithm '%s'" % tunerSelectionAlgorithm

        if len(nimList) == 0:
            print >> log, "[ABM-main][doTune] No NIMs found"
            self.showError(
                _('No NIMs found for ') +
                self.providers[self.currentAction]["name"])
            return

        resmanager = eDVBResourceManager.getInstance()
        if not resmanager:
            print >> log, "[ABM-main][doTune] Cannot retrieve Resource Manager instance"
            self.showError(_('Cannot retrieve Resource Manager instance'))
            return

        if self.providers[self.currentAction][
                "streamtype"] == "dvbs":  # If we have a choice of dishes sort the nimList so "fixed" dishes have a higher priority than "motorised".
            nimList = [
                slot for slot in nimList
                if not self.isRotorSat(slot, transponder["orbital_position"])
            ] + [
                slot for slot in nimList
                if self.isRotorSat(slot, transponder["orbital_position"])
            ]

        # stop pip if running
        if self.session.pipshown:
            self.session.pipshown = False
            del self.session.pip
            print >> log, "[ABM-main][doTune] Stopping PIP."

        # find currently playing nim
        currentlyPlayingNIM = None
        currentService = self.session and self.session.nav.getCurrentService()
        frontendInfo = currentService and currentService.frontendInfo()
        frontendData = frontendInfo and frontendInfo.getAll(True)
        if frontendData is not None:
            currentlyPlayingNIM = frontendData.get("tuner_number", None)
            # stop currently playing service if it is using a tuner in ("loopthrough", "satposdepends"), as running in this configuration will prevent getting rawchannel on the root tuner.
            if self.providers[self.currentAction][
                    "streamtype"] == "dvbs" and currentlyPlayingNIM is not None and nimmanager.nim_slots[
                        currentlyPlayingNIM].isCompatible("DVB-S"):
                try:
                    nimConfigMode = nimmanager.nim_slots[
                        currentlyPlayingNIM].config_mode
                except AttributeError:  # OpenATV > 5.3
                    nimConfigMode = nimmanager.nim_slots[
                        currentlyPlayingNIM].config_mode_dvbs
                if nimConfigMode in ("loopthrough", "satposdepends"):
                    self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference(
                    )
                    self.session.nav.stopService()
                    currentlyPlayingNIM = None
                    print >> log, "[ABM-main][doTune] The active service was using a %s tuner, so had to be stopped (slot id %s)." % (
                        nimConfigMode, currentlyPlayingNIM)
        del frontendInfo
        del currentService

        self.releaseFrontend()

        for current_slotid in nimList:
            self.rawchannel = resmanager.allocateRawChannel(current_slotid)
            if self.rawchannel:
                print >> log, "[ABM-main][doTune] Tuner %s selected%s" % (
                    chr(ord('A') + current_slotid),
                    (" for orbital position %d" %
                     transponder["orbital_position"]
                     if "orbital_position" in transponder else ""))
                break

        if not self.rawchannel:
            # if we are here the only possible option is to close the active service
            if currentlyPlayingNIM in nimList:
                print >> log, "[ABM-main][doTune] Tuner %s has been selected but it's busy. Stopping currently playing service." % chr(
                    ord('A') + currentlyPlayingNIM)
                self.postScanService = self.session.nav.getCurrentlyPlayingServiceReference(
                )
                self.session.nav.stopService()
                self.rawchannel = resmanager.allocateRawChannel(
                    currentlyPlayingNIM)
                if self.rawchannel:
                    print >> log, "[ABM-main][doTune] The active service was stopped, and tuner %s is now free to use." % chr(
                        ord('A') + currentlyPlayingNIM)
                    current_slotid = currentlyPlayingNIM

            if not self.rawchannel:
                if self.session.nav.RecordTimer.isRecording():
                    print >> log, "[ABM-main][doTune] Cannot free NIM because a recording is in progress"
                    self.showError(
                        _('Cannot free NIM because a recording is in progress')
                    )
                    return
                else:
                    print >> log, "[ABM-main][doTune] Cannot get the NIM"
                    self.showError(_('Cannot get the NIM'))
                    return

        # set extended timeout for rotors
        self.motorised = False
        if self.providers[self.currentAction][
                "streamtype"] == "dvbs" and self.isRotorSat(
                    current_slotid, transponder["orbital_position"]):
            self.motorised = True
            self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_ROTOR
            print >> log, "[ABM-main][doTune] Motorised dish. Will wait up to %i seconds for tuner lock." % (
                self.LOCK_TIMEOUT / 10)
        else:
            self.LOCK_TIMEOUT = self.LOCK_TIMEOUT_FIXED
            print >> log, "[ABM-main][doTune] Fixed dish. Will wait up to %i seconds for tuner lock." % (
                self.LOCK_TIMEOUT / 10)

        if not inStandby:
            self["tuner_text"].setText(chr(ord('A') + current_slotid))

        self.frontend = self.rawchannel.getFrontend()
        if not self.frontend:
            print >> log, "[ABM-main][doTune] Cannot get frontend"
            self.showError(_('Cannot get frontend'))
            return

        demuxer_id = self.rawchannel.reserveDemux()
        if demuxer_id < 0:
            print >> log, "[ABM-main][doTune] Cannot allocate the demuxer."
            self.showError(_('Cannot allocate the demuxer.'))
            return

        if self.providers[self.currentAction]["streamtype"] == "dvbs":
            params = eDVBFrontendParametersSatellite()
            params.frequency = transponder["frequency"]
            params.symbol_rate = transponder["symbol_rate"]
            params.polarisation = transponder["polarization"]
            params.fec = transponder["fec_inner"]
            params.inversion = transponder["inversion"]
            params.orbital_position = transponder["orbital_position"]
            params.system = transponder["system"]
            params.modulation = transponder["modulation"]
            params.rolloff = transponder["roll_off"]
            params.pilot = transponder["pilot"]
            if hasattr(eDVBFrontendParametersSatellite, "No_Stream_Id_Filter"):
                params.is_id = eDVBFrontendParametersSatellite.No_Stream_Id_Filter
            if hasattr(eDVBFrontendParametersSatellite, "PLS_Gold"):
                params.pls_mode = eDVBFrontendParametersSatellite.PLS_Gold
            if hasattr(eDVBFrontendParametersSatellite,
                       "PLS_Default_Gold_Code"):
                params.pls_code = eDVBFrontendParametersSatellite.PLS_Default_Gold_Code
            if hasattr(eDVBFrontendParametersSatellite, "No_T2MI_PLP_Id"):
                params.t2mi_plp_id = eDVBFrontendParametersSatellite.No_T2MI_PLP_Id
            if hasattr(eDVBFrontendParametersSatellite, "T2MI_Default_Pid"):
                params.t2mi_pid = eDVBFrontendParametersSatellite.T2MI_Default_Pid
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBS(params, False)

        elif self.providers[self.currentAction]["streamtype"] == "dvbt":
            params = eDVBFrontendParametersTerrestrial()
            params.frequency = transponder["frequency"]
            params.bandwidth = transponder["bandwidth"]
            params.code_rate_hp = transponder["code_rate_hp"]
            params.code_rate_lp = transponder["code_rate_lp"]
            params.inversion = transponder["inversion"]
            params.system = transponder["system"]
            params.modulation = transponder["modulation"]
            params.transmission_mode = transponder["transmission_mode"]
            params.guard_interval = transponder["guard_interval"]
            params.hierarchy = transponder["hierarchy"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBT(params)

        elif self.providers[self.currentAction]["streamtype"] == "dvbc":
            params = eDVBFrontendParametersCable()
            params.frequency = transponder["frequency"]
            params.symbol_rate = transponder["symbol_rate"]
            params.fec_inner = transponder["fec_inner"]
            params.inversion = transponder["inversion"]
            params.modulation = transponder["modulation"]
            params_fe = eDVBFrontendParameters()
            params_fe.setDVBC(params)

        try:
            self.rawchannel.requestTsidOnid()
        except (TypeError):
            # for compatibility with some third party images
            self.rawchannel.requestTsidOnid(self.gotTsidOnid)

        self.frontend.tune(params_fe)
        self.manager.setAdapter(0)  # FIX: use the correct device
        self.manager.setDemuxer(demuxer_id)
        self.manager.setFrontend(current_slotid)

        self.current_slotid = current_slotid
        self.lockcounter = 0
        self.locktimer = eTimer()
        self.locktimer.callback.append(self.checkTunerLock)
        self.locktimer.start(100, 1)
Пример #10
0
def convertToJSON(provider_dir):
    """Converts the given directory into a JSON file (stored in the directory itself as 'all.json').

    If '$dir/all.json' already exists, it will be overwritten.
    """
    
    original_dir = os.path.abspath(os.path.curdir)
    os.chdir(provider_dir)
    logging.info("Now in directory '%s'." % provider_dir)

    # TODO: how?
    # filename = "mol_source_%s.json" % provider_dir
    filename = "mol_source_this.json"
    if os.path.exists(filename):
        os.remove(filename)
    # all_json = open(filename, "a")
    all_json = codecs.open(filename, encoding='utf-8', mode="w")
    all_json.write("""{
  "type": "FeatureCollection",
  "features": [""")

    # We wrap this processing in a try-finally so that, no matter what happens,
    # we change back to the original directory before we leave this subroutine.
    try:
        # Step 1. Load and validate the config.yaml file.
        config = ProviderConfig("config.yaml", os.path.basename(provider_dir))
        config.validate()

        all_features = []

        # Step 2. For each collection, and then each shapefile in that collection:
        for collection in config.collections():
            name = collection.getname()

            logging.info("Switching to collection '%s'." % name)

            # This is where we will store all the features.
            features = []

            if os.path.isdir(name):
                # A directory of shapefiles.

                shapefiles = glob.glob('*.shp')
                for shapefile in shapefiles:

                    # Determine the "name" (filename without extension) of this file.
                    name = shapefile[0:shapefile.index('.shp')]

                    # Step 2.1. Convert this shapefile into a GeoJSON file, projected to
                    # EPSG 4326 (WGS 84).
                    json_filename = '%s.json' % name
                    
                    # Delete existing geojson file since we're appending.
                    if os.path.exists(json_filename):
                        os.remove(json_filename)

                    command = [ogr2ogr_path(), 
                        '-f', 'GeoJSON', 
                        '-t_srs', 'EPSG:4326',
                        json_filename,
                        '%s.shp' % name
                    ]
                                    
                    try:
                        subprocess.call(command)
                    except:
                        logging.warn('Unable to convert %s to GeoJSON - %s' % (name, command))
                        if os.path.exists(json_filename):
                            os.remove(json_filename)
                        continue

                    # Step 2.2. Load that GeoJSON file and do the mapping.
                    #logging.info('Mapping fields from DBF to specification: %s' % json_filename)
                    geojson = None
                    try:
                        geojson = simplejson.loads(
                            codecs.open(json_filename, encoding='utf-8').read(), 
                            encoding='utf-8')

                    except:
                        logging.error('Unable to open or process %s' % json_filename)
                        continue

                    features = geojson['features']

            elif os.path.isfile(name) and name.lower().rfind('.csv', len(name) - 4, len(name)) != -1:
                # This is a .csv file! 
                csvfile = open(name, "r")
                reader = UnicodeDictReader(csvfile)

                features = []
                feature_index = 0
                for entry in reader:
                    feature_index += 1
                    feature = {}

                    # As per the spec at http://geojson.org/geojson-spec.html
                    feature['type'] = 'Feature'
                    feature['properties'] = entry

                    lat = entry['Latitude']
                    if not lat:
                        logging.warn("Feature %d has no latitude, ignoring." % feature_index)
                        continue # Ignore features without latitudes.
                    long = entry['Longitude']
                    if not long:
                        logging.warn("Feature %d has no longitude, ignoring." % feature_index)
                        continue # Ignore features without longitudes.

                    feature['geometry'] = {'type': 'Point', 'coordinates': [
                            float(entry['Longitude']),
                            float(entry['Latitude'])
                        ]}
                        # TODO: We assume latitude and longitude (in WGS84) are
                        # present in the columns 'Latitude' and 'Longitude'
                        # respectively.
                    
                        # IMPORTANT TODO: at the moment, we assume the incoming coordinates
                        # are already in WGS84! THIS MIGHT NOT BE TRUE!

                    features.append(feature)

                csvfile.close()
                
            # Step 2.3. For every feature:
            row_count = 0
            for feature in features:
                row_count = row_count + 1

                properties = feature['properties']
                new_properties = collection.default_fields()

                # Map the properties over.
                for key in properties.keys():
                    (new_key, new_value) = collection.map_field(row_count, key, properties[key])
                    if new_value is not None:
                        new_properties[new_key] = unicode(new_value)

                # Convert field names to dbfnames.
                dbf_properties = {}
                for fieldname in new_properties.keys():
                    dbf_properties[ProviderConfig.fieldname_to_dbfname(fieldname)] = new_properties[fieldname]

                # Replace the existing properties with the new one.
                # feature['properties'] = dbf_properties
                # No - let's try uploading to CartoDB without.
                feature['properties'] = new_properties

                # Upload to CartoDB.
                uploadGeoJSONEntry(feature, _getoptions().table_name)

                # Save into all_features.
                all_features.append(feature)
            
            features_json = []
            for feature in all_features:
                try:
                    features_json.append(simplejson.dumps(feature, ensure_ascii=False))
                except:
                    logging.info('Unable to convert feature to JSON: %s' % feature)

            all_json.write(','.join(features_json))
            all_json.write(',')
            all_json.flush()
            all_features = []                
                
            logging.info('%s converted to GeoJSON' % name)

            os.chdir('..')

        # Zip up the GeoJSON document
        all_json.write("""]}""")
        all_json.close()

        #myzip = ZipFile('%s.zip' % filename, 'w')
        #myzip.write(filename) # TODO: Fails for big files (4GB)
        #myzip.close()

        logging.info("%s written successfully." % filename)

    finally:
        os.chdir(original_dir)

    logging.info("Processing of directory '%s' completed." % provider_dir)