Esempio n. 1
0
    def __init__(self):
        """类初始化工作"""
        cf = Configure()
        dict = cf.read_config('strategy.conf', 'mail', 'mail')

        self.server = "smtp.mailgun.org"  # 设置服务器
        self.user = "******"  # 用户名
        self.passwd = "823264073"  # 口令
        self.mail = eval(dict)  # 告警用户等级字典
Esempio n. 2
0
def main():
    arg = sys.argv[1]
    when = sys.argv[2]

    browser = _findBrowser()

    if arg == 'test':
        desktop_path = os.path.expanduser('~')+'\Desktop\\'
        config_file = desktop_path + 'test.yml'
    elif arg == 'run':
        config_file = 'config.yml'

    if when == 'hourly':
         time_to_tweet = HOUR
    elif when == 'now':
        time_to_tweet = MINUTE

    with open(config_file, 'r') as ymlfile:
        cfg = yaml.safe_load(ymlfile)

    while True:
        try:
            now = time.time()
            round(now)

            #forces tweet to initiate on the hour
            while now % time_to_tweet > EPSILON:
                print('Waiting to tweet.')
                now = time.time()
                round(now)
                time.sleep(MINUTE / 2)

            # creates a pricebot for each configuration setting
            for bot in cfg:
                config = Configure(cfg, str(bot))
                pricebot = Pricebot(config)

                total_coins =  config.getAllCoins()
                for coin in total_coins:
                    print(coin)
                    pricebot.plotTweet(coin)

                pricebot.updateTweet()

        except Exception as err:
            print(err)
        finally:
            time.sleep( time_to_tweet / 2 )
            #clears chrome window to avoid openning too many tabs and crashing system
            if browser == 'chrome.exe':
                Popen(['taskkill ', '/F',  '/IM', browser], shell=False)
            elif browser == 'chromium-browser':
                os.system('killall ' + browser)
            else:
                print('Cannot find browser to kill.')
                print(browser)
 def get_user_config(self):
     logger.debug('*** Running get_user_config ***')
     try:
         filename = INPY_APP_PATH + 'cfg/' + self.app_name + '/' + self.app_name + '.cfg'
         if os.path.exists(filename) is False:
             filename = INPY_APP_PATH + self.app_name + '/config.yaml'
         self.configure = Configure()
         logger.debug("filename: %s" % filename)
         self.configure.pars_yaml(filename)
     except Exception as e:
         logger.error('get App config error %s' % (e.__str__()))
         self.get_user_config()
         time.sleep(5)
Esempio n. 4
0
    def get_list():
        if Facilities.list == None:
            Facilities.list = list(conf.get('facilities').keys())
            Facilities.list.sort()
            Facilities.list.insert(0,'None')

        return Facilities.list
Esempio n. 5
0
 def __init__(self):
     """类初始化"""
     cf = Configure()
     self.cpu_percent = float(cf.read_config('strategy.conf', 'cpu', 'usage'))
     self.svmem_precent = float(cf.read_config('strategy.conf', 'svmem', 'usage'))
     self.swap_precent = float(cf.read_config('strategy.conf', 'swap', 'usage'))
     self.diskio_precent = float(cf.read_config('strategy.conf', 'diskio', 'usage'))
     self.diskusage_precent = float(cf.read_config('strategy.conf', 'diskusage', 'usage'))
     self.netio_precent = float(cf.read_config('strategy.conf', 'netio', 'usage'))
     self.user = tuple(eval(cf.read_config('strategy.conf', 'user', 'user')))
     self.port = tuple(eval(cf.read_config('strategy.conf', 'port', 'port')))
Esempio n. 6
0
 def __init__(self):
     """类初始化"""
     cf = Configure()
     self.host = cf.read_config('server.conf', 'mysql', 'host')
     self.port = int(cf.read_config('server.conf', 'mysql', 'port'))
     self.db = cf.read_config('server.conf', 'mysql', 'database')
     self.user = cf.read_config('server.conf', 'mysql', 'user')
     self.passwd = cf.read_config('server.conf', 'mysql', 'passwd')
Esempio n. 7
0
    def get_list():
        if Materials.list == None:
            mls = conf.get('facilities').values()
            result = []
            for ml in mls:
                result.extend(ml)

            Materials.list = list(set(result))
            Materials.list.sort()
            
            Materials.list.insert(0,'none')
        return Materials.list
Esempio n. 8
0
 def __init__(self):
     """类初始化"""
     cf = Configure()
     self.host = cf.read_config('server.conf', 'mysql', 'host')
     self.port = int(cf.read_config('server.conf', 'mysql', 'port'))
     self.db = cf.read_config('server.conf', 'mysql', 'database')
     self.user = cf.read_config('server.conf', 'mysql', 'user')
     self.passwd = cf.read_config('server.conf', 'mysql', 'passwd')
Esempio n. 9
0
 def __init__(self, thread_id, name):
     """一些类初始化工作"""
     threading.Thread.__init__(self)
     threading.threadID = thread_id
     threading.name = name
     # 读取配置文件
     cf = Configure()
     self.host = cf.read_config('server.conf', 'server', 'host')
     self.port = int(cf.read_config('server.conf', 'server', 'port'))
     self.max_line = int(cf.read_config('server.conf', 'server', 'max_line'))
     self.buf_size = int(cf.read_config('server.conf', 'buffer', 'size'))
     # 保存历史警告数据
     self.old_alarm_dict = {}
     self.init_alarm = {
         'cpu': 0,
         'svmem': 0,
         'sswap': 0,
         'disk_io': 0,
         'disk_usage': 0,
         'net_avrg': 0,
         'user': 0,
         'port': 0,
     }
Esempio n. 10
0
    def get_map():

        if  Facilities.map is None:
            map = np.zeros((len(Facilities.get_list()) , len(mt.get_list())))

            for f_name , m_names in conf.get('facilities').items():
                f_id = Facilities.get_id(f_name)
                for m_name in m_names:
                    m_id = mt.get_id(m_name)

                    map[f_id][m_id] = 1

            Facilities.map = map
        return Facilities.map
Esempio n. 11
0
    def __init__(self):
        super(VideoItem, self).__init__()
        self.setMinimumSize(500, 300)
        self.push_button = QPushButton('')
        self.push_button.setFixedSize(40, 40)
        self.configure = Configure()

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.push_button)
        main_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(main_layout)

        self.push_button.clicked.connect(self.configure.show)

        self.setStyleSheet('background-color: gray')

        self.timer_camera = QTimer(self)
        self.cap = cv2.VideoCapture('./test/test.3gp')
        self.timer_camera.timeout.connect(self.show_pic)
        self.timer_camera.start(10)
Esempio n. 12
0
 def __init__(self, thread_id, name):
     """一些类初始化工作"""
     threading.Thread.__init__(self)
     threading.threadID = thread_id
     threading.name = name
     # 读取配置文件
     cf = Configure()
     self.host = cf.read_config('server.conf', 'server', 'host')
     self.port = int(cf.read_config('server.conf', 'server', 'port'))
     self.max_line = int(cf.read_config('server.conf', 'server',
                                        'max_line'))
     self.buf_size = int(cf.read_config('server.conf', 'buffer', 'size'))
     # 保存历史警告数据
     self.old_alarm_dict = {}
     self.init_alarm = {
         'cpu': 0,
         'svmem': 0,
         'sswap': 0,
         'disk_io': 0,
         'disk_usage': 0,
         'net_avrg': 0,
         'user': 0,
         'port': 0,
     }
Esempio n. 13
0
 def get_conf():
     if(Field.conf is None):
         Field.conf = conf.get('fields')
     return Field.conf
Esempio n. 14
0
from Configure import Configure


def if_exists(idstr):
    try:
        elem = browser.find_element_by_class_name(idstr)
        elem = elem.find_element_by_class_name('username')
        elem.click()
        flag = 1
    except Exception as e:
        flag = -1
    return flag


try:
    c = Configure()
    chk = c.check()
    if chk == -1:
        chk = c.create()
        if chk == 1:
            print(
                'Please logout from all of your account while configuring...')
            time.sleep(3)
            c.configure()
    fp = open(r'config.dat', 'r')
    [username, password] = fp.readline().split(',')
    browser = webdriver.Edge()
    browser.get(r'yahoo.co.in')
    time.sleep(2)
    elem = browser.find_element_by_id('uh-mail-link')
    elem.click()
class App(AppTemplate):
    logger.debug('*** Running App ***')

    def __init__(self, vendor_name, app_name):
        AppTemplate.__init__(self, vendor_name, app_name)
        self.app_name = app_name
        self.configure = None

        self.dev_mgmt = None
        self.topic = ""

        # Initialize variables
        # Event data
        self.evt_data_tb = None
        # Real-time data
        self.var_data_tb = None
        # historical data
        self.his_data_tb = None
        # Event history upload data
        self.evt_his_upload_data_tb = None
        # The debug is enabled by default and is enabled at debug level for the initial phase
        self.logger = logger
        self.logger._logger.setLevel(logging.DEBUG)
        # Configuration upload
        self.config_timer = libevent.Timer(self.base,
                                           self._config_timer_handler,
                                           userdata=None)

    def _init_conf(self):
        logger.debug('*** Running _init_config_ ***')
        self.get_user_config()
        logger.debug('user_conf=%s' % self.user_conf)
        self.running_conf = self.configure.config
        logger.load_config(self.running_conf)
        if self.running_conf.has_option('REMOTE', 'host'):
            self.target_host = self.running_conf.get('REMOTE', 'host').strip()
        else:
            self.target_host = '127.0.0.1'
        if self.running_conf.has_option('REMOTE', 'port'):
            self.target_port = self.running_conf.get('REMOTE', 'port')
        else:
            self.target_port = 1883
        if self.running_conf.has_option('REMOTE', 'username'):
            self.target_username = self.running_conf.get('REMOTE',
                                                         'username').strip()
        else:
            self.target_username = None
        if self.running_conf.has_option('REMOTE', 'passwd'):
            self.target_passwd = self.running_conf.get('REMOTE',
                                                       'passwd').strip()
        else:
            self.target_passwd = None
            self.target_passwd = self.target_username
        if self.running_conf.has_option('REMOTE', 'tls'):
            self.target_tls = self.running_conf.get('REMOTE', 'tls').strip()
            if self.running_conf.has_option('REMOTE', 'capath'):
                self.target_capath = self.running_conf.get('REMOTE',
                                                           'capath').strip()
            else:
                self.target_capath = '/var/pycore/lib/python2.7/site-packages/requests/cacert.pem'
        else:
            self.target_tls = None
            self.target_capath = None

        self.topic = self.running_conf.get('REMOTE', 'topic').strip()

        logger.info("Server Details : %s |%s |%s |%s |" %
                    (self.target_host, self.target_port, self.target_username,
                     self.target_passwd))

    def on_log(self, client, userdata, level, buf):
        logger.debug('*** Running on_log ***')
        logger.debug('%s' % buf)

    def _proc_init(self, device):
        logger.debug('*** Running _proc_init ***')
        self._preinit()
        self.configure.devices = {device.id: device}
        self._device_init()
        self._end_init()

    def _norm_init(self):
        logger.debug('*** Running _norm_init ***')
        self._preinit()
        self._device_init()
        self._end_init()

    def _device_init(self):
        logger.debug('*** Running _device_init ***')
        self.dev_mgmt = DevMgmt(self.base, self.configure,
                                self.mq_publish_callback)
        self.dev_mgmt.init_devices()

        for device in self.configure.devices.values():
            group_mgmt = GroupMgmt(self.base, device,
                                   self.dev_mgmt.masters[device.id],
                                   device.groups, self.mq_publish_callback,
                                   self.configure.config.mode,
                                   self.configure.config.cloud)
            # Start data collection task
            for g in group_mgmt.readTimerEvt:
                g.timer.add(1)
            self.dev_mgmt.group_mgmts.append(group_mgmt)

        self.mqclient.add_sub("InMB/variable/set", self.variable_set_sub)

    def _end_init(self):
        logger.debug('*** Running _end_init ***')
        self.mqclient.mqtt_client.on_log = self.on_log
        if not self.zero_service:
            self.mqclient.add_sub(Topics.TOP_SERVICE_STATE_UNICAST_FMT %
                                  self.app_info.app_id,
                                  self._dep_app_handler,
                                  qos=1)
            self.mqclient.add_sub(Topics.TOP_SERVICE_STATE_BROADCAST,
                                  self._dep_app_handler,
                                  qos=1)
        if self.use_bridge:
            self.mqclient.add_sub(Topics.TOP_BRIDGE_STATE, self._bridge_state)
        self.mqclient.connect()
        self.mq_timer.add(1)
        if self.service_keepalive:
            self.ka_timer.add(1)
        self.sig_int.add()
        self.sig_term.add()
        if self.conf_monitor:
            self.sig_hup.add()
        self.sig_usr1.add()

    def create_process(self, device):
        logger.debug('*** Running _create_process ***')
        self.base = libevent.Base()
        self.client_id = str(uuid.uuid4())
        self._init_mqclient()
        self._proc_init(device)
        self.base.dispatch()
        logging.info("Process Exit ...")

    def init(self):
        logger.debug('*** Running init ***')
        self._init_conf()
        self._init_mqclient()
        self._norm_init()
        self.use_bridge = False

    def _preinit(self):
        logger.debug('*** Running _preinit ***')
        pass

    # modbus publish callback
    def mq_publish_callback(self,
                            topic,
                            payload,
                            qos_level=1,
                            check_bridge=True):
        logger.debug('*** Running mq_publish_callback ***')
        if self.bridge_mqtt_is_ready(check_bridge):
            topic = self.topic
            self.mqclient.publish(topic, payload, qos_level)
            return True
        return False

    def variable_set_sub(self, topic, payload):
        logger.debug('*** Running variable_set_sub ***')
        # Write controller task
        try:
            logger.info("write mbvar value %s" % payload)
            message = json.loads(payload)
            self.group_mgmts.writehandle(message)
        except Exception as e:
            logger.error("write data error in GroupExtHandle:%s" % e)

    def _on_pub_topic_ack_handler(self, topic, userdata):
        logger.debug('*** Running _on_pub_topic_ack_handler ***')
        logger.debug('Msg(topic %s, userdata %s)is sent' % (topic, userdata))

    def bridge_mqtt_is_ready(self, check_bridge=True):
        logger.debug('*** Running bridge_mqtt_is_ready ***')
        return self.mqclient.is_ready() and self.bridge_ready(
        ) if check_bridge and self.use_bridge else True

    def _config_timer_handler(self, evt, userdata):
        logger.debug('*** Running _config_timer_handler ***')
        self.upload_config_var()

    # Report the variable dictionary to the platform
    def upload_var_dict(self):
        logger.debug('*** Running upload_var_dict ***')
        topic = 'InMB/controllers_configuration'
        data = self.configure.to_json()
        logger.debug("Send the var dict to the platform: %s" % data)
        self.mqclient.publish(topic, data, 1)

    # Report the variable dictionary to the platform
    def upload_config_var(self):
        logger.debug('*** Running upload_config_var ***')
        if self.bridge_mqtt_is_ready():
            # self.upload_var_dict()
            # Serial network port configuration upload
            self.dev_mgmt.config_timer.add(1)

            # Start statistics task
            # self.config_timer.add(5)
        else:
            logger.error("Upload configuration channel is not available.")
            # self.config_timer.add(5)

    # After reading the configuration, start the modbus read task according to the collection policy group (group).
    def get_user_config(self):
        logger.debug('*** Running get_user_config ***')
        try:
            filename = INPY_APP_PATH + 'cfg/' + self.app_name + '/' + self.app_name + '.cfg'
            if os.path.exists(filename) is False:
                filename = INPY_APP_PATH + self.app_name + '/config.yaml'
            self.configure = Configure()
            logger.debug("filename: %s" % filename)
            self.configure.pars_yaml(filename)
        except Exception as e:
            logger.error('get App config error %s' % (e.__str__()))
            self.get_user_config()
            time.sleep(5)
Esempio n. 16
0
                self.MAC2.delete(0, END)
                self.MAC1.focus_set()
            else:
                self.config.Put('PcbaSN', self.SN.get())
                self.config.Put('CanisterSN', self.SN.get())
                self.config.Put('BmcMAC1', self.MAC1.get())
                self.config.Put('BmcMAC2', self.MAC2.get())
                self.root.destroy()
        else:
            self.MAC2.delete(0, END)

    def FindHostName(self):
        cmdStr = '/bin/hostname'
        findHostName = subprocess.Popen(cmdStr, shell=True, \
                                      stdout=subprocess.PIPE, \
                                      stderr=subprocess.PIPE)
        findHostName.wait()
        hostname = findHostName.communicate()[0].strip()
        self.config.Put('StationName', hostname)
        return hostname


if __name__ == "__main__":
    home_dir = os.environ['FT']
    config = Configure(home_dir + '/SFTConfig.txt')
    ScanBarCode(config)
    print config.Get('CanisterSN')
    #print config.Get('PcbaSN')
    #print config.Get('BmcMAC1')
    #print config.Get('BmcMAC2')
Esempio n. 17
0
            os.system(moveFAIL1)
            #print moveFAIL2
            #os.system(moveFAIL2)

    def DoPowerOFF(self):
        InvokeYesNoButton("Click YES to start shutting down SATI")
        try:
            open("REPLY_NO")
        except IOError:
            self.powerdown.TurnOff()
        else:
            pass

if __name__ == '__main__':
    home_dir = os.environ['FT']
    config = Configure()
    #to read the station config file
    stationcfg = Configure()
    stationcfg.Load(home_dir + '/TestConfig/station.cfg')
    #GetBarcode(config).Start()
    #FFGetUnitInfo(config, eventManager, log, comm)
    #FFGetUnitInfo(config,None,None,None).Start()
    #print "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    #print config.Get("CanisterPN")
    #print "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    if sys.argv[1] == "SKU_Auto":
        sku_name = config.Get("CanisterPN") + ".sku"
    else:
        sku_name = sys.argv[1]

    config.Load(home_dir + '/TestConfig/' + sku_name)
Esempio n. 18
0
class ZenPack(object):

    def __init__(self,
                 id,
                 author=defaults.author,
                 version=defaults.version,
                 license=License(defaults.license),
                 install_requires=None,
                 compat_zenoss_vers=">=4.2",
                 prev_zenpack_name="",
                 zProperties=None,
                 deviceClasses=None,
                 relationships=None,
                 opts=Opts(),
                 ):

        self.id = id
        self.opts = opts
        self.destdir = DirLayout(self, opts.prefix)
        self.namespace = id
        self.deviceClasses = {}
        self.components = {}
        self.relationships = {}
        self.componentJSs = {}
        self.zproperties = {}
        self.author = author
        self.version = version
        self.license = license

        self.prepname = prepId(id).replace('.', '_')
        if install_requires:
            if isinstance(install_requires, basestring):
                self.install_requires = [install_requires]
            else:
                self.install_requires = list(install_requires)
        else:
            self.install_requires = []
        self.compat_zenoss_vers = compat_zenoss_vers
        self.prev_zenpack_name = prev_zenpack_name

        packages = []
        parts = self.id.split('.')
        for i in range(len(parts)):
            packages.append('.'.join(parts[:i+1]))
        self.packages = packages
        self.namespace_packages = packages[:-1]

        self.configure_zcml = Configure(self)
        self.utils = UtilsTemplate(self)
        self.setup = Setup(self)
        self.rootinit = RootInit(self)
        self.zenpackUI = ZenPackUI(self)

        if zProperties:
            for zp in zProperties:
                self.addZProperty(**zp)

        if deviceClasses:
            for dc in deviceClasses:
                self.addDeviceClass(**dc)

        if relationships:
            for rel in relationships:
                self.addRelation(**rel)

    @memoize
    def addDeviceClass(self, *args, **kwargs):
        dc = DeviceClass(self, *args, **kwargs)
        return dc

    @memoize
    def addComponentType(self, *args, **kwargs):
        c = Component(self, *args, **kwargs)
        return c

    def addRelation(self, *args, **kwargs):
        r = Relationship(self, *args, **kwargs)
        return r

    def addZProperty(self, name, type='string', default='', Category=None):
        if type == 'string':
            if not default.startswith('\''):
                default = '\'' + default
                if len(default) == 1:
                    default = default + '\''
            if not default.endswith('\''):
                default = default + '\''

        self.zproperties[name] = (name, default, type, Category)

    def registerComponent(self, component):
        self.components[component.id] = component

    def registerRelationship(self, relationship):
        self.relationships[relationship.id] = relationship

    def registerDeviceClass(self, deviceClass):
        self.deviceClasses[deviceClass.id] = deviceClass
        #Add the ComponentJS pieces when we are at it.
        cjs = ComponentJS(deviceClass)
        self.componentJSs[cjs.name] = cjs

    def __repr__(self):
        return "%s \n\tAUTHOR: %s\n\tVERSION: %s\n\tLICENSE: %s" \
               % (self.id, self.author, self.version, self.license)

    def updateGitTemplates(self): # pragma: no cover
        # Create the git repo
        repo = Repo.init(self.destdir .path)
        try:
            repo.commit()
        except:
            repo.index.commit('Initial Commit from zpg')

        #Update the repo
        repo.index.add([self.destdir .path+'/Templates'])

        if repo.is_dirty():
            repo.index.commit('zpg: Committed Template changes')

    def write(self):
        # Write the destination folders
        self.destdir.write()

        # Write the base setup.py
        self.setup.write()

        # Write configure.zcml
        self.configure_zcml.write()

        # Create the components
        for component in self.components.values():
            component.write()

        for cjs in self.componentJSs.values():
            cjs.write()

        self.zenpackUI.write()

        #Create the root level __init__.py file
        self.rootinit.write()

        # Create a utils file.
        self.utils.write()

        self.updateGitTemplates()
Esempio n. 19
0
    def __init__(self,
                 id,
                 author=defaults.author,
                 version=defaults.version,
                 license=License(defaults.license),
                 install_requires=None,
                 compat_zenoss_vers=">=4.2",
                 prev_zenpack_name="",
                 zProperties=None,
                 deviceClasses=None,
                 relationships=None,
                 opts=Opts(),
                 ):

        self.id = id
        self.opts = opts
        self.destdir = DirLayout(self, opts.prefix)
        self.namespace = id
        self.deviceClasses = {}
        self.components = {}
        self.relationships = {}
        self.componentJSs = {}
        self.zproperties = {}
        self.author = author
        self.version = version
        self.license = license

        self.prepname = prepId(id).replace('.', '_')
        if install_requires:
            if isinstance(install_requires, basestring):
                self.install_requires = [install_requires]
            else:
                self.install_requires = list(install_requires)
        else:
            self.install_requires = []
        self.compat_zenoss_vers = compat_zenoss_vers
        self.prev_zenpack_name = prev_zenpack_name

        packages = []
        parts = self.id.split('.')
        for i in range(len(parts)):
            packages.append('.'.join(parts[:i+1]))
        self.packages = packages
        self.namespace_packages = packages[:-1]

        self.configure_zcml = Configure(self)
        self.utils = UtilsTemplate(self)
        self.setup = Setup(self)
        self.rootinit = RootInit(self)
        self.zenpackUI = ZenPackUI(self)

        if zProperties:
            for zp in zProperties:
                self.addZProperty(**zp)

        if deviceClasses:
            for dc in deviceClasses:
                self.addDeviceClass(**dc)

        if relationships:
            for rel in relationships:
                self.addRelation(**rel)