some fixes for empty tuner slots (use slotid instead of dvb api frontend
[enigma2.git] / lib / python / Components / NimManager.py
1 from config import config, ConfigSubsection, ConfigSelection, ConfigFloat, ConfigSatlist, ConfigYesNo, ConfigInteger, ConfigSubList, ConfigNothing, ConfigSubDict, ConfigOnOff
2
3 from enigma import eDVBSatelliteEquipmentControl as secClass, \
4         eDVBSatelliteLNBParameters as lnbParam, \
5         eDVBSatelliteDiseqcParameters as diseqcParam, \
6         eDVBSatelliteSwitchParameters as switchParam, \
7         eDVBSatelliteRotorParameters as rotorParam, \
8         eDVBResourceManager
9
10 import xml.dom.minidom
11 from xml.dom import EMPTY_NAMESPACE
12 from skin import elementsWithTag
13 from Tools import XMLTools
14
15 from xml.sax import make_parser
16 from xml.sax.handler import ContentHandler
17
18 from Tools.BoundFunction import boundFunction
19
20 def getConfigSatlist(orbpos, satlist):
21         default_orbpos = None
22         for x in satlist:
23                 if x[0] == orbpos:
24                         default_orbpos = orbpos
25                         break
26         return ConfigSatlist(satlist, default_orbpos)
27
28 def tryOpen(filename):
29         try:
30                 procFile = open(filename)
31         except IOError:
32                 return None
33         return procFile
34
35 class SecConfigure:
36         def addLNBSimple(self, sec, slotid, diseqcmode, toneburstmode = 0, diseqcpos = 0, orbpos = 0, longitude = 0, latitude = 0, loDirection = 0, laDirection = 0):
37                 #simple defaults
38                 sec.addLNB()
39                 tunermask = 1 << slotid
40                 if self.equal.has_key(slotid):
41                         tunermask |= (1 << self.equal[slotid])
42                 elif self.linked.has_key(slotid):
43                         tunermask |= (1 << self.linked[slotid])
44                 sec.setLNBLOFL(9750000)
45                 sec.setLNBLOFH(10600000)
46                 sec.setLNBThreshold(11700000)
47                 sec.setLNBIncreasedVoltage(lnbParam.OFF)
48                 sec.setRepeats(0)
49                 sec.setFastDiSEqC(0)
50                 sec.setSeqRepeat(0)
51                 sec.setVoltageMode(switchParam.HV)
52                 sec.setToneMode(switchParam.HILO)
53                 sec.setCommandOrder(0)
54
55                 #user values
56                 sec.setDiSEqCMode(diseqcmode)
57                 sec.setToneburst(toneburstmode)
58                 sec.setCommittedCommand(diseqcpos)
59                 #print "set orbpos to:" + str(orbpos)
60
61                 if 0 <= diseqcmode < 3:
62                         sec.addSatellite(orbpos)
63                         self.satList.append(orbpos)
64                 elif (diseqcmode == 3): # diseqc 1.2
65                         if self.satposdepends.has_key(slotid):
66                                 tunermask |= (1 << self.satposdepends[slotid])
67                         sec.setLatitude(latitude)
68                         sec.setLaDirection(laDirection)
69                         sec.setLongitude(longitude)
70                         sec.setLoDirection(loDirection)
71                         sec.setUseInputpower(True)
72                         sec.setInputpowerDelta(50)
73
74                         for x in self.NimManager.satList:
75                                 print "Add sat " + str(x[0])
76                                 sec.addSatellite(int(x[0]))
77                                 sec.setVoltageMode(0)
78                                 sec.setToneMode(0)
79                                 sec.setRotorPosNum(0) # USALS
80                                 self.satList.append(int(x[0]))
81
82                 sec.setLNBTunerMask(tunermask)
83
84         def setSatposDepends(self, sec, nim1, nim2):
85                 print "tuner", nim1, "depends on satpos of", nim2
86                 sec.setTunerDepends(nim1, nim2)
87
88         def linkNIMs(self, sec, nim1, nim2):
89                 print "link tuner", nim1, "to tuner", nim2
90                 sec.setTunerLinked(nim1, nim2)
91
92         def getSatList(self):
93                 return self.satList
94
95         def update(self):
96                 sec = secClass.getInstance()
97                 sec.clear() ## this do unlinking NIMs too !!
98                 print "sec config cleared"
99                 self.satList = []
100
101                 self.linked = { }
102                 self.satposdepends = { }
103                 self.equal = { }
104                 
105                 nim_slots = self.NimManager.nim_slots
106                 
107                 for slot in nim_slots:
108                         x = slot.slot
109                         nim = slot.config
110                         if slot.isCompatible("DVB-S"):
111                                 # save what nim we link to/are equal to/satposdepends to.
112                                 # this is stored in the *value* (not index!) of the config list
113                                 if nim.configMode.value == "equal":
114                                         self.equal[int(nim.equalTo.value)]=x
115                                 if nim.configMode.value == "loopthrough":
116                                         self.linkNIMs(sec, x, int(nim.linkedTo.value))
117                                         self.linked[int(nim.linkedTo.value)]=x
118                                 elif nim.configMode.value == "satposdepends":
119                                         self.setSatposDepends(sec, x, int(nim.satposDependsTo.value))
120                                         self.satposdepends[int(nim.satposDependsTo.value)]=x
121
122                 for slot in nim_slots:
123                         x = slot.slot
124                         nim = slot.config
125                         if slot.isCompatible("DVB-S"):
126                                 print "slot: " + str(x) + " configmode: " + str(nim.configMode.value)
127                                 print "diseqcmode: ", nim.configMode.value
128                                 if nim.configMode.value in [ "loopthrough", "satposdepends", "equal", "nothing" ]:
129                                         pass
130                                 elif nim.configMode.value == "simple":          #simple config
131                                         if nim.diseqcMode.value == "single":                    #single
132                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.NONE, diseqcpos = diseqcParam.SENDNO)
133                                         elif nim.diseqcMode.value == "toneburst_a_b":           #Toneburst A/B
134                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.A, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO)
135                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.B, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO)
136                                         elif nim.diseqcMode.value == "diseqc_a_b":              #DiSEqC A/B
137                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA)
138                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB)
139                                         elif nim.diseqcMode.value == "diseqc_a_b_c_d":          #DiSEqC A/B/C/D
140                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA)
141                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB)
142                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcC.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BA)
143                                                 self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcD.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BB)
144                                         elif nim.diseqcMode.value == "positioner":              #Positioner
145                                                 if nim.latitudeOrientation.value == "north":
146                                                         laValue = rotorParam.NORTH
147                                                 else:
148                                                         laValue = rotorParam.SOUTH
149                                                 if nim.longitudeOrientation.value == "east":
150                                                         loValue = rotorParam.EAST
151                                                 else:
152                                                         loValue = rotorParam.WEST
153                                                 self.addLNBSimple(sec, slotid = x, diseqcmode = 3,
154                                                         longitude = nim.longitude.float,
155                                                         loDirection = loValue,
156                                                         latitude = nim.latitude.float,
157                                                         laDirection = laValue)
158                                 elif nim.configMode.value == "advanced": #advanced config
159                                         self.updateAdvanced(sec, x)
160                 print "sec config completed"
161
162         def updateAdvanced(self, sec, slotid):
163                 lnbSat = {}
164                 for x in range(1,33):
165                         lnbSat[x] = []
166                 for x in self.NimManager.satList:
167                         lnb = int(config.Nims[slotid].advanced.sat[x[0]].lnb.value)
168                         if lnb != 0:
169                                 print "add", x[0], "to", lnb
170                                 lnbSat[lnb].append(x[0])
171                 for x in range(1,33):
172                         if len(lnbSat[x]) > 0:
173                                 currLnb = config.Nims[slotid].advanced.lnb[x]
174                                 sec.addLNB()
175
176                                 tunermask = 1 << slotid
177                                 if self.equal.has_key(slotid):
178                                         tunermask |= (1 << self.equal[slotid])
179                                 elif self.linked.has_key(slotid):
180                                         tunermask |= (1 << self.linked[slotid])
181
182                                 if currLnb.lof.value == "universal_lnb":
183                                         sec.setLNBLOFL(9750000)
184                                         sec.setLNBLOFH(10600000)
185                                         sec.setLNBThreshold(11700000)
186                                 elif currLnb.lof.value == "c_band":
187                                         sec.setLNBLOFL(5150000)
188                                         sec.setLNBLOFH(5150000)
189                                         sec.setLNBThreshold(5150000)
190                                 elif currLnb.lof.value == "user_defined":
191                                         sec.setLNBLOFL(currLnb.lofl.value * 1000)
192                                         sec.setLNBLOFH(currLnb.lofh.value * 1000)
193                                         sec.setLNBThreshold(currLnb.threshold.value * 1000)
194                                         
195 #                               if currLnb.output_12v.value == "0V":
196 #                                       pass # nyi in drivers
197 #                               elif currLnb.output_12v.value == "12V":
198 #                                       pass # nyi in drivers
199                                         
200                                 if currLnb.increased_voltage.value:
201                                         sec.setLNBIncreasedVoltage(lnbParam.ON)
202                                 else:
203                                         sec.setLNBIncreasedVoltage(lnbParam.OFF)
204                                 
205                                 dm = currLnb.diseqcMode.value 
206                                 if dm == "none":
207                                         sec.setDiSEqCMode(diseqcParam.NONE)
208                                 elif dm == "1_0":
209                                         sec.setDiSEqCMode(diseqcParam.V1_0)
210                                 elif dm == "1_1":
211                                         sec.setDiSEqCMode(diseqcParam.V1_1)
212                                 elif dm == "1_2":
213                                         sec.setDiSEqCMode(diseqcParam.V1_2)
214
215                                         if self.satposdepends.has_key(slotid):  # only useable with rotors
216                                                 tunermask |= (1 << self.satposdepends[slotid])
217
218                                 if dm != "none":
219                                         if currLnb.toneburst.value == "none":
220                                                 sec.setToneburst(diseqcParam.NO)
221                                         elif currLnb.toneburst.value == "A":
222                                                 sec.setToneburst(diseqcParam.A)
223                                         elif currLnb.toneburst.value == "B":
224                                                 sec.setToneburst(diseqcParam.B)
225                                         
226                                         # Committed Diseqc Command
227                                         cdc = currLnb.commitedDiseqcCommand.value
228                                         
229                                         c = { "none": diseqcParam.SENDNO,
230                                                 "AA": diseqcParam.AA,
231                                                 "AB": diseqcParam.AB,
232                                                 "BA": diseqcParam.BA,
233                                                 "BB": diseqcParam.BB }
234
235                                         if c.has_key(cdc):
236                                                 sec.setCommittedCommand(c[cdc])
237                                         else:
238                                                 sec.setCommittedCommand(long(cdc))
239
240                                         sec.setFastDiSEqC(currLnb.fastDiseqc.value)
241                                                 
242                                         sec.setSeqRepeat(currLnb.sequenceRepeat.value)
243                                                 
244                                         if currLnb.diseqcMode.value == "1_0":
245                                                 currCO = currLnb.commandOrder1_0.value
246                                         else:
247                                                 currCO = currLnb.commandOrder.value
248
249                                                 udc = int(currLnb.uncommittedDiseqcCommand.value)
250                                                 if udc > 0:
251                                                         sec.setUncommittedCommand(0xF0|(udc-1))
252                                                 else:
253                                                         sec.setUncommittedCommand(0) # SENDNO
254
255                                                 sec.setRepeats({"none": 0, "one": 1, "two": 2, "three": 3}[currLnb.diseqcRepeats.value])
256
257                                         setCommandOrder = False
258                                         
259                                         # 0 "committed, toneburst", 
260                                         # 1 "toneburst, committed", 
261                                         # 2 "committed, uncommitted, toneburst",
262                                         # 3 "toneburst, committed, uncommitted",
263                                         # 4 "uncommitted, committed, toneburst"
264                                         # 5 "toneburst, uncommitted, commmitted"
265                                         order_map = {"ct": 0, "tc": 1, "cut": 2, "tcu": 3, "uct": 4, "tuc": 5}
266                                         sec.setCommandOrder(order_map[currCO])
267
268                                 if dm == "1_2":
269                                         latitude = currLnb.latitude.float
270                                         sec.setLatitude(latitude)
271                                         longitude = currLnb.longitude.float
272                                         sec.setLongitude(longitude)
273                                         if currLnb.latitudeOrientation.value == "north":
274                                                 sec.setLaDirection(rotorParam.NORTH)
275                                         else:
276                                                 sec.setLaDirection(rotorParam.SOUTH)
277                                         if currLnb.longitudeOrientation.value == "east":
278                                                 sec.setLoDirection(rotorParam.EAST)
279                                         else:
280                                                 sec.setLoDirection(rotorParam.WEST)
281                                                 
282                                 if currLnb.powerMeasurement.value:
283                                         sec.setUseInputpower(True)
284                                         sec.setInputpowerDelta(currLnb.powerThreshold.value)
285                                 else:
286                                         sec.setUseInputpower(False)
287
288                                 sec.setLNBTunerMask(tunermask)
289
290                                 # finally add the orbital positions
291                                 for y in lnbSat[x]:
292                                         sec.addSatellite(y)
293                                         currSat = config.Nims[slotid].advanced.sat[y]
294
295                                         if currSat.voltage.value == "polarization":
296                                                 sec.setVoltageMode(switchParam.HV)
297                                         elif currSat.voltage.value == "13V":
298                                                 sec.setVoltageMode(switchParam._14V)
299                                         elif currSat.voltage.value == "18V":
300                                                 sec.setVoltageMode(switchParam._18V)
301                                                 
302                                         if currSat.tonemode == "band":
303                                                 sec.setToneMode(switchParam.HILO)
304                                         elif currSat.tonemode == "on":
305                                                 sec.setToneMode(switchParam.ON)
306                                         elif currSat.tonemode == "off":
307                                                 sec.setToneMode(switchParam.OFF)
308                                                 
309                                         if not currSat.usals.value:
310                                                 sec.setRotorPosNum(currSat.rotorposition.value)
311                                         else:
312                                                 sec.setRotorPosNum(0) #USALS
313
314         def __init__(self, nimmgr):
315                 self.NimManager = nimmgr
316                 self.update()
317
318 class NIM(object):
319         def __init__(self, slot, type, description):
320                 self.slot = slot
321
322                 if type not in ["DVB-S", "DVB-C", "DVB-T", "DVB-S2", None]:
323                         print "warning: unknown NIM type %s, not using." % type
324                         type = None
325
326                 self.type = type
327                 self.description = description
328
329         def isCompatible(self, what):
330                 compatible = {
331                                 None: [None],
332                                 "DVB-S": ["DVB-S", None],
333                                 "DVB-C": ["DVB-C", None],
334                                 "DVB-T": ["DVB-T", None],
335                                 "DVB-S2": ["DVB-S", "DVB-S2", None]
336                         }
337                 return what in compatible[self.type]
338
339         def getSlotName(self):
340                 # get a friendly description for a slot name.
341                 # we name them "Tuner A/B/C/...", because that's what's usually written on the back
342                 # of the device.
343                 return _("Tuner ") + chr(ord('A') + self.slot)
344
345         slot_name = property(getSlotName)
346
347         def getSlotID(self):
348                 return chr(ord('A') + self.slot)
349
350         slot_id = property(getSlotID)
351
352         def getFriendlyType(self):
353                 return {
354                         "DVB-S": "DVB-S", 
355                         "DVB-T": "DVB-T",
356                         "DVB-S2": "DVB-S2",
357                         "DVB-C": "DVB-C",
358                         None: _("empty")
359                         }[self.type]
360
361         friendly_type = property(getFriendlyType)
362
363         def getFriendlyFullDescription(self):
364                 nim_text = self.slot_name + ": "
365                         
366                 if self.empty:
367                         nim_text += _("(empty)")
368                 else:
369                         nim_text += self.description + " (" + self.friendly_type + ")"
370                 
371                 return nim_text
372
373         friendly_full_description = property(getFriendlyFullDescription)
374         config_mode = property(lambda self: config.Nims[self.slot].configMode.value)
375         config = property(lambda self: config.Nims[self.slot])
376         empty = property(lambda self: self.type is None)
377
378 class NimManager:
379         class parseSats(ContentHandler):
380                 def __init__(self, satList, satellites, transponders):
381                         self.isPointsElement, self.isReboundsElement = 0, 0
382                         self.satList = satList
383                         self.satellites = satellites
384                         self.transponders = transponders
385         
386                 def startElement(self, name, attrs):
387                         if (name == "sat"):
388                                 #print "found sat " + attrs.get('name',"") + " " + str(attrs.get('position',""))
389                                 tpos = int(attrs.get('position',""))
390                                 if tpos < 0:
391                                         tpos = 3600 + tpos
392                                 tname = attrs.get('name',"").encode("UTF-8")
393                                 self.satellites[tpos] = tname
394                                 self.satList.append( (tpos, tname) )
395                                 self.parsedSat = int(tpos)
396                         elif (name == "transponder"):
397                                 modulation = int(attrs.get('modulation',"1")) # QPSK default
398                                 system = int(attrs.get('system',"0")) # DVB-S default
399                                 freq = int(attrs.get('frequency',""))
400                                 sr = int(attrs.get('symbol_rate',""))
401                                 pol = int(attrs.get('polarization',""))
402                                 fec = int(attrs.get('fec_inner',"0")) # AUTO default
403                                 if self.parsedSat in self.transponders:
404                                         pass
405                                 else:
406                                         self.transponders[self.parsedSat] = [ ]
407
408                                 self.transponders[self.parsedSat].append((0, freq, sr, pol, fec, system, modulation))
409
410         class parseCables(ContentHandler):
411                 def __init__(self, cablesList, transponders):
412                         self.isPointsElement, self.isReboundsElement = 0, 0
413                         self.cablesList = cablesList
414                         for x in self.cablesList:
415                                 self.cablesList.remove(x)
416                         self.transponders = transponders
417         
418                 def startElement(self, name, attrs):
419                         if (name == "cable"):
420                                 #print "found sat " + attrs.get('name',"") + " " + str(attrs.get('position',""))
421                                 tname = attrs.get('name',"").encode("UTF-8")
422                                 tflags = int(attrs.get('flags',"0"))
423                                 self.cablesList.append((tname, tflags))
424                                 self.parsedCab = tname
425                         elif (name == "transponder"):
426                                 freq = int(attrs.get('frequency',""))
427                                 while freq > 999999:
428                                         freq /= 10
429                                 sr = int(attrs.get('symbol_rate',"0"))
430                                 mod = int(attrs.get('modulation',"3")) # QAM64 default
431                                 fec = int(attrs.get('fec_inner',"0")) # AUTO default
432                                 if self.parsedCab in self.transponders:
433                                         pass
434                                 else:
435                                         self.transponders[self.parsedCab] = [ ]
436                                 self.transponders[self.parsedCab].append((1, freq, sr, mod, fec))
437
438         class parseTerrestrials(ContentHandler):
439                 def __init__(self, terrestrialsList, transponders):
440                         self.isPointsElement, self.isReboundsElement = 0, 0
441                         self.terrestrialsList = terrestrialsList
442                         self.transponders = transponders
443         
444                 def startElement(self, name, attrs):
445                         if (name == "terrestrial"):
446                                 #print "found sat " + attrs.get('name',"") + " " + str(attrs.get('position',""))
447                                 tname = attrs.get('name',"").encode("UTF-8")
448                                 tflags = attrs.get('flags',"")
449                                 self.terrestrialsList.append((tname, tflags))
450                                 self.parsedTer = str(tname)
451                         elif (name == "transponder"):
452                                 # TODO finish this!
453                                 freq = int(attrs.get('centre_frequency',""))
454                                 bw = int(attrs.get('bandwidth',"3")) # AUTO
455                                 const = int(attrs.get('constellation',"1")) # AUTO
456                                 crh = int(attrs.get('code_rate_hp',"5")) # AUTO
457                                 if crh > 5: # our terrestrial.xml is buggy... 6 for AUTO
458                                         crh = 5
459                                 crl = int(attrs.get('code_rate_lp',"5")) # AUTO
460                                 if crl > 5: # our terrestrial.xml is buggy... 6 for AUTO
461                                         crl = 5
462                                 guard = int(attrs.get('guard_interval',"4")) # AUTO
463                                 transm = int(attrs.get('transmission_mode',"2")) # AUTO
464                                 hierarchy = int(attrs.get('hierarchy_information',"4")) # AUTO
465                                 inv = int(attrs.get('inversion',"2")) # AUTO
466                                 if self.parsedTer in self.transponders:
467                                         pass
468                                 else:
469                                         self.transponders[self.parsedTer] = [ ]
470
471                                 self.transponders[self.parsedTer].append((2, freq, bw, const, crh, crl, guard, transm, hierarchy, inv))
472
473         def getTransponders(self, pos):
474                 if self.transponders.has_key(pos):
475                         return self.transponders[pos]
476                 else:
477                         return []
478
479         def getTranspondersCable(self, nim):
480                 nimConfig = config.Nims[nim]
481                 if nimConfig.configMode.value != "nothing" and nimConfig.cable.scan_type.value == "provider":
482                         return self.transponderscable[self.cablesList[nimConfig.cable.scan_provider.index][0]]
483                 return [ ]
484
485         def getTranspondersTerrestrial(self, region):
486                 return self.transpondersterrestrial[region]
487         
488         def getCableDescription(self, nim):
489                 return self.cablesList[config.Nims[nim].scan_provider.index][0]
490
491         def getCableFlags(self, nim):
492                 return self.cablesList[config.Nims[nim].scan_provider.index][1]
493
494         def getTerrestrialDescription(self, nim):
495                 return self.terrestrialsList[config.Nims[nim].terrestrial.index][0]
496
497         def getTerrestrialFlags(self, nim):
498                 return self.terrestrialsList[config.Nims[nim].terrestrial.index][1]
499
500         def getConfiguredSats(self):
501                 return self.sec.getSatList()
502
503         def getSatDescription(self, pos):
504                 return self.satellites[pos]
505
506         def readSatsfromFile(self):
507                 # read initial networks from file. we only read files which we are interested in,
508                 # which means only these where a compatible tuner exists.
509                 self.satellites = { }
510                 self.transponders = { }
511                 self.transponderscable = { }
512                 self.transpondersterrestrial = { }              
513
514                 parser = make_parser()
515                 
516                 if self.hasNimType("DVB-S"):
517                         print "Reading satellites.xml"
518                         satHandler = self.parseSats(self.satList, self.satellites, self.transponders)
519                         parser.setContentHandler(satHandler)
520                         parser.parse('/etc/tuxbox/satellites.xml')
521
522                 if self.hasNimType("DVB-C"):
523                         print "Reading cables.xml"
524                         cabHandler = self.parseCables(self.cablesList, self.transponderscable)
525                         parser.setContentHandler(cabHandler)
526                         parser.parse('/etc/tuxbox/cables.xml')
527
528                 if self.hasNimType("DVB-T"):
529                         print "Reading terrestrial.xml"
530                         terHandler = self.parseTerrestrials(self.terrestrialsList, self.transpondersterrestrial)
531                         parser.setContentHandler(terHandler)
532                         parser.parse('/etc/tuxbox/terrestrial.xml')
533
534         def enumerateNIMs(self):
535                 # enum available NIMs. This is currently very dreambox-centric and uses the /proc/bus/nim_sockets interface.
536                 # the result will be stored into nim_slots.
537                 # the content of /proc/bus/nim_sockets looks like:
538                 # NIM Socket 0:
539                 #          Type: DVB-S
540                 #          Name: BCM4501 DVB-S2 NIM (internal)
541                 # NIM Socket 1:
542                 #          Type: DVB-S
543                 #          Name: BCM4501 DVB-S2 NIM (internal)
544                 # NIM Socket 2:
545                 #          Type: DVB-T
546                 #          Name: Philips TU1216
547                 # NIM Socket 3:
548                 #          Type: DVB-S
549                 #          Name: Alps BSBE1 702A
550                 
551                 #
552                 # Type will be either "DVB-S", "DVB-S2", "DVB-T", "DVB-C" or None.
553
554                 nimfile = tryOpen("/proc/bus/nim_sockets")
555
556                 if nimfile is None:
557                         return
558
559                 current_slot = None
560
561                 entries = {}
562                 for line in nimfile.readlines():
563                         if line == "":
564                                 break
565                         if line.strip().startswith("NIM Socket"):
566                                 parts = line.strip().split(" ")
567                                 current_slot = int(parts[2][:-1])
568                                 entries[current_slot] = {}
569                         elif line.strip().startswith("Type:"):
570                                 entries[current_slot]["type"] = str(line.strip()[6:])
571                         elif line.strip().startswith("Name:"):
572                                 entries[current_slot]["name"] = str(line.strip()[6:])
573                         elif line.strip().startswith("empty"):
574                                 entries[current_slot]["type"] = None
575                                 entries[current_slot]["name"] = _("N/A")
576                 nimfile.close()
577                 
578                 # nim_slots is an array which has exactly one entry for each slot, even for empty ones.
579                 self.nim_slots = [ ]
580
581                 for id, entry in entries.items():
582                         if not (entry.has_key("name") and entry.has_key("type")):
583                                 entry["name"] =  _("N/A")
584                                 entry["type"] = None
585                         self.nim_slots.append(NIM(slot = id, description = entry["name"], type = entry["type"]))
586
587         def hasNimType(self, chktype):
588                 for slot in self.nim_slots:
589                         if slot.isCompatible(chktype):
590                                 return True
591                 return False
592
593         def getNimListOfType(self, type, exception = -1):
594                 # returns a list of indexes for NIMs compatible to the given type, except for 'exception'
595                 list = []
596                 for x in self.nim_slots:
597                         if x.isCompatible(type) and x.slot != exception:
598                                 list.append(x.slot)
599                 return list
600
601         def __init__(self):
602                 self.satList = [ ]
603                 self.cablesList = []
604                 self.terrestrialsList = []
605                 self.enumerateNIMs()
606                 self.readSatsfromFile()
607
608                 InitNimManager(self)    #init config stuff
609
610         # get a list with the friendly full description
611         def nimList(self):
612                 list = [ ]
613                 for slot in self.nim_slots:
614                         list.append(slot.friendly_full_description)
615                 return list
616
617         def getSatList(self):
618                 return self.satList
619
620         def getSatListForNim(self, slotid):
621                 list = []
622                 if self.nim_slots[slotid].isCompatible("DVB-S"):
623                         #print "slotid:", slotid
624
625                         #print "self.satellites:", self.satList[config.Nims[slotid].diseqcA.index]
626                         #print "diseqcA:", config.Nims[slotid].diseqcA.value
627                         configMode = config.Nims[slotid].configMode.value
628
629                         if configMode == "equal":
630                                 slotid=0 #FIXME add handling for more than two tuners !!!
631                                 configMode = config.Nims[slotid].configMode.value
632
633                         if configMode == "simple":
634                                 dm = config.Nims[slotid].diseqcMode.value
635                                 if dm in ["single", "toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"]:
636                                         list.append(self.satList[config.Nims[slotid].diseqcA.index])
637                                 if dm in ["toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"]:
638                                         list.append(self.satList[config.Nims[slotid].diseqcB.index])
639                                 if dm == "diseqc_a_b_c_d":
640                                         list.append(self.satList[config.Nims[slotid].diseqcC.index])
641                                         list.append(self.satList[config.Nims[slotid].diseqcD.index])
642                                 if dm == "positioner":
643                                         for x in self.satList:
644                                                 list.append(x)
645                         elif configMode == "advanced":
646                                 for x in self.satList:
647                                         if int(config.Nims[slotid].advanced.sat[x[0]].lnb.value) != 0:
648                                                 list.append(x)
649                 
650                 return list
651
652         def getRotorSatListForNim(self, slotid):
653                 list = []
654                 if self.nim_slots[slotid].isCompatible("DVB-S"):
655                         #print "slotid:", slotid
656
657                         #print "self.satellites:", self.satList[config.Nims[slotid].diseqcA.value]
658                         #print "diseqcA:", config.Nims[slotid].diseqcA.value
659                         configMode = config.Nims[slotid].configMode.value
660                         if configMode == "simple":
661                                 if config.Nims[slotid].diseqcMode.value == "positioner":
662                                         for x in self.satList:
663                                                 list.append(x)
664                         elif configMode == "advanced":
665                                 for x in self.satList:
666                                         nim = config.Nims[slotid]
667                                         lnbnum = int(nim.advanced.sat[x[0]].lnb.value)
668                                         if lnbnum != 0:
669                                                 lnb = nim.advanced.lnb[lnbnum]
670                                                 if lnb.diseqcMode.value == "1_2":
671                                                         list.append(x)
672                 return list
673
674 def InitSecParams():
675         config.sec = ConfigSubsection()
676
677         x = ConfigInteger(default=15, limits = (0, 9999))
678         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_CONT_TONE, configElement.value))
679         config.sec.delay_after_continuous_tone_change = x
680
681         x = ConfigInteger(default=10, limits = (0, 9999))
682         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_FINAL_VOLTAGE_CHANGE, configElement.value))
683         config.sec.delay_after_final_voltage_change = x
684
685         x = ConfigInteger(default=120, limits = (0, 9999))
686         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_BETWEEN_DISEQC_REPEATS, configElement.value))
687         config.sec.delay_between_diseqc_repeats = x
688
689         x = ConfigInteger(default=50, limits = (0, 9999))
690         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_LAST_DISEQC_CMD, configElement.value))
691         config.sec.delay_after_last_diseqc_command = x
692
693         x = ConfigInteger(default=50, limits = (0, 9999))
694         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_TONEBURST, configElement.value))
695         config.sec.delay_after_toneburst = x
696
697         x = ConfigInteger(default=750, limits = (0, 9999))
698         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_ENABLE_VOLTAGE_BEFORE_SWITCH_CMDS, configElement.value))
699         config.sec.delay_after_enable_voltage_before_switch_command = x
700
701         x = ConfigInteger(default=700, limits = (0, 9999))
702         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_BETWEEN_SWITCH_AND_MOTOR_CMD, configElement.value))
703         config.sec.delay_between_switch_and_motor_command = x
704
705         x = ConfigInteger(default=150, limits = (0, 9999))
706         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_MEASURE_IDLE_INPUTPOWER, configElement.value))
707         config.sec.delay_after_voltage_change_before_measure_idle_inputpower = x
708
709         x = ConfigInteger(default=750, limits = (0, 9999))
710         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_ENABLE_VOLTAGE_BEFORE_MOTOR_CMD, configElement.value))
711         config.sec.delay_after_enable_voltage_before_motor_command = x
712
713         x = ConfigInteger(default=150, limits = (0, 9999))
714         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_MOTOR_STOP_CMD, configElement.value))
715         config.sec.delay_after_motor_stop_command = x
716
717         x = ConfigInteger(default=150, limits = (0, 9999))
718         x.addNotifier(lambda configElement: secClass.setParam(secClass.DELAY_AFTER_VOLTAGE_CHANGE_BEFORE_MOTOR_CMD, configElement.value))
719         config.sec.delay_after_voltage_change_before_motor_command = x
720
721         x = ConfigInteger(default=120, limits = (0, 9999))
722         x.addNotifier(lambda configElement: secClass.setParam(secClass.MOTOR_RUNNING_TIMEOUT, configElement.value))
723         config.sec.motor_running_timeout = x
724
725         x = ConfigInteger(default=1, limits = (0, 5))
726         x.addNotifier(lambda configElement: secClass.setParam(secClass.MOTOR_COMMAND_RETRIES, configElement.value))
727         config.sec.motor_command_retries = x
728
729 def InitNimManager(nimmgr):
730         InitSecParams()
731
732         config.Nims = ConfigSubList()
733         for x in range(len(nimmgr.nim_slots)):
734                 config.Nims.append(ConfigSubsection())
735
736         used_nim_slots = [ ]
737
738         for slot in nimmgr.nim_slots:
739                 x = slot.slot
740                 nim = config.Nims[x]
741                 
742                 # HACK: currently, we can only looptrough to socket A
743
744                 if slot.type is not None:
745                         used_nim_slots.append((slot.slot, slot.description))
746
747                 if slot.isCompatible("DVB-S"):
748                         if slot.slot == 0:
749                                 nim.configMode = ConfigSelection(
750                                         choices = {
751                                                 "simple": _("simple"),
752                                                 "advanced": _("advanced"),
753                                                 "nothing": _("nothing connected"),
754                                                 },
755                                         default = "simple")
756                         else:
757                                 nim.configMode = ConfigSelection(
758                                         choices = {
759                                                 "equal": _("equal to Socket A"),
760                                                 "loopthrough": _("loopthrough to socket A"),
761                                                 "nothing": _("nothing connected"),
762                                                 "satposdepends": _("second cable of motorized LNB"),
763                                                 "simple": _("simple"),
764                                                 "advanced": _("advanced")},
765                                         default = "loopthrough")
766
767                         #important - check if just the 2nd one is LT only and the first one is DVB-S
768                         # CHECKME: is this logic correct for >2 slots?
769                         if nim.configMode.value in ["loopthrough", "satposdepends", "equal"]:
770                                 if x == 0: # first one can never be linked to anything
771                                         # reset to simple
772                                         nim.configMode.value = "simple"
773                                         nim.configMode.save()
774                                 else:
775                                         #FIXME: make it better
776                                         for y in nimmgr.nim_slots:
777                                                 if y.slot == 0:
778                                                         if not y.isCompatible("DVB-S"):
779                                                                 # reset to simple
780                                                                 nim.configMode.value = "simple"
781                                                                 nim.configMode.save()
782
783                         nim.diseqcMode = ConfigSelection(
784                                 choices = [
785                                         ("single", _("Single")),
786                                         ("toneburst_a_b", _("Toneburst A/B")),
787                                         ("diseqc_a_b", _("DiSEqC A/B")),
788                                         ("diseqc_a_b_c_d", _("DiSEqC A/B/C/D")),
789                                         ("positioner", _("Positioner"))],
790                                 default = "diseqc_a_b")
791
792                         nim.diseqcA = getConfigSatlist(192, nimmgr.satList)
793                         nim.diseqcB = getConfigSatlist(130, nimmgr.satList)
794                         nim.diseqcC = ConfigSatlist(list = nimmgr.satList)
795                         nim.diseqcD = ConfigSatlist(list = nimmgr.satList)
796                         nim.positionerMode = ConfigSelection(
797                                 choices = [
798                                         ("usals", _("USALS")),
799                                         ("manual", _("manual"))],
800                                 default = "usals")
801                         nim.longitude = ConfigFloat(default=[5,100], limits=[(0,359),(0,999)])
802                         nim.longitudeOrientation = ConfigSelection(choices={"east": _("East"), "west": _("West")}, default = "east")
803                         nim.latitude = ConfigFloat(default=[50,767], limits=[(0,359),(0,999)])
804                         nim.latitudeOrientation = ConfigSelection(choices={"north": _("North"), "south": _("South")}, default="north")
805                         
806                         # get other frontends of the same type
807                         satNimList = nimmgr.getNimListOfType(slot.type, slot.slot)
808                         satNimListNames = {}
809
810                         for x in satNimList:
811                                 n = nimmgr.nim_slots[x]
812                                 satNimListNames["%d" % n.slot] = n.friendly_full_description
813
814                         if len(satNimListNames):
815                                 nim.equalTo = ConfigSelection(choices = satNimListNames)
816                                 nim.linkedTo = ConfigSelection(choices = satNimListNames)
817                                 nim.satposDependsTo = ConfigSelection(choices = satNimListNames)
818
819                         # advanced config:
820                         nim.advanced = ConfigSubsection()
821                         nim.advanced.sats = getConfigSatlist(192,nimmgr.satList)
822                         nim.advanced.sat = ConfigSubDict()
823                         lnbs = [("0", "not available")]
824                         for y in range(1, 33):
825                                 lnbs.append((str(y), "LNB " + str(y)))
826
827                         for x in nimmgr.satList:
828                                 nim.advanced.sat[x[0]] = ConfigSubsection()
829                                 nim.advanced.sat[x[0]].voltage = ConfigSelection(choices={"polarization": _("Polarization"), "13V": _("13 V"), "18V": _("18 V")}, default = "polarization")
830                                 nim.advanced.sat[x[0]].tonemode = ConfigSelection(choices={"band": _("Band"), "on": _("On"), "off": _("Off")}, default = "band")
831                                 nim.advanced.sat[x[0]].usals = ConfigYesNo(default=True)
832                                 nim.advanced.sat[x[0]].rotorposition = ConfigInteger(default=1, limits=(1, 255))
833                                 nim.advanced.sat[x[0]].lnb = ConfigSelection(choices = lnbs)
834
835                         csw = [("none", _("None")), ("AA", _("AA")), ("AB", _("AB")), ("BA", _("BA")), ("BB", _("BB"))]
836                         for y in range(0, 16):
837                                 csw.append((str(0xF0|y), "Input " + str(y+1)))
838
839                         ucsw = [("0", _("None"))]
840                         for y in range(1, 17):
841                                 ucsw.append((str(y), "Input " + str(y)))
842
843                         nim.advanced.lnb = ConfigSubList()
844                         nim.advanced.lnb.append(ConfigNothing())
845                         for x in range(1, 33):
846                                 nim.advanced.lnb.append(ConfigSubsection())
847                                 nim.advanced.lnb[x].lof = ConfigSelection(choices={"universal_lnb": _("Universal LNB"), "c_band": _("C-Band"), "user_defined": _("User defined")}, default="universal_lnb")
848                                 nim.advanced.lnb[x].lofl = ConfigInteger(default=9750, limits = (0, 99999))
849                                 nim.advanced.lnb[x].lofh = ConfigInteger(default=10600, limits = (0, 99999))
850                                 nim.advanced.lnb[x].threshold = ConfigInteger(default=11700, limits = (0, 99999))
851 #                               nim.advanced.lnb[x].output_12v = ConfigSelection(choices = [("0V", _("0 V")), ("12V", _("12 V"))], default="0V")
852                                 nim.advanced.lnb[x].increased_voltage = ConfigYesNo(default=False)
853                                 nim.advanced.lnb[x].toneburst = ConfigSelection(choices = [("none", _("None")), ("A", _("A")), ("B", _("B"))], default = "none")
854                                 nim.advanced.lnb[x].diseqcMode = ConfigSelection(choices = [("none", _("None")), ("1_0", _("1.0")), ("1_1", _("1.1")), ("1_2", _("1.2"))], default = "none")
855                                 nim.advanced.lnb[x].commitedDiseqcCommand = ConfigSelection(choices = csw)
856                                 nim.advanced.lnb[x].fastDiseqc = ConfigYesNo(default=False)
857                                 nim.advanced.lnb[x].sequenceRepeat = ConfigYesNo(default=False)
858                                 nim.advanced.lnb[x].commandOrder1_0 = ConfigSelection(choices = [("ct", "committed, toneburst"), ("tc", "toneburst, committed")], default = "ct")
859                                 nim.advanced.lnb[x].commandOrder = ConfigSelection(choices = [
860                                                 ("ct", "committed, toneburst"),
861                                                 ("tc", "toneburst, committed"),
862                                                 ("cut", "committed, uncommitted, toneburst"),
863                                                 ("tcu", "toneburst, committed, uncommitted"),
864                                                 ("uct", "uncommitted, committed, toneburst"),
865                                                 ("tuc", "toneburst, uncommitted, commmitted")],
866                                                 default="ct")
867                                 nim.advanced.lnb[x].uncommittedDiseqcCommand = ConfigSelection(choices = ucsw)
868                                 nim.advanced.lnb[x].diseqcRepeats = ConfigSelection(choices = [("none", _("None")), ("one", _("One")), ("two", _("Two")), ("three", _("Three"))], default = "none")
869                                 nim.advanced.lnb[x].longitude = ConfigFloat(default = [5,100], limits = [(0,359),(0,999)])
870                                 nim.advanced.lnb[x].longitudeOrientation = ConfigSelection(choices = [("east", _("East")), ("west", _("West"))], default = "east")
871                                 nim.advanced.lnb[x].latitude = ConfigFloat(default = [50,767], limits = [(0,359),(0,999)])
872                                 nim.advanced.lnb[x].latitudeOrientation = ConfigSelection(choices = [("north", _("North")), ("south", _("South"))], default = "north")
873                                 nim.advanced.lnb[x].powerMeasurement = ConfigYesNo(default=True)
874                                 nim.advanced.lnb[x].powerThreshold = ConfigInteger(default=50, limits=(0, 100))
875
876                 elif slot.isCompatible("DVB-C"):
877                         nim.configMode = ConfigSelection(
878                                 choices = {
879                                         "enabled": _("enabled"),
880                                         "nothing": _("nothing connected"),
881                                         },
882                                 default = "enabled")
883                         list = [ ]
884                         n = 0
885                         for x in nimmgr.cablesList:
886                                 list.append((str(n), x[0]))
887                                 n += 1
888                         nim.cable = ConfigSubsection()
889                         possible_scan_types = [("bands", _("Frequency bands")), ("steps", _("Frequency steps"))]
890                         if n:
891                                 possible_scan_types.append(("provider", _("Provider")))
892                         nim.cable.scan_type = ConfigSelection(default = "bands", choices = possible_scan_types)
893                         nim.cable.scan_provider = ConfigSelection(default = "0", choices = list)
894                         nim.cable.scan_band_EU_VHF_I = ConfigYesNo(default = True)
895                         nim.cable.scan_band_EU_MID = ConfigYesNo(default = True)
896                         nim.cable.scan_band_EU_VHF_III = ConfigYesNo(default = True)
897                         nim.cable.scan_band_EU_UHF_IV = ConfigYesNo(default = True)
898                         nim.cable.scan_band_EU_UHF_V = ConfigYesNo(default = True)
899                         nim.cable.scan_band_EU_SUPER = ConfigYesNo(default = True)
900                         nim.cable.scan_band_EU_HYPER = ConfigYesNo(default = True)
901                         nim.cable.scan_band_US_LOW = ConfigYesNo(default = False)
902                         nim.cable.scan_band_US_MID = ConfigYesNo(default = False)
903                         nim.cable.scan_band_US_HIGH = ConfigYesNo(default = False)
904                         nim.cable.scan_band_US_SUPER = ConfigYesNo(default = False)
905                         nim.cable.scan_band_US_HYPER = ConfigYesNo(default = False)
906                         nim.cable.scan_frequency_steps = ConfigInteger(default = 1000, limits = (1000, 10000))
907                         nim.cable.scan_mod_qam16 = ConfigYesNo(default = False)
908                         nim.cable.scan_mod_qam32 = ConfigYesNo(default = False)
909                         nim.cable.scan_mod_qam64 = ConfigYesNo(default = True)
910                         nim.cable.scan_mod_qam128 = ConfigYesNo(default = False)
911                         nim.cable.scan_mod_qam256 = ConfigYesNo(default = True)
912                         nim.cable.scan_sr_6900 = ConfigYesNo(default = True)
913                         nim.cable.scan_sr_6875 = ConfigYesNo(default = True)
914                         nim.cable.scan_sr_ext1 = ConfigInteger(default = 0, limits = (0, 7230))
915                         nim.cable.scan_sr_ext2 = ConfigInteger(default = 0, limits = (0, 7230))
916                 elif slot.isCompatible("DVB-T"):
917                         nim.configMode = ConfigSelection(
918                                 choices = {
919                                         "enabled": _("enabled"),
920                                         "nothing": _("nothing connected"),
921                                         },
922                                 default = "enabled")
923                         list = []
924                         n = 0
925                         for x in nimmgr.terrestrialsList:
926                                 list.append((str(n), x[0]))
927                                 n += 1
928                         nim.terrestrial = ConfigSelection(choices = list)
929                         nim.terrestrial_5V = ConfigOnOff()
930                 else:
931                         nim.configMode = ConfigSelection(choices = { "nothing": _("disabled") }, default="nothing");
932                         print "pls add support for this frontend type!"         
933 #                       assert False
934
935         eDVBResourceManager.getInstance().setFrontendSlotInformations(used_nim_slots)
936
937         nimmgr.sec = SecConfigure(nimmgr)
938
939 nimmanager = NimManager()