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