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