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