ScanSetup: Return the TerrestrialDescription in list and only when something is conne...
[openblackhole/openblackhole-enigma2.git] / lib / python / Screens / ScanSetup.py
1 from Screen import Screen
2 from ServiceScan import ServiceScan
3 from Components.config import config, ConfigSubsection, ConfigSelection, \
4         ConfigYesNo, ConfigInteger, getConfigListEntry, ConfigSlider, ConfigEnableDisable
5 from Components.ActionMap import NumberActionMap, ActionMap
6 from Components.Sources.StaticText import StaticText
7 from Components.SystemInfo import SystemInfo
8 from Components.ConfigList import ConfigListScreen
9 from Components.NimManager import nimmanager, getConfigSatlist
10 from Components.Label import Label
11 from Tools.HardwareInfo import HardwareInfo
12 from Tools.Transponder import getChannelNumber, supportedChannels, channel2frequency
13 from Screens.InfoBar import InfoBar
14 from Screens.MessageBox import MessageBox
15 from enigma import eTimer, eDVBFrontendParametersSatellite, eComponentScan, \
16         eDVBSatelliteEquipmentControl, eDVBFrontendParametersTerrestrial, \
17         eDVBFrontendParametersCable, eConsoleAppContainer, eDVBResourceManager
18
19 def buildTerTransponder(frequency,
20                 inversion=2, bandwidth = 7000000, fechigh = 6, feclow = 6,
21                 modulation = 2, transmission = 2, guard = 4,
22                 hierarchy = 4, system = 0, plpid = 0):
23 #       print "freq", frequency, "inv", inversion, "bw", bandwidth, "fech", fechigh, "fecl", feclow, "mod", modulation, "tm", transmission, "guard", guard, "hierarchy", hierarchy
24         parm = eDVBFrontendParametersTerrestrial()
25         parm.frequency = frequency
26         parm.inversion = inversion
27         parm.bandwidth = bandwidth
28         parm.code_rate_HP = fechigh
29         parm.code_rate_LP = feclow
30         parm.modulation = modulation
31         parm.transmission_mode = transmission
32         parm.guard_interval = guard
33         parm.hierarchy = hierarchy
34         parm.system = system
35         parm.plpid = plpid
36         return parm
37
38 def getInitialTransponderList(tlist, pos):
39         list = nimmanager.getTransponders(pos)
40         for x in list:
41                 if x[0] == 0:           #SAT
42                         parm = eDVBFrontendParametersSatellite()
43                         parm.frequency = x[1]
44                         parm.symbol_rate = x[2]
45                         parm.polarisation = x[3]
46                         parm.fec = x[4]
47                         parm.inversion = x[7]
48                         parm.orbital_position = pos
49                         parm.system = x[5]
50                         parm.modulation = x[6]
51                         parm.rolloff = x[8]
52                         parm.pilot = x[9]
53                         tlist.append(parm)
54
55 def getInitialCableTransponderList(tlist, nim):
56         list = nimmanager.getTranspondersCable(nim)
57         for x in list:
58                 if x[0] == 1: #CABLE
59                         parm = eDVBFrontendParametersCable()
60                         parm.frequency = x[1]
61                         parm.symbol_rate = x[2]
62                         parm.modulation = x[3]
63                         parm.fec_inner = x[4]
64                         parm.inversion = x[5]
65                         parm.system = x[6]
66                         tlist.append(parm)
67
68 def getInitialTerrestrialTransponderList(tlist, region, tsystem = eDVBFrontendParametersTerrestrial.System_DVB_T_T2, skip_t2 = False):
69         list = nimmanager.getTranspondersTerrestrial(region)
70
71         #self.transponders[self.parsedTer].append((2,freq,bw,const,crh,crl,guard,transm,hierarchy,inv))
72
73         #def buildTerTransponder(frequency, inversion = 2, bandwidth = 3, fechigh = 6, feclow = 6,
74                                 #modulation = 2, transmission = 2, guard = 4, hierarchy = 4):
75
76         for x in list:
77                 if x[0] == 2: #TERRESTRIAL
78                         if skip_t2 and x[10] == eDVBFrontendParametersTerrestrial.System_DVB_T2:
79                                 # Should be searching on TerrestrialTransponderSearchSupport.
80                                 continue
81                         if tsystem == eDVBFrontendParametersTerrestrial.System_DVB_T_T2:
82                                 parm = buildTerTransponder(x[1], x[9], x[2], x[4], x[5], x[3], x[7], x[6], x[8], x[10], x[11])
83                         elif x[10] == eDVBFrontendParametersTerrestrial.System_DVB_T_T2 or x[10] == tsystem:
84                                 parm = buildTerTransponder(x[1], x[9], x[2], x[4], x[5], x[3], x[7], x[6], x[8], tsystem, x[11])
85                         else:
86                                 continue
87                         tlist.append(parm)
88
89 cable_bands = {
90         "DVBC_BAND_EU_VHF_I" : 1 << 0,
91         "DVBC_BAND_EU_MID" : 1 << 1,
92         "DVBC_BAND_EU_VHF_III" : 1 << 2,
93         "DVBC_BAND_EU_SUPER" : 1 << 3,
94         "DVBC_BAND_EU_HYPER" : 1 << 4,
95         "DVBC_BAND_EU_UHF_IV" : 1 << 5,
96         "DVBC_BAND_EU_UHF_V" : 1 << 6,
97         "DVBC_BAND_US_LO" : 1 << 7,
98         "DVBC_BAND_US_MID" : 1 << 8,
99         "DVBC_BAND_US_HI" : 1 << 9,
100         "DVBC_BAND_US_SUPER" : 1 << 10,
101         "DVBC_BAND_US_HYPER" : 1 << 11,
102 }
103
104 cable_autoscan_nimtype = {
105 'SSH108' : 'ssh108',
106 'TT3L10' : 'tt3l10',
107 'TURBO' : 'vuplus_turbo_c'
108 }
109
110 terrestrial_autoscan_nimtype = {
111 'SSH108' : 'ssh108_t2_scan',
112 'TT3L10' : 'tt3l10_t2_scan',
113 'TURBO' : 'vuplus_turbo_t'
114 }
115
116 def GetDeviceId(filter, nim_idx):
117         tuners={}
118         device_id = 0
119         socket_id = 0
120         for nim in nimmanager.nim_slots:
121                 name_token = nim.description.split(' ')
122                 name = name_token[-1][4:-1]
123                 if name == filter:
124                         if socket_id == nim_idx:
125                                 break
126                         if device_id:
127                                 device_id = 0
128                         else:
129                                 device_id = 1
130                 socket_id += 1
131         return device_id
132
133 class CableTransponderSearchSupport:
134
135         def __init__(self):
136                 pass
137
138         def tryGetRawFrontend(self, feid):
139                 res_mgr = eDVBResourceManager.getInstance()
140                 if res_mgr:
141                         raw_channel = res_mgr.allocateRawChannel(self.feid)
142                         if raw_channel:
143                                 frontend = raw_channel.getFrontend()
144                                 if frontend:
145                                         frontend.closeFrontend() # immediate close...
146                                         del frontend
147                                         del raw_channel
148                                         return True
149                 return False
150
151         def cableTransponderSearchSessionClosed(self, *val):
152                 print "cableTransponderSearchSessionClosed, val", val
153                 self.cable_search_container.appClosed.remove(self.cableTransponderSearchClosed)
154                 self.cable_search_container.dataAvail.remove(self.getCableTransponderData)
155                 if val and len(val):
156                         if val[0]:
157                                 self.setCableTransponderSearchResult(self.__tlist)
158                         else:
159                                 self.cable_search_container.sendCtrlC()
160                                 self.setCableTransponderSearchResult(None)
161                 self.cable_search_container = None
162                 self.cable_search_session = None
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                 #prepend any remaining data from the previous call
172                 str = self.remainingdata + str
173                 #split in lines
174                 lines = str.split('\n')
175                 #'str' should end with '\n', so when splitting, the last line should be empty. If this is not the case, we received an incomplete line
176                 if len(lines[-1]):
177                         #remember this data for next time
178                         self.remainingdata = lines[-1]
179                         lines = lines[0:-1]
180                 else:
181                         self.remainingdata = ""
182
183                 for line in lines:
184                         data = line.split()
185                         if len(data):
186                                 if data[0] == 'OK' and data[4] != 'NOT_IMPLEMENTED':
187                                         print str
188                                         parm = eDVBFrontendParametersCable()
189                                         qam = { "QAM16" : parm.Modulation_QAM16,
190                                                 "QAM32" : parm.Modulation_QAM32,
191                                                 "QAM64" : parm.Modulation_QAM64,
192                                                 "QAM128" : parm.Modulation_QAM128,
193                                                 "QAM256" : parm.Modulation_QAM256 }
194                                         inv = { "INVERSION_OFF" : parm.Inversion_Off,
195                                                 "INVERSION_ON" : parm.Inversion_On,
196                                                 "INVERSION_AUTO" : parm.Inversion_Unknown }
197                                         fec = { "FEC_AUTO" : parm.FEC_Auto,
198                                                 "FEC_1_2" : parm.FEC_1_2,
199                                                 "FEC_2_3" : parm.FEC_2_3,
200                                                 "FEC_3_4" : parm.FEC_3_4,
201                                                 "FEC_5_6" : parm.FEC_5_6,
202                                                 "FEC_7_8" : parm.FEC_7_8,
203                                                 "FEC_8_9" : parm.FEC_8_9,
204                                                 "FEC_3_5" : parm.FEC_3_5,
205                                                 "FEC_4_5" : parm.FEC_4_5,
206                                                 "FEC_9_10" : parm.FEC_9_10,
207                                                 "FEC_NONE" : parm.FEC_None }
208                                         parm.frequency = int(data[1])
209                                         parm.symbol_rate = int(data[2])
210                                         parm.fec_inner = fec[data[3]]
211                                         parm.modulation = qam[data[4]]
212                                         parm.inversion = inv[data[5]]
213                                         self.__tlist.append(parm)
214                                 tmpstr = _("Try to find used transponders in cable network.. please wait...")
215                                 tmpstr += "\n\n"
216                                 tmpstr += data[1].isdigit() and "%s MHz " % (int(data[1]) / 1000.) or data[1]
217                                 tmpstr += data[0]
218                                 self.cable_search_session["text"].setText(tmpstr)
219
220         def startCableTransponderSearch(self, nim_idx):
221                 def GetCommand(nim_idx):
222                         global cable_autoscan_nimtype
223                         try:
224                                 nim_name = nimmanager.getNimName(nim_idx)
225                                 if nim_name is not None and nim_name != "":
226                                         device_id = ""
227                                         nim_name = nim_name.split(' ')[-1][4:-1]
228                                         if nim_name == 'TT3L10':
229                                                 try:
230                                                         device_id = GetDeviceId('TT3L10', nim_idx)
231                                                         device_id = "--device=%s" % (device_id)
232                                                 except Exception, err:
233                                                         print "GetCommand ->", err
234                                                         device_id = "--device=0"
235                                         command = "%s %s" % (cable_autoscan_nimtype[nim_name], device_id)
236                                         return command
237                         except Exception, err:
238                                 print "GetCommand ->", err
239                         return "tda1002x"
240
241                 if not self.tryGetRawFrontend(nim_idx):
242                         self.session.nav.stopService()
243                         if not self.tryGetRawFrontend(nim_idx):
244                                 if self.session.pipshown:
245                                         self.session.infobar.showPiP()
246                                 if not self.tryGetRawFrontend(nim_idx):
247                                         self.cableTransponderSearchFinished()
248                                         return
249                 self.__tlist = []
250                 self.remainingdata = ""
251                 self.cable_search_container = eConsoleAppContainer()
252                 self.cable_search_container.appClosed.append(self.cableTransponderSearchClosed)
253                 self.cable_search_container.dataAvail.append(self.getCableTransponderData)
254                 cableConfig = config.Nims[nim_idx].cable
255                 tunername = nimmanager.getNimName(nim_idx)
256                 try:
257                         bus = nimmanager.getI2CDevice(nim_idx)
258                         if bus is None:
259                                 print "ERROR: could not get I2C device for nim", nim_idx, "for cable transponder search"
260                                 bus = 2
261                 except:
262                         # older API
263                         if nim_idx < 2:
264                                 if HardwareInfo().get_device_name() == "dm500hd":
265                                         bus = 2
266                                 else:
267                                         bus = nim_idx
268                         else:
269                                 if nim_idx == 2:
270                                         bus = 2 # DM8000 first nim is /dev/i2c/2
271                                 else:
272                                         bus = 4 # DM8000 second num is /dev/i2c/4
273
274                 bin_name = None
275                 if tunername == "CXD1981":
276                         bin_name = "CXD1981"
277                         cmd = "cxd1978 --init --scan --verbose --wakeup --inv 2 --bus %d" % bus
278                 elif tunername.startswith("Sundtek"):
279                         bin_name = "mediaclient"
280                         cmd = "/opt/bin/mediaclient --blindscan %d" % nim_idx
281                 else:
282                         bin_name = GetCommand(nim_idx)
283                         cmd = "%(BIN_NAME)s --init --scan --verbose --wakeup --inv 2 --bus %(BUS)d" % {'BIN_NAME':bin_name, 'BUS':bus}
284
285                 if cableConfig.scan_type.value == "bands":
286                         cmd += " --scan-bands "
287                         bands = 0
288                         if cableConfig.scan_band_EU_VHF_I.value:
289                                 bands |= cable_bands["DVBC_BAND_EU_VHF_I"]
290                         if cableConfig.scan_band_EU_MID.value:
291                                 bands |= cable_bands["DVBC_BAND_EU_MID"]
292                         if cableConfig.scan_band_EU_VHF_III.value:
293                                 bands |= cable_bands["DVBC_BAND_EU_VHF_III"]
294                         if cableConfig.scan_band_EU_UHF_IV.value:
295                                 bands |= cable_bands["DVBC_BAND_EU_UHF_IV"]
296                         if cableConfig.scan_band_EU_UHF_V.value:
297                                 bands |= cable_bands["DVBC_BAND_EU_UHF_V"]
298                         if cableConfig.scan_band_EU_SUPER.value:
299                                 bands |= cable_bands["DVBC_BAND_EU_SUPER"]
300                         if cableConfig.scan_band_EU_HYPER.value:
301                                 bands |= cable_bands["DVBC_BAND_EU_HYPER"]
302                         if cableConfig.scan_band_US_LOW.value:
303                                 bands |= cable_bands["DVBC_BAND_US_LO"]
304                         if cableConfig.scan_band_US_MID.value:
305                                 bands |= cable_bands["DVBC_BAND_US_MID"]
306                         if cableConfig.scan_band_US_HIGH.value:
307                                 bands |= cable_bands["DVBC_BAND_US_HI"]
308                         if cableConfig.scan_band_US_SUPER.value:
309                                 bands |= cable_bands["DVBC_BAND_US_SUPER"]
310                         if cableConfig.scan_band_US_HYPER.value:
311                                 bands |= cable_bands["DVBC_BAND_US_HYPER"]
312                         cmd += str(bands)
313                 else:
314                         cmd += " --scan-stepsize "
315                         cmd += str(cableConfig.scan_frequency_steps.value)
316                 if cableConfig.scan_mod_qam16.value:
317                         cmd += " --mod 16"
318                 if cableConfig.scan_mod_qam32.value:
319                         cmd += " --mod 32"
320                 if cableConfig.scan_mod_qam64.value:
321                         cmd += " --mod 64"
322                 if cableConfig.scan_mod_qam128.value:
323                         cmd += " --mod 128"
324                 if cableConfig.scan_mod_qam256.value:
325                         cmd += " --mod 256"
326                 if cableConfig.scan_sr_6900.value:
327                         cmd += " --sr 6900000"
328                 if cableConfig.scan_sr_6875.value:
329                         cmd += " --sr 6875000"
330                 if cableConfig.scan_sr_ext1.value > 450:
331                         cmd += " --sr "
332                         cmd += str(cableConfig.scan_sr_ext1.value)
333                         cmd += "000"
334                 if cableConfig.scan_sr_ext2.value > 450:
335                         cmd += " --sr "
336                         cmd += str(cableConfig.scan_sr_ext2.value)
337                         cmd += "000"
338                 print bin_name, " CMD is", cmd
339
340                 self.cable_search_container.execute(cmd)
341                 tmpstr = _("Try to find used transponders in cable network.. please wait...")
342                 tmpstr += "\n\n..."
343                 self.cable_search_session = self.session.openWithCallback(self.cableTransponderSearchSessionClosed, MessageBox, tmpstr, MessageBox.TYPE_INFO)
344
345 class TerrestrialTransponderSearchSupport:
346
347         def terrestrialTransponderSearchSessionClosed(self, *val):
348                 print "TerrestrialTransponderSearchSessionClosed, val", val
349                 self.terrestrial_search_container.appClosed.remove(self.terrestrialTransponderSearchClosed)
350                 self.terrestrial_search_container.dataAvail.remove(self.getTerrestrialTransponderData)
351                 if val and len(val):
352                         if val[0]:
353                                 self.setTerrestrialTransponderSearchResult(self.__tlist)
354                         else:
355                                 self.terrestrial_search_container.sendCtrlC()
356                                 self.setTerrestrialTransponderSearchResult(None)
357                 self.terrestrial_search_container = None
358                 self.terrestrial_search_session = None
359                 self.__tlist = None
360                 self.terrestrialTransponderSearchFinished()
361
362         def terrestrialTransponderSearchClosed(self, retval):
363                 if self.terrestrial_tunerName.startswith("Sundtek"):
364                         self.terrestrial_search_session.close(True)
365                 else:
366                         self.setTerrestrialTransponderData()
367                         opt = self.terrestrialTransponderGetOpt()
368                         if opt is None:
369                                 print "terrestrialTransponderSearch finished", retval
370                                 self.terrestrial_search_session.close(True)
371                         else:
372                                 (freq, bandWidth) = opt
373                                 self.terrestrialTransponderSearch(freq, bandWidth)
374
375         def getTerrestrialTransponderData(self, str):
376                 print str
377                 if self.terrestrial_tunerName.startswith("Sundtek"):
378                         str = self.remaining_data + str
379                         lines = str.split('\n')
380                         if len(lines[-1]):
381                                 self.remaining_data = lines[-1]
382                                 lines = lines[0:-1]
383                         else:
384                                 self.remaining_data = ""
385                         for line in lines:
386                                 data = line.split()
387                                 if len(data):
388                                         if 'MODE' in data[0]:
389                                                 parm = eDVBFrontendParametersTerrestrial()
390                                                 parm.frequency = int(data[3])
391                                                 parm.bandwidth = self.terrestrialTransponderconvBandwidth_P(int(data[5]))
392                                                 parm.inversion = parm.Inversion_Unknown
393                                                 parm.code_rate_HP = parm.FEC_Auto
394                                                 parm.code_rate_LP = parm.FEC_Auto
395                                                 parm.modulation = parm.Modulation_Auto
396                                                 parm.transmission_mode = parm.TransmissionMode_Auto
397                                                 parm.guard_interval = parm.GuardInterval_Auto
398                                                 parm.hierarchy = parm.Hierarchy_Auto
399                                                 parm.system = 'DVB-T2' in data[1] and parm.System_DVB_T_T2 or parm.System_DVB_T
400                                                 parm.plpid = 0
401                                                 self.__tlist.append(parm)
402                                         tmpstr = _("Try to find used transponders in terrestrial network... please wait...")
403                                         tmpstr += "\n\n"
404                                         if 'MODE' in line:
405                                                 tmpstr += data[3]
406                                                 tmpstr += " kHz "
407                                         else:
408                                                 tmpstr += _(line)
409                         self.terrestrial_search_session["text"].setText(tmpstr)
410                 else:
411                         self.terrestrial_search_data += str
412
413         def setTerrestrialTransponderData(self):
414                 data = self.terrestrial_search_data.split()
415                 if len(data):
416 #                       print "[setTerrestrialTransponderData] data : ", data
417                         if data[0] == 'OK':
418                                 # DVB-T : OK frequency bandwidth delivery system -1
419                                 # DVB-T2 : OK frequency bandwidth delivery system number_of_plp plp_id0:plp_type0
420                                 if data[3] == 1: # DVB-T
421                                         parm = eDVBFrontendParametersTerrestrial()
422                                         parm.frequency = int(data[1])
423                                         parm.bandwidth = int(data[2])
424                                         parm.inversion = parm.Inversion_Unknown
425                                         parm.code_rate_HP = parm.FEC_Auto
426                                         parm.code_rate_LP = parm.FEC_Auto
427                                         parm.modulation = parm.Modulation_Auto
428                                         parm.transmission_mode = parm.TransmissionMode_Auto
429                                         parm.guard_interval = parm.GuardInterval_Auto
430                                         parm.hierarchy = parm.Hierarchy_Auto
431                                         parm.system = parm.System_DVB_T
432                                         parm.plpid = 0
433                                         self.__tlist.append(parm)
434                                 else:
435                                         plp_list = data[5:]
436                                         plp_num = int(data[4])
437                                         if len(plp_list) > plp_num:
438                                                 plp_list = plp_list[:plp_num]
439                                         for plp in plp_list:
440                                                 (plp_id, plp_type) = plp.split(':')
441                                                 if plp_type == '0': # common PLP:
442                                                         continue
443                                                 parm = eDVBFrontendParametersTerrestrial()
444                                                 parm.frequency = int(data[1])
445                                                 parm.bandwidth = self.terrestrialTransponderconvBandwidth_P(int(data[2]))
446                                                 parm.inversion = parm.Inversion_Unknown
447                                                 parm.code_rate_HP = parm.FEC_Auto
448                                                 parm.code_rate_LP = parm.FEC_Auto
449                                                 parm.modulation = parm.Modulation_Auto
450                                                 parm.transmission_mode = parm.TransmissionMode_Auto
451                                                 parm.guard_interval = parm.GuardInterval_Auto
452                                                 parm.hierarchy = parm.Hierarchy_Auto
453                                                 parm.system = parm.System_DVB_T2
454                                                 parm.plpid = int(plp_id)
455                                                 self.__tlist.append(parm)
456                                 tmpstr = _("Try to find used transponders in terrestrial network... please wait...")
457                                 tmpstr += "\n\n"
458                                 tmpstr += data[1][:-3]
459                                 tmpstr += " kHz "
460                                 tmpstr += data[0]
461                                 self.terrestrial_search_session["text"].setText(tmpstr)
462
463         def terrestrialTransponderInitSearchList(self, searchList, region):
464                 tpList = nimmanager.getTranspondersTerrestrial(region)
465                 for x in tpList:
466                         if x[0] == 2: #TERRESTRIAL
467                                 freq = x[1] # frequency
468                                 bandWidth = self.terrestrialTransponderConvBandwidth_I(x[2]) # bandWidth
469                                 parm = (freq, bandWidth)
470                                 searchList.append(parm)
471
472         def terrestrialTransponderConvBandwidth_I(self, _bandWidth):
473                 bandWidth = {
474                         eDVBFrontendParametersTerrestrial.Bandwidth_8MHz : 8000000,
475                         eDVBFrontendParametersTerrestrial.Bandwidth_7MHz : 7000000,
476                         eDVBFrontendParametersTerrestrial.Bandwidth_6MHz : 6000000,
477                         eDVBFrontendParametersTerrestrial.Bandwidth_5MHz : 5000000,
478                         eDVBFrontendParametersTerrestrial.Bandwidth_1_712MHz : 1712000,
479                         eDVBFrontendParametersTerrestrial.Bandwidth_10MHz : 10000000,
480                 }.get(_bandWidth, 8000000)
481                 return bandWidth
482
483         def terrestrialTransponderconvBandwidth_P(self, _bandWidth):
484                 bandWidth = {
485                         8000000 : eDVBFrontendParametersTerrestrial.Bandwidth_8MHz,
486                         7000000 : eDVBFrontendParametersTerrestrial.Bandwidth_7MHz,
487                         6000000 : eDVBFrontendParametersTerrestrial.Bandwidth_6MHz,
488                         5000000 : eDVBFrontendParametersTerrestrial.Bandwidth_5MHz,
489                         1712000 : eDVBFrontendParametersTerrestrial.Bandwidth_1_712MHz,
490                         10000000 : eDVBFrontendParametersTerrestrial.Bandwidth_10MHz,
491                 }.get(_bandWidth, eDVBFrontendParametersTerrestrial.Bandwidth_8MHz)
492                 return bandWidth
493
494         def terrestrialTransponderGetOpt(self):
495                 if len(self.terrestrial_search_list) > 0:
496                         return self.terrestrial_search_list.pop(0)
497                 else:
498                         return None
499
500         def terrestrialTransponderGetCmd(self, nim_idx):
501                 global terrestrial_autoscan_nimtype
502                 try:
503                         if self.terrestrial_tunerName is not None and self.terrestrial_tunerName != "":
504                                 device_id = ""
505                                 tunerName = self.terrestrial_tunerName.split(' ')[-1][4:-1]
506                                 if tunerName == 'TT3L10':
507                                         try:
508                                                 device_id = GetDeviceId('TT3L10', nim_idx)
509                                                 device_id = "--device %s" % (device_id)
510                                         except Exception, err:
511                                                 print "terrestrialTransponderGetCmd ->", err
512                                                 device_id = "--device 0"
513                                 command = "%s %s" % (terrestrial_autoscan_nimtype[tunerName], device_id)
514                                 return command
515                 except Exception, err:
516                         print "terrestrialTransponderGetCmd ->", err
517                 return ""
518
519         def startTerrestrialTransponderSearch(self, nim_idx, region):
520                 if not self.tryGetRawFrontend(nim_idx):
521                         self.session.nav.stopService()
522                         if not self.tryGetRawFrontend(nim_idx):
523                                 if self.session.pipshown:
524                                         self.session.infobar.showPiP()
525                                 if not self.tryGetRawFrontend(nim_idx):
526                                         self.terrestrialTransponderSearchFinished()
527                                         return
528                 self.__tlist = [ ]
529                 self.remaining_data = ""
530                 self.terrestrial_search_container = eConsoleAppContainer()
531                 self.terrestrial_search_container.appClosed.append(self.terrestrialTransponderSearchClosed)
532                 self.terrestrial_search_container.dataAvail.append(self.getTerrestrialTransponderData)
533                 self.terrestrial_tunerName = nimmanager.getNimName(nim_idx)
534                 if self.terrestrial_tunerName.startswith("Sundtek"):
535                         cmd = "/opt/bin/mediaclient --blindscan /dev/dvb/adapter1/frontend0"
536                         print "SCAN CMD : ",cmd
537                         self.terrestrial_search_container.execute(cmd)
538                 else:
539                         self.terrestrial_search_binName = self.terrestrialTransponderGetCmd(nim_idx)
540                         self.terrestrial_search_bus = nimmanager.getI2CDevice(nim_idx)
541                         if self.terrestrial_search_bus is None:
542 #                       print "ERROR: could not get I2C device for nim", nim_idx, "for terrestrial transponder search"
543                                 self.terrestrial_search_bus = 2
544
545                         self.terrestrial_search_list = []
546                         self.terrestrialTransponderInitSearchList(self.terrestrial_search_list ,region)
547                         (freq, bandWidth) = self.terrestrialTransponderGetOpt()
548                         self.terrestrialTransponderSearch(freq, bandWidth)
549                 tmpstr = _("Try to find used transponders in terrestrial network... please wait...")
550                 tmpstr += "\n\n..."
551                 self.terrestrial_search_session = self.session.openWithCallback(self.terrestrialTransponderSearchSessionClosed, MessageBox, tmpstr, MessageBox.TYPE_INFO)
552
553         def terrestrialTransponderSearch(self, freq, bandWidth):
554                 self.terrestrial_search_data = ""
555                 cmd = "%s --freq %d --bw %d --bus %d --ds 2" % (self.terrestrial_search_binName, freq, bandWidth, self.terrestrial_search_bus)
556                 print "SCAN CMD : ",cmd
557                 self.terrestrial_search_container.execute(cmd)
558
559 class ScanSetup(ConfigListScreen, Screen, CableTransponderSearchSupport, TerrestrialTransponderSearchSupport):
560         def __init__(self, session):
561                 Screen.__init__(self, session)
562                 Screen.setTitle(self, _("Manual Scan"))
563
564                 self.finished_cb = None
565                 self.updateSatList()
566                 self.service = session.nav.getCurrentService()
567                 self.feinfo = None
568                 self.networkid = 0
569                 frontendData = None
570                 if self.service is not None:
571                         self.feinfo = self.service.frontendInfo()
572                         frontendData = self.feinfo and self.feinfo.getAll(True)
573
574                 self.ter_channel_input = False
575                 self.ter_tnumber = None
576                 self.createConfig(frontendData)
577
578                 del self.feinfo
579                 del self.service
580
581                 self.session.postScanService = session.nav.getCurrentlyPlayingServiceOrGroup()
582
583                 self["key_red"] = StaticText(_("Close"))
584                 self["key_green"] = StaticText(_("Scan"))
585
586                 self["actions"] = NumberActionMap(["SetupActions", "MenuActions", "ColorActions"],
587                 {
588                         "ok": self.keyGo,
589                         "save": self.keyGo,
590                         "cancel": self.keyCancel,
591                         "red": self.keyCancel,
592                         "green": self.keyGo,
593                         "menu": self.doCloseRecursive,
594                 }, -2)
595
596                 self.statusTimer = eTimer()
597                 self.statusTimer.callback.append(self.updateStatus)
598                 #self.statusTimer.start(5000, True)
599
600                 self.list = []
601                 ConfigListScreen.__init__(self, self.list)
602                 self["header"] = Label(_("Manual Scan"))
603                 if not self.scan_nims.value == "":
604                         self.createSetup()
605                         self["introduction"] = Label(_("Press OK to start the scan"))
606                 else:
607                         self["introduction"] = Label(_("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."))
608
609         def runAsync(self, finished_cb):
610                 self.finished_cb = finished_cb
611                 self.keyGo()
612
613         def updateSatList(self):
614                 self.satList = []
615                 for slot in nimmanager.nim_slots:
616                         if slot.isCompatible("DVB-S"):
617                                 self.satList.append(nimmanager.getSatListForNim(slot.slot))
618                         else:
619                                 self.satList.append(None)
620
621         def createSetup(self):
622                 self.list = []
623                 self.multiscanlist = []
624                 index_to_scan = int(self.scan_nims.value)
625                 print "ID: ", index_to_scan
626
627                 self.tunerEntry = getConfigListEntry(_("Tuner"), self.scan_nims)
628                 self.list.append(self.tunerEntry)
629
630                 if self.scan_nims == [ ]:
631                         return
632
633                 self.typeOfScanEntry = None
634                 self.typeOfInputEntry = None
635                 self.systemEntry = None
636                 self.modulationEntry = None
637                 self.preDefSatList = None
638                 self.TerrestrialTransponders = None
639                 self.TerrestrialRegionEntry = None
640                 self.TerrestrialCompleteEntry = None
641                 nim = nimmanager.nim_slots[index_to_scan]
642                 if nim.isCompatible("DVB-S"):
643                         self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.scan_type)
644                         self.list.append(self.typeOfScanEntry)
645                 elif nim.isCompatible("DVB-C"):
646                         if config.Nims[index_to_scan].cable.scan_type.value != "provider": # only show predefined transponder if in provider mode
647                                 if self.scan_typecable.value == "predefined_transponder":
648                                         self.scan_typecable.value = self.cable_toggle[self.last_scan_typecable]
649                         self.last_scan_typecable = self.scan_typecable.value
650                         self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.scan_typecable)
651                         self.list.append(self.typeOfScanEntry)
652                 elif nim.isCompatible("DVB-T"):
653                         self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.scan_typeterrestrial)
654                         self.list.append(self.typeOfScanEntry)
655                         if self.scan_typeterrestrial.value == "single_transponder":
656                                 self.typeOfInputEntry = getConfigListEntry(_("Use frequency or channel"), self.scan_input_as)
657                                 if self.ter_channel_input:
658                                         self.list.append(self.typeOfInputEntry)
659                                 else:
660                                         self.scan_input_as.value = self.scan_input_as.choices[0]
661
662                 self.scan_networkScan.value = False
663                 if nim.isCompatible("DVB-S"):
664                         if self.scan_type.value == "single_transponder":
665                                 self.updateSatList()
666                                 if nim.isCompatible("DVB-S2"):
667                                         self.systemEntry = getConfigListEntry(_('System'), self.scan_sat.system)
668                                         self.list.append(self.systemEntry)
669                                 else:
670                                         # downgrade to dvb-s, in case a -s2 config was active
671                                         self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S
672                                 self.list.append(getConfigListEntry(_('Satellite'), self.scan_satselection[index_to_scan]))
673                                 self.list.append(getConfigListEntry(_('Frequency'), self.scan_sat.frequency))
674                                 self.list.append(getConfigListEntry(_('Inversion'), self.scan_sat.inversion))
675                                 self.list.append(getConfigListEntry(_('Symbol rate'), self.scan_sat.symbolrate))
676                                 self.list.append(getConfigListEntry(_('Polarization'), self.scan_sat.polarization))
677                                 if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
678                                         self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec))
679                                 elif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
680                                         self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec_s2))
681                                         self.modulationEntry = getConfigListEntry(_('Modulation'), self.scan_sat.modulation)
682                                         self.list.append(self.modulationEntry)
683                                         self.list.append(getConfigListEntry(_('Roll-off'), self.scan_sat.rolloff))
684                                         self.list.append(getConfigListEntry(_('Pilot'), self.scan_sat.pilot))
685                         elif self.scan_type.value == "predefined_transponder" and self.satList[index_to_scan]:
686                                 self.updateSatList()
687                                 self.preDefSatList = getConfigListEntry(_('Satellite'), self.scan_satselection[index_to_scan])
688                                 self.list.append(self.preDefSatList)
689                                 sat = self.satList[index_to_scan][self.scan_satselection[index_to_scan].index]
690                                 self.predefinedTranspondersList(sat[0])
691                                 self.list.append(getConfigListEntry(_('Transponder'), self.preDefTransponders))
692                         elif self.scan_type.value == "single_satellite":
693                                 self.updateSatList()
694                                 print self.scan_satselection[index_to_scan]
695                                 self.list.append(getConfigListEntry(_("Satellite"), self.scan_satselection[index_to_scan]))
696                                 self.scan_networkScan.value = True
697                         elif "multisat" in self.scan_type.value:
698                                 tlist = []
699                                 SatList = nimmanager.getSatListForNim(index_to_scan)
700                                 for x in SatList:
701                                         if self.Satexists(tlist, x[0]) == 0:
702                                                 tlist.append(x[0])
703                                                 sat = ConfigEnableDisable(default = "_yes" in self.scan_type.value and True or False)
704                                                 configEntry = getConfigListEntry(nimmanager.getSatDescription(x[0]), sat)
705                                                 self.list.append(configEntry)
706                                                 self.multiscanlist.append((x[0], sat))
707                                 self.scan_networkScan.value = True
708                 elif nim.isCompatible("DVB-C"):
709                         if self.scan_typecable.value == "single_transponder":
710                                 self.list.append(getConfigListEntry(_("Frequency"), self.scan_cab.frequency))
711                                 self.list.append(getConfigListEntry(_("Inversion"), self.scan_cab.inversion))
712                                 self.list.append(getConfigListEntry(_("Symbol rate"), self.scan_cab.symbolrate))
713                                 self.list.append(getConfigListEntry(_("Modulation"), self.scan_cab.modulation))
714                                 self.list.append(getConfigListEntry(_("FEC"), self.scan_cab.fec))
715                         elif self.scan_typecable.value == "predefined_transponder":
716                                 self.predefinedCabTranspondersList()
717                                 self.list.append(getConfigListEntry(_('Transponder'), self.CableTransponders))
718                         if config.Nims[index_to_scan].cable.scan_networkid.value:
719                                 self.networkid = config.Nims[index_to_scan].cable.scan_networkid.value
720                                 self.scan_networkScan.value = True
721                 elif nim.isCompatible("DVB-T"):
722                         if self.scan_typeterrestrial.value == "single_transponder":
723                                 if nim.isCompatible("DVB-T2"):
724                                         self.systemEntry = getConfigListEntry(_('System'), self.scan_ter.system)
725                                         self.list.append(self.systemEntry)
726                                 else:
727                                         self.scan_ter.system.value = eDVBFrontendParametersTerrestrial.System_DVB_T
728                                 if self.ter_channel_input and self.scan_input_as.value == "channel":
729                                         channel = getChannelNumber(self.scan_ter.frequency.value*1000, self.ter_tnumber)
730                                         if channel:
731                                                 self.scan_ter.channel.value = int(channel.replace("+","").replace("-",""))
732                                         self.list.append(getConfigListEntry(_("Channel"), self.scan_ter.channel))
733                                 else:
734                                         prev_val = self.scan_ter.frequency.value
735                                         self.scan_ter.frequency.value = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)/1000
736                                         if self.scan_ter.frequency.value == 474000:
737                                                 self.scan_ter.frequency.value = prev_val
738                                         self.list.append(getConfigListEntry(_("Frequency"), self.scan_ter.frequency))
739                                 self.list.append(getConfigListEntry(_("Inversion"), self.scan_ter.inversion))
740                                 self.list.append(getConfigListEntry(_("Bandwidth"), self.scan_ter.bandwidth))
741                                 self.list.append(getConfigListEntry(_("Code rate HP"), self.scan_ter.fechigh))
742                                 self.list.append(getConfigListEntry(_("Code rate LP"), self.scan_ter.feclow))
743                                 self.list.append(getConfigListEntry(_("Modulation"), self.scan_ter.modulation))
744                                 self.list.append(getConfigListEntry(_("Transmission mode"), self.scan_ter.transmission))
745                                 self.list.append(getConfigListEntry(_("Guard interval"), self.scan_ter.guard))
746                                 self.list.append(getConfigListEntry(_("Hierarchy info"), self.scan_ter.hierarchy))
747                                 if self.scan_ter.system.value == eDVBFrontendParametersTerrestrial.System_DVB_T2:
748                                         self.list.append(getConfigListEntry(_('PLP ID'), self.scan_ter.plp_id))
749                         elif self.scan_typeterrestrial.value == "predefined_transponder":
750                                 if nim.isCompatible("DVB-T2"):
751                                         self.systemEntry = getConfigListEntry(_('System'), self.scan_ter.system)
752                                         self.list.append(self.systemEntry)
753                                 else:
754                                         self.scan_ter.system.value = eDVBFrontendParametersTerrestrial.System_DVB_T
755                                 self.TerrestrialRegion = self.terrestrial_nims_regions[index_to_scan]
756                                 self.TerrestrialRegionEntry = getConfigListEntry(_('Region'), self.TerrestrialRegion)
757                                 self.list.append(self.TerrestrialRegionEntry)
758                                 self.predefinedTerrTranspondersList()
759                                 self.list.append(getConfigListEntry(_('Transponder'), self.TerrestrialTransponders))
760                         elif self.scan_typeterrestrial.value == "complete":
761                                 self.TerrestrialRegion = self.terrestrial_nims_regions[index_to_scan]
762                                 if nimmanager.getNimName(nim.slot).startswith("Sundtek"):
763                                         self.TerrestrialCompleteEntry = getConfigListEntry(_('Scan options'), self.scan_ter_complete_type)
764                                         self.list.append(self.TerrestrialCompleteEntry)
765                                 if self.TerrestrialCompleteEntry is None or self.scan_ter_complete_type.value == "extended":
766                                         if nim.isCompatible("DVB-T2"):
767                                                 self.systemEntry = getConfigListEntry(_('System'), self.scan_ter.system)
768                                                 self.list.append(self.systemEntry)
769                                         else:
770                                                 self.scan_ter.system.value = eDVBFrontendParametersTerrestrial.System_DVB_T
771                                         self.TerrestrialRegionEntry = getConfigListEntry(_('Region'), self.TerrestrialRegion)
772                                         self.list.append(self.TerrestrialRegionEntry)
773                 self.list.append(getConfigListEntry(_("Network scan"), self.scan_networkScan))
774                 self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices))
775                 self.list.append(getConfigListEntry(_("Only free scan"), self.scan_onlyfree))
776                 self["config"].list = self.list
777                 self["config"].l.setList(self.list)
778
779         def Satexists(self, tlist, pos):
780                 for x in tlist:
781                         if x == pos:
782                                 return 1
783                 return 0
784
785         def newConfig(self):
786                 cur = self["config"].getCurrent()
787                 print "cur is", cur
788                 if cur == self.typeOfScanEntry or \
789                         cur == self.typeOfInputEntry or \
790                         cur == self.tunerEntry or \
791                         cur == self.systemEntry or \
792                         cur == self.preDefSatList or \
793                         cur == self.TerrestrialRegionEntry or \
794                         cur == self.TerrestrialCompleteEntry or \
795                         (self.modulationEntry and self.systemEntry[1].value == eDVBFrontendParametersSatellite.System_DVB_S2 and cur == self.modulationEntry):
796                         self.createSetup()
797
798         def createConfig(self, frontendData):
799                 defaultSat = {
800                         "orbpos": 192,
801                         "system": eDVBFrontendParametersSatellite.System_DVB_S,
802                         "frequency": 11836,
803                         "inversion": eDVBFrontendParametersSatellite.Inversion_Unknown,
804                         "symbolrate": 27500,
805                         "polarization": eDVBFrontendParametersSatellite.Polarisation_Horizontal,
806                         "fec": eDVBFrontendParametersSatellite.FEC_Auto,
807                         "fec_s2": eDVBFrontendParametersSatellite.FEC_9_10,
808                         "modulation": eDVBFrontendParametersSatellite.Modulation_QPSK }
809                 defaultCab = {
810                         "frequency": 466,
811                         "inversion": eDVBFrontendParametersCable.Inversion_Unknown,
812                         "modulation": eDVBFrontendParametersCable.Modulation_QAM64,
813                         "fec": eDVBFrontendParametersCable.FEC_Auto,
814                         "symbolrate": 6900,
815                         "system": eDVBFrontendParametersCable.System_DVB_C_ANNEX_A }
816                 defaultTer = {
817                         "frequency" : 474000,
818                         "inversion" : eDVBFrontendParametersTerrestrial.Inversion_Unknown,
819                         "bandwidth" : 8000000,
820                         "fechigh" : eDVBFrontendParametersTerrestrial.FEC_Auto,
821                         "feclow" : eDVBFrontendParametersTerrestrial.FEC_Auto,
822                         "modulation" : eDVBFrontendParametersTerrestrial.Modulation_Auto,
823                         "transmission_mode" : eDVBFrontendParametersTerrestrial.TransmissionMode_Auto,
824                         "guard_interval" : eDVBFrontendParametersTerrestrial.GuardInterval_Auto,
825                         "hierarchy": eDVBFrontendParametersTerrestrial.Hierarchy_Auto,
826                         "system": eDVBFrontendParametersTerrestrial.System_DVB_T,
827                         "plp_id": 0 }
828
829                 if frontendData is not None:
830                         ttype = frontendData.get("tuner_type", "UNKNOWN")
831                         if ttype == "DVB-S":
832                                 defaultSat["system"] = frontendData.get("system", eDVBFrontendParametersSatellite.System_DVB_S)
833                                 defaultSat["frequency"] = frontendData.get("frequency", 0) / 1000
834                                 defaultSat["inversion"] = frontendData.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown)
835                                 defaultSat["symbolrate"] = frontendData.get("symbol_rate", 0) / 1000
836                                 defaultSat["polarization"] = frontendData.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal)
837                                 if defaultSat["system"] == eDVBFrontendParametersSatellite.System_DVB_S2:
838                                         defaultSat["fec_s2"] = frontendData.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
839                                         defaultSat["rolloff"] = frontendData.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35)
840                                         defaultSat["pilot"] = frontendData.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown)
841                                 else:
842                                         defaultSat["fec"] = frontendData.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto)
843                                 defaultSat["modulation"] = frontendData.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK)
844                                 defaultSat["orbpos"] = frontendData.get("orbital_position", 0)
845                         elif ttype == "DVB-C":
846                                 defaultCab["frequency"] = frontendData.get("frequency", 0) / 1000
847                                 defaultCab["symbolrate"] = frontendData.get("symbol_rate", 0) / 1000
848                                 defaultCab["inversion"] = frontendData.get("inversion", eDVBFrontendParametersCable.Inversion_Unknown)
849                                 defaultCab["fec"] = frontendData.get("fec_inner", eDVBFrontendParametersCable.FEC_Auto)
850                                 defaultCab["modulation"] = frontendData.get("modulation", eDVBFrontendParametersCable.Modulation_QAM16)
851                                 defaultCab["system"] = frontendData.get("system", eDVBFrontendParametersCable.System_DVB_C_ANNEX_A)
852                         elif ttype == "DVB-T":
853                                 defaultTer["frequency"] = frontendData.get("frequency", 47400000) / 1000
854                                 defaultTer["inversion"] = frontendData.get("inversion", eDVBFrontendParametersTerrestrial.Inversion_Unknown)
855                                 defaultTer["bandwidth"] = frontendData.get("bandwidth", 8000000)
856                                 defaultTer["fechigh"] = frontendData.get("code_rate_hp", eDVBFrontendParametersTerrestrial.FEC_Auto)
857                                 defaultTer["feclow"] = frontendData.get("code_rate_lp", eDVBFrontendParametersTerrestrial.FEC_Auto)
858                                 defaultTer["modulation"] = frontendData.get("constellation", eDVBFrontendParametersTerrestrial.Modulation_Auto)
859                                 defaultTer["transmission_mode"] = frontendData.get("transmission_mode", eDVBFrontendParametersTerrestrial.TransmissionMode_Auto)
860                                 defaultTer["guard_interval"] = frontendData.get("guard_interval", eDVBFrontendParametersTerrestrial.GuardInterval_Auto)
861                                 defaultTer["hierarchy"] = frontendData.get("hierarchy_information", eDVBFrontendParametersTerrestrial.Hierarchy_Auto)
862                                 defaultTer["system"] = frontendData.get("system", eDVBFrontendParametersTerrestrial.System_DVB_T)
863                                 defaultTer["plp_id"] = frontendData.get("plp_id", 0)
864
865                 self.scan_sat = ConfigSubsection()
866                 self.scan_cab = ConfigSubsection()
867                 self.scan_ter = ConfigSubsection()
868
869                 nim_list = []
870                 # collect all nims which are *not* set to "nothing"
871                 for n in nimmanager.nim_slots:
872                         if n.config_mode == "nothing":
873                                 continue
874                         if n.config_mode == "advanced" and len(nimmanager.getSatListForNim(n.slot)) < 1:
875                                 continue
876                         if n.config_mode in ("loopthrough", "satposdepends"):
877                                 root_id = nimmanager.sec.getRoot(n.slot_id, int(n.config.connectedTo.value))
878                                 if n.type == nimmanager.nim_slots[root_id].type: # check if connected from a DVB-S to DVB-S2 Nim or vice versa
879                                         continue
880                         nim_list.append((str(n.slot), n.friendly_full_description))
881
882                 self.scan_nims = ConfigSelection(choices = nim_list)
883                 if frontendData is not None and len(nim_list) > 0:
884                         self.scan_nims.value = str(frontendData.get("tuner_number", nim_list[0][0]))
885
886                 for slot in nimmanager.nim_slots:
887                         if slot.isCompatible("DVB-T"):
888                                 self.ter_tnumber = slot.slot
889                 if self.ter_tnumber is not None:
890                         self.ter_channel_input = supportedChannels(self.ter_tnumber)
891
892                 # status
893                 self.scan_snr = ConfigSlider()
894                 self.scan_snr.enabled = False
895                 self.scan_agc = ConfigSlider()
896                 self.scan_agc.enabled = False
897                 self.scan_ber = ConfigSlider()
898                 self.scan_ber.enabled = False
899
900                 # sat
901                 self.scan_sat.system = ConfigSelection(default = defaultSat["system"], choices = [
902                         (eDVBFrontendParametersSatellite.System_DVB_S, _("DVB-S")),
903                         (eDVBFrontendParametersSatellite.System_DVB_S2, _("DVB-S2"))])
904                 self.scan_sat.frequency = ConfigInteger(default = defaultSat["frequency"], limits = (1, 99999))
905                 self.scan_sat.inversion = ConfigSelection(default = defaultSat["inversion"], choices = [
906                         (eDVBFrontendParametersSatellite.Inversion_Off, _("Off")),
907                         (eDVBFrontendParametersSatellite.Inversion_On, _("On")),
908                         (eDVBFrontendParametersSatellite.Inversion_Unknown, _("Auto"))])
909                 self.scan_sat.symbolrate = ConfigInteger(default = defaultSat["symbolrate"], limits = (1, 99999))
910                 self.scan_sat.polarization = ConfigSelection(default = defaultSat["polarization"], choices = [
911                         (eDVBFrontendParametersSatellite.Polarisation_Horizontal, _("horizontal")),
912                         (eDVBFrontendParametersSatellite.Polarisation_Vertical, _("vertical")),
913                         (eDVBFrontendParametersSatellite.Polarisation_CircularLeft, _("circular left")),
914                         (eDVBFrontendParametersSatellite.Polarisation_CircularRight, _("circular right"))])
915                 self.scan_sat.fec = ConfigSelection(default = defaultSat["fec"], choices = [
916                         (eDVBFrontendParametersSatellite.FEC_Auto, _("Auto")),
917                         (eDVBFrontendParametersSatellite.FEC_1_2, "1/2"),
918                         (eDVBFrontendParametersSatellite.FEC_2_3, "2/3"),
919                         (eDVBFrontendParametersSatellite.FEC_3_4, "3/4"),
920                         (eDVBFrontendParametersSatellite.FEC_5_6, "5/6"),
921                         (eDVBFrontendParametersSatellite.FEC_7_8, "7/8"),
922                         (eDVBFrontendParametersSatellite.FEC_None, _("None"))])
923                 self.scan_sat.fec_s2 = ConfigSelection(default = defaultSat["fec_s2"], choices = [
924                         (eDVBFrontendParametersSatellite.FEC_Auto, _("Auto")),
925                         (eDVBFrontendParametersSatellite.FEC_1_2, "1/2"),
926                         (eDVBFrontendParametersSatellite.FEC_2_3, "2/3"),
927                         (eDVBFrontendParametersSatellite.FEC_3_4, "3/4"),
928                         (eDVBFrontendParametersSatellite.FEC_3_5, "3/5"),
929                         (eDVBFrontendParametersSatellite.FEC_4_5, "4/5"),
930                         (eDVBFrontendParametersSatellite.FEC_5_6, "5/6"),
931                         (eDVBFrontendParametersSatellite.FEC_7_8, "7/8"),
932                         (eDVBFrontendParametersSatellite.FEC_8_9, "8/9"),
933                         (eDVBFrontendParametersSatellite.FEC_9_10, "9/10")])
934                 self.scan_sat.modulation = ConfigSelection(default = defaultSat["modulation"], choices = [
935                         (eDVBFrontendParametersSatellite.Modulation_QPSK, "QPSK"),
936                         (eDVBFrontendParametersSatellite.Modulation_8PSK, "8PSK")])
937                 self.scan_sat.rolloff = ConfigSelection(default = defaultSat.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35), choices = [
938                         (eDVBFrontendParametersSatellite.RollOff_alpha_0_35, "0.35"),
939                         (eDVBFrontendParametersSatellite.RollOff_alpha_0_25, "0.25"),
940                         (eDVBFrontendParametersSatellite.RollOff_alpha_0_20, "0.20"),
941                         (eDVBFrontendParametersSatellite.RollOff_auto, _("Auto"))])
942                 self.scan_sat.pilot = ConfigSelection(default = defaultSat.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown), choices = [
943                         (eDVBFrontendParametersSatellite.Pilot_Off, _("Off")),
944                         (eDVBFrontendParametersSatellite.Pilot_On, _("On")),
945                         (eDVBFrontendParametersSatellite.Pilot_Unknown, _("Auto"))])
946
947                 # cable
948                 self.scan_cab.frequency = ConfigInteger(default = defaultCab["frequency"], limits = (50, 999))
949                 self.scan_cab.inversion = ConfigSelection(default = defaultCab["inversion"], choices = [
950                         (eDVBFrontendParametersCable.Inversion_Off, _("Off")),
951                         (eDVBFrontendParametersCable.Inversion_On, _("On")),
952                         (eDVBFrontendParametersCable.Inversion_Unknown, _("Auto"))])
953                 self.scan_cab.modulation = ConfigSelection(default = defaultCab["modulation"], choices = [
954                         (eDVBFrontendParametersCable.Modulation_QAM16, "16-QAM"),
955                         (eDVBFrontendParametersCable.Modulation_QAM32, "32-QAM"),
956                         (eDVBFrontendParametersCable.Modulation_QAM64, "64-QAM"),
957                         (eDVBFrontendParametersCable.Modulation_QAM128, "128-QAM"),
958                         (eDVBFrontendParametersCable.Modulation_QAM256, "256-QAM")])
959                 self.scan_cab.fec = ConfigSelection(default = defaultCab["fec"], choices = [
960                         (eDVBFrontendParametersCable.FEC_Auto, _("Auto")),
961                         (eDVBFrontendParametersCable.FEC_1_2, "1/2"),
962                         (eDVBFrontendParametersCable.FEC_2_3, "2/3"),
963                         (eDVBFrontendParametersCable.FEC_3_4, "3/4"),
964                         (eDVBFrontendParametersCable.FEC_5_6, "5/6"),
965                         (eDVBFrontendParametersCable.FEC_7_8, "7/8"),
966                         (eDVBFrontendParametersCable.FEC_8_9, "8/9"),
967                         (eDVBFrontendParametersCable.FEC_3_5, "3/5"),
968                         (eDVBFrontendParametersCable.FEC_4_5, "4/5"),
969                         (eDVBFrontendParametersCable.FEC_9_10, "9/10"),
970                         (eDVBFrontendParametersCable.FEC_None, _("None"))])
971                 self.scan_cab.symbolrate = ConfigInteger(default = defaultCab["symbolrate"], limits = (1, 99999))
972                 self.scan_cab.system = ConfigSelection(default = defaultCab["system"], choices = [
973                         (eDVBFrontendParametersCable.System_DVB_C_ANNEX_A, _("DVB-C")),
974                         (eDVBFrontendParametersCable.System_DVB_C_ANNEX_C, _("DVB-C ANNEX C"))])
975
976                 # terrestial
977                 self.scan_ter.frequency = ConfigInteger(default = defaultTer["frequency"], limits = (50000, 999000))
978                 self.scan_ter.channel = ConfigInteger(default = 21, limits = (1, 99))
979                 self.scan_ter.inversion = ConfigSelection(default = defaultTer["inversion"], choices = [
980                         (eDVBFrontendParametersTerrestrial.Inversion_Off, _("Off")),
981                         (eDVBFrontendParametersTerrestrial.Inversion_On, _("On")),
982                         (eDVBFrontendParametersTerrestrial.Inversion_Unknown, _("Auto"))])
983                 # WORKAROUND: we can't use BW-auto
984                 self.scan_ter.bandwidth = ConfigSelection(default = defaultTer["bandwidth"], choices = [
985                         (1712000, "1.712MHz"),
986                         (5000000, "5MHz"),
987                         (6000000, "6MHz"),
988                         (7000000, "7MHz"),
989                         (8000000, "8MHz"),
990                         (10000000,"10MHz")
991                         ])
992                 #, (eDVBFrontendParametersTerrestrial.Bandwidth_Auto, _("Auto"))))
993                 self.scan_ter.fechigh = ConfigSelection(default = defaultTer["fechigh"], choices = [
994                         (eDVBFrontendParametersTerrestrial.FEC_1_2, "1/2"),
995                         (eDVBFrontendParametersTerrestrial.FEC_2_3, "2/3"),
996                         (eDVBFrontendParametersTerrestrial.FEC_3_4, "3/4"),
997                         (eDVBFrontendParametersTerrestrial.FEC_5_6, "5/6"),
998                         (eDVBFrontendParametersTerrestrial.FEC_6_7, "6/7"),
999                         (eDVBFrontendParametersTerrestrial.FEC_7_8, "7/8"),
1000                         (eDVBFrontendParametersTerrestrial.FEC_8_9, "8/9"),
1001                         (eDVBFrontendParametersTerrestrial.FEC_Auto, _("Auto"))])
1002                 self.scan_ter.feclow = ConfigSelection(default = defaultTer["feclow"], choices = [
1003                         (eDVBFrontendParametersTerrestrial.FEC_1_2, "1/2"),
1004                         (eDVBFrontendParametersTerrestrial.FEC_2_3, "2/3"),
1005                         (eDVBFrontendParametersTerrestrial.FEC_3_4, "3/4"),
1006                         (eDVBFrontendParametersTerrestrial.FEC_5_6, "5/6"),
1007                         (eDVBFrontendParametersTerrestrial.FEC_6_7, "6/7"),
1008                         (eDVBFrontendParametersTerrestrial.FEC_7_8, "7/8"),
1009                         (eDVBFrontendParametersTerrestrial.FEC_8_9, "8/9"),
1010                         (eDVBFrontendParametersTerrestrial.FEC_Auto, _("Auto"))])
1011                 self.scan_ter.modulation = ConfigSelection(default = defaultTer["modulation"], choices = [
1012                         (eDVBFrontendParametersTerrestrial.Modulation_QPSK, "QPSK"),
1013                         (eDVBFrontendParametersTerrestrial.Modulation_QAM16, "QAM16"),
1014                         (eDVBFrontendParametersTerrestrial.Modulation_QAM64, "QAM64"),
1015                         (eDVBFrontendParametersTerrestrial.Modulation_QAM256, "QAM256"),
1016                         (eDVBFrontendParametersTerrestrial.Modulation_Auto, _("Auto"))])
1017                 self.scan_ter.transmission = ConfigSelection(default = defaultTer["transmission_mode"], choices = [
1018                         (eDVBFrontendParametersTerrestrial.TransmissionMode_1k, "1K"),
1019                         (eDVBFrontendParametersTerrestrial.TransmissionMode_2k, "2K"),
1020                         (eDVBFrontendParametersTerrestrial.TransmissionMode_4k, "4K"),
1021                         (eDVBFrontendParametersTerrestrial.TransmissionMode_8k, "8K"),
1022                         (eDVBFrontendParametersTerrestrial.TransmissionMode_16k, "16K"),
1023                         (eDVBFrontendParametersTerrestrial.TransmissionMode_32k, "32K"),
1024                         (eDVBFrontendParametersTerrestrial.TransmissionMode_Auto, _("Auto"))])
1025                 self.scan_ter.guard = ConfigSelection(default = defaultTer["guard_interval"], choices = [
1026                         (eDVBFrontendParametersTerrestrial.GuardInterval_1_32, "1/32"),
1027                         (eDVBFrontendParametersTerrestrial.GuardInterval_1_16, "1/16"),
1028                         (eDVBFrontendParametersTerrestrial.GuardInterval_1_8, "1/8"),
1029                         (eDVBFrontendParametersTerrestrial.GuardInterval_1_4, "1/4"),
1030                         (eDVBFrontendParametersTerrestrial.GuardInterval_1_128, "1/128"),
1031                         (eDVBFrontendParametersTerrestrial.GuardInterval_19_128, "19/128"),
1032                         (eDVBFrontendParametersTerrestrial.GuardInterval_19_256, "19/256"),
1033                         (eDVBFrontendParametersTerrestrial.GuardInterval_Auto, _("Auto"))])
1034                 self.scan_ter.hierarchy = ConfigSelection(default = defaultTer["hierarchy"], choices = [
1035                         (eDVBFrontendParametersTerrestrial.Hierarchy_None, _("None")),
1036                         (eDVBFrontendParametersTerrestrial.Hierarchy_1, "1"),
1037                         (eDVBFrontendParametersTerrestrial.Hierarchy_2, "2"),
1038                         (eDVBFrontendParametersTerrestrial.Hierarchy_4, "4"),
1039                         (eDVBFrontendParametersTerrestrial.Hierarchy_Auto, _("Auto"))])
1040                 self.scan_ter.system = ConfigSelection(default = defaultTer["system"], choices = [
1041                         (eDVBFrontendParametersTerrestrial.System_DVB_T_T2, _("Auto")),
1042                         (eDVBFrontendParametersTerrestrial.System_DVB_T, _("DVB-T")),
1043                         (eDVBFrontendParametersTerrestrial.System_DVB_T2, _("DVB-T2"))])
1044                 self.scan_ter.plp_id = ConfigInteger(default = defaultTer["plp_id"], limits = (0, 255))
1045
1046                 self.scan_scansat = {}
1047                 for sat in nimmanager.satList:
1048                         #print sat[1]
1049                         self.scan_scansat[sat[0]] = ConfigYesNo(default = False)
1050
1051                 self.scan_satselection = []
1052                 for slot in nimmanager.nim_slots:
1053                         if slot.isCompatible("DVB-S"):
1054                                 self.scan_satselection.append(getConfigSatlist(defaultSat["orbpos"], self.satList[slot.slot]))
1055                         else:
1056                                 self.scan_satselection.append(None)
1057
1058                 self.terrestrial_nims_regions = []
1059                 for slot in nimmanager.nim_slots:
1060                         if slot.isCompatible("DVB-T"):
1061                                 self.terrestrial_nims_regions.append(self.getTerrestrialRegionsList(slot.slot))
1062                         else:
1063                                 self.terrestrial_nims_regions.append(None)
1064
1065                 if frontendData is not None and ttype == "DVB-S" and self.predefinedTranspondersList(defaultSat["orbpos"]) is not None:
1066                         defaultSatSearchType = "predefined_transponder"
1067                 else:
1068                         defaultSatSearchType = "single_transponder"
1069                 if frontendData is not None and ttype == "DVB-T" and self.predefinedTerrTranspondersList() is not None:
1070                         defaultTerrSearchType = "predefined_transponder"
1071                 else:
1072                         defaultTerrSearchType = "single_transponder"
1073
1074                 if frontendData is not None and ttype == "DVB-C" and self.predefinedCabTranspondersList() is not None:
1075                         defaultCabSearchType = "predefined_transponder"
1076                 else:
1077                         defaultCabSearchType = "single_transponder"
1078
1079                 self.scan_type = ConfigSelection(default = defaultSatSearchType, choices = [("single_transponder", _("User defined transponder")), ("predefined_transponder", _("Predefined transponder")), ("single_satellite", _("Single satellite")), ("multisat", _("Multisat")), ("multisat_yes", _("Multisat all select"))])
1080                 self.scan_typecable = ConfigSelection(default = defaultCabSearchType, choices = [("single_transponder", _("User defined transponder")), ("predefined_transponder", _("Predefined transponder")), ("complete", _("Complete"))])
1081                 self.last_scan_typecable = "single_transponder"
1082                 self.cable_toggle = {"single_transponder":"complete", "complete":"single_transponder"}
1083                 self.scan_typeterrestrial = ConfigSelection(default = defaultTerrSearchType, choices = [("single_transponder", _("User defined transponder")), ("predefined_transponder", _("Predefined transponder")), ("complete", _("Complete"))])
1084                 self.scan_input_as = ConfigSelection(default = "channel", choices = [("frequency", _("Frequency")), ("channel", _("Channel"))])
1085                 self.scan_ter_complete_type = ConfigSelection(default = "all", choices = [("all", _("All frequency")), ("extended", _("Extended"))])
1086                 self.scan_clearallservices = ConfigSelection(default = "no", choices = [("no", _("no")), ("yes", _("yes")), ("yes_hold_feeds", _("yes (keep feeds)"))])
1087                 self.scan_onlyfree = ConfigYesNo(default = False)
1088                 self.scan_networkScan = ConfigYesNo(default = False)
1089
1090                 return True
1091
1092         def keyLeft(self):
1093                 ConfigListScreen.keyLeft(self)
1094                 self.newConfig()
1095
1096         def keyRight(self):
1097                 ConfigListScreen.keyRight(self)
1098                 self.newConfig()
1099
1100         def handleKeyFileCallback(self, answer):
1101                 ConfigListScreen.handleKeyFileCallback(self, answer)
1102                 self.newConfig()
1103
1104         def updateStatus(self):
1105                 print "updatestatus"
1106
1107         def addSatTransponder(self, tlist, frequency, symbol_rate, polarisation, fec, inversion, orbital_position, system, modulation, rolloff, pilot):
1108                 print "Add Sat: frequ: " + str(frequency) + " symbol: " + str(symbol_rate) + " pol: " + str(polarisation) + " fec: " + str(fec) + " inversion: " + str(inversion) + " modulation: " + str(modulation) + " system: " + str(system) + " rolloff" + str(rolloff) + " pilot" + str(pilot)
1109                 print "orbpos: " + str(orbital_position)
1110                 parm = eDVBFrontendParametersSatellite()
1111                 parm.modulation = modulation
1112                 parm.system = system
1113                 parm.frequency = frequency * 1000
1114                 parm.symbol_rate = symbol_rate * 1000
1115                 parm.polarisation = polarisation
1116                 parm.fec = fec
1117                 parm.inversion = inversion
1118                 parm.orbital_position = orbital_position
1119                 parm.rolloff = rolloff
1120                 parm.pilot = pilot
1121                 tlist.append(parm)
1122
1123         def addCabTransponder(self, tlist, frequency, symbol_rate, modulation, fec, inversion):
1124                 print "Add Cab: frequ: " + str(frequency) + " symbol: " + str(symbol_rate) + " pol: " + str(modulation) + " fec: " + str(fec) + " inversion: " + str(inversion)
1125                 parm = eDVBFrontendParametersCable()
1126                 parm.frequency = frequency
1127                 parm.symbol_rate = symbol_rate
1128                 parm.modulation = modulation
1129                 parm.fec_inner = fec
1130                 parm.inversion = inversion
1131                 tlist.append(parm)
1132
1133         def addTerTransponder(self, tlist, *args, **kwargs):
1134                 tlist.append(buildTerTransponder(*args, **kwargs))
1135
1136         def keyGo(self):
1137                 infoBarInstance = InfoBar.instance
1138                 if infoBarInstance:
1139                         infoBarInstance.checkTimeshiftRunning(self.keyGoCheckTimeshiftCallback)
1140                 else:
1141                         self.keyGoCheckTimeshiftCallback(True)
1142
1143         def keyGoCheckTimeshiftCallback(self, answer):
1144                 START_SCAN = 0
1145                 SEARCH_CABLE_TRANSPONDERS = 1
1146                 SEARCH_TERRESTRIAL2_TRANSPONDERS = 2
1147                 if not answer or self.scan_nims.value == "":
1148                         return
1149                 tlist = []
1150                 flags = None
1151                 removeAll = True
1152                 action = START_SCAN
1153                 index_to_scan = int(self.scan_nims.value)
1154
1155                 if self.scan_nims == [ ]:
1156                         self.session.open(MessageBox, _("No tuner is enabled!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR)
1157                         return
1158
1159                 nim = nimmanager.nim_slots[index_to_scan]
1160                 print "nim", nim.slot
1161                 if nim.isCompatible("DVB-S"):
1162                         print "is compatible with DVB-S"
1163                         if self.scan_type.value == "single_transponder":
1164                                 # these lists are generated for each tuner, so this has work.
1165                                 assert len(self.satList) > index_to_scan
1166                                 assert len(self.scan_satselection) > index_to_scan
1167
1168                                 nimsats = self.satList[index_to_scan]
1169                                 selsatidx = self.scan_satselection[index_to_scan].index
1170
1171                                 # however, the satList itself could be empty. in that case, "index" is 0 (for "None").
1172                                 if len(nimsats):
1173                                         orbpos = nimsats[selsatidx][0]
1174                                         if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S:
1175                                                 fec = self.scan_sat.fec.value
1176                                         else:
1177                                                 fec = self.scan_sat.fec_s2.value
1178                                         print "add sat transponder"
1179                                         self.addSatTransponder(tlist, self.scan_sat.frequency.value,
1180                                                                 self.scan_sat.symbolrate.value,
1181                                                                 self.scan_sat.polarization.value,
1182                                                                 fec,
1183                                                                 self.scan_sat.inversion.value,
1184                                                                 orbpos,
1185                                                                 self.scan_sat.system.value,
1186                                                                 self.scan_sat.modulation.value,
1187                                                                 self.scan_sat.rolloff.value,
1188                                                                 self.scan_sat.pilot.value)
1189                                 removeAll = False
1190                         elif self.scan_type.value == "predefined_transponder":
1191                                 nimsats = self.satList[index_to_scan]
1192                                 selsatidx = self.scan_satselection[index_to_scan].index
1193                                 if len(nimsats):
1194                                         orbpos = nimsats[selsatidx][0]
1195                                         tps = nimmanager.getTransponders(orbpos)
1196                                         if len(tps) and len(tps) > self.preDefTransponders.index:
1197                                                 tp = tps[self.preDefTransponders.index]
1198                                                 self.addSatTransponder(tlist, tp[1] / 1000, tp[2] / 1000, tp[3], tp[4], tp[7], orbpos, tp[5], tp[6], tp[8], tp[9])
1199                                 removeAll = False
1200                         elif self.scan_type.value == "single_satellite":
1201                                 sat = self.satList[index_to_scan][self.scan_satselection[index_to_scan].index]
1202                                 getInitialTransponderList(tlist, sat[0])
1203                         elif "multisat" in self.scan_type.value:
1204                                 SatList = nimmanager.getSatListForNim(index_to_scan)
1205                                 for x in self.multiscanlist:
1206                                         if x[1].value:
1207                                                 print "   " + str(x[0])
1208                                                 getInitialTransponderList(tlist, x[0])
1209
1210                 elif nim.isCompatible("DVB-C"):
1211                         if self.scan_typecable.value == "single_transponder":
1212                                 self.addCabTransponder(tlist, self.scan_cab.frequency.value*1000,
1213                                                                                           self.scan_cab.symbolrate.value*1000,
1214                                                                                           self.scan_cab.modulation.value,
1215                                                                                           self.scan_cab.fec.value,
1216                                                                                           self.scan_cab.inversion.value)
1217                                 removeAll = False
1218                         elif self.scan_typecable.value == "predefined_transponder":
1219                                 tps = nimmanager.getTranspondersCable(index_to_scan)
1220                                 if len(tps) and len(tps) > self.CableTransponders.index :
1221                                         tp = tps[self.CableTransponders.index]
1222                                         # 0 transponder type, 1 freq, 2 sym, 3 mod, 4 fec, 5 inv, 6 sys
1223                                         self.addCabTransponder(tlist, tp[1], tp[2], tp[3], tp[4], tp[5])
1224                                 removeAll = False
1225                         elif self.scan_typecable.value == "complete":
1226                                 if config.Nims[index_to_scan].cable.scan_type.value == "provider":
1227                                         getInitialCableTransponderList(tlist, index_to_scan)
1228                                 else:
1229                                         action = SEARCH_CABLE_TRANSPONDERS
1230
1231                 elif nim.isCompatible("DVB-T"):
1232                         if self.scan_typeterrestrial.value == "single_transponder":
1233                                 if self.scan_input_as.value == "channel":
1234                                         frequency = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)
1235                                 else:
1236                                         frequency = self.scan_ter.frequency.value * 1000
1237                                 self.addTerTransponder(tlist,
1238                                                 frequency,
1239                                                 inversion = self.scan_ter.inversion.value,
1240                                                 bandwidth = self.scan_ter.bandwidth.value,
1241                                                 fechigh = self.scan_ter.fechigh.value,
1242                                                 feclow = self.scan_ter.feclow.value,
1243                                                 modulation = self.scan_ter.modulation.value,
1244                                                 transmission = self.scan_ter.transmission.value,
1245                                                 guard = self.scan_ter.guard.value,
1246                                                 hierarchy = self.scan_ter.hierarchy.value,
1247                                                 system = self.scan_ter.system.value,
1248                                                 plpid = self.scan_ter.plp_id.value)
1249                                 removeAll = False
1250                         elif self.scan_typeterrestrial.value == "predefined_transponder":
1251                                 if self.TerrestrialTransponders is not None:
1252                                         region = self.terrestrial_nims_regions[index_to_scan].value
1253                                         tps = nimmanager.getTranspondersTerrestrial(region)
1254                                         if len(tps) and len(tps) > self.TerrestrialTransponders.index:
1255                                                 tp = tps[self.TerrestrialTransponders.index]
1256                                                 tlist.append(buildTerTransponder(tp[1], tp[9], tp[2], tp[4], tp[5], tp[3], tp[7], tp[6], tp[8], self.scan_ter.system.value, tp[11]))
1257                                 removeAll = False
1258                         elif self.scan_typeterrestrial.value == "complete":
1259                                 skip_t2 = False
1260                                 if nimmanager.getNimName(nim.slot).startswith("Sundtek") and self.scan_ter_complete_type.value == "all":
1261                                         action = SEARCH_TERRESTRIAL2_TRANSPONDERS
1262                                 elif SystemInfo["Blindscan_t2_available"]:
1263                                         skip_t2 = True
1264                                         if nim.isCompatible("DVB-T2"):
1265                                                 if len(self.terrestrialTransponderGetCmd(nim.slot)):
1266                                                         action = SEARCH_TERRESTRIAL2_TRANSPONDERS
1267                                                 else:
1268                                                         skip_t2 = False
1269                                 getInitialTerrestrialTransponderList(tlist, self.TerrestrialRegion.value, int(self.scan_ter.system.value), skip_t2)
1270
1271                 flags = self.scan_networkScan.value and eComponentScan.scanNetworkSearch or 0
1272
1273                 tmp = self.scan_clearallservices.value
1274                 if tmp == "yes":
1275                         flags |= eComponentScan.scanRemoveServices
1276                 elif tmp == "yes_hold_feeds":
1277                         flags |= eComponentScan.scanRemoveServices
1278                         flags |= eComponentScan.scanDontRemoveFeeds
1279
1280                 if tmp != "no" and not removeAll:
1281                         flags |= eComponentScan.scanDontRemoveUnscanned
1282
1283                 if self.scan_onlyfree.value:
1284                         flags |= eComponentScan.scanOnlyFree
1285
1286                 for x in self["config"].list:
1287                         x[1].save()
1288
1289                 if action == START_SCAN:
1290                         self.startScan(tlist, flags, index_to_scan, self.networkid)
1291                 elif action == SEARCH_CABLE_TRANSPONDERS:
1292                         self.flags = flags
1293                         self.feid = index_to_scan
1294                         self.tlist = []
1295                         self.startCableTransponderSearch(self.feid)
1296                 elif action == SEARCH_TERRESTRIAL2_TRANSPONDERS:
1297                         self.flags = flags
1298                         self.feid = index_to_scan
1299                         self.tlist = tlist
1300                         self.startTerrestrialTransponderSearch(self.feid, nimmanager.getTerrestrialDescription(self.feid))
1301
1302         def setCableTransponderSearchResult(self, tlist):
1303                 self.tlist = tlist
1304
1305         def cableTransponderSearchFinished(self):
1306                 if self.tlist is None:
1307                         self.tlist = []
1308                 else:
1309                         self.startScan(self.tlist, self.flags, self.feid)
1310
1311         def setTerrestrialTransponderSearchResult(self, tlist):
1312                 self.tlist = tlist
1313
1314         def terrestrialTransponderSearchFinished(self):
1315                 if self.tlist is None:
1316                         self.tlist = []
1317                 else:
1318                         self.startScan(self.tlist, self.flags, self.feid)
1319
1320         def predefinedTranspondersList(self, orbpos):
1321                 default = None
1322                 if orbpos is not None:
1323                         list = []
1324                         if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2:
1325                                 fec = self.scan_sat.fec_s2.value
1326                         else:
1327                                 fec = self.scan_sat.fec.value
1328                         compare = [0, self.scan_sat.frequency.value*1000, self.scan_sat.symbolrate.value*1000, self.scan_sat.polarization.value, fec]
1329                         i = 0
1330                         tps = nimmanager.getTransponders(orbpos)
1331                         for tp in tps:
1332                                 if tp[0] == 0:
1333                                         if default is None and self.compareTransponders(tp, compare):
1334                                                 default = str(i)
1335                                         list.append((str(i), self.humanReadableTransponder(tp)))
1336                                         i += 1
1337                         self.preDefTransponders = ConfigSelection(choices = list, default = default)
1338                 return default
1339
1340         def humanReadableTransponder(self, tp):
1341                 if tp[3] in range (4) and tp[4] in range (11):
1342                         pol_list = ['H','V','L','R']
1343                         fec_list = ['Auto','1/2','2/3','3/4','5/6','7/8','8/9','3/5','4/5','9/10','None']
1344                         return str(tp[1] / 1000) + " " + pol_list[tp[3]] + " " + str(tp[2] / 1000) + " " + fec_list[tp[4]]
1345                 return _("Invalid transponder data")
1346
1347         def compareTransponders(self, tp, compare):
1348                 frequencyTolerance = 2000 #2 MHz
1349                 symbolRateTolerance = 10
1350                 return abs(tp[1] - compare[1]) <= frequencyTolerance and abs(tp[2] - compare[2]) <= symbolRateTolerance and tp[3] == compare[3] and (not tp[4] or tp[4] == compare[4])
1351
1352         def predefinedTerrTranspondersList(self):
1353                 default = None
1354                 list = []
1355                 compare = [2, self.scan_ter.frequency.value*1000]
1356                 i = 0
1357                 index_to_scan = int(self.scan_nims.value)
1358                 channels = supportedChannels(index_to_scan)
1359                 region = self.terrestrial_nims_regions[index_to_scan].value
1360                 tps = nimmanager.getTranspondersTerrestrial(region)
1361                 for tp in tps:
1362                         if tp[0] == 2: #TERRESTRIAL
1363                                 channel = ''
1364                                 if channels:
1365                                         channel = _(' (Channel %s)') % (getChannelNumber(tp[1], index_to_scan))
1366                                 if default is None and self.compareTerrTransponders(tp, compare):
1367                                         default = str(i)
1368                                 list.append((str(i), '%s MHz %s' % (str(tp[1] / 1000000), channel)))
1369                                 i += 1
1370                                 print "channel", channel
1371                 self.TerrestrialTransponders = ConfigSelection(choices = list, default = default)
1372                 return default
1373
1374         def compareTerrTransponders(self, tp, compare):
1375                 frequencyTolerance = 1000000 #1 MHz
1376                 return abs(tp[1] - compare[1]) <= frequencyTolerance
1377
1378         def getTerrestrialRegionsList(self, index_to_scan = None):
1379                 default = None
1380                 list = []
1381                 if index_to_scan is None:
1382                         index_to_scan = int(self.scan_nims.value)
1383                 defaultRegionForNIM = nimmanager.getTerrestrialDescription(index_to_scan)
1384                 for r in nimmanager.terrestrialsList:
1385                         if default is None and r[0] == defaultRegionForNIM:
1386                                 default = r[0]
1387                         list.append((r[0], r[0][:46]))
1388                 return ConfigSelection(choices = list, default = default)
1389
1390         def predefinedCabTranspondersList(self):
1391                 default = None
1392                 list = []
1393                 # 0 transponder type, 1 freq, 2 sym, 3 mod, 4 fec, 5 inv, 6 sys
1394                 compare = [1, self.scan_cab.frequency.value*1000, self.scan_cab.symbolrate.value*1000, self.scan_cab.modulation.value, self.scan_cab.fec.value, self.scan_cab.inversion.value, self.scan_cab.system.value]
1395                 i = 0
1396                 index_to_scan = int(self.scan_nims.value)
1397                 tps = nimmanager.getTranspondersCable(index_to_scan)
1398                 for tp in tps:
1399                         if tp[0] == 1: #CABLE
1400                                 if default is None and self.compareCabTransponders(tp, compare):
1401                                         default = str(i)
1402                                 list.append((str(i), self.humanReadableCabTransponder(tp)))
1403                                 i += 1
1404                 self.CableTransponders = ConfigSelection(choices = list, default = default)
1405                 return default
1406
1407         def humanReadableCabTransponder(self, tp):
1408                 if tp[3] in range (6) and (tp[4] in range (10) or tp[4] == 15):
1409                         mod_list = ['Auto', '16-QAM','32-QAM','64-QAM','128-QAM', '256-QAM']
1410                         fec_list = {0:"Auto", 1:'1/2', 2:'2/3', 3:'3/4', 4:'5/6', 5:'7/8', 6:'8/9', 7:'3/5', 8:'4/5', 9:'9/10', 15:'None'}
1411                         print str(tp[1]/1000) + " MHz " + fec_list[tp[4]] + " " + str(tp[2]/1000) + " " + mod_list[tp[3]]
1412                         return str(tp[1]/1000) + " MHz " + fec_list[tp[4]] + " " + str(tp[2]/1000) + " " + mod_list[tp[3]]
1413                 return _("Invalid transponder data")
1414
1415         def compareCabTransponders(self, tp, compare):
1416                 frequencyTolerance = 1000000 #1 MHz
1417                 symbolRateTolerance = 10
1418                 return abs(tp[1] - compare[1]) <= frequencyTolerance and abs(tp[2] - compare[2]) <= symbolRateTolerance and tp[3] == compare[3] and (not tp[4] or tp[4] == compare[4])
1419
1420         def startScan(self, tlist, flags, feid, networkid = 0):
1421                 if len(tlist):
1422                         # flags |= eComponentScan.scanSearchBAT
1423                         if self.finished_cb:
1424                                 self.session.openWithCallback(self.finished_cb, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])
1425                         else:
1426                                 self.session.openWithCallback(self.startScanCallback, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}])
1427                 else:
1428                         if self.finished_cb:
1429                                 self.session.openWithCallback(self.finished_cb, MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR)
1430                         else:
1431                                 self.session.open(MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR)
1432
1433         def startScanCallback(self, answer=True):
1434                 if answer:
1435                         self.doCloseRecursive()
1436
1437         def keyCancel(self):
1438                 self.session.nav.playService(self.session.postScanService)
1439                 for x in self["config"].list:
1440                         x[1].cancel()
1441                 self.close()
1442
1443         def doCloseRecursive(self):
1444                 self.session.nav.playService(self.session.postScanService)
1445                 self.closeRecursive()
1446
1447 class ScanSimple(ConfigListScreen, Screen, CableTransponderSearchSupport, TerrestrialTransponderSearchSupport):
1448         def getNetworksForNim(self, nim):
1449                 if nim.isCompatible("DVB-S"):
1450                         networks = nimmanager.getSatListForNim(nim.slot)
1451                 elif nim.isCompatible("DVB-C"):
1452                         networks = nimmanager.getTranspondersCable(nim.slot)
1453                         if not networks and config.Nims[nim.slot].configMode.value == "enabled":
1454                                 networks = [ nim.type ]
1455                 elif nim.isCompatible("DVB-T"):
1456                         networks = [nimmanager.getTerrestrialDescription(nim.slot)]
1457                         if not nimmanager.somethingConnected(nim.slot):
1458                                 networks = []
1459                 elif not nim.empty:
1460                         networks = [ nim.type ] # "DVB-C" or "DVB-T". TODO: seperate networks for different C/T tuners, if we want to support that.
1461                 else:
1462                         # empty tuners provide no networks.
1463                         networks = [ ]
1464                 return networks
1465
1466         def __init__(self, session):
1467                 Screen.__init__(self, session)
1468                 Screen.setTitle(self, _("Automatic Scan"))
1469
1470                 self["key_red"] = StaticText(_("Close"))
1471                 self["key_green"] = StaticText(_("Scan"))
1472
1473                 self["actions"] = ActionMap(["SetupActions", "MenuActions", "ColorActions"],
1474                 {
1475                         "ok": self.keyGo,
1476                         "save": self.keyGo,
1477                         "cancel": self.keyCancel,
1478                         "menu": self.doCloseRecursive,
1479                         "red": self.keyCancel,
1480                         "green": self.keyGo,
1481                 }, -2)
1482
1483                 self.session.postScanService = session.nav.getCurrentlyPlayingServiceOrGroup()
1484
1485                 self.list = []
1486                 tlist = []
1487
1488                 known_networks = [ ]
1489                 nims_to_scan = [ ]
1490                 self.finished_cb = None
1491
1492                 for nim in nimmanager.nim_slots:
1493                         # collect networks provided by this tuner
1494
1495                         need_scan = False
1496                         networks = self.getNetworksForNim(nim)
1497
1498                         print "nim %d provides" % nim.slot, networks
1499                         print "known:", known_networks
1500
1501                         # we only need to scan on the first tuner which provides a network.
1502                         # this gives the first tuner for each network priority for scanning.
1503                         for x in networks:
1504                                 if x not in known_networks:
1505                                         need_scan = True
1506                                         print x, "not in ", known_networks
1507                                         known_networks.append(x)
1508
1509                         # don't offer to scan nims if nothing is connected
1510                         if not nimmanager.somethingConnected(nim.slot):
1511                                 need_scan = False
1512
1513                         if need_scan:
1514                                 nims_to_scan.append(nim)
1515
1516                 # we save the config elements to use them on keyGo
1517                 self.nim_enable = [ ]
1518
1519                 if len(nims_to_scan):
1520                         self.scan_networkScan = ConfigYesNo(default = True)
1521                         self.scan_clearallservices = ConfigSelection(default = "yes", choices = [("no", _("no")), ("yes", _("yes")), ("yes_hold_feeds", _("yes (keep feeds)"))])
1522                         self.list.append(getConfigListEntry(_("Network scan"), self.scan_networkScan))
1523                         self.list.append(getConfigListEntry(_("Clear before scan"), self.scan_clearallservices))
1524
1525                         for nim in nims_to_scan:
1526                                 nimconfig = ConfigYesNo(default = True)
1527                                 nimconfig.nim_index = nim.slot
1528                                 self.nim_enable.append(nimconfig)
1529                                 self.list.append(getConfigListEntry(_("Scan ") + nim.slot_name + " (" + nim.friendly_type + ")", nimconfig))
1530
1531                 ConfigListScreen.__init__(self, self.list)
1532                 self["header"] = Label(_("Automatic scan"))
1533                 self["footer"] = Label(_("Press OK to scan"))
1534
1535         def runAsync(self, finished_cb):
1536                 self.finished_cb = finished_cb
1537                 self.keyGo()
1538
1539         def keyGo(self):
1540                 InfoBarInstance = InfoBar.instance
1541                 if InfoBarInstance:
1542                         InfoBarInstance.checkTimeshiftRunning(self.keyGoCheckTimeshiftCallback)
1543                 else:
1544                         self.keyGoCheckTimeshiftCallback(True)
1545
1546         def keyGoCheckTimeshiftCallback(self, answer):
1547                 if answer:
1548                         self.scanList = []
1549                         self.known_networks = set()
1550                         self.nim_iter=0
1551                         self.buildTransponderList()
1552
1553         def buildTransponderList(self): # this method is called multiple times because of asynchronous stuff
1554                 APPEND_NOW = 0
1555                 SEARCH_CABLE_TRANSPONDERS = 1
1556                 SEARCH_TERRESTRIAL2_TRANSPONDERS = 2
1557                 action = APPEND_NOW
1558
1559                 n = self.nim_iter < len(self.nim_enable) and self.nim_enable[self.nim_iter] or None
1560                 self.nim_iter += 1
1561                 if n:
1562                         if n.value: # check if nim is enabled
1563                                 flags = 0
1564                                 nim = nimmanager.nim_slots[n.nim_index]
1565                                 networks = set(self.getNetworksForNim(nim))
1566                                 networkid = 0
1567
1568                                 # don't scan anything twice
1569                                 networks.discard(self.known_networks)
1570
1571                                 tlist = [ ]
1572                                 if nim.isCompatible("DVB-S"):
1573                                         # get initial transponders for each satellite to be scanned
1574                                         for sat in networks:
1575                                                 getInitialTransponderList(tlist, sat[0])
1576                                 elif nim.isCompatible("DVB-C"):
1577                                         if config.Nims[nim.slot].cable.scan_type.value == "provider":
1578                                                 getInitialCableTransponderList(tlist, nim.slot)
1579                                         else:
1580                                                 action = SEARCH_CABLE_TRANSPONDERS
1581                                                 networkid = config.Nims[nim.slot].cable.scan_networkid.value
1582                                 elif nim.isCompatible("DVB-T"):
1583                                         skip_t2 = False
1584                                         if SystemInfo["Blindscan_t2_available"]:
1585                                                 skip_t2 = True
1586                                                 if nim.isCompatible("DVB-T2"):
1587                                                         if len(self.terrestrialTransponderGetCmd(nim.slot)):
1588                                                                 action = SEARCH_TERRESTRIAL2_TRANSPONDERS
1589                                                         else:
1590                                                                 skip_t2 = False
1591                                         getInitialTerrestrialTransponderList(tlist, nimmanager.getTerrestrialDescription(nim.slot), skip_t2=skip_t2)
1592                                 else:
1593                                         assert False
1594
1595                                 flags = self.scan_networkScan.value and eComponentScan.scanNetworkSearch or 0
1596                                 tmp = self.scan_clearallservices.value
1597                                 if tmp == "yes":
1598                                         flags |= eComponentScan.scanRemoveServices
1599                                 elif tmp == "yes_hold_feeds":
1600                                         flags |= eComponentScan.scanRemoveServices
1601                                         flags |= eComponentScan.scanDontRemoveFeeds
1602
1603                                 if action == APPEND_NOW:
1604                                         self.scanList.append({"transponders": tlist, "feid": nim.slot, "flags": flags})
1605                                 elif action == SEARCH_CABLE_TRANSPONDERS:
1606                                         self.flags = flags
1607                                         self.feid = nim.slot
1608                                         self.networkid = networkid
1609                                         self.startCableTransponderSearch(nim.slot)
1610                                         return
1611                                 elif action == SEARCH_TERRESTRIAL2_TRANSPONDERS:
1612                                         self.tlist = tlist
1613                                         self.flags = flags
1614                                         self.feid = nim.slot
1615                                         self.startTerrestrialTransponderSearch(nim.slot, nimmanager.getTerrestrialDescription(nim.slot))
1616                                         return
1617                                 else:
1618                                         assert False
1619
1620                         self.buildTransponderList() # recursive call of this function !!!
1621                         return
1622                 # when we are here, then the recursion is finished and all enabled nims are checked
1623                 # so we now start the real transponder scan
1624                 self.startScan(self.scanList)
1625
1626         def startScan(self, scanList):
1627                 if len(scanList):
1628                         if self.finished_cb:
1629                                 self.session.openWithCallback(self.finished_cb, ServiceScan, scanList = scanList)
1630                         else:
1631                                 self.session.open(ServiceScan, scanList = scanList)
1632                 else:
1633                         if self.finished_cb:
1634                                 self.session.openWithCallback(self.finished_cb, MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR)
1635                         else:
1636                                 self.session.open(MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR)
1637
1638         def setCableTransponderSearchResult(self, tlist):
1639                 if tlist is not None:
1640                         self.scanList.append({"transponders": tlist, "feid": self.feid, "flags": self.flags})
1641
1642         def cableTransponderSearchFinished(self):
1643                 self.buildTransponderList()
1644
1645         def setTerrestrialTransponderSearchResult(self, tlist):
1646                 if tlist is not None:
1647                         self.tlist.extend(tlist)
1648                 if self.tlist is not None:
1649                         self.scanList.append({"transponders": self.tlist, "feid": self.feid, "flags": self.flags})
1650
1651         def terrestrialTransponderSearchFinished(self):
1652                 self.buildTransponderList()
1653
1654         def keyCancel(self):
1655                 self.session.nav.playService(self.session.postScanService)
1656                 self.close()
1657
1658         def doCloseRecursive(self):
1659                 self.session.nav.playService(self.session.postScanService)
1660                 self.closeRecursive()
1661
1662         def Satexists(self, tlist, pos):
1663                 for x in tlist:
1664                         if x == pos:
1665                                 return 1
1666                 return 0