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