Advertisement
SharkyEXE

Untitled

Nov 2nd, 2018
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.35 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from Plugins.Plugin import PluginDescriptor
  3. from Screens.Screen import Screen
  4. from Screens.MessageBox import MessageBox
  5. from Components.Button import Button
  6. from Components.ActionMap import ActionMap
  7. from Components.ConfigList import ConfigListScreen
  8. #from Components.config import config, ConfigSubsection, ConfigDateTime, ConfigClock, ConfigText, getConfigListEntry, ConfigInteger, ConfigSequence, ConfigSelection, ConfigYesNo, configfile
  9. from Components.config import config, ConfigSubsection, ConfigDateTime, ConfigClock, ConfigText, getConfigListEntry, ConfigInteger, ConfigSequence, ConfigSelection, ConfigYesNo
  10. import enigma
  11. from enigma import eTimer, iServiceInformation, eDVBLocalTimeHandler
  12. from datetime import datetime, time as dt_time
  13. from os import system
  14. import gettext
  15. import time, httplib
  16. from Screens.Console import Console
  17. import os
  18. from os import popen
  19. from Tools.Directories import fileExists
  20. try:
  21. from Tools.StbHardware import setRTCtime
  22. except:
  23. from Tools.DreamboxHardware import setRTCtime
  24.  
  25. config.plugins.SetClock = ConfigSubsection()
  26. config.plugins.SetClock.HostName = ConfigText(default='vniiftri.ru', fixed_size=False)
  27. #config.plugins.SetClock.NTPName01 = ConfigText(default='vniiftri2.khv.ru', fixed_size=False)
  28. #config.plugins.SetClock.NTPName02 = ConfigText(default='vniiftri.khv.ru', fixed_size=False)
  29. #config.plugins.SetClock.NTPName03 = ConfigText(default='ntp2.niiftri.irkutsk.ru', fixed_size=False)
  30. #config.plugins.SetClock.NTPName04 = ConfigText(default='ntp1.niiftri.irkutsk.ru', fixed_size=False)
  31. #config.plugins.SetClock.NTPName05 = ConfigText(default='ntp21.vniiftri.ru', fixed_size=False)
  32. #config.plugins.SetClock.NTPName06 = ConfigText(default='ntp4.vniiftri.ru', fixed_size=False)
  33. #config.plugins.SetClock.NTPName07 = ConfigText(default='ntp3.vniiftri.ru', fixed_size=False)
  34. #config.plugins.SetClock.NTPName08 = ConfigText(default='ntp1.vniiftri.ru', fixed_size=False)
  35. #config.plugins.SetClock.NTPName09 = ConfigText(default='ntp2.vniiftri.ru', fixed_size=False)
  36. config.plugins.SetClock.NTPName01 = ConfigText(default='ntp2.vniiftri.ru', fixed_size=False)
  37. config.plugins.SetClock.timeout = ConfigInteger(default = 1, limits = (1,120))
  38. config.plugins.SetClock.choiceSystemTime = ConfigSelection([("0", _("Transponder Time")),("1", _("Internet Time"))], default="1")
  39. #config.plugins.SetClock.choiceSystemTime = ConfigSelection([("1", _("Internet Time"))], default="1")
  40. config.plugins.SetClock.useNTPminutes = ConfigSelection(default = "5", choices = [("0", _("ВЫКЛ")),("5", _("5 мин")),("15", _("15 мин")),("30", _("30 мин")), ("60", _("1 час")), ("120", _("2 часа")),("240", _("4 часа")), ("720", _("12 часов")), ("1440", _("24 часа")), ("2880", _("48 часов"))])
  41. #config.plugins.SetClock.useNTPminutes = ConfigSelection(default = "5", choices = [("0", _("ВЫКЛ")), ("5", _("5 минут")), ("15", _("15 минут")), ("30", _("30 минут")), ("45", _("45 минут")), ("60", _("01 час")), ("120", _("02 часа")), ("240", _("04 часа")), ("360", _("06 часов")), ("480", _("08 часов")), ("600", _("10 часов")), ("720", _("12 часов")), ("1440", _("24 часа")), ("2880", _("48 часов"))])
  42. config.plugins.SetClock.syncNTPcoldstart = ConfigYesNo(default = False)
  43. config.plugins.SetClock.useRTCstart = ConfigYesNo(default = False)
  44. config.plugins.SetClock.wifi_delay = ConfigInteger(0, limits=(0,120))
  45. #config.plugins.SetClock.wifi_delay = ConfigInteger(default = 0, limits = (0,120))
  46. config.plugins.SetClock.syncDVBtime = ConfigSelection(default = "1", choices = [("1", _('Нажмите кнопку "OK"'))])
  47. #config.plugins.SetClock.ip = ConfigText(default="ntp2.vniiftri.ru", fixed_size = False) # Set the IP address of the preferred NTP server. Default is pool.ntp.org.
  48. config.plugins.SetClock.ip = ConfigText(default="pool.ntp.org", fixed_size = False) # Set the IP address of the preferred NTP server. Default is pool.ntp.org.
  49. ver = '1.1'
  50.  
  51. from NTPSyncPoller import NTPSyncPoller
  52. ntpsyncpoller = None
  53.  
  54. def Plugins(path, **kwargs):
  55. global plugin_path
  56. plugin_path = path
  57. return [PluginDescriptor(name='SetClock', description='SetClock plug-in v.' + ver + ' (c)2011 by SatCat', where=PluginDescriptor.WHERE_PLUGINMENU, icon='plugin.png', fnc=main), PluginDescriptor(name='SetClock', description='SetClock plug-in v.' + ver + '(c)2011 by SatCat', where=[PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc=autostart)]
  58.  
  59.  
  60. def main(session, servicereference = None, **kwargs):
  61. session.open(SetClockMain)
  62.  
  63. #def autostart(reason, **kwargs):
  64. #global session
  65. #if reason == 0 and kwargs.has_key('session'):
  66. #session = kwargs['session']
  67. #session.open(AutoCorrTime)
  68.  
  69. def autostart(reason=0, **kwargs):
  70. if reason == 0:
  71. global ntpsyncpoller
  72. if ntpsyncpoller is None:
  73. ntpsyncpoller = NTPSyncPoller()
  74. ntpsyncpoller.start()
  75. removeNetworkStart()
  76. elif reason == 1:
  77. nowTime = time.time()
  78. if nowTime > 1388534400:
  79. setRTCtime(nowTime)
  80.  
  81. def get_time_str(res_time):
  82. replace_months = {
  83. 'Jan': '1',
  84. 'Feb': '2',
  85. 'Mar': '3',
  86. 'Apr': '4',
  87. 'May': '5',
  88. 'June': '6',
  89. 'Jun': '6',
  90. 'July': '7',
  91. 'Jul': '7',
  92. 'Aug': '8',
  93. 'Sept': '9',
  94. 'Sep': '9',
  95. 'Oct': '10',
  96. 'Nov': '11',
  97. 'Dec': '12'
  98. }
  99. gmts = [
  100. 'UTC',
  101. 'GMT'
  102. ]
  103. _res_time = res_time
  104. try:
  105. time_tuple = time.strptime(res_time, '%a, %d %b %Y %H:%M:%S %Z')
  106. except ValueError:
  107. for m1, m2 in replace_months.items():
  108. res_time = res_time.replace(m1, m2)
  109. for gmt in gmts:
  110. res_time = res_time.replace(gmt, '')
  111. res_time = res_time.split(', ')[1].strip()
  112. try:
  113. time_tuple = time.strptime(res_time, '%d %m %Y %H:%M:%S')
  114. #open('/usr/lib/enigma2/python/Plugins/Extensions/SetClock/log.txt', 'a').write(_res_time)
  115. except ValueError:
  116. open('/usr/lib/enigma2/python/Plugins/Extensions/SetClock/log.txt', 'a').write(_res_time)
  117. raise
  118. t = time.localtime(time.mktime(time_tuple) - time.timezone)
  119. return time.strftime('%Y%m%d%H%M.%S', t)
  120.  
  121. class AutoCorrTime(Screen):
  122. skin = '''
  123. <screen position="100,100" size="280,300" title="SetClock" >
  124. </screen>'''
  125.  
  126. def __init__(self, session):
  127. Screen.__init__(self, session)
  128. self.session = session
  129. if time.localtime().tm_year == 2000:
  130. self.limit = 0
  131. self.cursorTimer = eTimer()
  132. self.cursorTimer.callback.append(self.timer)
  133. self.cursorTimer.start(75, False)
  134.  
  135. def timer(self):
  136. if time.localtime().tm_year > 2000:
  137. refstr = dtt = 'n/a'
  138. try:
  139. service = self.session.nav.getCurrentService()
  140. if service:
  141. info = service.info()
  142. if info:
  143. refstr = info.getInfoString(iServiceInformation.sServiceref)
  144. except:
  145. refstr = 'ref error'
  146.  
  147. if refstr == '1:0:1:1:65:64:3840000:0:0:0:':
  148. tc = time.time() - 189391980
  149. dtt = datetime.fromtimestamp(tc).strftime('%Y%m%d%H%M')
  150. enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
  151. try:
  152. system('/bin/date -s %s' % dtt)
  153. print '[SetClock] Set clock!'
  154. except:
  155. pass
  156.  
  157. self.cursorTimer.stop()
  158. self.limit = self.limit + 1
  159. if self.limit > 1200:
  160. self.cursorTimer.stop()
  161. print '[SetClock] Stop timer (limit).'
  162.  
  163.  
  164. class SetClockMain(ConfigListScreen, Screen):
  165. skin = '''
  166. <screen position="center,200" size="640,365" title="SetClock" >
  167. <widget name="config" position="0,0" size="640,365" scrollbarMode="showOnDemand" />
  168. <widget name="key_red" position="0,325" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1"/>
  169. <ePixmap name="red" position="0,325" size="140,40" zPosition="2" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
  170. <widget name="key_green" position="140,325" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;20" transparent="1"/>
  171. <ePixmap name="green" position="140,325" size="140,40" zPosition="2" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
  172. <widget name="key_yellow" position="280,325" size="140,40" valign="center" halign="center" zPosition="4" backgroundColor="#a08500" font="Regular;20" transparent="1"/>
  173. <ePixmap name="yellow" position="280,325" size="140,40" zPosition="2" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
  174. <widget name="key_blue" position="395,325" size="270,40" valign="center" halign="center" zPosition="4" backgroundColor="#a08500" font="Regular;20" transparent="1"/>
  175. <ePixmap name="blue" position="420,325" size="270,40" zPosition="2" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
  176. <ePixmap name="blue" position="500,325" size="140,40" zPosition="2" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
  177. </screen>'''
  178.  
  179. def __init__(self, session, servicelist = None, args = None):
  180. self.servicelist = servicelist
  181. self.skin = SetClockMain.skin
  182. self.session = session
  183. Screen.__init__(self, session)
  184. self.list = []
  185. self.date_en = ConfigDate(default=time.time())
  186. self.entryDate = getConfigListEntry(_('Дата :'), self.date_en)
  187. self.time_en = ConfigClock(default=time.time())
  188. self.entryTime = getConfigListEntry(_('Время :'), self.time_en)
  189. self.list.append(self.entryDate)
  190. self.list.append(self.entryTime)
  191. self.list.append(getConfigListEntry('HTTP хост :', config.plugins.SetClock.HostName))
  192. #self.list.append(getConfigListEntry('NTP сервер № 01 :', config.plugins.SetClock.NTPName01))
  193. #self.list.append(getConfigListEntry('NTP сервер № 02 :', config.plugins.SetClock.NTPName02))
  194. #self.list.append(getConfigListEntry('NTP сервер № 03 :', config.plugins.SetClock.NTPName03))
  195. #self.list.append(getConfigListEntry('NTP сервер № 04 :', config.plugins.SetClock.NTPName04))
  196. #self.list.append(getConfigListEntry('NTP сервер № 05 :', config.plugins.SetClock.NTPName05))
  197. #self.list.append(getConfigListEntry('NTP сервер № 06 :', config.plugins.SetClock.NTPName06))
  198. #self.list.append(getConfigListEntry('NTP сервер № 07 :', config.plugins.SetClock.NTPName07))
  199. #self.list.append(getConfigListEntry('NTP сервер № 08 :', config.plugins.SetClock.NTPName08))
  200. #self.list.append(getConfigListEntry('NTP сервер № 09 :', config.plugins.SetClock.NTPName09))
  201. self.list.append(getConfigListEntry('NTP сервер № 01 :', config.plugins.SetClock.NTPName01))
  202. self.list.append(getConfigListEntry(_('NTP сервер таймаут [сек] :'), config.plugins.SetClock.timeout))
  203. self.list.append(getConfigListEntry(_('Синхронизировать с NTP каждые :'), config.plugins.SetClock.useNTPminutes, _("Set how often the receiver will connect to the NTP server to sync time.")))
  204. self.list.append(getConfigListEntry(_('Синхронизировать с NTP при старте ресивера :'), config.plugins.SetClock.syncNTPcoldstart, _("On receiver 'cold start', allow any required time adjustments to be 'stepped'.")))
  205. self.list.append(getConfigListEntry(_('Задержка [сек] при использовании сети Wi-Fi :'), config.plugins.SetClock.wifi_delay, _("After receiver's boot, wait for the specified delay before connecting to the NTP server. This allows the Wi-Fi connection to be fully established.")))
  206. #self.list.append(getConfigListEntry(_('Синхронизировать сейчас с текущего транспондера'), config.plugins.SetClock.syncDVBtime))
  207. #self.list.append(getConfigListEntry(_('Синхронизация сейчас с текущего транспондера'), config.plugins.SetClock.syncDVBtime))
  208. #self.list.append(getConfigListEntry(_('Синхронизация с транспондера :'), config.plugins.SetClock.syncDVBtime))
  209. #self.list.append(getConfigListEntry(_('Синхронизация с текущего транспондера :'), config.plugins.SetClock.syncDVBtime))
  210. self.list.append(getConfigListEntry(_('Синхронизировать с транспондера :'), config.plugins.SetClock.syncDVBtime, _("Get current time from the specified DVB transponder.")))
  211. self.list.append(getConfigListEntry(_('Использовать время RTC при старте ресивера :'), config.plugins.SetClock.useRTCstart, _("When the receiver starts from deep standby, use the time provided by the Real Time Clock, if it appears to be valid.")))
  212. self['key_red'] = Button(_('Отмена'))
  213. self['key_green'] = Button(_('HTTP SET'))
  214. self['key_yellow'] = Button(_('NTP SET'))
  215. self['key_blue'] = Button(_('Установить!'))
  216. ConfigListScreen.__init__(self, self.list, session=session)
  217. if config.plugins.SetClock.syncNTPcoldstart.value and not fileExists("/etc/init.d/ntpdate"):
  218. config.plugins.SetClock.syncNTPcoldstart.value = False
  219. config.plugins.SetClock.syncNTPcoldstart.save()
  220. if config.plugins.SetClock.useRTCstart.value and not fileExists("/etc/init.d/set-rtctime"):
  221. config.plugins.SetClock.useRTCstart.value = False
  222. config.plugins.SetClock.useRTCstart.save()
  223. self['setupActions'] = ActionMap(['OkCancelActions', 'ColorActions'], {'red': self.exit,
  224. 'green': self.inet_set,
  225. 'yellow': self.NTP_set,
  226. #'blue': self.set,
  227. 'blue': self.keyBlue,
  228. 'cancel': self.exit,
  229. #'ok': self.pressed_ok,
  230. 'ok': self.keyGo}, -2)
  231. self['config'].list = self.list
  232. self['config'].l.setList(self.list)
  233. self["config"].onSelectionChanged.append(self.configPosition)
  234.  
  235. def set(self, dtt = 0):
  236. if self.date_en.value[2] >= 2038 and self.date_en.value[1] >= 1 and self.date_en.value[0] >= 19 and self.time_en.value[0] >= 6 and self.time_en.value[1] >= 14 and self.time_en.value[2] > 5:
  237. self.date_en.value[2] = 2038
  238. self.date_en.value[1] = 1
  239. self.date_en.value[0] = 19
  240. self.time_en.value[0] = 6
  241. self.time_en.value[1] = 14
  242. self.time_en.value[2] = 5
  243. dtt = '%d%02d%02d%02d%02d.%02d' % (self.date_en.value[2],
  244. self.date_en.value[1],
  245. self.date_en.value[0],
  246. self.time_en.value[0],
  247. self.time_en.value[1],
  248. self.time_en.value[2])
  249. enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
  250. try:
  251. system('/bin/date -s %s' % dtt)
  252. except:
  253. pass
  254.  
  255. self.close()
  256. #print '[SetClock] SET! ** %s' % time.strftime('%X %x (%Y) %Z')
  257.  
  258. def inet_set(self):
  259. config.plugins.SetClock.HostName.save()
  260. conn = httplib.HTTPConnection(config.plugins.SetClock.HostName.value)
  261. try:
  262. conn.request('HEAD', '/favicon.ico')
  263. t_rtt = time.clock()
  264. res_time = conn.getresponse().getheader('date')
  265. except:
  266. #self.session.open(MessageBox, 'Error: No server responce: ' + config.plugins.SetClock.HostName.value, MessageBox.TYPE_ERROR, timeout=3)
  267. self.session.open(MessageBox, 'No server responce: ' + config.plugins.SetClock.HostName.value, MessageBox.TYPE_ERROR)
  268. return
  269.  
  270. enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
  271.  
  272. try:
  273. system('/bin/date -s %s' % get_time_str(res_time))
  274. except:
  275. pass
  276.  
  277. self.close()
  278. #print '[SetClock] inet SET! ** %s' % time.strftime('%X %x (%Y) %Z')
  279.  
  280. #def cancel(self):
  281. #self.close()
  282.  
  283. def save(self):
  284. for x in self['config'].list:
  285. x[1].save()
  286. self.close()
  287.  
  288. def exit(self):
  289. for x in self['config'].list:
  290. x[1].cancel()
  291. self.close()
  292.  
  293. def NTP_set(self):
  294. #if (config.plugins.SetClock.NTPName01.value == "" and config.plugins.SetClock.NTPName02.value == "" and config.plugins.SetClock.NTPName03.value == "" and config.plugins.SetClock.NTPName04.value == "" and config.plugins.SetClock.NTPName05.value == "" and config.plugins.SetClock.NTPName06.value == "" and config.plugins.SetClock.NTPName07.value == "" and config.plugins.SetClock.NTPName08.value == "" and config.plugins.SetClock.NTPName09.value == ""):
  295. #self.session.open(MessageBox, _("no timeserver configured!"), MessageBox.TYPE_INFO)
  296. #else:
  297. #log_file = open('/usr/lib/enigma2/python/Plugins/Extensions/SetClock/log_NTP.txt', 'a')
  298. def execute_cmd(cmd):
  299. #log_file.write("Начинаю выполнять команду: %s\n" % cmd)
  300. fo = popen(cmd)
  301. output = fo.read()
  302. exit_code = fo.close()
  303. #log_file.write("Результат выполнения команды: %s; вывод: `%s`; код-завершения: %i\n" % (cmd, output, 0 if exit_code is None else exit_code))
  304. return output
  305. if os.path.exists(os.path.join(plugin_path, "ntpdate")):
  306. #log_file.write("Программа существует по указанному пути\n")
  307. #Lite_OutPut_In_Console_1_stroke
  308. #cmd = '/usr/bin/ntpdate -b -t %s %s && echo "\n"' % (config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName.value)
  309. #cmd = '%s%s %s %s && echo "\n"' % (plugin_path, "/ntpdate -b -t ", config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName01.value)
  310. #cmd = '%s%s %s %s %s %s %s %s %s %s %s %s && echo "\n"' % (plugin_path, "/ntpdate -b -t ", config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName01.value, config.plugins.SetClock.NTPName02.value, config.plugins.SetClock.NTPName03.value, config.plugins.SetClock.NTPName04.value, config.plugins.SetClock.NTPName05.value, config.plugins.SetClock.NTPName06.value, config.plugins.SetClock.NTPName07.value, config.plugins.SetClock.NTPName08.value, config.plugins.SetClock.NTPName09.value)
  311. #Extended_OutPut_In_Console_2_stroke
  312. #cmd = '/usr/bin/ntpdate -v -u %s %s && echo "\n"' % (config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName.value)
  313. #cmd = '%s%s %s %s && echo "\n"' % (plugin_path, "/ntpdate -v -u ", config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName01.value)
  314. cmd = '%s%s %s %s && echo "\n"' % (plugin_path, "/ntpdate -v -u", config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName01.value)
  315. #cmd = '%s%s %s %s %s %s %s %s %s %s %s %s && echo "\n"' % (plugin_path, "/ntpdate -v -u ", config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName01.value, config.plugins.SetClock.NTPName02.value, config.plugins.SetClock.NTPName03.value, config.plugins.SetClock.NTPName04.value, config.plugins.SetClock.NTPName05.value, config.plugins.SetClock.NTPName06.value, config.plugins.SetClock.NTPName07.value, config.plugins.SetClock.NTPName08.value, config.plugins.SetClock.NTPName09.value)
  316. res = execute_cmd(cmd)
  317. pipe = popen(cmd)
  318. res = pipe.read()
  319. exit_code = pipe.close()
  320. if exit_code == 256:
  321. self.session.open(MessageBox, _("ntpdate problem: Internet connection ok? Time server ok?"), MessageBox.TYPE_INFO)
  322. elif res == "":
  323. cmd = "ls -l %s%s" % (plugin_path, "/ntpdate")
  324. res = execute_cmd(cmd)
  325. if res[3]!="x":
  326. cmd = "chmod 755 %s%s" % (plugin_path, "/ntpdate")
  327. res = execute_cmd(cmd)
  328. self.session.open(MessageBox, _("ntpdate problem: attributes for 'ntpdate' have not been correct! Fixed now! Try again!\n%s" % res), MessageBox.TYPE_INFO)
  329. else:
  330. self.session.open(MessageBox, _("ntpdate problem: Internet connection ok? Time server ok?"), MessageBox.TYPE_INFO)
  331. else:
  332. self.session.open(MyConsole, _("Системное время с NTP ..."), [cmd])
  333. self.close()
  334. self.close()
  335. else:
  336. #log_file.write("Программа не существует по указанному пути")
  337. self.session.open(MessageBox, _("'ntpdate' не установлен !"), MessageBox.TYPE_ERROR)
  338. #log_file.close()
  339.  
  340. #self.close()
  341. #print '[SetClock] NTP SET! ** %s' % time.strftime('%X %x (%Y) %Z')
  342.  
  343. #self.close()
  344. #print '[SetClock] NTP SET! ** %s' % time.strftime('%X %x (%Y) %Z')
  345.  
  346. def addNTPcoldstart(self):
  347. if os.path.exists("/usr/sbin/ntpdate") or os.path.exists("/usr/sbin/ntpd"):
  348. if os.path.exists("/usr/sbin/ntpdate"):
  349. cmd = "echo -e '#!/bin/sh\n\nsleep %s\n\n[ -x /usr/sbin/ntpdate ] && /usr/sbin/ntpdate -s -u %s\n\nexit 0' >> /etc/init.d/ntpdate" % (str(config.plugins.SetClock.wifi_delay.value), config.plugins.SetClock.ip.value)
  350. elif os.path.exists("/usr/sbin/ntpd"):
  351. cmd = "echo -e '#!/bin/sh\n\nsleep %s\n\n[ -x usr/sbin/ntpd ] && /usr/sbin/ntpd -dnqp %s\n\nexit 0' >> /etc/init.d/ntpdate" % (str(config.plugins.SetClock.wifi_delay.value), config.plugins.SetClock.ip.value)
  352. if fileExists("/etc/init.d/ntpdate"):
  353. os.chmod("/etc/init.d/ntpdate", 0755)
  354. os.system("update-rc.d ntpdate defaults 99")
  355. else:
  356. os.system(cmd)
  357. if fileExists("/etc/init.d/ntpdate"):
  358. os.chmod("/etc/init.d/ntpdate", 0755)
  359. os.system("update-rc.d ntpdate defaults 99")
  360. else:
  361. config.plugins.SetClock.syncNTPcoldstart.value = False
  362. else:
  363. self.session.open(MessageBox,"'ntpd' / " + _("'ntpdate' not installed !"), MessageBox.TYPE_ERROR, timeout=3)
  364. config.plugins.SetClock.syncNTPcoldstart.value = False
  365.  
  366. def removeNTPcoldstart(self):
  367. os.system("update-rc.d -f ntpdate remove")
  368. if fileExists("/etc/init.d/ntpdate"):
  369. os.system("rm -rf /etc/init.d/ntpdate")
  370.  
  371. def addUseRTC(self):
  372. if fileExists("/etc/init.d/set-rtctime"):
  373. os.chmod("/etc/init.d/set-rtctime", 0755)
  374. os.system("update-rc.d set-rtctime defaults 40")
  375. else:
  376. #os.system("cp /usr/lib/enigma2/python/Plugins/SystemPlugins/SystemTime/set-rtctime /etc/init.d/set-rtctime")
  377. os.system("cp /usr/lib/enigma2/python/Plugins/Extensions/SetClock/set-rtctime /etc/init.d/set-rtctime")
  378. if fileExists("/etc/init.d/set-rtctime"):
  379. os.chmod("/etc/init.d/set-rtctime", 0755)
  380. os.system("update-rc.d set-rtctime defaults 40")
  381. else:
  382. #self.session.open(MessageBox,_("Script 'set-rtctime' not found !"), MessageBox.TYPE_ERROR, timeout=3)
  383. self.session.open(MessageBox,_("Script 'set-rtctime' not found !"), MessageBox.TYPE_ERROR)
  384. config.plugins.SetClock.useRTCstart.value = False
  385.  
  386. def removeUseRTC(self):
  387. os.system("update-rc.d -f set-rtctime remove")
  388.  
  389. def keyGo(self):
  390. sel = self["config"].getCurrent() and self["config"].getCurrent()[0]
  391. if sel == _("Синхронизация с текущего транспондера :"):
  392. #log_file = open('/usr/lib/enigma2/python/Plugins/Extensions/SetClock/log_DVB.txt', 'a')
  393. def execute_cmd(cmd):
  394. #log_file.write("Начинаю выполнять команду: %s\n" % cmd)
  395. fo = popen(cmd)
  396. output = fo.read()
  397. exit_code = fo.close()
  398. #log_file.write("Результат выполнения команды: %s; вывод: `%s`; код-завершения: %i\n" % (cmd, output, 0 if exit_code is None else exit_code))
  399. return output
  400. #if os.path.exists("/usr/bin/dvbdate"):
  401. if os.path.exists(os.path.join(plugin_path, "dvbdate")):
  402. #log_file.write("Программа существует по указанному пути\n")
  403. #cmd = '/usr/bin/dvbdate -p -s -f && echo "\n"'
  404. cmd = '%s%s && echo "\n"' % (plugin_path, "/dvbdate -p -s -f")
  405. res = execute_cmd(cmd)
  406. pipe = popen(cmd)
  407. res = pipe.read()
  408. exit_code = pipe.close()
  409. if exit_code == 256:
  410. self.session.open(MessageBox, _("dvbdate problem: Satellite connection ok?"), MessageBox.TYPE_INFO)
  411. elif res == "":
  412. cmd = "ls -l %s%s" % (plugin_path, "/dvbdate")
  413. res = execute_cmd(cmd)
  414. if res[3]!="x":
  415. cmd = "chmod 755 %s%s" % (plugin_path, "/dvbdate")
  416. res = execute_cmd(cmd)
  417. self.session.open(MessageBox, _("dvbdate problem: attributes for 'dvbdate' have not been correct! Fixed now! Try again!\n%s" % res), MessageBox.TYPE_INFO)
  418. else:
  419. self.session.open(MessageBox, _("dvbdate problem: Satellite connection ok?"), MessageBox.TYPE_INFO)
  420. else:
  421. self.session.open(MyConsole, _("Системное время с DVB ..."), [cmd])
  422. self.close()
  423. self.close()
  424. else:
  425. #log_file.write("Программа не существует по указанному пути")
  426. self.session.open(MessageBox, _("'dvbdate' не установлен !"), MessageBox.TYPE_ERROR)
  427. #log_file.close()
  428. if (sel == _("Дата :") or sel == _("Время :")):
  429. self.set()
  430. if (sel == _("HTTP хост :") or sel == _("NTP сервер № 01 :") or sel == _("NTP сервер таймаут [сек] :") or sel == _("Синхронизировать с NTP каждые :") or sel == _("Синхронизировать с NTP при старте ресивера :") or sel == _("Использовать время RTC при старте ресивера :") or sel == _("Задержка [сек] при использовании сети Wi-Fi :")):
  431. if (sel == _("HTTP хост :") or sel == _("NTP сервер № 01 :") or sel == _("NTP сервер таймаут [сек] :") or sel == _("Синхронизировать с NTP каждые :")):
  432. if sel == _("HTTP хост :"):
  433. config.plugins.SetClock.HostName.save()
  434. if sel == _("NTP сервер № 01 :"):
  435. config.plugins.SetClock.NTPName01.save()
  436. if sel == _("NTP сервер таймаут [сек] :"):
  437. config.plugins.SetClock.timeout.save()
  438. if sel == _("Синхронизировать с NTP каждые :"):
  439. config.plugins.SetClock.useNTPminutes.save()
  440. if (sel == _("Синхронизировать с NTP при старте ресивера :") or sel == _("Использовать время RTC при старте ресивера :") or sel == _("Задержка [сек] при использовании сети Wi-Fi :")):
  441. if config.plugins.SetClock.syncNTPcoldstart.value:
  442. if config.plugins.SetClock.ip.value or config.plugins.SetClock.wifi_delay.value:
  443. self.removeNTPcoldstart()
  444. self.addNTPcoldstart()
  445. else:
  446. self.removeNTPcoldstart()
  447. if config.plugins.SetClock.useRTCstart.value:
  448. self.addUseRTC()
  449. else:
  450. self.removeUseRTC()
  451. if config.plugins.SetClock.choiceSystemTime.value == "0":
  452. eDVBLocalTimeHandler.getInstance().setUseDVBTime(True)
  453. #config.misc.useTransponderTime.value = True
  454. #config.misc.useTransponderTime.save()
  455. else:
  456. eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
  457. #config.misc.useTransponderTime.value = False
  458. #config.misc.useTransponderTime.save()
  459. removeNetworkStart()
  460. config.plugins.SetClock.save()
  461. #configfile.save()
  462. #self.close()
  463. self.session.open(MessageBox, _("Настройки сохранены !"), MessageBox.TYPE_INFO)
  464. self.exit()
  465.  
  466. def configPosition(self):
  467. self["key_blue"].setText("")
  468. sel = self["config"].getCurrent() and self["config"].getCurrent()[0]
  469. if (sel == _("Дата :") or sel == _("Время :")):
  470. self["key_blue"].setText(_("Установить!"))
  471. if (sel == _("HTTP хост :") or sel == _("NTP сервер № 01 :") or sel == _("NTP сервер таймаут [сек] :") or sel == _("Синхронизировать с NTP каждые :") or sel == _("Синхронизировать с NTP при старте ресивера :") or sel == _("Использовать время RTC при старте ресивера :") or sel == _("Задержка [сек] при использовании сети Wi-Fi :")):
  472. self["key_blue"].setText(_("Сохранить"))
  473. if sel == _("Синхронизация с текущего транспондера :"):
  474. self["key_blue"].setText(_("Выбор транспондера"))
  475.  
  476. def keyBlue(self):
  477. if self["key_blue"].getText() == _("Выбор транспондера"):
  478. if self.servicelist is None:
  479. for (dlg,flag) in self.session.dialog_stack:
  480. if dlg.__class__.__name__ == "InfoBar":
  481. self.servicelist = dlg.servicelist
  482. break
  483. if not self.servicelist is None:
  484. self.session.execDialog(self.servicelist)
  485. else:
  486. self.keyGo()
  487.  
  488. class MyConsole(Console):
  489. skin = '''
  490. <screen position="center,245" size="485,290" title="Command execution..." >
  491. <widget name="text" position="0,0" size="485,290" font="Regular;20" />
  492. </screen>'''
  493.  
  494. def __init__(self, session, title = "My Console...", cmdlist = None):
  495. Console.__init__(self, session, title, cmdlist)
  496.  
  497. date_limits = [(1, 31), (1, 12), (1970, 2090)]
  498. class ConfigDate(ConfigSequence):
  499. def __init__(self, default):
  500. d = time.localtime(default)
  501. ConfigSequence.__init__(self, seperator=".", limits=date_limits, default=[d.tm_mday, d.tm_mon, d.tm_year])
  502.  
  503. time_limits = [(0, 23), (0, 59), (0, 59)]
  504. class ConfigClock(ConfigSequence):
  505. def __init__(self, default):
  506. d = time.localtime(default)
  507. ConfigSequence.__init__(self, seperator=":", limits=time_limits, default=[d.tm_hour, d.tm_min, d.tm_sec])
  508.  
  509. def removeNetworkStart():
  510. if os.path.exists("/usr/bin/ntpdate-sync"):
  511. os.system("rm -rf /usr/bin/ntpdate-sync && rm -rf /etc/network/if-up.d/ntpdate-sync")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement