9845be9543223abb3070b23227d23acf8df6276f
[enigma2.git] / lib / python / Screens / ScanSetup.py
1 from Screen import Screen
2 from ServiceScan import *
3 from Components.config import config, ConfigSubsection, ConfigSelection, \
4         ConfigYesNo, ConfigInteger, getConfigListEntry, ConfigSlider, ConfigSatlist, ConfigEnableDisable
5 from Components.ActionMap import NumberActionMap
6 from Components.ConfigList import ConfigList, ConfigListScreen
7 from Components.NimManager import nimmanager, getConfigSatlist
8 from Components.Label import Label
9 from Screens.MessageBox import MessageBox
10 from enigma import eTimer, eDVBFrontendParametersSatellite, eComponentScan, \
11         eDVBSatelliteEquipmentControl, eDVBFrontendParametersTerrestrial, \
12         eDVBFrontendParametersCable, eConsoleAppContainer, eDVBResourceManager
13
14 def buildTerTransponder(frequency, 
15                 inversion=2, bandwidth = 3, fechigh = 6, feclow = 6,
16                 modulation = 2, transmission = 2, guard = 4,
17                 hierarchy = 4):
18
19 #       print "freq", frequency, "inv", inversion, "bw", bandwidth, "fech", fechigh, "fecl", feclow, "mod", modulation, "tm", transmission, "guard", guard, "hierarchy", hierarchy
20
21         # WARNING: normally, enums are working directly.
22         # Don't copy this (very bad)!! Instead either fix swig (good) or
23         # move this into a central place.
24         Bw8MHz = 0
25         Bw7MHz = 1
26         Bw6MHz = 2
27         #Bw5MHz = 3 #not implemented for e1 compatibilty
28         BwAuto = 3
29         
30         f1_2 = 0
31         f2_3 = 1
32         f3_4 = 2
33         f5_6 = 3
34         f7_8 = 4
35         fAuto = 5
36         
37         TM2k = 0
38         TM8k = 1
39         #TM4k = 2  #not implemented for e1 compatibilty
40         TMAuto = 2
41         
42         GI_1_32 = 0
43         GI_1_16 = 1
44         GI_1_8 = 2
45         GI_1_4 = 3
46         GI_Auto = 4
47         
48         HNone = 0
49         H1 = 1
50         H2 = 2
51         H4 = 3
52         HAuto = 4
53
54         QPSK = 0
55         QAM16 = 1
56         QAM64 = 2
57         Auto = 3
58         
59         Off = 0
60         On = 1
61         Unknown = 2
62
63         parm = eDVBFrontendParametersTerrestrial()
64
65         parm.frequency = frequency
66
67         parm.inversion = [Off, On, Unknown][inversion]
68         parm.bandwidth = [Bw8MHz, Bw7MHz, Bw6MHz, BwAuto][bandwidth] # Bw5MHz unsupported
69         parm.code_rate_HP = [f1_2, f2_3, f3_4, f5_6, f7_8, fAuto][fechigh]
70         parm.code_rate_LP = [f1_2, f2_3, f3_4, f5_6, f7_8, fAuto][feclow]
71         parm.modulation = [QPSK, QAM16, QAM64, Auto][modulation]
72         parm.transmission_mode = [TM2k, TM8k, TMAuto][transmission] # TM4k unsupported
73         parm.guard_interval = [GI_1_32, GI_1_16, GI_1_8, GI_1_4, GI_Auto][guard]
74         parm.hierarchy = [HNone, H1, H2, H4, HAuto][hierarchy]
75         
76         return parm
77
78 def getInitialTransponderList(tlist, pos):
79         list = nimmanager.getTransponders(pos)
80         for x in list:
81                 if x[0] == 0:           #SAT
82                         parm = eDVBFrontendParametersSatellite()
83                         parm.frequency = x[1]
84                         parm.symbol_rate = x[2]
85                         parm.polarisation = x[3]
86                         parm.fec = x[4]
87                         parm.inversion = 2 # AUTO
88                         parm.orbital_position = pos
89                         parm.system = x[5]
90                         parm.modulation = x[6]
91                         tlist.append(parm)
92
93 def getInitialCableTransponderList(tlist, nim):
94         list = nimmanager.getTranspondersCable(nim)
95         for x in list:
96                 if x[0] == 1: #CABLE
97                         parm = eDVBFrontendParametersCable()
98                         parm.frequency = x[1]
99                         parm.symbol_rate = x[2]
100                         parm.modulation = x[3]
101                         parm.fec_inner = x[4]
102                         parm.inversion = 2 # AUTO
103                         #print "frequency:", x[1]
104                         #print "symbol_rate:", x[2]
105                         #print "modulation:", x[3]
106                         #print "fec_inner:", x[4]
107                         #print "inversion:", 2
108                         tlist.append(parm)
109
110 def getInitialTerrestrialTransponderList(tlist, region):
111         list = nimmanager.getTranspondersTerrestrial(region)
112
113         #self.transponders[self.parsedTer].append((2,freq,bw,const,crh,crl,guard,transm,hierarchy,inv))
114
115         #def buildTerTransponder(frequency, inversion = 2, bandwidth = 3, fechigh = 6, feclow = 6,
116                                 #modulation = 2, transmission = 2, guard = 4, hierarchy = 4):
117
118         for x in list:
119                 if x[0] == 2: #TERRESTRIAL
120                         parm = buildTerTransponder(x[1], x[9], x[2], x[4], x[5], x[3], x[7], x[6], x[8])
121                         tlist.append(parm)
122
123 cable_bands = {
124         "DVBC_BAND_EU_VHF_I" : 1 << 0,
125         "DVBC_BAND_EU_MID" : 1 << 1,
126         "DVBC_BAND_EU_VHF_III" : 1 << 2,
127         "DVBC_BAND_EU_SUPER" : 1 << 3,
128         "DVBC_BAND_EU_HYPER" : 1 << 4,
129         "DVBC_BAND_EU_UHF_IV" : 1 << 5,
130         "DVBC_BAND_EU_UHF_V" : 1 << 6,
131         "DVBC_BAND_US_LO" : 1 << 7,
132         "DVBC_BAND_US_MID" : 1 << 8,
133         "DVBC_BAND_US_HI" : 1 << 9,
134         "DVBC_BAND_US_SUPER" : 1 << 10,
135         "DVBC_BAND_US_HYPER" : 1 << 11,
136 }
137
138 class CableTransponderSearchSupport:
139 #       def setCableTransponderSearchResult(self, tlist):
140 #               pass
141
142 #       def cableTransponderSearchFinished(self):
143 #               pass
144
145         def tryGetRawFrontend(self, feid):
146                 res_mgr = eDVBResourceManager.getInstance()
147                 if res_mgr:
148                         raw_channel = res_mgr.allocateRawChannel(self.feid)
149                         if raw_channel:
150                                 frontend = raw_channel.getFrontend()
151                                 if frontend:
152                                         del frontend
153                                         del raw_channel
154                                         return True
155                 return False
156
157         def cableTransponderSearchSessionClosed(self, *val):
158                 print "cableTransponderSearchSessionClosed, val", val
159                 self.cable_search_container = None
160                 self.cable_search_session = None
161                 if val and len(val) and val[0]:
162                         self.setCableTransponderSearchResult(self.__tlist)
163                 self.__tlist = None
164                 self.cableTransponderSearchFinished()
165
166         def cableTransponderSearchClosed(self, retval):
167                 print "cableTransponderSearch finished", retval
168                 self.cable_search_session.close(True)
169
170         def getCableTransponderData(self, str):
171                 data = str.split()
172                 if len(data):
173                         if data[0] == 'OK':
174                                 print str
175                                 qam = { "QAM16" : 1, "QAM32" : 2, "QAM64" : 3, "QAM128" : 4, "QAM256" : 5 }
176                                 inv = { "INVERSION_OFF" : 0, "INVERSION_ON" : 1 }
177                                 fec = { "FEC_AUTO" : 0, "FEC_1_2" : 1, "FEC_2_3" : 2, "FEC_3_4" : 3, "FEC_5_6": 4, "FEC_7_8" : 5, "FEC_8_9" : 6, "FEC_NONE" : 15 }
178                                 parm = eDVBFrontendParametersCable()
179                                 parm.frequency = int(data[1])
180                                 parm.symbol_rate = int(data[2])
181                                 parm.fec_inner = fec[data[3]]
182                                 parm.modulation = qam[data[4]]
183                                 parm.inversion = inv[data[5]]
184                                 self.__tlist.append(parm)
185                 tmpstr = _("Try to find used Transponders in cable network.. please wait...")
186                 tmpstr += "\n\n"
187                 tmpstr += data[1]
188                 tmpstr += " kHz "
189                 tmpstr += data[0]
190                 self.cable_search_session["text"].setText(tmpstr)
191
192         def startCableTransponderSearch(self, nim_idx):
193                 if not self.tryGetRawFrontend(nim_idx):
194                         self.session.nav.stopService()
195                         if not self.tryGetRawFrontend(nim_idx):
196                                 if self.session.pipshown: # try to disable pip
197                                         self.session.pipshown = False
198                                         del self.session.pip
199                                 if not self.tryGetRawFrontend(nim_idx):
200                                         self.cableTransponderSearchFinished()
201                                         return
202                 self.__tlist = [ ]
203                 self.cable_search_container = eConsoleAppContainer()
204                 self.cable_search_container.appClosed.get().append(self.cableTransponderSearchClosed)
205                 self.cable_search_container.dataAvail.get().append(self.getCableTransponderData)
206                 cableConfig = config.Nims[nim_idx].cable
207                 cmd = "tda1002x --scan --verbose --wakeup --bus="
208                 cmd += str(nim_idx)
209                 if cableConfig.scan_type.value == "bands":
210                         cmd += " --scan-bands="
211                         bands = 0
212                         if cableConfig.scan_band_EU_VHF_I.value:
213                                 bands |= cable_bands["DVBC_BAND_EU_VHF_I"]
214                         if cableConfig.scan_band_EU_MID.value:
215                                 bands |= cable_bands["DVBC_BAND_EU_MID"]
216                         if cableConfig.scan_band_EU_VHF_III.value:
217                                 bands |= cable_bands["DVBC_BAND_EU_VHF_III"]
218                         if cableConfig.scan_band_EU_UHF_IV.value:
219                                 bands |= cable_bands["DVBC_BAND_EU_UHF_IV"]
220                         if cableConfig.scan_band_EU_UHF_V.value:
221                                 bands |= cable_bands["DVBC_BAND_EU_UHF_V"]
222                         if cableConfig.scan_band_EU_SUPER.value:
223                                 bands |= cable_bands["DVBC_BAND_EU_SUPER"]
224                         if cableConfig.scan_band_EU_HYPER.value:
225                                 bands |= cable_bands["DVBC_BAND_EU_HYPER"]
226                         if cableConfig.scan_band_US_LOW.value:
227                                 bands |= cable_bands["DVBC_BAND_US_LO"]
228                         if cableConfig.scan_band_US_MID.value:
229                                 bands |= cable_bands["DVBC_BAND_US_MID"]
230                         if cableConfig.scan_band_US_HIGH.value:
231                                 bands |= cable_bands["DVBC_BAND_US_HI"]
232                         if cableConfig.scan_band_US_SUPER.value:
233                                 bands |= cable_bands["DVBC_BAND_US_SUPER"]
234                         if cableConfig.scan_band_US_HYPER.value:
235                                 bands |= cable_bands["DVBC_BAND_US_HYPER"]
236                         cmd += str(bands)
237                 else:
238                         cmd += " --scan-stepsize="
239                         cmd += str(cableConfig.scan_frequency_steps.value)
240                 if cableConfig.scan_mod_qam16.value:
241                         cmd += " --mod 16"
242                 if cableConfig.scan_mod_qam32.value:
243                         cmd += " --mod 32"
244                 if cableConfig.scan_mod_qam64.value:
245                         cmd += " --mod 64"
246                 if cableConfig.scan_mod_qam128.value:
247                         cmd += " --mod 128"
248                 if cableConfig.scan_mod_qam256.value:
249                         cmd += " --mod 256"
250                 if cableConfig.scan_sr_6900.value:
251                         cmd += " --sr 6900000"
252                 if cableConfig.scan_sr_6875.value:
253                         cmd += " --sr 6875000"
254                 if cableConfig.scan_sr_ext1.value > 450:
255                         cmd += " --sr "
256                         cmd += str(cableConfig.scan_sr_ext1.value)
257                         cmd += "000"
258                 if cableConfig.scan_sr_ext2.value > 450:
259                         cmd += " --sr "
260                         cmd += str(cableConfig.scan_sr_ext2.value)
261                         cmd += "000"
262                 print "TDA1002x CMD is", cmd
263
264                 self.cable_search_container.execute(cmd)
265                 tmpstr = _("Try to find used transponders in cable network.. please wait...")
266                 tmpstr += "\n\n..."
267                 self.cable_search_session = self.session.openWithCallback(self.cableTransponderSearchSessionClosed, MessageBox, tmpstr, MessageBox.TYPE_INFO)
268
269 class ScanSetup(ConfigListScreen, Screen, CableTransponderSearchSupport):
270         def __init__(self, session):
271                 Screen.__init__(self, session)
272
273                 self.updateSatList()
274                 self.service = session.nav.getCurrentService()
275                 self.feinfo = None
276                 frontendData = None
277                 if self.service is not None:
278                         self.feinfo = self.service.frontendInfo()
279                         frontendData = self.feinfo and self.feinfo.getAll(True)
280                 
281                 self.createConfig(frontendData)
282
283                 del self.feinfo
284                 del self.service
285
286                 self["actions"] = NumberActionMap(["SetupActions"],
287                 {
288                         "ok": self.keyGo,
289                         "cancel": self.keyCancel,
290                 }, -2)
291
292                 self.statusTimer = eTimer()
293                 self.statusTimer.timeout.get().append(self.updateStatus)
294                 #self.statusTimer.start(5000, True)
295
296                 self.list = []
297                 ConfigListScreen.__init__(self, self.list)
298                 self.createSetup()
299
300                 self["introduction"] = Label(_("Press OK to start the scan"))
301
302         def run(self):
303                 self.keyGo()
304
305         def updateSatList(self):
306                 self.satList = []
307                 for slot in nimmanager.nim_slots:
308                         if slot.isCompatible("DVB-S"):
309                                 self.satList.append(nimmanager.getSatListForNim(slot.slot))
310                         else:
311                                 self.satList.append(None)
312
313         def createSetup(self):
314                 self.list = []
315                 self.multiscanlist = []
316                 index_to_scan = int(self.scan_nims.value)
317                 print "ID: ", index_to_scan
318
319                 self.tunerEntry = getConfigListEntry(_("Tuner"), self.scan_nims)
320                 self.list.append(self.tunerEntry)
321                 
322                 if self.scan_nims == [ ]:
323                         return
324                 
325                 self.typeOfScanEntry = None
326                 self.systemEntry = None
327                 nim = nimmanager.nim_slots[index_to_scan]
328                 if nim.isCompatible("DVB-S"):
329                         self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.scan_type)
330                         self.list.append(self.typeOfScanEntry)
331                 elif nim.isCompatible("DVB-C"):
332                         self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.scan_typecable)
333                         self.list.append(self.typeOfScanEntry)
334                 elif nim.isCompatible("DVB-T"):
335                         self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.scan_typeterrestrial)
336                         self.list.append(self.typeOfScanEntry)
337
338                 if nim.isCompatible("DVB-S"):
339                         if self.scan_type.value == "single_transponder":
340                                 self.updateSatList()
341                                 if nim.isCompatible("DVB-S2"):
342                                         self.systemEntry = getConfigListEntry(_('System'), self.scan_sat.system)
343                                         self.list.append(self.systemEntry)
344                                 else:
345                                         # downgrade to dvb-s, in case a -s2 config was active
346                                         self.scan_sat.system.value = "dvb-s"
347                                 self.list.append(getConfigListEntry(_('Satellite'), self.scan_satselection[index_to_scan]))
348                                 self.list.append(getConfigListEntry(_('Frequency'), self.scan_sat.frequency))
349                                 self.list.append(getConfigListEntry(_('Inversion'), self.scan_sat.inversion))
350                                 self.list.append(getConfigListEntry(_('Symbol Rate'), self.scan_sat.symbolrate))
351                                 self.list.append(getConfigListEntry(_("Polarity"), self.scan_sat.polarization))
352                                 if self.scan_sat.system.value == "dvb-s":
353                                         self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec))
354                                 elif self.scan_sat.system.value == "dvb-s2":
355                                         self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
356                                         self.list.append(getConfigListEntry(_('Modulation'), self.scan_sat.modulation))
357                                 self.list.append(getConfigListEntry(_("Network scan"), self.scan_networkScan))
358                         elif self.scan_type.value == "single_satellite":
359                                 self.updateSatList()
360                                 print self.scan_satselection[index_to_scan]
361                                 self.list.append(getConfigListEntry(_("Satellite"), self.scan_satselection[index_to_scan]))
362                                 self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices))
363                         elif self.scan_type.value == "multisat":
364                                 # if (norotor)
365                                 tlist = []
366                                 SatList = nimmanager.getSatListForNim(index_to_scan)
367                                 self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices))
368                                 for x in SatList:
369                                         if self.Satexists(tlist, x[0]) == 0:
370                                                 tlist.append(x[0])
371                                                 sat = ConfigEnableDisable(default = True)
372                                                 configEntry = getConfigListEntry(nimmanager.getSatDescription(x[0]), sat)
373                                                 self.list.append(configEntry)
374                                                 self.multiscanlist.append((x[0], sat))
375                                 # if (rotor):
376                            # for sat in nimmanager.satList:
377                                 #       self.list.append(getConfigListEntry(sat[1], self.scan_scansat[sat[0]]))
378                 elif nim.isCompatible("DVB-C"):
379                         if self.scan_typecable.value == "single_transponder":
380                                 self.list.append(getConfigListEntry(_("Frequency"), self.scan_cab.frequency))
381                                 self.list.append(getConfigListEntry(_("Inversions"), self.scan_cab.inversion))
382                                 self.list.append(getConfigListEntry(_("Symbol Rate"), self.scan_cab.symbolrate))
383                                 self.list.append(getConfigListEntry(_("Modulation"), self.scan_cab.modulation))
384                                 self.list.append(getConfigListEntry(_("FEC"), self.scan_cab.fec))
385                                 self.list.append(getConfigListEntry(_("Network scan"), self.scan_networkScan))
386                         elif self.scan_typecable.value == "complete":
387                                 self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices))
388                 elif nim.isCompatible("DVB-T"):
389                         if self.scan_typeterrestrial.value == "single_transponder":
390                                 self.list.append(getConfigListEntry(_("Frequency"), self.scan_ter.frequency))
391                                 self.list.append(getConfigListEntry(_("Inversion"), self.scan_ter.inversion))
392                                 self.list.append(getConfigListEntry(_("Bandwidth"), self.scan_ter.bandwidth))
393                                 self.list.append(getConfigListEntry(_("Code rate high"), self.scan_ter.fechigh))
394                                 self.list.append(getConfigListEntry(_("Code rate low"), self.scan_ter.feclow))
395                                 self.list.append(getConfigListEntry(_("Modulation"), self.scan_ter.modulation))
396                                 self.list.append(getConfigListEntry(_("Transmission mode"), self.scan_ter.transmission))
397                                 self.list.append(getConfigListEntry(_("Guard interval mode"), self.scan_ter.guard))
398                                 self.list.append(getConfigListEntry(_("Hierarchy mode"), self.scan_ter.hierarchy))
399                                 self.list.append(getConfigListEntry(_("Network scan"), self.scan_networkScan))
400                         elif self.scan_typeterrestrial.value == "complete":
401                                 self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices))
402
403 #               if (nim.isCompatible("DVB-S") and self.scan_type.type == "single_transponder") or \
404 #                       (nim.isCompatbile("DVB-C") and self.scan_typecable.type == "single_transponder") or \
405 #                       (nim.isCompatible("DVB-T") and self.scan_typeterrestrial.type == "single_transponder"):
406 #                               self.configElementSNR = getConfigListEntry(_("SNR"), self.scan_snr)
407 #                               self.list.append(self.configElementSNR)
408 #                               self.configElementACG = getConfigListEntry(_("AGC"), self.scan_agc)
409 #                               self.list.append(self.configElementACG)
410 #                               self.configElementBER = getConfigListEntry(_("BER"), self.scan_ber)
411 #                               self.list.append(self.configElementBER)
412 #                               self.statusTimer.start(500, False)
413 #               else:
414 #                       self.statusTimer.stop()
415
416                 self["config"].list = self.list
417                 self["config"].l.setList(self.list)
418
419         def Satexists(self, tlist, pos):
420                 for x in tlist:
421                         if x == pos:
422                                 return 1
423                 return 0
424
425         def newConfig(self):
426                 cur = self["config"].getCurrent()
427                 print "cur is", cur
428                 if cur == self.typeOfScanEntry or \
429                         cur == self.tunerEntry or \
430                         cur == self.systemEntry:
431                         self.createSetup()
432
433         def createConfig(self, frontendData):
434                                                            #("Type", frontendData["system"], TYPE_TEXT),
435                                            #("Modulation", frontendData["modulation"], TYPE_TEXT),
436                                            #("Orbital position", frontendData["orbital_position"], TYPE_VALUE_DEC),
437                                            #("Frequency", frontendData["frequency"], TYPE_VALUE_DEC),
438                                            #("Symbolrate", frontendData["symbol_rate"], TYPE_VALUE_DEC),
439                                            #("Polarization", frontendData["polarization"], TYPE_TEXT),
440                                            #("Inversion", frontendData["inversion"], TYPE_TEXT),
441                                            #("FEC inner", frontendData["fec_inner"], TYPE_TEXT),
442                                                 #)
443                 #elif frontendData["tuner_type"] == "DVB-C":
444                         #return ( ("NIM", ['A', 'B', 'C', 'D'][frontendData["tuner_number"]], TYPE_TEXT),
445                                            #("Type", frontendData["tuner_type"], TYPE_TEXT),
446                                            #("Frequency", frontendData["frequency"], TYPE_VALUE_DEC),
447                                            #("Symbolrate", frontendData["symbol_rate"], TYPE_VALUE_DEC),
448                                            #("Modulation", frontendData["modulation"], TYPE_TEXT),
449                                            #("Inversion", frontendData["inversion"], TYPE_TEXT),
450                         #                  ("FEC inner", frontendData["fec_inner"], TYPE_TEXT),
451                                                 #)
452                 #elif frontendData["tuner_type"] == "DVB-T":
453                         #return ( ("NIM", ['A', 'B', 'C', 'D'][frontendData["tuner_number"]], TYPE_TEXT),
454                                            #("Type", frontendData["tuner_type"], TYPE_TEXT),
455                                            #("Frequency", frontendData["frequency"], TYPE_VALUE_DEC),
456                                            #("Inversion", frontendData["inversion"], TYPE_TEXT),
457                                            #("Bandwidth", frontendData["bandwidth"], TYPE_VALUE_DEC),
458                                            #("CodeRateLP", frontendData["code_rate_lp"], TYPE_TEXT),
459                                            #("CodeRateHP", frontendData["code_rate_hp"], TYPE_TEXT),
460                                            #("Constellation", frontendData["constellation"], TYPE_TEXT),
461                                            #("Transmission Mode", frontendData["transmission_mode"], TYPE_TEXT),
462                                            #("Guard Interval", frontendData["guard_interval"], TYPE_TEXT),
463                                            #("Hierarchy Inform.", frontendData["hierarchy_information"], TYPE_TEXT),
464                         defaultSat = { "orbpos": 192, "system": "dvb-s", "frequency": 11836, "inversion": "auto", "symbolrate": 27500, "polarization": "horizontal", "fec": "auto", "fec_s2": "9_10", "modulation": "qpsk" }
465                         defaultCab = {"frequency": 466, "inversion": "auto", "modulation": "64qam", "fec": "auto", "symbolrate": 6900}
466                         if frontendData is not None:
467                                 ttype = frontendData.get("tuner_type", "UNKNOWN")
468                                 if ttype == "DVB-S":
469                                         defaultSat["system"] = {"DVB-S": "dvb-s", "DVB-S2": "dvb-s2"}[frontendData.get("system", "DVB-S")]
470                                         defaultSat["frequency"] = int(frontendData.get("frequency", 0) / 1000)
471                                         defaultSat["inversion"] = {"INVERSION_OFF": "off", "INVERSION_ON": "on", "INVERSION_AUTO": "auto"}[frontendData.get("inversion", "INVERSION_AUTO")]
472                                         defaultSat["symbolrate"] = int(frontendData.get("symbol_rate", 0) / 1000)
473                                         defaultSat["polarization"] = {"HORIZONTAL": "horizontal", "VERTICAL": "vertical", "CIRCULAR_LEFT": "circular_left", "CIRCULAR_RIGHT": "circular_right", "UNKNOWN": None}[frontendData.get("polarization", "HORIZONTAL")]
474                                         
475                                         if frontendData.get("system", "DVB-S") == "DVB-S2":
476                                                 defaultSat["fec_s2"] = {"FEC_1_2": "1_2", "FEC_2_3": "2_3", "FEC_3_4": "3_4", "FEC_4_5": "4_5", "FEC_5_6": "5_6", "FEC_7_8": "7_8", "FEC_8_9": "8_9", "FEC_9_10": "9_10"} \
477                                                                                         [frontendData.get("fec_inner", "FEC_AUTO")]
478                                         else:
479                                                 defaultSat["fec"] = {"FEC_AUTO": "auto", "FEC_1_2": "1_2", "FEC_2_3": "2_3", "FEC_3_4": "3_4", "FEC_5_6": "5_6", "FEC_7_8": "7_8", "FEC_NONE": "none"} \
480                                                         [frontendData.get("fec_inner", "FEC_AUTO")]
481
482                                         defaultSat["modulation"] = {"QPSK": "qpsk", "8PSK": "8psk"}[frontendData.get("modulation", "QPSK")]
483                                         defaultSat["orbpos"] = frontendData.get("orbital_position", 0)
484                                 elif ttype == "DVB-C":
485                                         defaultCab["frequency"] = int(frontendData.get("frequency", 0) / 1000)
486                                         defaultCab["symbolrate"] = int(frontendData.get("symbol_rate", 0) / 1000)
487                                         defaultCab["inversion"] = {"INVERSION_OFF": "off", "INVERSION_ON": "on", "INVERSION_AUTO": "auto"}[frontendData.get("inversion", "INVERSION_AUTO")]
488                                         defaultCab["fec"] = {"FEC_AUTO": "auto", "FEC_1_2": "1_2", "FEC_2_3": "2_3", "FEC_3_4": "3_4", "FEC_5_6": "5_6", "FEC_7_8": "7_8", "FEC_8_9": "8_9", "FEC_NONE": "none"}[frontendData.get("fec_inner", "FEC_AUTO")]
489                                         defaultCab["modulation"] = {"QAM_AUTO": "auto", "QAM_16": "16qam", "QAM_32": "32qam", "QAM_64": "64qam", "QAM_128": "128qam", "QAM_256": "256qam"}[frontendData.get("modulation", "QAM_16")]
490
491                         self.scan_sat = ConfigSubsection()
492                         self.scan_cab = ConfigSubsection()
493                         self.scan_ter = ConfigSubsection()
494
495                         self.scan_type = ConfigSelection(default = "single_transponder", choices = [("single_transponder", _("Single transponder")), ("single_satellite", _("Single satellite")), ("multisat", _("Multisat"))])
496                         self.scan_typecable = ConfigSelection(default = "single_transponder", choices = [("single_transponder", _("Single transponder")), ("complete", _("Complete"))])
497                         self.scan_typeterrestrial = ConfigSelection(default = "single_transponder", choices = [("single_transponder", _("Single transponder")), ("complete", _("Complete"))])
498                         self.scan_clearallservices = ConfigSelection(default = "no", choices = [("no", _("no")), ("yes", _("yes")), ("yes_hold_feeds", _("yes (keep feeds)"))])
499                         self.scan_networkScan = ConfigYesNo(default = False)
500
501                         nim_list = []
502                         # collect all nims which are *not* set to "nothing"
503                         for n in nimmanager.nim_slots:
504                                 if n.config_mode != "nothing":
505                                         nim_list.append((str(n.slot), n.friendly_full_description))
506
507                         self.scan_nims = ConfigSelection(choices = nim_list)
508
509                         # status
510                         self.scan_snr = ConfigSlider()
511                         self.scan_snr.enabled = False
512                         self.scan_agc = ConfigSlider()
513                         self.scan_agc.enabled = False
514                         self.scan_ber = ConfigSlider()
515                         self.scan_ber.enabled = False
516
517                         # sat
518                         self.scan_sat.system = ConfigSelection(default = defaultSat["system"], choices = [("dvb-s", _("DVB-S")), ("dvb-s2", _("DVB-S2"))])
519                         self.scan_sat.frequency = ConfigInteger(default = defaultSat["frequency"], limits = (1, 99999))
520                         self.scan_sat.inversion = ConfigSelection(default = defaultSat["inversion"], choices = [("off", _("off")), ("on", _("on")), ("auto", _("Auto"))])
521                         self.scan_sat.symbolrate = ConfigInteger(default = defaultSat["symbolrate"], limits = (1, 99999))
522                         self.scan_sat.polarization = ConfigSelection(default = defaultSat["polarization"], choices = [("horizontal", _("horizontal")), ("vertical", _("vertical")),  ("circular_left", _("circular left")), ("circular_right", _("circular right"))])
523                         self.scan_sat.fec = ConfigSelection(default = defaultSat["fec"], choices = [("auto", _("Auto")), ("1_2", "1/2"), ("2_3", "2/3"), ("3_4", "3/4"), ("5_6", "5/6"), ("7_8", "7/8"), ("none", _("None"))])
524                         self.scan_sat.fec_s2 = ConfigSelection(default = defaultSat["fec_s2"], choices = [("1_2", "1/2"), ("2_3", "2/3"), ("3_4", "3/4"), ("3_5", "3/5"), ("4_5", "4/5"), ("5_6", "5/6"), ("7_8", "7/8"), ("8_9", "8/9"), ("9_10", "9/10")])
525                         self.scan_sat.modulation = ConfigSelection(default = defaultSat["modulation"], choices = [("qpsk", "QPSK"), ("8psk", "8PSK")])
526
527                         # cable
528                         self.scan_cab.frequency = ConfigInteger(default = defaultCab["frequency"], limits = (50, 999))
529                         self.scan_cab.inversion = ConfigSelection(default = defaultCab["inversion"], choices = [("off", _("off")), ("on", _("on")), ("auto", _("Auto"))])
530                         self.scan_cab.modulation = ConfigSelection(default = defaultCab["modulation"], choices = [("16qam", "16-QAM"), ("32qam", "32-QAM"), ("64qam", "64-QAM"), ("128qam", "128-QAM"), ("256qam", "256-QAM")])
531                         self.scan_cab.fec = ConfigSelection(default = defaultCab["fec"], choices = [("auto", _("Auto")), ("1_2", "1/2"), ("2_3", "2/3"), ("3_4", "3/4"), ("5_6", "5/6"), ("7_8", "7/8"), ("8_9", "8/9"), ("none", _("None"))])
532                         self.scan_cab.symbolrate = ConfigInteger(default = defaultCab["symbolrate"], limits = (1, 99999))
533
534                         # terrestial
535                         self.scan_ter.frequency = ConfigInteger(default = 466000, limits = (50000, 999000))
536                         self.scan_ter.inversion = ConfigSelection(default = "auto", choices = [("off", _("off")), ("on", _("on")), ("auto", _("Auto"))])
537                         # WORKAROUND: we can't use BW-auto
538                         self.scan_ter.bandwidth = ConfigSelection(default = "8MHz", choices = [("8MHz", "8MHz"), ("7MHz", "7MHz"), ("6MHz", "6MHz")])
539                         #, ("auto", _("Auto"))))
540                         self.scan_ter.fechigh = ConfigSelection(default = "auto", choices = [("1_2", "1/2"), ("2_3", "2/3"), ("3_4", "3/4"), ("5_6", "5/6"), ("7_8", "7/8"), ("auto", _("Auto"))])
541                         self.scan_ter.feclow = ConfigSelection(default = "auto", choices = [("1_2", "1/2"), ("2_3", "2/3"), ("3_4", "3/4"), ("5_6", "5/6"), ("7_8", "7/8"), ("auto", _("Auto"))])
542                         self.scan_ter.modulation = ConfigSelection(default = "auto", choices = [("qpsk", "QPSK"), ("qam16", "QAM16"), ("qam64", "QAM64"), ("auto", _("Auto"))])
543                         self.scan_ter.transmission = ConfigSelection(default = "auto", choices = [("2k", "2K"), ("8k", "8K"), ("auto", _("Auto"))])
544                         self.scan_ter.guard = ConfigSelection(default = "auto", choices = [("1_32", "1/32"), ("1_16", "1/16"), ("1_8", "1/8"), ("1_4", "1/4"), ("auto", _("Auto"))])
545                         self.scan_ter.hierarchy = ConfigSelection(default = "auto", choices = [("none", _("None")), ("1", "1"), ("2", "2"), ("4", "4"), ("auto", _("Auto"))])
546
547                         self.scan_scansat = {}
548                         for sat in nimmanager.satList:
549                                 #print sat[1]
550                                 self.scan_scansat[sat[0]] = ConfigYesNo(default = False)
551
552                         self.scan_satselection = []
553                         for slot in nimmanager.nim_slots:
554                                 if slot.isCompatible("DVB-S"):
555                                         self.scan_satselection.append(getConfigSatlist(int(defaultSat["orbpos"]), self.satList[slot.slot]))
556                                 else:
557                                         self.scan_satselection.append(None)
558
559                         return True
560
561         def keyLeft(self):
562                 ConfigListScreen.keyLeft(self)
563                 self.newConfig()
564
565         def keyRight(self):
566                 ConfigListScreen.keyRight(self)
567                 self.newConfig()
568
569         def updateStatus(self):
570                 print "updatestatus"
571
572         fecmap = { "auto": 0,
573                            "1_2": 1,
574                            "2_3": 2,
575                            "3_4": 3,
576                            "5_6": 4,
577                            "7_8": 5,
578                            "8_9": 6,
579                            "3_5": 7,
580                            "4_5": 8,
581                            "9_10": 9,
582                            "none": 15
583                            }
584
585         def addSatTransponder(self, tlist, frequency, symbol_rate, polarisation, fec, inversion, orbital_position, system, modulation):
586                 print "Add Sat: frequ: " + str(frequency) + " symbol: " + str(symbol_rate) + " pol: " + str(polarisation) + " fec: " + str(self.fecmap[fec]) + " inversion: " + str(inversion) + " modulation: " + str(modulation) + " system: " + str(system)
587                 print "orbpos: " + str(orbital_position)
588                 parm = eDVBFrontendParametersSatellite()
589                 if modulation == 1:
590                         parm.modulation = 2 # eDVBFrontendParametersSatellite.Modulation.8PSK
591                 else:
592                         parm.modulation = 1 # eDVBFrontendParametersSatellite.Modulation.QPSK
593                 parm.system = system
594                 parm.frequency = frequency * 1000
595                 parm.symbol_rate = symbol_rate * 1000
596                 parm.polarisation = polarisation
597                 parm.fec = self.fecmap[fec]
598                 parm.inversion = inversion
599                 parm.orbital_position = int(orbital_position)
600                 tlist.append(parm)
601
602         def addCabTransponder(self, tlist, frequency, symbol_rate, modulation, fec, inversion):
603                 print "Add Cab: frequ: " + str(frequency) + " symbol: " + str(symbol_rate) + " pol: " + str(modulation) + " fec: " + str(fec) + " inversion: " + str(inversion)
604                 parm = eDVBFrontendParametersCable()
605                 parm.frequency = frequency * 1000
606                 parm.symbol_rate = symbol_rate * 1000
607                 parm.modulation = modulation
608                 parm.fec = self.fecmap[fec]
609                 parm.inversion = inversion
610                 tlist.append(parm)
611
612         def addTerTransponder(self, tlist, *args, **kwargs):
613                 tlist.append(buildTerTransponder(*args, **kwargs))
614
615         def keyGo(self):
616                 tlist = []
617                 flags = None
618                 extFlags = True
619                 
620                 startScan = True
621                 index_to_scan = int(self.scan_nims.value)
622                 
623                 if self.scan_nims == [ ]:
624                         self.session.open(MessageBox, _("No tuner is enabled!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR)
625                         return
626
627                 nim = nimmanager.nim_slots[index_to_scan]
628                 print "nim", nim.slot
629                 if nim.isCompatible("DVB-S"):
630                         print "is compatible with DVB-S"
631                         if self.scan_type.value == "single_transponder":
632                                 # these lists are generated for each tuner, so this has work.
633                                 assert len(self.satList) > index_to_scan
634                                 assert len(self.scan_satselection) > index_to_scan
635                                 
636                                 nimsats = self.satList[index_to_scan]
637                                 selsatidx = self.scan_satselection[index_to_scan].index
638
639                                 # however, the satList itself could be empty. in that case, "index" is 0 (for "None").
640                                 if len(nimsats):
641                                         orbpos = nimsats[selsatidx][0]
642                                         if self.scan_sat.system.value == "dvb-s":
643                                                 fec = self.scan_sat.fec.value
644                                         else:
645                                                 fec = self.scan_sat.fec_s2.value
646                                         print "add sat transponder"
647                                         self.addSatTransponder(tlist, self.scan_sat.frequency.value,
648                                                                 self.scan_sat.symbolrate.value,
649                                                                 self.scan_sat.polarization.index,
650                                                                 fec,
651                                                                 self.scan_sat.inversion.index,
652                                                                 orbpos,
653                                                                 self.scan_sat.system.index,
654                                                                 self.scan_sat.modulation.index)
655                                 flags = self.scan_networkScan.value and eComponentScan.scanNetworkSearch or 0
656                                 extFlags = False
657                         elif self.scan_type.value == "single_satellite":
658                                 sat = self.satList[index_to_scan][self.scan_satselection[index_to_scan].index]
659                                 getInitialTransponderList(tlist, sat[0])
660                         elif self.scan_type.value == "multisat":
661                                 SatList = nimmanager.getSatListForNim(index_to_scan)
662                                 for x in self.multiscanlist:
663                                         if x[1].value:
664                                                 print "   " + str(x[0])
665                                                 getInitialTransponderList(tlist, x[0])
666
667                 elif nim.isCompatible("DVB-C"):
668                         if self.scan_typecable.value == "single_transponder":
669                                 fec = self.scan_cab.fec.value
670                                 self.addCabTransponder(tlist, self.scan_cab.frequency.value,
671                                                                                           self.scan_cab.symbolrate.value,
672                                                                                           self.scan_cab.modulation.index + 1,
673                                                                                           fec,
674                                                                                           self.scan_cab.inversion.index)
675                                 flags = self.scan_networkScan.value and eComponentScan.scanNetworkSearch or 0
676                                 extFlags = False
677                         elif self.scan_typecable.value == "complete":
678                                 if config.Nims[index_to_scan].cable.scan_type.value == "provider":
679                                         getInitialCableTransponderList(tlist, index_to_scan)
680                                 else:
681                                         startScan = False
682
683                 elif nim.isCompatible("DVB-T"):
684                         if self.scan_typeterrestrial.value == "single_transponder":
685                                 self.addTerTransponder(tlist,
686                                                 self.scan_ter.frequency.value * 1000,
687                                                 inversion = self.scan_ter.inversion.index,
688                                                 bandwidth = self.scan_ter.bandwidth.index,
689                                                 fechigh = self.scan_ter.fechigh.index,
690                                                 feclow = self.scan_ter.feclow.index,
691                                                 modulation = self.scan_ter.modulation.index,
692                                                 transmission = self.scan_ter.transmission.index,
693                                                 guard = self.scan_ter.guard.index,
694                                                 hierarchy = self.scan_ter.hierarchy.index)
695                                 flags = self.scan_networkScan.value and eComponentScan.scanNetworkSearch or 0
696                                 extFlags = False
697                         elif self.scan_typeterrestrial.value == "complete":
698                                 getInitialTerrestrialTransponderList(tlist, nimmanager.getTerrestrialDescription(index_to_scan))
699
700                 if flags is None:
701                         flags = eComponentScan.scanNetworkSearch
702
703                 if extFlags:
704                         tmp = self.scan_clearallservices.value
705                         if tmp == "yes":
706                                 flags |= eComponentScan.scanRemoveServices
707                         elif tmp == "yes_hold_feeds":
708                                 flags |= eComponentScan.scanRemoveServices
709                                 flags |= eComponentScan.scanDontRemoveFeeds
710
711                 for x in self["config"].list:
712                         x[1].save()
713
714                 if startScan:
715                         self.startScan(tlist, flags, index_to_scan)
716                 else:
717                         self.flags = flags
718                         self.feid = index_to_scan
719                         self.tlist = []
720                         self.startCableTransponderSearch(self.feid)
721
722         def setCableTransponderSearchResult(self, tlist):
723                 self.tlist = tlist
724
725         def cableTransponderSearchFinished(self):
726                 self.startScan(self.tlist, self.flags, self.feid)
727
728         def startScan(self, tlist, flags, feid):
729                 if len(tlist):
730                         # flags |= eComponentScan.scanSearchBAT
731                         self.session.open(ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags}])
732                 else:
733                         self.session.open(MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR)
734
735         def keyCancel(self):
736                 for x in self["config"].list:
737                         x[1].cancel()
738                 self.close()
739
740 class ScanSimple(ConfigListScreen, Screen, CableTransponderSearchSupport):
741         def getNetworksForNim(self, nim):
742                 if nim.isCompatible("DVB-S"):
743                         networks = nimmanager.getSatListForNim(nim.slot)
744 # the original code took "loopthrough" etc. into account. Do we need this?
745 #                       if nimmanager.getNimConfigMode(1) in ["loopthrough", "satposdepends", "equal", "nothing"]:
746 #                               return False
747 #                       sec = eDVBSatelliteEquipmentControl.getInstance()
748 #                       if sec is not None:
749 #                               exclusive_satellites = sec.get_exclusive_satellites(0,1)
750 #                               if len(exclusive_satellites) == 2:
751 #                                       return False
752 #                               idx = exclusive_satellites[0]+1
753 #                               exclusive_nim_sats = exclusive_satellites[idx+1:idx+1+exclusive_satellites[idx]]
754 #                               if len(exclusive_nim_sats):
755 #                                       return True
756                 elif not nim.empty:
757                         networks = [ nim.type ] # "DVB-C" or "DVB-T". TODO: seperate networks for different C/T tuners, if we want to support that.
758                 else:
759                         # empty tuners provide no networks.
760                         networks = [ ]
761                 return networks
762
763         def __init__(self, session):
764                 Screen.__init__(self, session)
765
766                 self["actions"] = ActionMap(["SetupActions"],
767                 {
768                         "ok": self.keyGo,
769                         "cancel": self.keyCancel,
770                 }, -2)
771
772                 self.list = []
773                 tlist = []
774
775                 known_networks = [ ]
776                 nims_to_scan = [ ]
777
778                 for nim in nimmanager.nim_slots:
779                         # collect networks provided by this tuner
780
781                         need_scan = False
782                         networks = self.getNetworksForNim(nim)
783                         
784                         print "nim %d provides" % nim.slot, networks
785                         print "known:", known_networks
786
787                         # we only need to scan on the first tuner which provides a network.
788                         # this gives the first tuner for each network priority for scanning.
789                         for x in networks:
790                                 if x not in known_networks:
791                                         need_scan = True
792                                         print x, "not in ", known_networks
793                                         known_networks.append(x)
794
795                         if need_scan:
796                                 nims_to_scan.append(nim)
797
798                 # we save the config elements to use them on keyGo
799                 self.nim_enable = [ ]
800
801                 if len(nims_to_scan):
802                         self.scan_clearallservices = ConfigSelection(default = "yes", choices = [("no", _("no")), ("yes", _("yes")), ("yes_hold_feeds", _("yes (keep feeds)"))])
803                         self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices))
804
805                         for nim in nims_to_scan:
806                                 nimconfig = ConfigYesNo(default = True)
807                                 nimconfig.nim_index = nim.slot
808                                 self.nim_enable.append(nimconfig)
809                                 self.list.append(getConfigListEntry(_("Scan ") + nim.slot_name + " (" + nim.friendly_type + ")", nimconfig))
810
811                 ConfigListScreen.__init__(self, self.list)
812                 self["header"] = Label(_("Automatic Scan"))
813                 self["footer"] = Label(_("Press OK to scan"))
814
815         def run(self):
816                 self.keyGo()
817
818         def keyGo(self):
819                 self.scanList = []
820                 self.known_networks = set()
821                 self.nim_iter=0
822                 self.buildTransponderList()
823
824         def buildTransponderList(self): # this method is called multiple times because of asynchronous stuff
825                 APPEND_NOW = 0
826                 SEARCH_CABLE_TRANSPONDERS = 1
827                 action = APPEND_NOW
828
829                 n = self.nim_iter < len(self.nim_enable) and self.nim_enable[self.nim_iter] or None
830                 self.nim_iter += 1
831                 if n and n.value: # check if nim is enabled
832                         flags = 0
833                         nim = nimmanager.nim_slots[n.nim_index]
834                         networks = set(self.getNetworksForNim(nim))
835
836                         # don't scan anything twice
837                         networks.discard(self.known_networks)
838
839                         tlist = [ ]
840                         if nim.isCompatible("DVB-S"):
841                                 # get initial transponders for each satellite to be scanned
842                                 for sat in networks:
843                                         getInitialTransponderList(tlist, sat[0])
844                         elif nim.isCompatible("DVB-C"):
845                                 if config.Nims[nim.slot].cable.scan_type.value == "provider":
846                                         getInitialCableTransponderList(tlist, nim.slot)
847                                 else:
848                                         action = SEARCH_CABLE_TRANSPONDERS
849                         elif nim.isCompatible("DVB-T"):
850                                 getInitialTerrestrialTransponderList(tlist, nimmanager.getTerrestrialDescription(nim.slot))
851                         else:
852                                 assert False
853
854                         flags |= eComponentScan.scanNetworkSearch #FIXMEEE.. use flags from cables / satellites / terrestrial.xml
855                         tmp = self.scan_clearallservices.value
856                         if tmp == "yes":
857                                 flags |= eComponentScan.scanRemoveServices
858                         elif tmp == "yes_hold_feeds":
859                                 flags |= eComponentScan.scanRemoveServices
860                                 flags |= eComponentScan.scanDontRemoveFeeds
861
862                         if action == APPEND_NOW:
863                                 self.scanList.append({"transponders": tlist, "feid": nim.slot, "flags": flags})
864                         elif action == SEARCH_CABLE_TRANSPONDERS:
865                                 self.flags = flags
866                                 self.feid = nim.slot
867                                 self.startCableTransponderSearch(nim.slot)
868                                 return
869                         else:
870                                 assert False
871                         self.buildTransponderList() # recursive call of this function !!!
872                         return
873                 # when we are here, then the recursion is finished and all enabled nims are checked
874                 # so we now start the real transponder scan
875                 self.startScan(self.scanList)
876
877         def startScan(self, scanList):
878                 if len(scanList):
879                         self.session.open(ServiceScan, scanList = scanList)
880                 else:
881                         self.session.open(MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR)
882
883         def setCableTransponderSearchResult(self, tlist):
884                 self.scanList.append({"transponders": tlist, "feid": self.feid, "flags": self.flags})
885
886         def cableTransponderSearchFinished(self):
887                 self.buildTransponderList()
888
889         def keyCancel(self):
890                 self.close()
891
892         def Satexists(self, tlist, pos):
893                 for x in tlist:
894                         if x == pos:
895                                 return 1
896                 return 0
897