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