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