SharkyEXE icon

Untitled

SharkyEXE | PRO | 11/02/18 04:49:26 PM UTC | 0 ⭐ | 800 👁️ | Never ⏰ | []
text |

28.35 KB

|

None

|

0 👍

/

0 👎

# -*- coding: utf-8 -*-
from Plugins.Plugin import PluginDescriptor
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.Button import Button
from Components.ActionMap import ActionMap
from Components.ConfigList import ConfigListScreen
#from Components.config import config, ConfigSubsection, ConfigDateTime, ConfigClock, ConfigText, getConfigListEntry, ConfigInteger, ConfigSequence, ConfigSelection, ConfigYesNo, configfile
from Components.config import config, ConfigSubsection, ConfigDateTime, ConfigClock, ConfigText, getConfigListEntry, ConfigInteger, ConfigSequence, ConfigSelection, ConfigYesNo
import enigma
from enigma import eTimer, iServiceInformation, eDVBLocalTimeHandler
from datetime import datetime, time as dt_time
from os import system
import gettext
import time, httplib
from Screens.Console import Console
import os
from os import popen
from Tools.Directories import fileExists
try:
	from Tools.StbHardware import setRTCtime
except:
	from Tools.DreamboxHardware import setRTCtime
 config.plugins.SetClock = ConfigSubsection()
config.plugins.SetClock.HostName = ConfigText(default='vniiftri.ru', fixed_size=False)
#config.plugins.SetClock.NTPName01 = ConfigText(default='vniiftri2.khv.ru', fixed_size=False)
#config.plugins.SetClock.NTPName02 = ConfigText(default='vniiftri.khv.ru', fixed_size=False)
#config.plugins.SetClock.NTPName03 = ConfigText(default='ntp2.niiftri.irkutsk.ru', fixed_size=False)
#config.plugins.SetClock.NTPName04 = ConfigText(default='ntp1.niiftri.irkutsk.ru', fixed_size=False)
#config.plugins.SetClock.NTPName05 = ConfigText(default='ntp21.vniiftri.ru', fixed_size=False)
#config.plugins.SetClock.NTPName06 = ConfigText(default='ntp4.vniiftri.ru', fixed_size=False)
#config.plugins.SetClock.NTPName07 = ConfigText(default='ntp3.vniiftri.ru', fixed_size=False)
#config.plugins.SetClock.NTPName08 = ConfigText(default='ntp1.vniiftri.ru', fixed_size=False)
#config.plugins.SetClock.NTPName09 = ConfigText(default='ntp2.vniiftri.ru', fixed_size=False)
config.plugins.SetClock.NTPName01 = ConfigText(default='ntp2.vniiftri.ru', fixed_size=False)
config.plugins.SetClock.timeout = ConfigInteger(default = 1, limits = (1,120))
config.plugins.SetClock.choiceSystemTime = ConfigSelection([("0", _("Transponder Time")),("1", _("Internet Time"))], default="1")
#config.plugins.SetClock.choiceSystemTime = ConfigSelection([("1", _("Internet Time"))], default="1")
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 часов"))])
#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 часов"))])
config.plugins.SetClock.syncNTPcoldstart = ConfigYesNo(default = False)
config.plugins.SetClock.useRTCstart = ConfigYesNo(default = False)
config.plugins.SetClock.wifi_delay = ConfigInteger(0, limits=(0,120))
#config.plugins.SetClock.wifi_delay = ConfigInteger(default = 0, limits = (0,120))
config.plugins.SetClock.syncDVBtime = ConfigSelection(default = "1", choices = [("1", _('Нажмите кнопку "OK"'))])
#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.
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.
ver = '1.1'
 from NTPSyncPoller import NTPSyncPoller
ntpsyncpoller = None
 def Plugins(path, **kwargs):
 global plugin_path
 plugin_path = path
 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)]
  def main(session, servicereference = None, **kwargs):
 session.open(SetClockMain)
 #def autostart(reason, **kwargs):
 #global session
 #if reason == 0 and kwargs.has_key('session'):
  #session = kwargs['session']
  #session.open(AutoCorrTime)
 def autostart(reason=0, **kwargs):
 if reason == 0:
  global ntpsyncpoller
  if ntpsyncpoller is None:
   ntpsyncpoller = NTPSyncPoller()
   ntpsyncpoller.start()
   removeNetworkStart()
 elif reason == 1:
  nowTime = time.time()
  if nowTime > 1388534400:
   setRTCtime(nowTime)
 def get_time_str(res_time):     
 replace_months = {
  'Jan': '1',
  'Feb': '2',
  'Mar': '3',
  'Apr': '4',
  'May': '5',
  'June': '6',
  'Jun': '6',
  'July': '7',
  'Jul': '7',
  'Aug': '8',
  'Sept': '9',
  'Sep': '9',
  'Oct': '10',
  'Nov': '11',
  'Dec': '12'
 }
 gmts = [
  'UTC',
  'GMT'
 ]
 _res_time = res_time
 try:
  time_tuple = time.strptime(res_time, '%a, %d %b %Y %H:%M:%S %Z')
 except ValueError:
  for m1, m2 in replace_months.items():    
   res_time = res_time.replace(m1, m2)
  for gmt in gmts:
   res_time = res_time.replace(gmt, '')
  res_time = res_time.split(', ')[1].strip()
  try:
   time_tuple = time.strptime(res_time, '%d %m %Y %H:%M:%S')
   #open('/usr/lib/enigma2/python/Plugins/Extensions/SetClock/log.txt', 'a').write(_res_time)
  except ValueError:
   open('/usr/lib/enigma2/python/Plugins/Extensions/SetClock/log.txt', 'a').write(_res_time)
   raise
 t = time.localtime(time.mktime(time_tuple) - time.timezone)
 return time.strftime('%Y%m%d%H%M.%S', t)
 class AutoCorrTime(Screen):
 skin = '''
 <screen position="100,100" size="280,300" title="SetClock" >
 </screen>'''
  def __init__(self, session):
  Screen.__init__(self, session)
  self.session = session
  if time.localtime().tm_year == 2000:
   self.limit = 0
   self.cursorTimer = eTimer()
   self.cursorTimer.callback.append(self.timer)
   self.cursorTimer.start(75, False)
  def timer(self):
  if time.localtime().tm_year > 2000:
   refstr = dtt = 'n/a'
   try:
    service = self.session.nav.getCurrentService()
    if service:
     info = service.info()
     if info:
      refstr = info.getInfoString(iServiceInformation.sServiceref)
   except:
    refstr = 'ref error'
    if refstr == '1:0:1:1:65:64:3840000:0:0:0:':
    tc = time.time() - 189391980
    dtt = datetime.fromtimestamp(tc).strftime('%Y%m%d%H%M')
    enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
    try:
     system('/bin/date -s %s' % dtt)
     print '[SetClock] Set clock!'
    except:
     pass
     self.cursorTimer.stop()
  self.limit = self.limit + 1
  if self.limit > 1200:
   self.cursorTimer.stop()
   print '[SetClock] Stop timer (limit).'
  class SetClockMain(ConfigListScreen, Screen):
 skin = '''
 <screen position="center,200" size="640,365" title="SetClock" >
 <widget name="config" position="0,0" size="640,365" scrollbarMode="showOnDemand" />
 <widget name="key_red" position="0,325" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;20" transparent="1"/>
 <ePixmap name="red" position="0,325" size="140,40" zPosition="2" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
 <widget name="key_green" position="140,325" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;20" transparent="1"/>
 <ePixmap name="green" position="140,325" size="140,40" zPosition="2" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
 <widget name="key_yellow" position="280,325" size="140,40" valign="center" halign="center" zPosition="4"  backgroundColor="#a08500" font="Regular;20" transparent="1"/>
 <ePixmap name="yellow" position="280,325" size="140,40" zPosition="2" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
 <widget name="key_blue" position="395,325" size="270,40" valign="center" halign="center" zPosition="4"  backgroundColor="#a08500" font="Regular;20" transparent="1"/>
 <ePixmap name="blue" position="420,325" size="270,40" zPosition="2" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
 <ePixmap name="blue" position="500,325" size="140,40" zPosition="2" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
 </screen>'''
  def __init__(self, session, servicelist = None, args = None):
  self.servicelist = servicelist
  self.skin = SetClockMain.skin
  self.session = session
  Screen.__init__(self, session)
  self.list = []
  self.date_en = ConfigDate(default=time.time())
  self.entryDate = getConfigListEntry(_('Дата :'), self.date_en)
  self.time_en = ConfigClock(default=time.time())
  self.entryTime = getConfigListEntry(_('Время :'), self.time_en)
  self.list.append(self.entryDate)
  self.list.append(self.entryTime)
  self.list.append(getConfigListEntry('HTTP хост :', config.plugins.SetClock.HostName))
  #self.list.append(getConfigListEntry('NTP сервер № 01 :', config.plugins.SetClock.NTPName01))
  #self.list.append(getConfigListEntry('NTP сервер № 02 :', config.plugins.SetClock.NTPName02))
  #self.list.append(getConfigListEntry('NTP сервер № 03 :', config.plugins.SetClock.NTPName03))
  #self.list.append(getConfigListEntry('NTP сервер № 04 :', config.plugins.SetClock.NTPName04))
  #self.list.append(getConfigListEntry('NTP сервер № 05 :', config.plugins.SetClock.NTPName05))
  #self.list.append(getConfigListEntry('NTP сервер № 06 :', config.plugins.SetClock.NTPName06))
  #self.list.append(getConfigListEntry('NTP сервер № 07 :', config.plugins.SetClock.NTPName07))
  #self.list.append(getConfigListEntry('NTP сервер № 08 :', config.plugins.SetClock.NTPName08))
  #self.list.append(getConfigListEntry('NTP сервер № 09 :', config.plugins.SetClock.NTPName09))
  self.list.append(getConfigListEntry('NTP сервер № 01 :', config.plugins.SetClock.NTPName01))
  self.list.append(getConfigListEntry(_('NTP сервер таймаут [сек] :'), config.plugins.SetClock.timeout))
  self.list.append(getConfigListEntry(_('Синхронизировать с NTP каждые :'), config.plugins.SetClock.useNTPminutes, _("Set how often the receiver will connect to the NTP server to sync time.")))
  self.list.append(getConfigListEntry(_('Синхронизировать с NTP при старте ресивера :'), config.plugins.SetClock.syncNTPcoldstart, _("On receiver 'cold start', allow any required time adjustments to be 'stepped'.")))
  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.")))
  #self.list.append(getConfigListEntry(_('Синхронизировать сейчас с текущего транспондера'), config.plugins.SetClock.syncDVBtime))
  #self.list.append(getConfigListEntry(_('Синхронизация сейчас с текущего транспондера'), config.plugins.SetClock.syncDVBtime))
  #self.list.append(getConfigListEntry(_('Синхронизация с транспондера :'), config.plugins.SetClock.syncDVBtime))
  #self.list.append(getConfigListEntry(_('Синхронизация с текущего транспондера :'), config.plugins.SetClock.syncDVBtime))
  self.list.append(getConfigListEntry(_('Синхронизировать с транспондера :'), config.plugins.SetClock.syncDVBtime, _("Get current time from the specified DVB transponder.")))
  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.")))
  self['key_red'] = Button(_('Отмена'))
  self['key_green'] = Button(_('HTTP SET'))
  self['key_yellow'] = Button(_('NTP SET'))
  self['key_blue'] = Button(_('Установить!'))
  ConfigListScreen.__init__(self, self.list, session=session)
  if config.plugins.SetClock.syncNTPcoldstart.value and not fileExists("/etc/init.d/ntpdate"):
   config.plugins.SetClock.syncNTPcoldstart.value = False
   config.plugins.SetClock.syncNTPcoldstart.save()
  if config.plugins.SetClock.useRTCstart.value and not fileExists("/etc/init.d/set-rtctime"):
   config.plugins.SetClock.useRTCstart.value = False
   config.plugins.SetClock.useRTCstart.save()
  self['setupActions'] = ActionMap(['OkCancelActions', 'ColorActions'], {'red': self.exit,
   'green': self.inet_set,
   'yellow': self.NTP_set,
   #'blue': self.set,
   'blue': self.keyBlue,
   'cancel': self.exit,
   #'ok': self.pressed_ok,
   'ok': self.keyGo}, -2)
  self['config'].list = self.list
  self['config'].l.setList(self.list)
  self["config"].onSelectionChanged.append(self.configPosition)
  def set(self, dtt = 0):
  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:
   self.date_en.value[2] = 2038
   self.date_en.value[1] = 1
   self.date_en.value[0] = 19
   self.time_en.value[0] = 6
   self.time_en.value[1] = 14
   self.time_en.value[2] = 5
  dtt = '%d%02d%02d%02d%02d.%02d' % (self.date_en.value[2],
   self.date_en.value[1],
   self.date_en.value[0],
   self.time_en.value[0],
   self.time_en.value[1],
   self.time_en.value[2])
  enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
  try:
   system('/bin/date -s %s' % dtt)
  except:
   pass
   self.close()
  #print '[SetClock] SET! ** %s' % time.strftime('%X %x (%Y) %Z')
  def inet_set(self):
  config.plugins.SetClock.HostName.save()
  conn = httplib.HTTPConnection(config.plugins.SetClock.HostName.value)
  try:
   conn.request('HEAD', '/favicon.ico')
   t_rtt = time.clock()
   res_time = conn.getresponse().getheader('date')
  except:
   #self.session.open(MessageBox, 'Error: No server responce: ' + config.plugins.SetClock.HostName.value, MessageBox.TYPE_ERROR, timeout=3)
   self.session.open(MessageBox, 'No server responce: ' + config.plugins.SetClock.HostName.value, MessageBox.TYPE_ERROR)
   return            
   enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
   try:
   system('/bin/date -s %s' % get_time_str(res_time))
  except:
   pass
   self.close()
  #print '[SetClock] inet SET! ** %s' % time.strftime('%X %x (%Y) %Z')
  #def cancel(self):
  #self.close()
  def save(self):
  for x in self['config'].list:
   x[1].save()
  self.close()
  def exit(self):
  for x in self['config'].list:
   x[1].cancel()
  self.close()
  def NTP_set(self):
  #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 == ""):
  #self.session.open(MessageBox, _("no timeserver configured!"), MessageBox.TYPE_INFO)
  #else:
  #log_file = open('/usr/lib/enigma2/python/Plugins/Extensions/SetClock/log_NTP.txt', 'a')
  def execute_cmd(cmd):
   #log_file.write("Начинаю выполнять команду: %s\n" % cmd)
   fo = popen(cmd)
   output = fo.read()
   exit_code = fo.close()
   #log_file.write("Результат выполнения команды: %s; вывод: `%s`; код-завершения: %i\n" % (cmd, output, 0 if exit_code is None else exit_code))
   return output
  if os.path.exists(os.path.join(plugin_path, "ntpdate")):
   #log_file.write("Программа существует по указанному пути\n")
   #Lite_OutPut_In_Console_1_stroke
   #cmd = '/usr/bin/ntpdate -b -t %s %s && echo "\n"' % (config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName.value)
   #cmd = '%s%s %s %s && echo "\n"' % (plugin_path, "/ntpdate -b -t ", config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName01.value)
   #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)
   #Extended_OutPut_In_Console_2_stroke
   #cmd = '/usr/bin/ntpdate -v -u %s %s && echo "\n"' % (config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName.value)
   #cmd = '%s%s %s %s && echo "\n"' % (plugin_path, "/ntpdate -v -u ", config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName01.value)
   cmd = '%s%s %s %s && echo "\n"' % (plugin_path, "/ntpdate -v -u", config.plugins.SetClock.timeout.value, config.plugins.SetClock.NTPName01.value)
   #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)
   res = execute_cmd(cmd)
   pipe = popen(cmd)
   res = pipe.read()
   exit_code = pipe.close()
   if exit_code == 256:
    self.session.open(MessageBox, _("ntpdate problem: Internet connection ok? Time server ok?"), MessageBox.TYPE_INFO)
   elif res == "":
    cmd = "ls -l %s%s" % (plugin_path, "/ntpdate")
    res = execute_cmd(cmd)
    if res[3]!="x":
     cmd = "chmod 755 %s%s" % (plugin_path, "/ntpdate")
     res = execute_cmd(cmd)
     self.session.open(MessageBox, _("ntpdate problem: attributes for 'ntpdate' have not been correct! Fixed now! Try again!\n%s" % res), MessageBox.TYPE_INFO)
    else:
     self.session.open(MessageBox, _("ntpdate problem: Internet connection ok? Time server ok?"), MessageBox.TYPE_INFO)
   else:
    self.session.open(MyConsole, _("Системное время с NTP ..."), [cmd])
    self.close()
    self.close()
  else:
   #log_file.write("Программа не существует по указанному пути")
   self.session.open(MessageBox, _("'ntpdate' не установлен !"), MessageBox.TYPE_ERROR)
  #log_file.close()
   #self.close()
  #print '[SetClock] NTP SET! ** %s' % time.strftime('%X %x (%Y) %Z')
   #self.close()
  #print '[SetClock] NTP SET! ** %s' % time.strftime('%X %x (%Y) %Z')
  def addNTPcoldstart(self):
  if os.path.exists("/usr/sbin/ntpdate") or os.path.exists("/usr/sbin/ntpd"):
   if os.path.exists("/usr/sbin/ntpdate"):
    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)
   elif os.path.exists("/usr/sbin/ntpd"):
    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)
   if fileExists("/etc/init.d/ntpdate"):
    os.chmod("/etc/init.d/ntpdate", 0755)
    os.system("update-rc.d ntpdate defaults 99")
   else:
    os.system(cmd)
    if fileExists("/etc/init.d/ntpdate"):
     os.chmod("/etc/init.d/ntpdate", 0755)
     os.system("update-rc.d ntpdate defaults 99")
    else:
     config.plugins.SetClock.syncNTPcoldstart.value = False
  else:
   self.session.open(MessageBox,"'ntpd' / " + _("'ntpdate' not installed !"), MessageBox.TYPE_ERROR, timeout=3)
   config.plugins.SetClock.syncNTPcoldstart.value = False
  def removeNTPcoldstart(self):
  os.system("update-rc.d -f ntpdate remove")
  if fileExists("/etc/init.d/ntpdate"):
   os.system("rm -rf /etc/init.d/ntpdate")
  def addUseRTC(self):
  if fileExists("/etc/init.d/set-rtctime"):
   os.chmod("/etc/init.d/set-rtctime", 0755)
   os.system("update-rc.d set-rtctime defaults 40")
  else:
   #os.system("cp /usr/lib/enigma2/python/Plugins/SystemPlugins/SystemTime/set-rtctime /etc/init.d/set-rtctime")
   os.system("cp /usr/lib/enigma2/python/Plugins/Extensions/SetClock/set-rtctime /etc/init.d/set-rtctime")
   if fileExists("/etc/init.d/set-rtctime"):
    os.chmod("/etc/init.d/set-rtctime", 0755)
    os.system("update-rc.d set-rtctime defaults 40")
   else:
    #self.session.open(MessageBox,_("Script 'set-rtctime' not found !"), MessageBox.TYPE_ERROR, timeout=3)
    self.session.open(MessageBox,_("Script 'set-rtctime' not found !"), MessageBox.TYPE_ERROR)
    config.plugins.SetClock.useRTCstart.value = False
  def removeUseRTC(self):
  os.system("update-rc.d -f set-rtctime remove")
  def keyGo(self):
  sel = self["config"].getCurrent() and self["config"].getCurrent()[0]
  if sel == _("Синхронизация с текущего транспондера :"):
   #log_file = open('/usr/lib/enigma2/python/Plugins/Extensions/SetClock/log_DVB.txt', 'a')
   def execute_cmd(cmd):
    #log_file.write("Начинаю выполнять команду: %s\n" % cmd)
    fo = popen(cmd)
    output = fo.read()
    exit_code = fo.close()
    #log_file.write("Результат выполнения команды: %s; вывод: `%s`; код-завершения: %i\n" % (cmd, output, 0 if exit_code is None else exit_code))
    return output
   #if os.path.exists("/usr/bin/dvbdate"):
   if os.path.exists(os.path.join(plugin_path, "dvbdate")):
    #log_file.write("Программа существует по указанному пути\n")
    #cmd = '/usr/bin/dvbdate -p -s -f && echo "\n"'
    cmd = '%s%s && echo "\n"' % (plugin_path, "/dvbdate -p -s -f")
    res = execute_cmd(cmd)
    pipe = popen(cmd)
    res = pipe.read()
    exit_code = pipe.close()
    if exit_code == 256:
     self.session.open(MessageBox, _("dvbdate problem: Satellite connection ok?"), MessageBox.TYPE_INFO)
    elif res == "":
     cmd = "ls -l %s%s" % (plugin_path, "/dvbdate")
     res = execute_cmd(cmd)
     if res[3]!="x":
      cmd = "chmod 755 %s%s" % (plugin_path, "/dvbdate")
      res = execute_cmd(cmd)
      self.session.open(MessageBox, _("dvbdate problem: attributes for 'dvbdate' have not been correct! Fixed now! Try again!\n%s" % res), MessageBox.TYPE_INFO)
     else:
      self.session.open(MessageBox, _("dvbdate problem: Satellite connection ok?"), MessageBox.TYPE_INFO)
    else:
     self.session.open(MyConsole, _("Системное время с DVB ..."), [cmd])
     self.close()
     self.close()
   else:
    #log_file.write("Программа не существует по указанному пути")
    self.session.open(MessageBox, _("'dvbdate' не установлен !"), MessageBox.TYPE_ERROR)
   #log_file.close()
  if (sel == _("Дата :") or sel == _("Время :")):
   self.set()
  if (sel == _("HTTP хост :") or sel == _("NTP сервер № 01 :") or sel == _("NTP сервер таймаут [сек] :") or sel == _("Синхронизировать с NTP каждые :") or sel == _("Синхронизировать с NTP при старте ресивера :") or sel == _("Использовать время RTC при старте ресивера :") or sel == _("Задержка [сек] при использовании сети Wi-Fi :")):
   if (sel == _("HTTP хост :") or sel == _("NTP сервер № 01 :") or sel == _("NTP сервер таймаут [сек] :") or sel == _("Синхронизировать с NTP каждые :")):
    if sel == _("HTTP хост :"):
     config.plugins.SetClock.HostName.save()
    if sel == _("NTP сервер № 01 :"):
     config.plugins.SetClock.NTPName01.save()
    if sel == _("NTP сервер таймаут [сек] :"):
     config.plugins.SetClock.timeout.save()
    if sel == _("Синхронизировать с NTP каждые :"):
     config.plugins.SetClock.useNTPminutes.save()
   if (sel == _("Синхронизировать с NTP при старте ресивера :") or sel == _("Использовать время RTC при старте ресивера :") or sel == _("Задержка [сек] при использовании сети Wi-Fi :")):
    if config.plugins.SetClock.syncNTPcoldstart.value:
     if config.plugins.SetClock.ip.value or config.plugins.SetClock.wifi_delay.value:
      self.removeNTPcoldstart()
     self.addNTPcoldstart()
    else:
     self.removeNTPcoldstart()
    if config.plugins.SetClock.useRTCstart.value:
     self.addUseRTC()
    else:
     self.removeUseRTC()
    if config.plugins.SetClock.choiceSystemTime.value == "0":
     eDVBLocalTimeHandler.getInstance().setUseDVBTime(True)
     #config.misc.useTransponderTime.value = True
     #config.misc.useTransponderTime.save()
    else:
     eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
     #config.misc.useTransponderTime.value = False
     #config.misc.useTransponderTime.save()
    removeNetworkStart()
    config.plugins.SetClock.save()
    #configfile.save()
    #self.close()
   self.session.open(MessageBox, _("Настройки сохранены !"), MessageBox.TYPE_INFO)
   self.exit()
  def configPosition(self):
  self["key_blue"].setText("")
  sel = self["config"].getCurrent() and self["config"].getCurrent()[0]
  if (sel == _("Дата :") or sel == _("Время :")):
   self["key_blue"].setText(_("Установить!"))
  if (sel == _("HTTP хост :") or sel == _("NTP сервер № 01 :") or sel == _("NTP сервер таймаут [сек] :") or sel == _("Синхронизировать с NTP каждые :") or sel == _("Синхронизировать с NTP при старте ресивера :") or sel == _("Использовать время RTC при старте ресивера :") or sel == _("Задержка [сек] при использовании сети Wi-Fi :")):
   self["key_blue"].setText(_("Сохранить"))
  if sel == _("Синхронизация с текущего транспондера :"):
   self["key_blue"].setText(_("Выбор транспондера"))
  def keyBlue(self):
  if self["key_blue"].getText() == _("Выбор транспондера"):
   if self.servicelist is None:
    for (dlg,flag) in self.session.dialog_stack:
     if dlg.__class__.__name__ == "InfoBar":
      self.servicelist = dlg.servicelist
      break
   if not self.servicelist is None:
     self.session.execDialog(self.servicelist)
  else:
   self.keyGo()
 class MyConsole(Console):
 skin = '''
 <screen position="center,245" size="485,290" title="Command execution..." >
 <widget name="text" position="0,0" size="485,290" font="Regular;20" />
 </screen>'''
  def __init__(self, session, title = "My Console...", cmdlist = None):
  Console.__init__(self, session, title, cmdlist)
 date_limits = [(1, 31), (1, 12), (1970, 2090)]
class ConfigDate(ConfigSequence):
	def __init__(self, default):
		d = time.localtime(default)
		ConfigSequence.__init__(self, seperator=".", limits=date_limits, default=[d.tm_mday, d.tm_mon, d.tm_year])
 time_limits = [(0, 23), (0, 59), (0, 59)]
class ConfigClock(ConfigSequence):
	def __init__(self, default):
		d = time.localtime(default)
		ConfigSequence.__init__(self, seperator=":", limits=time_limits, default=[d.tm_hour, d.tm_min, d.tm_sec])
 def removeNetworkStart():
 if os.path.exists("/usr/bin/ntpdate-sync"):
  os.system("rm -rf /usr/bin/ntpdate-sync && rm -rf /etc/network/if-up.d/ntpdate-sync")

Comments