4.2.0r10
[enigma2.git] / usr / lib / enigma2 / python / Components / NimManager.py
1 from Tools.HardwareInfo import HardwareInfo
2 from Tools.BoundFunction import boundFunction
3
4 from config import config, ConfigSubsection, ConfigSelection, ConfigFloat, \
5         ConfigSatlist, ConfigYesNo, ConfigInteger, ConfigSubList, ConfigNothing, \
6         ConfigSubDict, ConfigOnOff, ConfigDateTime
7
8 from enigma import eDVBSatelliteEquipmentControl as secClass, \
9         eDVBSatelliteLNBParameters as lnbParam, \
10         eDVBSatelliteDiseqcParameters as diseqcParam, \
11         eDVBSatelliteSwitchParameters as switchParam, \
12         eDVBSatelliteRotorParameters as rotorParam, \
13         eDVBResourceManager, eDVBDB, eEnv, iDVBFrontend
14
15 from time import localtime, mktime
16 from datetime import datetime
17 from Tools.BoundFunction import boundFunction
18
19 import xml.etree.cElementTree
20
21 def getConfigSatlist(orbpos, satlist):
22         default_orbpos = None
23         for x in satlist:
24                 if x[0] == orbpos:
25                         default_orbpos = orbpos
26                         break
27         return ConfigSatlist(satlist, default_orbpos)
28
29 def tryOpen(filename):
30         try:
31                 procFile = open(filename)
32         except IOError:
33                 return None
34         return procFile
35
36 class SecConfigure:
37         def getConfiguredSats(self):
38                 return self.configuredSatellites
39
40         def addSatellite(self, sec, orbpos):
41                 sec.addSatellite(orbpos)
42                 self.configuredSatellites.add(orbpos)
43
44         def addLNBSimple(self, sec, slotid, diseqcmode, toneburstmode = diseqcParam.NO, diseqcpos = diseqcParam.SENDNO, orbpos = 0, longitude = 0, latitude = 0, loDirection = 0, laDirection = 0, turningSpeed = rotorParam.FAST, useInputPower=True, inputPowerDelta=50, fastDiSEqC = False, setVoltageTone = True, diseqc13V = False):
45                 if orbpos is None or orbpos == 3601:
46                         return
47                 #simple defaults
48                 sec.addLNB()
49                 tunermask = 1 << slotid
50                 if self.equal.has_key(slotid):
51                         for slot in self.equal[slotid]:
52                                 tunermask |= (1 << slot)
53                 if self.linked.has_key(slotid):
54                         for slot in self.linked[slotid]:
55                                 tunermask |= (1 << slot)
56                 sec.setLNBSatCR(-1)
57                 sec.setLNBNum(1)
58                 sec.setLNBLOFL(9750000)
59                 sec.setLNBLOFH(10600000)
60                 sec.setLNBThreshold(11700000)
61                 sec.setLNBIncreasedVoltage(lnbParam.OFF)
62                 sec.setRepeats(0)
63                 sec.setFastDiSEqC(fastDiSEqC)
64                 sec.setSeqRepeat(0)
65                 sec.setCommandOrder(0)
66
67                 #user values
68                 sec.setDiSEqCMode(diseqcmode)
69                 sec.setToneburst(toneburstmode)
70                 sec.setCommittedCommand(diseqcpos)
71                 sec.setUncommittedCommand(0) # SENDNO
72                 #print "set orbpos to:" + str(orbpos)
73
74                 if 0 <= diseqcmode < 3:
75                         self.addSatellite(sec, orbpos)
76                         if setVoltageTone:
77                                 if diseqc13V:
78                                         sec.setVoltageMode(switchParam.HV_13)
79                                 else:
80                                         sec.setVoltageMode(switchParam.HV)
81                                 sec.setToneMode(switchParam.HILO)
82                         else:
83                                 sec.setVoltageMode(switchParam._14V)
84                                 sec.setToneMode(switchParam.OFF)
85                 elif (diseqcmode == 3): # diseqc 1.2
86                         if self.satposdepends.has_key(slotid):
87                                 for slot in self.satposdepends[slotid]:
88                                         tunermask |= (1 << slot)
89                         sec.setLatitude(latitude)
90                         sec.setLaDirection(laDirection)
91                         sec.setLongitude(longitude)
92                         sec.setLoDirection(loDirection)
93                         sec.setUseInputpower(useInputPower)
94                         sec.setInputpowerDelta(inputPowerDelta)
95                         sec.setRotorTurningSpeed(turningSpeed)
96
97                         for x in self.NimManager.satList:
98                                 print "Add sat " + str(x[0])
99                                 self.addSatellite(sec, int(x[0]))
100                                 if diseqc13V:
101                                         sec.setVoltageMode(switchParam.HV_13)
102                                 else:
103                                         sec.setVoltageMode(switchParam.HV)
104                                 sec.setToneMode(switchParam.HILO)
105                                 sec.setRotorPosNum(0) # USALS
106                 
107                 sec.setLNBSlotMask(tunermask)
108
109         def setSatposDepends(self, sec, nim1, nim2):
110                 print "tuner", nim1, "depends on satpos of", nim2
111                 sec.setTunerDepends(nim1, nim2)
112                 
113         def linkInternally(self, slotid):
114                 nim = self.NimManager.getNim(slotid)
115                 if nim.internallyConnectableTo is not None:
116                         nim.setInternalLink()
117
118         def linkNIMs(self, sec, nim1, nim2):
119                 print "link tuner", nim1, "to tuner", nim2
120                 if nim2 == (nim1 - 1):
121                         self.linkInternally(nim1)
122                 sec.setTunerLinked(nim1, nim2)
123                 
124         def getRoot(self, slotid, connto):
125                 visited = []
126                 while (self.NimManager.getNimConfig(connto).configMode.value in ("satposdepends", "equal", "loopthrough")):
127                         connto = int(self.NimManager.getNimConfig(connto).connectedTo.value)
128                         if connto in visited: # prevent endless loop
129                                 return slotid
130                         visited.append(connto)
131                 return connto
132
133         def update(self):
134                 sec = secClass.getInstance()
135                 self.configuredSatellites = set()
136                 for slotid in self.NimManager.getNimListOfType("DVB-S"):
137                         if self.NimManager.nimInternallyConnectableTo(slotid) is not None:
138                                 self.NimManager.nimRemoveInternalLink(slotid)
139                 sec.clear() ## this do unlinking NIMs too !!
140                 print "sec config cleared"
141
142                 self.linked = { }
143                 self.satposdepends = { }
144                 self.equal = { }
145
146                 nim_slots = self.NimManager.nim_slots
147
148                 used_nim_slots = [ ]
149
150                 for slot in nim_slots:
151                         used_nim_slots.append((slot.slot, slot.description, slot.config.configMode.value != "nothing" and True or False, slot.frontend_id is None and -1 or slot.frontend_id, slot.input_name or ""))
152                 eDVBResourceManager.getInstance().setFrontendSlotInformations(used_nim_slots)
153
154                 for slot in nim_slots:
155                         x = slot.slot
156                         nim = slot.config
157                         if slot.isCompatible("DVB-S"):
158                                 # save what nim we link to/are equal to/satposdepends to.
159                                 # this is stored in the *value* (not index!) of the config list
160                                 if nim.configMode.value == "equal":
161                                         connto = self.getRoot(x, int(nim.connectedTo.value))
162                                         if not self.equal.has_key(connto):
163                                                 self.equal[connto] = []
164                                         self.equal[connto].append(x)
165                                 elif nim.configMode.value == "loopthrough":
166                                         self.linkNIMs(sec, x, int(nim.connectedTo.value))
167                                         connto = self.getRoot(x, int(nim.connectedTo.value))
168                                         if not self.linked.has_key(connto):
169                                                 self.linked[connto] = []
170                                         self.linked[connto].append(x)
171                                 elif nim.configMode.value == "satposdepends":
172                                         self.setSatposDepends(sec, x, int(nim.connectedTo.value))
173                                         connto = self.getRoot(x, int(nim.connectedTo.value))
174                                         if not self.satposdepends.has_key(connto):
175                                                 self.satposdepends[connto] = []
176                                         self.satposdepends[connto].append(x)
177
178                 for slot in nim_slots:
179                         x = slot.slot
180                         nim = slot.config
181                         hw = HardwareInfo()
182                         if slot.isCompatible("DVB-S"):
183                                 print "slot: " + str(x) + " configmode: " + str(nim.configMode.value)
184                                 if nim.configMode.value in ( "loopthrough", "satposdepends", "nothing" ):
185                                         pass
186                                 else:
187                                         slotLinked = False
188                                         if nim.configMode.value == "equal":
189                                                 pass
190                                         elif nim.configMode.value == "simple":          #simple config
191                                                 print "diseqcmode: ", nim.diseqcMode.value
192                                                 if nim.diseqcMode.value == "single":                    #single
193                                                         if nim.simpleSingleSendDiSEqC.value:
194                                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA, diseqc13V = nim.diseqc13V.value)
195                                                         else:
196                                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.NONE, diseqcpos = diseqcParam.SENDNO, diseqc13V = nim.diseqc13V.value)
197                                                 elif nim.diseqcMode.value == "toneburst_a_b":           #Toneburst A/B
198                                                         self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.A, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO, diseqc13V = nim.diseqc13V.value)
199                                                         self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.B, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO, diseqc13V = nim.diseqc13V.value)
200                                                 elif nim.diseqcMode.value == "diseqc_a_b":              #DiSEqC A/B
201                                                         fastDiSEqC = nim.simpleDiSEqCOnlyOnSatChange.value
202                                                         setVoltageTone = nim.simpleDiSEqCSetVoltageTone.value
203                                                         self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value)
204                                                         self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value)
205                                                 elif nim.diseqcMode.value == "diseqc_a_b_c_d":          #DiSEqC A/B/C/D
206                                                         fastDiSEqC = nim.simpleDiSEqCOnlyOnSatChange.value
207                                                         setVoltageTone = nim.simpleDiSEqCSetVoltageTone.value
208                                                         self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value)
209                                                         self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value)
210                                                         self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcC.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BA, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value)
211                                                         self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcD.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BB, fastDiSEqC = fastDiSEqC, setVoltageTone = setVoltageTone, diseqc13V = nim.diseqc13V.value)
212                                                 elif nim.diseqcMode.value == "positioner":              #Positioner
213                                                         if nim.latitudeOrientation.value == "north":
214                                                                 laValue = rotorParam.NORTH
215                                                         else:
216                                                                 laValue = rotorParam.SOUTH
217                                                         if nim.longitudeOrientation.value == "east":
218                                                                 loValue = rotorParam.EAST
219                                                         else:
220                                                                 loValue = rotorParam.WEST
221                                                         inputPowerDelta=nim.powerThreshold.value
222                                                         useInputPower=False
223                                                         turning_speed=0
224                                                         if nim.powerMeasurement.value:
225                                                                 useInputPower=True
226                                                                 turn_speed_dict = { "fast": rotorParam.FAST, "slow": rotorParam.SLOW }
227                                                                 if turn_speed_dict.has_key(nim.turningSpeed.value):
228                                                                         turning_speed = turn_speed_dict[nim.turningSpeed.value]
229                                                                 else:
230                                                                         beg_time = localtime(nim.fastTurningBegin.value)
231                                                                         end_time = localtime(nim.fastTurningEnd.value)
232                                                                         turning_speed = ((beg_time.tm_hour+1) * 60 + beg_time.tm_min + 1) << 16
233                                                                         turning_speed |= (end_time.tm_hour+1) * 60 + end_time.tm_min + 1
234                                                         self.addLNBSimple(sec, slotid = x, diseqcmode = 3,
235                                                                 longitude = nim.longitude.float,
236                                                                 loDirection = loValue,
237                                                                 latitude = nim.latitude.float,
238                                                                 laDirection = laValue,
239                                                                 turningSpeed = turning_speed,
240                                                                 useInputPower = useInputPower,
241                                                                 inputPowerDelta = inputPowerDelta,
242                                                                 diseqc13V = nim.diseqc13V.value)
243                                         elif nim.configMode.value == "advanced": #advanced config
244                                                 slotLinked = self.updateAdvanced(sec, x)
245                                         if not slotLinked:
246                                                 sec.setSlotNotLinked(x)
247                 print "sec config completed"
248
249         def updateAdvanced(self, sec, slotid):
250                 slotLinked = False
251                 try:
252                         if config.Nims[slotid].advanced.unicableconnected is not None:
253                                 if config.Nims[slotid].advanced.unicableconnected.value:
254                                         config.Nims[slotid].advanced.unicableconnectedTo.save_forced = True
255                                         self.linkNIMs(sec, slotid, int(config.Nims[slotid].advanced.unicableconnectedTo.value))
256                                         connto = self.getRoot(slotid, int(config.Nims[slotid].advanced.unicableconnectedTo.value))
257                                         if not self.linked.has_key(connto):
258                                                 self.linked[connto] = []
259                                         self.linked[connto].append(slotid)
260                                         slotLinked = True
261                                 else:
262                                         config.Nims[slotid].advanced.unicableconnectedTo.save_forced = False
263                 except:
264                         pass
265
266                 lnbSat = {}
267                 for x in range(1,37):
268                         lnbSat[x] = []
269
270                 #wildcard for all satellites ( for rotor )
271                 for x in range(3601, 3605):
272                         lnb = int(config.Nims[slotid].advanced.sat[x].lnb.value)
273                         if lnb != 0:
274                                 for x in self.NimManager.satList:
275                                         print "add", x[0], "to", lnb
276                                         lnbSat[lnb].append(x[0])
277
278                 for x in self.NimManager.satList:
279                         lnb = int(config.Nims[slotid].advanced.sat[x[0]].lnb.value)
280                         if lnb != 0:
281                                 print "add", x[0], "to", lnb
282                                 lnbSat[lnb].append(x[0])
283
284                 for x in range(1,37):
285                         if len(lnbSat[x]) > 0:
286                                 currLnb = config.Nims[slotid].advanced.lnb[x]
287                                 sec.addLNB()
288
289                                 if x < 33:
290                                         sec.setLNBNum(x)
291
292                                 tunermask = 1 << slotid
293                                 if self.equal.has_key(slotid):
294                                         for slot in self.equal[slotid]:
295                                                 tunermask |= (1 << slot)
296                                 if self.linked.has_key(slotid):
297                                         for slot in self.linked[slotid]:
298                                                 tunermask |= (1 << slot)
299
300                                 if currLnb.lof.value != "unicable":
301                                         sec.setLNBSatCR(-1)
302
303                                 if currLnb.lof.value == "universal_lnb":
304                                         sec.setLNBLOFL(9750000)
305                                         sec.setLNBLOFH(10600000)
306                                         sec.setLNBThreshold(11700000)
307                                 elif currLnb.lof.value == "unicable":
308                                         def setupUnicable(configManufacturer, ProductDict):
309                                                 manufacturer_name = configManufacturer.value
310                                                 manufacturer = ProductDict[manufacturer_name]
311                                                 product_name = manufacturer.product.value
312                                                 sec.setLNBSatCR(manufacturer.scr[product_name].index)
313                                                 sec.setLNBSatCRvco(manufacturer.vco[product_name][manufacturer.scr[product_name].index].value*1000)
314                                                 sec.setLNBSatCRpositions(manufacturer.positions[product_name][0].value)
315                                                 sec.setLNBLOFL(manufacturer.lofl[product_name][0].value * 1000)
316                                                 sec.setLNBLOFH(manufacturer.lofh[product_name][0].value * 1000)
317                                                 sec.setLNBThreshold(manufacturer.loft[product_name][0].value * 1000)
318                                                 configManufacturer.save_forced = True
319                                                 manufacturer.product.save_forced = True
320                                                 manufacturer.vco[product_name][manufacturer.scr[product_name].index].save_forced = True
321
322                                         if currLnb.unicable.value == "unicable_user":
323 #TODO satpositions for satcruser
324                                                 sec.setLNBLOFL(currLnb.lofl.value * 1000)
325                                                 sec.setLNBLOFH(currLnb.lofh.value * 1000)
326                                                 sec.setLNBThreshold(currLnb.threshold.value * 1000)
327                                                 sec.setLNBSatCR(currLnb.satcruser.index)
328                                                 sec.setLNBSatCRvco(currLnb.satcrvcouser[currLnb.satcruser.index].value*1000)
329                                                 sec.setLNBSatCRpositions(1)     #HACK
330                                         elif currLnb.unicable.value == "unicable_matrix":
331                                                 setupUnicable(currLnb.unicableMatrixManufacturer, currLnb.unicableMatrix)
332                                         elif currLnb.unicable.value == "unicable_lnb":
333                                                 setupUnicable(currLnb.unicableLnbManufacturer, currLnb.unicableLnb)
334                                 elif currLnb.lof.value == "c_band":
335                                         sec.setLNBLOFL(5150000)
336                                         sec.setLNBLOFH(5150000)
337                                         sec.setLNBThreshold(5150000)
338                                 elif currLnb.lof.value == "user_defined":
339                                         sec.setLNBLOFL(currLnb.lofl.value * 1000)
340                                         sec.setLNBLOFH(currLnb.lofh.value * 1000)
341                                         sec.setLNBThreshold(currLnb.threshold.value * 1000)
342
343 #                               if currLnb.output_12v.value == "0V":
344 #                                       pass # nyi in drivers
345 #                               elif currLnb.output_12v.value == "12V":
346 #                                       pass # nyi in drivers
347
348                                 if currLnb.increased_voltage.value:
349                                         sec.setLNBIncreasedVoltage(lnbParam.ON)
350                                 else:
351                                         sec.setLNBIncreasedVoltage(lnbParam.OFF)
352
353                                 dm = currLnb.diseqcMode.value
354                                 if dm == "none":
355                                         sec.setDiSEqCMode(diseqcParam.NONE)
356                                 elif dm == "1_0":
357                                         sec.setDiSEqCMode(diseqcParam.V1_0)
358                                 elif dm == "1_1":
359                                         sec.setDiSEqCMode(diseqcParam.V1_1)
360                                 elif dm == "1_2":
361                                         sec.setDiSEqCMode(diseqcParam.V1_2)
362
363                                         if self.satposdepends.has_key(slotid):
364                                                 for slot in self.satposdepends[slotid]:
365                                                         tunermask |= (1 << slot)
366
367                                 if dm != "none":
368                                         if currLnb.toneburst.value == "none":
369                                                 sec.setToneburst(diseqcParam.NO)
370                                         elif currLnb.toneburst.value == "A":
371                                                 sec.setToneburst(diseqcParam.A)
372                                         elif currLnb.toneburst.value == "B":
373                                                 sec.setToneburst(diseqcParam.B)
374
375                                         # Committed Diseqc Command
376                                         cdc = currLnb.commitedDiseqcCommand.value
377
378                                         c = { "none": diseqcParam.SENDNO,
379                                                 "AA": diseqcParam.AA,
380                                                 "AB": diseqcParam.AB,
381                                                 "BA": diseqcParam.BA,
382                                                 "BB": diseqcParam.BB }
383
384                                         if c.has_key(cdc):
385                                                 sec.setCommittedCommand(c[cdc])
386                                         else:
387                                                 sec.setCommittedCommand(long(cdc))
388
389                                         sec.setFastDiSEqC(currLnb.fastDiseqc.value)
390
391                                         sec.setSeqRepeat(currLnb.sequenceRepeat.value)
392
393                                         if currLnb.diseqcMode.value == "1_0":
394                                                 currCO = currLnb.commandOrder1_0.value
395                                                 sec.setRepeats(0)
396                                         else:
397                                                 currCO = currLnb.commandOrder.value
398
399                                                 udc = int(currLnb.uncommittedDiseqcCommand.value)
400                                                 if udc > 0:
401                                                         sec.setUncommittedCommand(0xF0|(udc-1))
402                                                 else:
403                                                         sec.setUncommittedCommand(0) # SENDNO
404
405                                                 sec.setRepeats({"none": 0, "one": 1, "two": 2, "three": 3}[currLnb.diseqcRepeats.value])
406
407                                         setCommandOrder = False
408
409                                         # 0 "committed, toneburst",
410                                         # 1 "toneburst, committed",
411                                         # 2 "committed, uncommitted, toneburst",
412                                         # 3 "toneburst, committed, uncommitted",
413                                         # 4 "uncommitted, committed, toneburst"
414                                         # 5 "toneburst, uncommitted, commmitted"
415                                         order_map = {"ct": 0, "tc": 1, "cut": 2, "tcu": 3, "uct": 4, "tuc": 5}
416                                         sec.setCommandOrder(order_map[currCO])
417
418                                 if dm == "1_2":
419                                         latitude = currLnb.latitude.float
420                                         sec.setLatitude(latitude)
421                                         longitude = currLnb.longitude.float
422                                         sec.setLongitude(longitude)
423                                         if currLnb.latitudeOrientation.value == "north":
424                                                 sec.setLaDirection(rotorParam.NORTH)
425                                         else:
426                                                 sec.setLaDirection(rotorParam.SOUTH)
427                                         if currLnb.longitudeOrientation.value == "east":
428                                                 sec.setLoDirection(rotorParam.EAST)
429                                         else:
430                                                 sec.setLoDirection(rotorParam.WEST)
431
432                                         if currLnb.powerMeasurement.value:
433                                                 sec.setUseInputpower(True)
434                                                 sec.setInputpowerDelta(currLnb.powerThreshold.value)
435                                                 turn_speed_dict = { "fast": rotorParam.FAST, "slow": rotorParam.SLOW }
436                                                 if turn_speed_dict.has_key(currLnb.turningSpeed.value):
437                                                         turning_speed = turn_speed_dict[currLnb.turningSpeed.value]
438                                                 else:
439                                                         beg_time = localtime(currLnb.fastTurningBegin.value)
440                                                         end_time = localtime(currLnb.fastTurningEnd.value)
441                                                         turning_speed = ((beg_time.tm_hour + 1) * 60 + beg_time.tm_min + 1) << 16
442                                                         turning_speed |= (end_time.tm_hour + 1) * 60 + end_time.tm_min + 1
443                                                 sec.setRotorTurningSpeed(turning_speed)
444                                         else:
445                                                 sec.setUseInputpower(False)
446
447                                 sec.setLNBSlotMask(tunermask)
448
449                                 sec.setLNBPrio(int(currLnb.prio.value))
450
451                                 # finally add the orbital positions
452                                 for y in lnbSat[x]:
453                                         self.addSatellite(sec, y)
454                                         if x > 32:
455                                                 satpos = x > 32 and (3604-(36 - x)) or y
456                                         else:
457                                                 satpos = y
458                                         currSat = config.Nims[slotid].advanced.sat[satpos]
459                                         if currSat.voltage.value == "polarization":
460                                                 if config.Nims[slotid].diseqc13V.value:
461                                                         sec.setVoltageMode(switchParam.HV_13)
462                                                 else:
463                                                         sec.setVoltageMode(switchParam.HV)
464                                         elif currSat.voltage.value == "13V":
465                                                 sec.setVoltageMode(switchParam._14V)
466                                         elif currSat.voltage.value == "18V":
467                                                 sec.setVoltageMode(switchParam._18V)
468
469                                         if currSat.tonemode.value == "band":
470                                                 sec.setToneMode(switchParam.HILO)
471                                         elif currSat.tonemode.value == "on":
472                                                 sec.setToneMode(switchParam.ON)
473                                         elif currSat.tonemode.value == "off":
474                                                 sec.setToneMode(switchParam.OFF)
475                                                 
476                                         if not currSat.usals.value and x < 34:
477                                                 sec.setRotorPosNum(currSat.rotorposition.value)
478                                         else:
479                                                 sec.setRotorPosNum(0) #USALS
480                 return slotLinked
481
482         def __init__(self, nimmgr):
483                 self.NimManager = nimmgr
484                 self.configuredSatellites = set()
485                 self.update()
486
487 class NIM(object):
488         def __init__(self, slot, type, description, has_outputs = True, internally_connectable = None, multi_type = {}, frontend_id = None, i2c = None, is_empty = False, input_name = None):
489                 self.slot = slot
490
491                 if type not in ("DVB-S", "DVB-C", "DVB-T", "DVB-S2", None):
492                         print "warning: unknown NIM type %s, not using." % type
493                         type = None
494
495                 self.type = type
496                 self.description = description
497                 self.has_outputs = has_outputs
498                 self.internally_connectable = internally_connectable
499                 self.multi_type = multi_type
500                 self.i2c = i2c
501                 self.frontend_id = frontend_id
502                 self.__is_empty = is_empty
503                 self.input_name = input_name
504
505         def isCompatible(self, what):
506                 if not self.isSupported():
507                         return False
508                 compatible = {
509                                 None: (None,),
510                                 "DVB-S": ("DVB-S", None),
511                                 "DVB-C": ("DVB-C", None),
512                                 "DVB-T": ("DVB-T", None),
513                                 "DVB-S2": ("DVB-S", "DVB-S2", None)
514                         }
515                 return what in compatible[self.type]
516         
517         def getType(self):
518                 return self.type
519         
520         def connectableTo(self):
521                 connectable = {
522                                 "DVB-S": ("DVB-S", "DVB-S2"),
523                                 "DVB-C": ("DVB-C",),
524                                 "DVB-T": ("DVB-T",),
525                                 "DVB-S2": ("DVB-S", "DVB-S2")
526                         }
527                 return connectable[self.type]
528         
529         def getSlotInputName(self):
530                 name = self.input_name
531                 if name is None:
532                         name = chr(ord('A') + self.slot)
533                 return name
534         
535         slot_input_name = property(getSlotInputName)
536
537         def getSlotName(self):
538                 # get a friendly description for a slot name.
539                 # we name them "Tuner A/B/C/...", because that's what's usually written on the back
540                 # of the device.
541                 descr = _("Tuner ")
542                 return descr + self.getSlotInputName()
543
544         slot_name = property(getSlotName)
545
546         def getSlotID(self):
547                 return chr(ord('A') + self.slot)
548         
549         def getI2C(self):
550                 return self.i2c
551         
552         def hasOutputs(self):
553                 return self.has_outputs
554         
555         def internallyConnectableTo(self):
556                 return self.internally_connectable
557         
558         def setInternalLink(self):
559                 if self.internally_connectable is not None:
560                         print "setting internal link on frontend id", self.frontend_id
561                         open("/proc/stb/frontend/%d/rf_switch" % self.frontend_id, "w").write("internal")
562                 
563         def removeInternalLink(self):
564                 if self.internally_connectable is not None:
565                         print "removing internal link on frontend id", self.frontend_id
566                         open("/proc/stb/frontend/%d/rf_switch" % self.frontend_id, "w").write("external")
567         
568         def isMultiType(self):
569                 return (len(self.multi_type) > 0)
570         
571         def isEmpty(self):
572                 return self.__is_empty
573         
574         # empty tuners are supported!
575         def isSupported(self):
576                 return (self.frontend_id is not None) or self.__is_empty
577         
578         # returns dict {<slotid>: <type>}
579         def getMultiTypeList(self):
580                 return self.multi_type
581
582         slot_id = property(getSlotID)
583
584         def getFriendlyType(self):
585                 return {
586                         "DVB-S": "DVB-S", 
587                         "DVB-T": "DVB-T",
588                         "DVB-S2": "DVB-S2",
589                         "DVB-C": "DVB-C",
590                         None: _("empty")
591                         }[self.type]
592
593         friendly_type = property(getFriendlyType)
594
595         def getFriendlyFullDescription(self):
596                 nim_text = self.slot_name + ": "
597                         
598                 if self.empty:
599                         nim_text += _("(empty)")
600                 elif not self.isSupported():
601                         nim_text += self.description + " (" + _("not supported") + ")"
602                 else:
603                         nim_text += self.description + " (" + self.friendly_type + ")"
604                 
605                 return nim_text
606
607         friendly_full_description = property(getFriendlyFullDescription)
608         config_mode = property(lambda self: config.Nims[self.slot].configMode.value)
609         config = property(lambda self: config.Nims[self.slot])
610         empty = property(lambda self: self.type is None)
611
612 class NimManager:
613         config_mode_str = {
614                 "nothing" : _("nothing connected"),
615                 "simple" : _("simple"),
616                 "advanced" : _("advanced"),
617                 "equal" : _("equal to"),
618                 "satposdepends" : _("second cable of motorized LNB"),
619                 "loopthrough" : "", # description is dynamically generated by connectedToChanged function (InitNimManager)
620                 }
621
622         def getConfigModeTuple(self, mode):
623                 return (mode, NimManager.config_mode_str[mode])
624
625         def getConfiguredSats(self):
626                 return self.sec.getConfiguredSats()
627
628         def getTransponders(self, pos):
629                 if self.transponders.has_key(pos):
630                         return self.transponders[pos]
631                 else:
632                         return []
633
634         def getTranspondersCable(self, nim):
635                 nimConfig = config.Nims[nim]
636                 if nimConfig.configMode.value != "nothing" and nimConfig.cable.scan_type.value == "provider":
637                         return self.transponderscable[self.cablesList[nimConfig.cable.scan_provider.index][0]]
638                 return [ ]
639
640         def getTranspondersTerrestrial(self, region):
641                 return self.transpondersterrestrial[region]
642         
643         def getCableDescription(self, nim):
644                 return self.cablesList[config.Nims[nim].scan_provider.index][0]
645
646         def getCableFlags(self, nim):
647                 return self.cablesList[config.Nims[nim].scan_provider.index][1]
648
649         def getTerrestrialDescription(self, nim):
650                 return self.terrestrialsList[config.Nims[nim].terrestrial.index][0]
651
652         def getTerrestrialFlags(self, nim):
653                 return self.terrestrialsList[config.Nims[nim].terrestrial.index][1]
654
655         def getSatDescription(self, pos):
656                 return self.satellites[pos]
657
658         def sortFunc(self, x):
659                 orbpos = x[0]
660                 if orbpos > 1800:
661                         return orbpos - 3600
662                 else:
663                         return orbpos + 1800
664
665         def readTransponders(self):
666                 # read initial networks from file. we only read files which we are interested in,
667                 # which means only these where a compatible tuner exists.
668                 self.satellites = { }
669                 self.transponders = { }
670                 self.transponderscable = { }
671                 self.transpondersterrestrial = { }
672                 db = eDVBDB.getInstance()
673                 if self.hasNimType("DVB-S"):
674                         print "Reading satellites.xml"
675                         db.readSatellites(self.satList, self.satellites, self.transponders)
676                         self.satList.sort(key = self.sortFunc) # sort by orbpos
677                         #print "SATLIST", self.satList
678                         #print "SATS", self.satellites
679                         #print "TRANSPONDERS", self.transponders
680
681                 if self.hasNimType("DVB-C"):
682                         print "Reading cables.xml"
683                         db.readCables(self.cablesList, self.transponderscable)
684 #                       print "CABLIST", self.cablesList
685 #                       print "TRANSPONDERS", self.transponders
686
687                 if self.hasNimType("DVB-T"):
688                         print "Reading terrestrial.xml"
689                         db.readTerrestrials(self.terrestrialsList, self.transpondersterrestrial)
690 #                       print "TERLIST", self.terrestrialsList
691 #                       print "TRANSPONDERS", self.transpondersterrestrial
692
693         def enumerateNIMs(self):
694                 # enum available NIMs. This is currently very dreambox-centric and uses the /proc/bus/nim_sockets interface.
695                 # the result will be stored into nim_slots.
696                 # the content of /proc/bus/nim_sockets looks like:
697                 # NIM Socket 0:
698                 #          Type: DVB-S
699                 #          Name: BCM4501 DVB-S2 NIM (internal)
700                 # NIM Socket 1:
701                 #          Type: DVB-S
702                 #          Name: BCM4501 DVB-S2 NIM (internal)
703                 # NIM Socket 2:
704                 #          Type: DVB-T
705                 #          Name: Philips TU1216
706                 # NIM Socket 3:
707                 #          Type: DVB-S
708                 #          Name: Alps BSBE1 702A
709                 
710                 #
711                 # Type will be either "DVB-S", "DVB-S2", "DVB-T", "DVB-C" or None.
712
713                 # nim_slots is an array which has exactly one entry for each slot, even for empty ones.
714                 self.nim_slots = [ ]
715
716                 nimfile = tryOpen("/proc/bus/nim_sockets")
717
718                 if nimfile is None:
719                         return
720
721                 current_slot = None
722
723                 entries = {}
724                 for line in nimfile.readlines():
725                         if line == "":
726                                 break
727                         if line.strip().startswith("NIM Socket"):
728                                 parts = line.strip().split(" ")
729                                 current_slot = int(parts[2][:-1])
730                                 entries[current_slot] = {}
731                         elif line.strip().startswith("Type:"):
732                                 entries[current_slot]["type"] = str(line.strip()[6:])
733                                 entries[current_slot]["isempty"] = False
734                         elif line.strip().startswith("Input_Name:"):
735                                 entries[current_slot]["input_name"] = str(line.strip()[12:])
736                         elif line.strip().startswith("Name:"):
737                                 entries[current_slot]["name"] = str(line.strip()[6:])
738                                 entries[current_slot]["isempty"] = False
739                         elif line.strip().startswith("Has_Outputs:"):
740                                 input = str(line.strip()[len("Has_Outputs:") + 1:])
741                                 entries[current_slot]["has_outputs"] = (input == "yes")
742                         elif line.strip().startswith("Internally_Connectable:"):
743                                 input = int(line.strip()[len("Internally_Connectable:") + 1:])
744                                 entries[current_slot]["internally_connectable"] = input
745                         elif line.strip().startswith("Frontend_Device:"):
746                                 input = int(line.strip()[len("Frontend_Device:") + 1:])
747                                 entries[current_slot]["frontend_device"] = input
748                         elif  line.strip().startswith("Mode"):
749                                 # "Mode 0: DVB-T" -> ["Mode 0", " DVB-T"]
750                                 split = line.strip().split(":")
751                                 # "Mode 0" -> ["Mode, "0"]
752                                 split2 = split[0].split(" ")
753                                 modes = entries[current_slot].get("multi_type", {})
754                                 modes[split2[1]] = split[1].strip()
755                                 entries[current_slot]["multi_type"] = modes
756                         elif line.strip().startswith("I2C_Device:"):
757                                 input = int(line.strip()[len("I2C_Device:") + 1:])
758                                 entries[current_slot]["i2c"] = input
759                         elif line.strip().startswith("empty"):
760                                 entries[current_slot]["type"] = None
761                                 entries[current_slot]["name"] = _("N/A")
762                                 entries[current_slot]["isempty"] = True
763                 nimfile.close()
764                 
765                 from os import path
766                 
767                 for id, entry in entries.items():
768                         if not (entry.has_key("name") and entry.has_key("type")):
769                                 entry["name"] =  _("N/A")
770                                 entry["type"] = None
771                         if not (entry.has_key("i2c")):
772                                 entry["i2c"] = None
773                         if entry.has_key("frontend_device"): # check if internally connectable
774                                 if path.exists("/proc/stb/frontend/%d/rf_switch" % entry["frontend_device"]):
775                                         entry["internally_connectable"] = id - 1
776                                 else:
777                                         entry["internally_connectable"] = None
778                         else:
779                                 entry["frontend_device"] = entry["internally_connectable"] = None
780                         if not (entry.has_key("multi_type")):
781                                 entry["multi_type"] = {}
782                         nim = NIM(slot = id, description = entry["name"], type = entry["type"], internally_connectable = entry["internally_connectable"], multi_type = entry["multi_type"], frontend_id = entry["frontend_device"], i2c = entry["i2c"], is_empty = entry["isempty"], input_name = entry.get("input_name", None))
783                         self.nim_slots.append(nim)
784
785         def hasNimType(self, chktype):
786                 for slot in self.nim_slots:
787                         if slot.isCompatible(chktype):
788                                 return True
789                         for type in slot.getMultiTypeList().values():
790                                 if chktype == type:
791                                         return True
792                 return False
793         
794         def getNimType(self, slotid):
795                 return self.nim_slots[slotid].type
796         
797         def getNimDescription(self, slotid):
798                 return self.nim_slots[slotid].friendly_full_description
799         
800         def getNimName(self, slotid):
801                 return self.nim_slots[slotid].description
802         
803         def getNimSlotInputName(self, slotid):
804                 # returns just "A", "B", ...
805                 return self.nim_slots[slotid].slot_input_name
806         
807         def getNimSlotName(self, slotid):
808                 # returns a friendly description string ("Tuner A", "Tuner B" etc.)
809                 return self.nim_slots[slotid].slot_name
810         
811         def getNim(self, slotid):
812                 return self.nim_slots[slotid]
813         
814         def getI2CDevice(self, slotid):
815                 return self.nim_slots[slotid].getI2C()
816
817         def getNimListOfType(self, type, exception = -1):
818                 # returns a list of indexes for NIMs compatible to the given type, except for 'exception'
819                 list = []
820                 for x in self.nim_slots:
821                         if x.isCompatible(type) and x.slot != exception:
822                                 list.append(x.slot)
823                 return list
824
825         def __init__(self):
826                 self.satList = [ ]
827                 self.cablesList = []
828                 self.terrestrialsList = []
829                 self.enumerateNIMs()
830                 self.readTransponders()
831                 InitNimManager(self)    #init config stuff
832
833         # get a list with the friendly full description
834         def nimList(self):
835                 list = [ ]
836                 for slot in self.nim_slots:
837                         list.append(slot.friendly_full_description)
838                 return list
839         
840         def getSlotCount(self):
841                 return len(self.nim_slots)
842         
843         def hasOutputs(self, slotid):
844                 return self.nim_slots[slotid].hasOutputs()
845         
846         def nimInternallyConnectableTo(self, slotid):
847                 return self.nim_slots[slotid].internallyConnectableTo()
848         
849         def nimRemoveInternalLink(self, slotid):
850                 self.nim_slots[slotid].removeInternalLink()
851         
852         def canConnectTo(self, slotid):
853                 slots = []
854                 internally_connectable = self.nimInternallyConnectableTo(slotid)
855                 if internally_connectable is not None:
856                         slots.append(internally_connectable)
857                 for type in self.nim_slots[slotid].connectableTo(): 
858                         for slot in self.getNimListOfType(type, exception = slotid):
859                                 if self.hasOutputs(slot):
860                                         slots.append(slot)
861                 # remove nims, that have a conntectedTo reference on
862                 for testnim in slots[:]:
863                         for nim in self.getNimListOfType("DVB-S", slotid):
864                                 nimConfig = self.getNimConfig(nim)
865                                 if nimConfig.content.items.has_key("configMode") and nimConfig.configMode.value == "loopthrough" and int(nimConfig.connectedTo.value) == testnim:
866                                         slots.remove(testnim)
867                                         break 
868                 slots.sort()
869                 
870                 return slots
871         
872         def canEqualTo(self, slotid):
873                 type = self.getNimType(slotid)
874                 if type == "DVB-S2":
875                         type = "DVB-S"
876                 nimList = self.getNimListOfType(type, slotid)
877                 for nim in nimList[:]:
878                         mode = self.getNimConfig(nim)
879                         if mode.configMode.value == "loopthrough" or mode.configMode.value == "satposdepends":
880                                 nimList.remove(nim)
881                 return nimList
882
883         def canDependOn(self, slotid):
884                 type = self.getNimType(slotid)
885                 if type == "DVB-S2":
886                         type = "DVB-S"
887                 nimList = self.getNimListOfType(type, slotid)
888                 positionerList = []
889                 for nim in nimList[:]:
890                         mode = self.getNimConfig(nim)
891                         nimHaveRotor = mode.configMode.value == "simple" and mode.diseqcMode.value == "positioner"
892                         if not nimHaveRotor and mode.configMode.value == "advanced":
893                                 for x in range(3601, 3605):
894                                         lnb = int(mode.advanced.sat[x].lnb.value)
895                                         if lnb != 0:
896                                                 nimHaveRotor = True
897                                                 break
898                                 if not nimHaveRotor:
899                                         for sat in mode.advanced.sat.values():
900                                                 lnb_num = int(sat.lnb.value)
901                                                 diseqcmode = lnb_num and mode.advanced.lnb[lnb_num].diseqcMode.value or ""
902                                                 if diseqcmode == "1_2":
903                                                         nimHaveRotor = True
904                                                         break
905                         if nimHaveRotor:
906                                 alreadyConnected = False
907                                 for testnim in nimList:
908                                         testmode = self.getNimConfig(testnim)
909                                         if testmode.configMode.value == "satposdepends" and int(testmode.connectedTo.value) == int(nim):
910                                                 alreadyConnected = True
911                                                 break
912                                 if not alreadyConnected:
913                                         positionerList.append(nim)
914                 return positionerList
915         
916         def getNimConfig(self, slotid):
917                 return config.Nims[slotid]
918         
919         def getSatName(self, pos):
920                 for sat in self.satList:
921                         if sat[0] == pos:
922                                 return sat[1]
923                 return _("N/A")
924
925         def getSatList(self):
926                 return self.satList
927         
928         # returns True if something is configured to be connected to this nim
929         # if slotid == -1, returns if something is connected to ANY nim
930         def somethingConnected(self, slotid = -1):
931                 if (slotid == -1):
932                         connected = False
933                         for id in range(self.getSlotCount()):
934                                 if self.somethingConnected(id):
935                                         connected = True
936                         return connected
937                 else:
938                         nim = config.Nims[slotid]
939                         configMode = nim.configMode.value
940                 
941                         if self.nim_slots[slotid].isCompatible("DVB-S") or self.nim_slots[slotid].isCompatible("DVB-T") or self.nim_slots[slotid].isCompatible("DVB-C"):
942                                 return not (configMode == "nothing")
943
944         def getSatListForNim(self, slotid):
945                 list = []
946                 if self.nim_slots[slotid].isCompatible("DVB-S"):
947                         nim = config.Nims[slotid]
948                         #print "slotid:", slotid
949
950                         #print "self.satellites:", self.satList[config.Nims[slotid].diseqcA.index]
951                         #print "diseqcA:", config.Nims[slotid].diseqcA.value
952                         configMode = nim.configMode.value
953
954                         if configMode == "equal":
955                                 slotid = int(nim.connectedTo.value)
956                                 nim = config.Nims[slotid]
957                                 configMode = nim.configMode.value
958                         elif configMode == "loopthrough":
959                                 slotid = self.sec.getRoot(slotid, int(nim.connectedTo.value))
960                                 nim = config.Nims[slotid]
961                                 configMode = nim.configMode.value
962
963                         if configMode == "simple":
964                                 dm = nim.diseqcMode.value
965                                 if dm in ("single", "toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"):
966                                         if nim.diseqcA.orbital_position != 3601:
967                                                 list.append(self.satList[nim.diseqcA.index-1])
968                                 if dm in ("toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"):
969                                         if nim.diseqcB.orbital_position != 3601:
970                                                 list.append(self.satList[nim.diseqcB.index-1])
971                                 if dm == "diseqc_a_b_c_d":
972                                         if nim.diseqcC.orbital_position != 3601:
973                                                 list.append(self.satList[nim.diseqcC.index-1])
974                                         if nim.diseqcD.orbital_position != 3601:
975                                                 list.append(self.satList[nim.diseqcD.index-1])
976                                 if dm == "positioner":
977                                         for x in self.satList:
978                                                 list.append(x)
979                         elif configMode == "advanced":
980                                 for x in range(3601, 3605):
981                                         if int(nim.advanced.sat[x].lnb.value) != 0:
982                                                 for x in self.satList:
983                                                         list.append(x)
984                                 if not list:
985                                         for x in self.satList:
986                                                 if int(nim.advanced.sat[x[0]].lnb.value) != 0:
987                                                         list.append(x)
988                 return list
989
990         def getRotorSatListForNim(self, slotid):
991                 list = []
992                 if self.nim_slots[slotid].isCompatible("DVB-S"):
993                         #print "slotid:", slotid
994                         #print "self.satellites:", self.satList[config.Nims[slotid].diseqcA.value]
995                         #print "diseqcA:", config.Nims[slotid].diseqcA.value
996                         configMode = config.Nims[slotid].configMode.value
997                         if configMode == "simple":
998                                 if config.Nims[slotid].diseqcMode.value == "positioner":
999                                         for x in self.satList:
1000                                                 list.append(x)
1001                         elif configMode == "advanced":
1002                                 nim = config.Nims[slotid]
1003                                 for x in range(3601, 3605):
1004                                         if int(nim.advanced.sat[x].lnb.value) != 0:
1005                                                 for x in self.satList:
1006                                                         list.append(x)
1007                                 if not list:
1008                                         for x in self.satList:
1009                                                 lnbnum = int(nim.advanced.sat[x[0]].lnb.value)
1010                                                 if lnbnum != 0:
1011                                                         lnb = nim.advanced.lnb[lnbnum]
1012                                                         if lnb.diseqcMode.value == "1_2":
1013                                                                 list.append(x)
1014                 return list
1015
1016 def InitSecParams():
1017         config.sec = ConfigSubsection()
1018
1019         x = ConfigInteger(default=25, limits = (0, 9999))
1020         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_CONT_TONE_DISABLE_BEFORE_DISEQC, configElement.value))
1021         config.sec.delay_after_continuous_tone_disable_before_diseqc = x
1022
1023         x = ConfigInteger(default=10, limits = (0, 9999))
1024         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_FINAL_CONT_TONE_CHANGE, configElement.value))
1025         config.sec.delay_after_final_continuous_tone_change = x
1026
1027         x = ConfigInteger(default=10, limits = (0, 9999))
1028         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_FINAL_VOLTAGE_CHANGE, configElement.value))
1029         config.sec.delay_after_final_voltage_change = x
1030
1031         x = ConfigInteger(default=120, limits = (0, 9999))
1032         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_BETWEEN_DISEQC_REPEATS, configElement.value))
1033         config.sec.delay_between_diseqc_repeats = x
1034
1035         x = ConfigInteger(default=50, limits = (0, 9999))
1036         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_LAST_DISEQC_CMD, configElement.value))
1037         config.sec.delay_after_last_diseqc_command = x
1038
1039         x = ConfigInteger(default=50, limits = (0, 9999))
1040         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_TONEBURST, configElement.value))
1041         config.sec.delay_after_toneburst = x
1042
1043         x = ConfigInteger(default=20, limits = (0, 9999))
1044         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_SWITCH_CMDS, configElement.value))
1045         config.sec.delay_after_change_voltage_before_switch_command = x
1046
1047         x = ConfigInteger(default=400, limits = (0, 9999))
1048         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_ENABLE_VOLTAGE_BEFORE_SWITCH_CMDS, configElement.value))
1049         config.sec.delay_after_enable_voltage_before_switch_command = x
1050
1051         x = ConfigInteger(default=700, limits = (0, 9999))
1052         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_BETWEEN_SWITCH_AND_MOTOR_CMD, configElement.value))
1053         config.sec.delay_between_switch_and_motor_command = x
1054
1055         x = ConfigInteger(default=500, limits = (0, 9999))
1056         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_MEASURE_IDLE_INPUTPOWER, configElement.value))
1057         config.sec.delay_after_voltage_change_before_measure_idle_inputpower = x
1058
1059         x = ConfigInteger(default=900, limits = (0, 9999))
1060         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_ENABLE_VOLTAGE_BEFORE_MOTOR_CMD, configElement.value))
1061         config.sec.delay_after_enable_voltage_before_motor_command = x
1062
1063         x = ConfigInteger(default=500, limits = (0, 9999))
1064         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_MOTOR_STOP_CMD, configElement.value))
1065         config.sec.delay_after_motor_stop_command = x
1066
1067         x = ConfigInteger(default=500, limits = (0, 9999))
1068         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_MOTOR_CMD, configElement.value))
1069         config.sec.delay_after_voltage_change_before_motor_command = x
1070
1071         x = ConfigInteger(default=70, limits = (0, 9999))
1072         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_BEFORE_SEQUENCE_REPEAT, configElement.value))
1073         config.sec.delay_before_sequence_repeat = x
1074
1075         x = ConfigInteger(default=360, limits = (0, 9999))
1076         x.addNotifier(lambda configElement: secClass.setParam(secClass.MOTOR_RUNNING_TIMEOUT, configElement.value))
1077         config.sec.motor_running_timeout = x
1078
1079         x = ConfigInteger(default=1, limits = (0, 5))
1080         x.addNotifier(lambda configElement: secClass.setParam(secClass.MOTOR_COMMAND_RETRIES, configElement.value))
1081         config.sec.motor_command_retries = x
1082
1083         x = ConfigInteger(default=50, limits = (0, 9999))
1084         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_DISEQC_RESET_CMD, configElement.value))
1085         config.sec.delay_after_diseqc_reset_cmd = x
1086
1087         x = ConfigInteger(default=150, limits = (0, 9999))
1088         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_DISEQC_PERIPHERIAL_POWERON_CMD, configElement.value))
1089         config.sec.delay_after_diseqc_peripherial_poweron_cmd = x
1090
1091         x = ConfigInteger(default=10, limits = (0, 9999))
1092         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_UNICABLE_CMD, configElement.value))
1093         config.sec.delay_after_voltage_change_before_unicable_cmd = x
1094
1095         x = ConfigInteger(default=5, limits = (0, 9999))
1096         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_UNICABLE_CMD, configElement.value))
1097         config.sec.delay_after_unicable_cmd = x
1098
1099         x = ConfigInteger(default=10, limits = (0, 9999))
1100         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_UNICABLE_FINAL_VOLTAGE_CHANGE, configElement.value))
1101         config.sec.delay_after_unicable_final_voltage_change = x
1102
1103 # TODO add support for satpos depending nims to advanced nim configuration
1104 # so a second/third/fourth cable from a motorized lnb can used behind a
1105 # diseqc 1.0 / diseqc 1.1 / toneburst switch
1106 # the C(++) part should can handle this
1107 # the configElement should be only visible when diseqc 1.2 is disabled
1108
1109 def InitNimManager(nimmgr, slot_no = None):
1110         hw = HardwareInfo()
1111         addNimConfig = False
1112         try:
1113                 config.Nims
1114                 assert slot_no is not None, "FATAL: you must call InitNimManager(nimmgr, slot_no = X) to reinitialize SINGLE nim slots"
1115         except:
1116                 addNimConfig = True
1117
1118         if addNimConfig:
1119                 InitSecParams()
1120                 config.Nims = ConfigSubList()
1121                 for x in range(len(nimmgr.nim_slots)):
1122                         config.Nims.append(ConfigSubsection())
1123
1124         lnb_choices = {
1125                 "universal_lnb": _("Universal LNB"),
1126                 "unicable": _("Unicable"),
1127                 "c_band": _("C-Band"),
1128                 "user_defined": _("User defined")}
1129
1130         lnb_choices_default = "universal_lnb"
1131
1132         unicablelnbproducts = {}
1133         unicablematrixproducts = {}
1134         doc = xml.etree.cElementTree.parse(eEnv.resolve("${datadir}/enigma2/unicable.xml"))
1135         root = doc.getroot()
1136
1137         entry = root.find("lnb")
1138         for manufacturer in entry.getchildren():
1139                 m={}
1140                 for product in manufacturer.getchildren():
1141                         scr=[]
1142                         lscr=("scr1","scr2","scr3","scr4","scr5","scr6","scr7","scr8")
1143                         for i in range(len(lscr)):
1144                                 scr.append(product.get(lscr[i],"0"))
1145                         for i in range(len(lscr)):
1146                                 if scr[len(lscr)-i-1] == "0":
1147                                         scr.pop()
1148                                 else:
1149                                         break;
1150                         lof=[]
1151                         lof.append(int(product.get("positions",1)))
1152                         lof.append(int(product.get("lofl",9750)))
1153                         lof.append(int(product.get("lofh",10600)))
1154                         lof.append(int(product.get("threshold",11700)))
1155                         scr.append(tuple(lof))
1156                         m.update({product.get("name"):tuple(scr)})
1157                 unicablelnbproducts.update({manufacturer.get("name"):m})
1158
1159         entry = root.find("matrix")
1160         for manufacturer in entry.getchildren():
1161                 m={}
1162                 for product in manufacturer.getchildren():
1163                         scr=[]
1164                         lscr=("scr1","scr2","scr3","scr4","scr5","scr6","scr7","scr8")
1165                         for i in range(len(lscr)):
1166                                 scr.append(product.get(lscr[i],"0"))
1167                         for i in range(len(lscr)):
1168                                 if scr[len(lscr)-i-1] == "0":
1169                                         scr.pop()
1170                                 else:
1171                                         break;
1172                         lof=[]
1173                         lof.append(int(product.get("positions",1)))
1174                         lof.append(int(product.get("lofl",9750)))
1175                         lof.append(int(product.get("lofh",10600)))
1176                         lof.append(int(product.get("threshold",11700)))
1177                         scr.append(tuple(lof))
1178                         m.update({product.get("name"):tuple(scr)})
1179                 unicablematrixproducts.update({manufacturer.get("name"):m})
1180
1181         UnicableLnbManufacturers = unicablelnbproducts.keys()
1182         UnicableLnbManufacturers.sort()
1183         UnicableMatrixManufacturers = unicablematrixproducts.keys()
1184         UnicableMatrixManufacturers.sort()
1185
1186         unicable_choices = {
1187                 "unicable_lnb": _("Unicable LNB"),
1188                 "unicable_matrix": _("Unicable Martix"),
1189                 "unicable_user": "Unicable "+_("User defined")}
1190         unicable_choices_default = "unicable_lnb"
1191
1192         advanced_lnb_satcruser_choices = [ ("1", "SatCR 1"), ("2", "SatCR 2"), ("3", "SatCR 3"), ("4", "SatCR 4"),
1193                                         ("5", "SatCR 5"), ("6", "SatCR 6"), ("7", "SatCR 7"), ("8", "SatCR 8")]
1194
1195         prio_list = [ ("-1", _("Auto")) ]
1196         prio_list += [(str(prio), str(prio)) for prio in range(65)+range(14000,14065)+range(19000,19065)]
1197
1198         advanced_lnb_csw_choices = [("none", _("None")), ("AA", _("AA")), ("AB", _("AB")), ("BA", _("BA")), ("BB", _("BB"))]
1199         advanced_lnb_csw_choices += [(str(0xF0|y), "Input " + str(y+1)) for y in range(0, 16)]
1200
1201         advanced_lnb_ucsw_choices = [("0", _("None"))] + [(str(y), "Input " + str(y)) for y in range(1, 17)]
1202
1203         diseqc_mode_choices = [
1204                 ("single", _("Single")), ("toneburst_a_b", _("Toneburst A/B")),
1205                 ("diseqc_a_b", _("DiSEqC A/B")), ("diseqc_a_b_c_d", _("DiSEqC A/B/C/D")),
1206                 ("positioner", _("Positioner"))]
1207
1208         positioner_mode_choices = [("usals", _("USALS")), ("manual", _("manual"))]
1209
1210         diseqc_satlist_choices = [(3601, _('nothing connected'), 1)] + nimmgr.satList
1211         
1212         longitude_orientation_choices = [("east", _("East")), ("west", _("West"))]
1213         latitude_orientation_choices = [("north", _("North")), ("south", _("South"))]
1214         turning_speed_choices = [("fast", _("Fast")), ("slow", _("Slow")), ("fast epoch", _("Fast epoch"))]
1215         
1216         advanced_satlist_choices = nimmgr.satList + [
1217                 (3601, _('All Satellites')+' 1', 1), (3602, _('All Satellites')+' 2', 1),
1218                 (3603, _('All Satellites')+' 3', 1), (3604, _('All Satellites')+' 4', 1)]
1219         advanced_lnb_choices = [("0", "not available")] + [(str(y), "LNB " + str(y)) for y in range(1, 33)]
1220         advanced_voltage_choices = [("polarization", _("Polarization")), ("13V", _("13 V")), ("18V", _("18 V"))]
1221         advanced_tonemode_choices = [("band", _("Band")), ("on", _("On")), ("off", _("Off"))]
1222         advanced_lnb_toneburst_choices = [("none", _("None")), ("A", _("A")), ("B", _("B"))]
1223         advanced_lnb_allsat_diseqcmode_choices = [("1_2", _("1.2"))]
1224         advanced_lnb_diseqcmode_choices = [("none", _("None")), ("1_0", _("1.0")), ("1_1", _("1.1")), ("1_2", _("1.2"))]
1225         advanced_lnb_commandOrder1_0_choices = [("ct", "committed, toneburst"), ("tc", "toneburst, committed")]
1226         advanced_lnb_commandOrder_choices = [
1227                 ("ct", "committed, toneburst"), ("tc", "toneburst, committed"),
1228                 ("cut", "committed, uncommitted, toneburst"), ("tcu", "toneburst, committed, uncommitted"),
1229                 ("uct", "uncommitted, committed, toneburst"), ("tuc", "toneburst, uncommitted, commmitted")]
1230         advanced_lnb_diseqc_repeat_choices = [("none", _("None")), ("one", _("One")), ("two", _("Two")), ("three", _("Three"))]
1231         advanced_lnb_fast_turning_btime = mktime(datetime(1970, 1, 1, 7, 0).timetuple());
1232         advanced_lnb_fast_turning_etime = mktime(datetime(1970, 1, 1, 19, 0).timetuple());
1233
1234         def configLOFChanged(configElement):
1235                 if configElement.value == "unicable":
1236                         x = configElement.slot_id
1237                         lnb = configElement.lnb_id
1238                         nim = config.Nims[x]
1239                         lnbs = nim.advanced.lnb
1240                         section = lnbs[lnb]
1241                         if isinstance(section.unicable, ConfigNothing):
1242                                 if lnb == 1:
1243                                         section.unicable = ConfigSelection(unicable_choices, unicable_choices_default)
1244                                 elif lnb == 2:
1245                                         section.unicable = ConfigSelection(choices = {"unicable_matrix": _("Unicable Martix"),"unicable_user": "Unicable "+_("User defined")}, default = "unicable_matrix")
1246                                 else:
1247                                         section.unicable = ConfigSelection(choices = {"unicable_user": _("User defined")}, default = "unicable_user")
1248
1249                 #TODO !!! Fix this function.. it creates when MATRIX and LNB is used 1700 ConfigElements per LNB!!!!
1250                 # this is realy slow ;(
1251                                 def fillUnicableConf(sectionDict, unicableproducts, vco_null_check):
1252                                         for y in unicableproducts:
1253                                                 products = unicableproducts[y].keys()
1254                                                 products.sort()
1255                                                 tmp = ConfigSubsection()
1256                                                 tmp.product = ConfigSelection(choices = products, default = products[0])
1257                                                 tmp.scr = ConfigSubDict()
1258                                                 tmp.vco = ConfigSubDict()
1259                                                 tmp.lofl = ConfigSubDict()
1260                                                 tmp.lofh = ConfigSubDict()
1261                                                 tmp.loft = ConfigSubDict()
1262                                                 tmp.positions = ConfigSubDict()
1263                                                 for z in products:
1264                                                         scrlist = []
1265                                                         vcolist = unicableproducts[y][z]
1266                                                         tmp.vco[z] = ConfigSubList()
1267                                                         for cnt in range(1,1+len(vcolist)-1):
1268                                                                 vcofreq = int(vcolist[cnt-1])
1269                                                                 if vcofreq == 0 and vco_null_check:
1270                                                                         scrlist.append(("%d" %cnt,"SCR %d " %cnt +_("not used")))
1271                                                                 else:
1272                                                                         scrlist.append(("%d" %cnt,"SCR %d" %cnt))
1273                                                                 tmp.vco[z].append(ConfigInteger(default=vcofreq, limits = (vcofreq, vcofreq)))
1274                                                                 tmp.scr[z] = ConfigSelection(choices = scrlist, default = scrlist[0][0])
1275
1276                                                                 positions = int(vcolist[len(vcolist)-1][0])
1277                                                                 tmp.positions[z] = ConfigSubList()
1278                                                                 tmp.positions[z].append(ConfigInteger(default=positions, limits = (positions, positions)))
1279
1280                                                                 lofl = vcolist[len(vcolist)-1][1]
1281                                                                 tmp.lofl[z] = ConfigSubList()
1282                                                                 tmp.lofl[z].append(ConfigInteger(default=lofl, limits = (lofl, lofl)))
1283
1284                                                                 lofh = int(vcolist[len(vcolist)-1][2])
1285                                                                 tmp.lofh[z] = ConfigSubList()
1286                                                                 tmp.lofh[z].append(ConfigInteger(default=lofh, limits = (lofh, lofh)))
1287
1288                                                                 loft = int(vcolist[len(vcolist)-1][3])
1289                                                                 tmp.loft[z] = ConfigSubList()
1290                                                                 tmp.loft[z].append(ConfigInteger(default=loft, limits = (loft, loft)))
1291                                                 sectionDict[y] = tmp
1292
1293                                 if lnb < 3:
1294                                         print "MATRIX"
1295                                         section.unicableMatrix = ConfigSubDict()
1296                                         section.unicableMatrixManufacturer = ConfigSelection(UnicableMatrixManufacturers, UnicableMatrixManufacturers[0])
1297                                         fillUnicableConf(section.unicableMatrix, unicablematrixproducts, True)
1298
1299                                 if lnb < 2:
1300                                         print "LNB"
1301                                         section.unicableLnb = ConfigSubDict()
1302                                         section.unicableLnbManufacturer = ConfigSelection(UnicableLnbManufacturers, UnicableLnbManufacturers[0])
1303                                         fillUnicableConf(section.unicableLnb, unicablelnbproducts, False)
1304
1305 #TODO satpositions for satcruser
1306                                 section.satcruser = ConfigSelection(advanced_lnb_satcruser_choices, default="1")
1307                                 tmp = ConfigSubList()
1308                                 tmp.append(ConfigInteger(default=1284, limits = (950, 2150)))
1309                                 tmp.append(ConfigInteger(default=1400, limits = (950, 2150)))
1310                                 tmp.append(ConfigInteger(default=1516, limits = (950, 2150)))
1311                                 tmp.append(ConfigInteger(default=1632, limits = (950, 2150)))
1312                                 tmp.append(ConfigInteger(default=1748, limits = (950, 2150)))
1313                                 tmp.append(ConfigInteger(default=1864, limits = (950, 2150)))
1314                                 tmp.append(ConfigInteger(default=1980, limits = (950, 2150)))
1315                                 tmp.append(ConfigInteger(default=2096, limits = (950, 2150)))
1316                                 section.satcrvcouser = tmp 
1317
1318                                 nim.advanced.unicableconnected = ConfigYesNo(default=False)
1319                                 nim.advanced.unicableconnectedTo = ConfigSelection([(str(id), nimmgr.getNimDescription(id)) for id in nimmgr.getNimListOfType("DVB-S") if id != x])
1320         
1321         def configDiSEqCModeChanged(configElement):
1322                 section = configElement.section
1323                 if configElement.value == "1_2" and isinstance(section.longitude, ConfigNothing):
1324                         section.longitude = ConfigFloat(default = [5,100], limits = [(0,359),(0,999)])
1325                         section.longitudeOrientation = ConfigSelection(longitude_orientation_choices, "east")
1326                         section.latitude = ConfigFloat(default = [50,767], limits = [(0,359),(0,999)])
1327                         section.latitudeOrientation = ConfigSelection(latitude_orientation_choices, "north")
1328                         section.powerMeasurement = ConfigYesNo(default=True)
1329                         section.powerThreshold = ConfigInteger(default=15, limits=(0, 100))
1330                         section.turningSpeed = ConfigSelection(turning_speed_choices, "fast")
1331                         section.fastTurningBegin = ConfigDateTime(default=advanced_lnb_fast_turning_btime, formatstring = _("%H:%M"), increment = 600)
1332                         section.fastTurningEnd = ConfigDateTime(default=advanced_lnb_fast_turning_etime, formatstring = _("%H:%M"), increment = 600)
1333
1334         def configLNBChanged(configElement):
1335                 x = configElement.slot_id
1336                 nim = config.Nims[x]
1337                 if isinstance(configElement.value, tuple):
1338                         lnb = int(configElement.value[0])
1339                 else:
1340                         lnb = int(configElement.value)
1341                 lnbs = nim.advanced.lnb
1342                 if lnb and lnb not in lnbs:
1343                         section = lnbs[lnb] = ConfigSubsection()
1344                         section.lofl = ConfigInteger(default=9750, limits = (0, 99999))
1345                         section.lofh = ConfigInteger(default=10600, limits = (0, 99999))
1346                         section.threshold = ConfigInteger(default=11700, limits = (0, 99999))
1347 #                       section.output_12v = ConfigSelection(choices = [("0V", _("0 V")), ("12V", _("12 V"))], default="0V")
1348                         section.increased_voltage = ConfigYesNo(False)
1349                         section.toneburst = ConfigSelection(advanced_lnb_toneburst_choices, "none")
1350                         section.longitude = ConfigNothing()
1351                         if lnb > 32:
1352                                 tmp = ConfigSelection(advanced_lnb_allsat_diseqcmode_choices, "1_2")
1353                                 tmp.section = section
1354                                 configDiSEqCModeChanged(tmp)
1355                         else:
1356                                 tmp = ConfigSelection(advanced_lnb_diseqcmode_choices, "none")
1357                                 tmp.section = section
1358                                 tmp.addNotifier(configDiSEqCModeChanged)
1359                         section.diseqcMode = tmp
1360                         section.commitedDiseqcCommand = ConfigSelection(advanced_lnb_csw_choices)
1361                         section.fastDiseqc = ConfigYesNo(False)
1362                         section.sequenceRepeat = ConfigYesNo(False)
1363                         section.commandOrder1_0 = ConfigSelection(advanced_lnb_commandOrder1_0_choices, "ct")
1364                         section.commandOrder = ConfigSelection(advanced_lnb_commandOrder_choices, "ct")
1365                         section.uncommittedDiseqcCommand = ConfigSelection(advanced_lnb_ucsw_choices)
1366                         section.diseqcRepeats = ConfigSelection(advanced_lnb_diseqc_repeat_choices, "none")
1367                         section.prio = ConfigSelection(prio_list, "-1")
1368                         section.unicable = ConfigNothing()
1369                         tmp = ConfigSelection(lnb_choices, lnb_choices_default)
1370                         tmp.slot_id = x
1371                         tmp.lnb_id = lnb
1372                         tmp.addNotifier(configLOFChanged, initial_call = False)
1373                         section.lof = tmp
1374
1375         def configModeChanged(configMode):
1376                 slot_id = configMode.slot_id
1377                 nim = config.Nims[slot_id]
1378                 if configMode.value == "advanced" and isinstance(nim.advanced, ConfigNothing):
1379                         # advanced config:
1380                         nim.advanced = ConfigSubsection()
1381                         nim.advanced.sat = ConfigSubDict()
1382                         nim.advanced.sats = getConfigSatlist(192, advanced_satlist_choices)
1383                         nim.advanced.lnb = ConfigSubDict()
1384                         nim.advanced.lnb[0] = ConfigNothing()
1385                         for x in nimmgr.satList:
1386                                 tmp = ConfigSubsection()
1387                                 tmp.voltage = ConfigSelection(advanced_voltage_choices, "polarization")
1388                                 tmp.tonemode = ConfigSelection(advanced_tonemode_choices, "band")
1389                                 tmp.usals = ConfigYesNo(True)
1390                                 tmp.rotorposition = ConfigInteger(default=1, limits=(1, 255))
1391                                 lnb = ConfigSelection(advanced_lnb_choices, "0")
1392                                 lnb.slot_id = slot_id
1393                                 lnb.addNotifier(configLNBChanged, initial_call = False)
1394                                 tmp.lnb = lnb
1395                                 nim.advanced.sat[x[0]] = tmp
1396                         for x in range(3601, 3605):
1397                                 tmp = ConfigSubsection()
1398                                 tmp.voltage = ConfigSelection(advanced_voltage_choices, "polarization")
1399                                 tmp.tonemode = ConfigSelection(advanced_tonemode_choices, "band")
1400                                 tmp.usals = ConfigYesNo(default=True)
1401                                 tmp.rotorposition = ConfigInteger(default=1, limits=(1, 255))
1402                                 lnbnum = 33+x-3601
1403                                 lnb = ConfigSelection([("0", "not available"), (str(lnbnum), "LNB %d"%(lnbnum))], "0")
1404                                 lnb.slot_id = slot_id
1405                                 lnb.addNotifier(configLNBChanged, initial_call = False)
1406                                 tmp.lnb = lnb
1407                                 nim.advanced.sat[x] = tmp
1408
1409         def scpcSearchRangeChanged(configElement):
1410                 fe_id = configElement.fe_id
1411                 slot_id = configElement.slot_id
1412                 name = nimmgr.nim_slots[slot_id].description
1413                 if name == 'Alps BSBE2' or name.find('BCM450') != -1:
1414                         open("/proc/stb/frontend/%d/use_scpc_optimized_search_range" %(fe_id), "w").write(configElement.value)
1415
1416         def toneAmplitudeChanged(configElement):
1417                 fe_id = configElement.fe_id
1418                 slot_id = configElement.slot_id
1419                 if nimmgr.nim_slots[slot_id].description == 'Alps BSBE2':
1420                         open("/proc/stb/frontend/%d/tone_amplitude" %(fe_id), "w").write(configElement.value)
1421
1422         def tunerTypeChanged(nimmgr, configElement):
1423                 slot_id = configElement.slot_id
1424                 raw_channel = eDVBResourceManager.getInstance().allocateRawChannel(slot_id)
1425                 frontend = raw_channel and raw_channel.getFrontend()
1426                 if frontend:
1427                         system = configElement.getText()
1428                         if system == 'DVB-S':
1429                                 ret = frontend.changeType(iDVBFrontend.feSatellite)
1430                         elif system == 'DVB-S2':
1431                                 ret = frontend.changeType(iDVBFrontend.feSatellite2)
1432                         elif system == 'DVB-C':
1433                                 ret = frontend.changeType(iDVBFrontend.feCable)
1434                         elif system == 'DVB-T':
1435                                 ret = frontend.changeType(iDVBFrontend.feTerrestrial)
1436                         else:
1437                                 ret = False
1438                         if ret:
1439                                 nimmgr.enumerateNIMs()
1440                         else:
1441                                 print "%d: tunerTypeChange to '%s' failed" %(slot_id, system)
1442                 else:
1443                         print "%d: tunerTypeChange to '%s' failed (BUSY)" %(slot_id, configElement.getText())
1444
1445         def connectedToChanged(slot_id, nimmgr, configElement):
1446                 configMode = nimmgr.getNimConfig(slot_id).configMode
1447                 if configMode.value == 'loopthrough':
1448                         internally_connectable = nimmgr.nimInternallyConnectableTo(slot_id)
1449                         dest_slot = configElement.value
1450                         if internally_connectable is not None and int(internally_connectable) == int(dest_slot):
1451                                 configMode.choices.updateItemDescription(configMode.index, _("internally loopthrough to"))
1452                         else:
1453                                 configMode.choices.updateItemDescription(configMode.index, _("externally loopthrough to"))
1454
1455         # since we set the multitype tuner type via linux tv api ioctl we must
1456         # call setFrontendSlotInformations before tunerTypeChanged is possible
1457         # because allocateRawChannel calls allocateFrontendByIndex which needs the slot_id...
1458         if addNimConfig:
1459                 multitype = 0
1460                 used_nim_slots = [ ]
1461                 for slot in nimmgr.nim_slots:
1462                         used_nim_slots.append((slot.slot, slot.description, False, slot.frontend_id is None and -1 or slot.frontend_id, slot.input_name or ""))
1463                         if slot.type is not None and slot.isMultiType():
1464                                 multitype += 1
1465                 if multitype:
1466                         eDVBResourceManager.getInstance().setFrontendSlotInformations(used_nim_slots)
1467
1468         for slot in nimmgr.nim_slots:
1469                 x = slot.slot
1470
1471                 # only re-init specific nim slot when InitNimManager is called again
1472                 if slot_no is not None and x != slot_no:
1473                         continue
1474
1475                 nim = config.Nims[x]
1476                 addMultiType = False
1477                 try:
1478                         nim.multiType
1479                 except:
1480                         addMultiType = True
1481                 if slot.isMultiType() and addMultiType:
1482                         typeList = []
1483                         for id in slot.getMultiTypeList().keys():
1484                                 type = slot.getMultiTypeList()[id]
1485                                 typeList.append((id, type))
1486                         nim.multiType = ConfigSelection(typeList, "0")
1487                         nim.multiType.slot_id = x
1488                         nim.multiType.addNotifier(boundFunction(tunerTypeChanged, nimmgr))
1489
1490         getConfigModeTuple=nimmgr.getConfigModeTuple
1491
1492         empty_slots = 0
1493         for slot in nimmgr.nim_slots:
1494                 x = slot.slot
1495
1496                 # only re-init specific nim slot when InitNimManager is called again
1497                 if slot_no is not None and x != slot_no:
1498                         continue
1499
1500                 nim = config.Nims[x]
1501
1502                 if slot.isCompatible("DVB-S"):
1503                         nim.toneAmplitude = ConfigSelection([("11", "340mV"), ("10", "360mV"), ("9", "600mV"), ("8", "700mV"), ("7", "800mV"), ("6", "900mV"), ("5", "1100mV")], "7")
1504                         nim.toneAmplitude.fe_id = x - empty_slots
1505                         nim.toneAmplitude.slot_id = x
1506                         nim.toneAmplitude.addNotifier(toneAmplitudeChanged)
1507                         nim.scpcSearchRange = ConfigSelection([("0", _("no")), ("1", _("yes"))], "0")
1508                         nim.scpcSearchRange.fe_id = x - empty_slots
1509                         nim.scpcSearchRange.slot_id = x
1510                         nim.scpcSearchRange.addNotifier(scpcSearchRangeChanged)
1511                         nim.diseqc13V = ConfigYesNo(False)
1512                         nim.diseqcMode = ConfigSelection(diseqc_mode_choices, "diseqc_a_b")
1513                         nim.connectedTo = ConfigSelection([(str(id), nimmgr.getNimDescription(id)) for id in nimmgr.getNimListOfType("DVB-S") if id != x])
1514                         nim.simpleSingleSendDiSEqC = ConfigYesNo(False)
1515                         nim.simpleDiSEqCSetVoltageTone = ConfigYesNo(True)
1516                         nim.simpleDiSEqCOnlyOnSatChange = ConfigYesNo(False)
1517                         nim.diseqcA = getConfigSatlist(192, diseqc_satlist_choices)
1518                         nim.diseqcB = getConfigSatlist(130, diseqc_satlist_choices)
1519                         nim.diseqcC = ConfigSatlist(list = diseqc_satlist_choices)
1520                         nim.diseqcD = ConfigSatlist(list = diseqc_satlist_choices)
1521                         nim.positionerMode = ConfigSelection(positioner_mode_choices, "usals")
1522                         nim.longitude = ConfigFloat(default=[5,100], limits=[(0,359),(0,999)])
1523                         nim.longitudeOrientation = ConfigSelection(longitude_orientation_choices, "east")
1524                         nim.latitude = ConfigFloat(default=[50,767], limits=[(0,359),(0,999)])
1525                         nim.latitudeOrientation = ConfigSelection(latitude_orientation_choices, "north")
1526                         nim.positionerExclusively = ConfigYesNo(True)
1527                         nim.powerMeasurement = ConfigYesNo(True)
1528                         nim.powerThreshold = ConfigInteger(default=hw.get_device_name() == "dm8000" and 15 or 50, limits=(0, 100))
1529                         nim.turningSpeed = ConfigSelection(turning_speed_choices, "fast")
1530                         btime = datetime(1970, 1, 1, 7, 0);
1531                         nim.fastTurningBegin = ConfigDateTime(default = mktime(btime.timetuple()), formatstring = _("%H:%M"), increment = 900)
1532                         etime = datetime(1970, 1, 1, 19, 0);
1533                         nim.fastTurningEnd = ConfigDateTime(default = mktime(etime.timetuple()), formatstring = _("%H:%M"), increment = 900)
1534                         config_mode_choices = [ getConfigModeTuple("nothing"), getConfigModeTuple("simple"), getConfigModeTuple("advanced") ]
1535                         if len(nimmgr.getNimListOfType(slot.type, exception = x)) > 0:
1536                                 config_mode_choices.append(getConfigModeTuple("equal"))
1537                                 config_mode_choices.append(getConfigModeTuple("satposdepends"))
1538                         if len(nimmgr.canConnectTo(x)) > 0:
1539                                 config_mode_choices.append(getConfigModeTuple("loopthrough"))
1540                         nim.advanced = ConfigNothing()
1541                         tmp = ConfigSelection(config_mode_choices, "nothing")
1542                         tmp.slot_id = x
1543                         tmp.addNotifier(configModeChanged, initial_call = False)
1544                         nim.configMode = tmp
1545                         nim.configMode.connectedToChanged = boundFunction(connectedToChanged, x, nimmgr)
1546                         nim.connectedTo.addNotifier(boundFunction(connectedToChanged, x, nimmgr), initial_call = False)
1547                 elif slot.isCompatible("DVB-C"):
1548                         nim.configMode = ConfigSelection(
1549                                 choices = {
1550                                         "enabled": _("enabled"),
1551                                         "nothing": _("nothing connected"),
1552                                         },
1553                                 default = "enabled")
1554                         list = [ ]
1555                         n = 0
1556                         for x in nimmgr.cablesList:
1557                                 list.append((str(n), x[0]))
1558                                 n += 1
1559                         nim.cable = ConfigSubsection()
1560                         possible_scan_types = [("bands", _("Frequency bands")), ("steps", _("Frequency steps"))]
1561                         if n:
1562                                 possible_scan_types.append(("provider", _("Provider")))
1563                                 nim.cable.scan_provider = ConfigSelection(default = "0", choices = list)
1564                         nim.cable.scan_type = ConfigSelection(default = "bands", choices = possible_scan_types)
1565                         nim.cable.scan_band_EU_VHF_I = ConfigYesNo(default = True)
1566                         nim.cable.scan_band_EU_MID = ConfigYesNo(default = True)
1567                         nim.cable.scan_band_EU_VHF_III = ConfigYesNo(default = True)
1568                         nim.cable.scan_band_EU_UHF_IV = ConfigYesNo(default = True)
1569                         nim.cable.scan_band_EU_UHF_V = ConfigYesNo(default = True)
1570                         nim.cable.scan_band_EU_SUPER = ConfigYesNo(default = True)
1571                         nim.cable.scan_band_EU_HYPER = ConfigYesNo(default = True)
1572                         nim.cable.scan_band_US_LOW = ConfigYesNo(default = False)
1573                         nim.cable.scan_band_US_MID = ConfigYesNo(default = False)
1574                         nim.cable.scan_band_US_HIGH = ConfigYesNo(default = False)
1575                         nim.cable.scan_band_US_SUPER = ConfigYesNo(default = False)
1576                         nim.cable.scan_band_US_HYPER = ConfigYesNo(default = False)
1577                         nim.cable.scan_band_US_ULTRA = ConfigYesNo(default = False)
1578                         nim.cable.scan_band_US_JUMBO = ConfigYesNo(default = False)
1579                         nim.cable.scan_frequency_steps = ConfigInteger(default = 1000, limits = (1000, 10000))
1580                         nim.cable.scan_mod_qam16 = ConfigYesNo(default = False)
1581                         nim.cable.scan_mod_qam32 = ConfigYesNo(default = False)
1582                         nim.cable.scan_mod_qam64 = ConfigYesNo(default = True)
1583                         nim.cable.scan_mod_qam128 = ConfigYesNo(default = False)
1584                         nim.cable.scan_mod_qam256 = ConfigYesNo(default = True)
1585                         nim.cable.scan_sr_6900 = ConfigYesNo(default = True)
1586                         nim.cable.scan_sr_6875 = ConfigYesNo(default = True)
1587                         nim.cable.scan_sr_ext1 = ConfigInteger(default = 0, limits = (0, 7230))
1588                         nim.cable.scan_sr_ext2 = ConfigInteger(default = 0, limits = (0, 7230))
1589                 elif slot.isCompatible("DVB-T"):
1590                         nim.configMode = ConfigSelection(
1591                                 choices = {
1592                                         "enabled": _("enabled"),
1593                                         "nothing": _("nothing connected"),
1594                                         },
1595                                 default = "enabled")
1596                         list = []
1597                         n = 0
1598                         for x in nimmgr.terrestrialsList:
1599                                 list.append((str(n), x[0]))
1600                                 n += 1
1601                         nim.terrestrial = ConfigSelection(choices = list)
1602                         nim.terrestrial_5V = ConfigOnOff()
1603                 else:
1604                         empty_slots += 1
1605                         nim.configMode = ConfigSelection(choices = { "nothing": _("disabled") }, default="nothing");
1606                         if slot.type is not None:
1607                                 print "pls add support for this frontend type!", slot.type
1608 #                       assert False
1609
1610         nimmgr.sec = SecConfigure(nimmgr)
1611
1612 nimmanager = NimManager()