def __init__(self, parent): wx.Dialog.__init__(self, parent) conf = Config() boxSizer = wx.BoxSizer(wx.HORIZONTAL) b = BucketConfigPanel(self, conf.getBuckets().keys(), self.onOkBtn) boxSizer.Add(b, 1, wx.EXPAND) self.Layout() self.Center()
def __init__(self, args): if not os.path.exists(args.path): print('The specified path does not exist.') exit(1) if not os.path.isdir(args.path): print('The specified path is not a directory.') exit(1) print('Creating .s4 directory') configdirpath = os.path.join(args.path, '.s4') os.mkdir(configdirpath, mode=0o700) print('Creating .s4/config.toml') configfilepath = os.path.join(configdirpath, 'config.toml') config = Config() config.save(configfilepath) print('Collecting user details') response = input('What is your "AWS Access Key ID": ') config.config['aws']['credentials']['aws_access_key_id'] = response response = input('What is your "AWS Access Key Secret": ') config.config['aws']['credentials']['aws_secret_access_key'] = response response = input('Name of the sync destination S3 bucket: ') config.config['aws']['bucket']['name'] = response # TODO: perform validation on the relative path response = input('Relative path inside the bucket to sync to: ') config.config['aws']['bucket']['path'] = response print('Saving .s4/config.toml') config.save(configfilepath)
def __init__(self): __config = Config() self.__host = __config.get('MySQL','Host') self.__user = __config.get('MySQL','User') self.__password = __config.get('MySQL','Pass') self.__database = __config.get('MySQL','Base') try: self.__conn = MySQLdb.connect(self.__host, self.__user, self.__password, self.__database) except MySQLdb.Error as e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1)
class Main(): def __init__(self, args): self.args = args self.config = Config() self.config.load('s4config.toml') session = boto3.session.Session(**self.config['aws']['credentials']) self.s3 = session.resource('s3') # Check if bucket exists check = self.check_bucket_access(self.config['aws']['bucket']['name']) if check == BucketAccess.NotFound: print('Configured bucket does not exist.') exit(1) elif check == BucketAccess.Forbidden: print('Error: do not have permission to access configured bucket') print('The following are some known causes of this error:') print(' - User does not have access to S3') print(' - The bucket is owned by another account') exit(1) # Sync files self.sync() def sync(self): for root, dirs, files in os.walk(self.config['sync']['root']['path']): # TODO: add code to ignore any s4 configuration files print('%s:' % root) for dire in dirs: print(' d %s' % dire) for file in files: print(' f %s' % file) def check_bucket_access(self, bucketname): ''' Check if a bucket with the specified name exists. :param str bucketname: the name of the bucket to check. :returns bool: true - if the bucket exists, false otherwise. ''' try: self.s3.meta.client.head_bucket(Bucket=bucketname) return BucketAccess.Accessible except botocore.exceptions.ClientError as err: error_code = int(err.response['Error']['Code']) if error_code in BucketAccess: return error_code else: raise err
def __init__(self): """__init__ """ sqbrowser_xrc.xrcfrmMain.__init__(self, None) self.SetSize((650, 500)) # setup the control events self.btOpenSqlFile.Bind(wx.EVT_BUTTON, self.btOpenSqlFile_Click) self.btOpenSqlDb.Bind(wx.EVT_BUTTON, self.btOpenSqlDb_Click) self.btExecuteFile.Bind(wx.EVT_BUTTON, self.btExecuteFile_Click) self.btCommit.Bind(wx.EVT_BUTTON, self.btCommit_Click) # setup timers self._interval = 2 # seconds self.tmrCheckFile = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.tmrCheckFile_Tick, self.tmrCheckFile) # file operation vars self.file = None self._lastCheckTime = None # status bar self.CreateStatusBar() self.SetStatusText("SQBrowser") # setup sqlengine self._sqlEngine = None # misc setup self.config = Config(self.configPath) self.config.load() self.StartTimer() if self.config.db_path: self.txtSqlDb.SetValue(self.config.db_path) if self.config.src_path: self.txtSqlFile.SetValue(self.config.src_path)
def __init__(self, parent, auth): wx.Panel.__init__(self, parent) self.__frame = self.GetParent().GetParent() self.__auth = auth self.__bucketManger = qiniu.BucketManager(self.__auth) self.__conf = Config() self.__bucketName = "" self.__download_url = None self.__prefix = "" self.__marker = None self.__limit = LIMIT self.__initImages() self.__boxSizer = wx.BoxSizer() self.__dataList = self.__initList() self.__boxSizer.Add(self.__dataList, 1, wx.EXPAND) self.__initPopMenu() self.SetSizer(self.__boxSizer) # init column sorter wx.lib.mixins.listctrl.ColumnSorterMixin.__init__(self, LIMIT)
def __init__(self, parent, buckets, onConfigSuccess): wx.Panel.__init__(self, parent, style=wx.BORDER_SIMPLE) self.frame = parent self.onConfigSuccess = onConfigSuccess self.buckets = buckets self.conf = Config() self.startConfigBucket()
def __init__(self, parent, onLoginSuccess): wx.Panel.__init__(self, parent, style=wx.BORDER_SIMPLE) self.frame = parent self.onLoginSuccess = onLoginSuccess self.conf = Config() accessKey, secretKey = self.conf.getKeys() loginTitle = wx.StaticText(self, -1, u" 登 陆 ") loginTitle.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) accessKeyLabel = wx.StaticText(self, -1, "AccessKey:") self.accessKey = wx.TextCtrl(self, -1, accessKey) secretKeyLabel = wx.StaticText(self, -1, "SecretKey:") self.secretKey = wx.TextCtrl(self, -1, secretKey, style=wx.PASSWORD) self.rememberMe = wx.CheckBox(self, -1, u"记住账号") if accessKey != "" and secretKey != "": self.rememberMe.SetValue(True) self.loginBtn = wx.Button(self, -1, u"登陆") self.loginBtn.Bind(wx.EVT_BUTTON, self.OnLogin) self.exitBtn = wx.Button(self, -1, u"退出") self.exitBtn.Bind(wx.EVT_BUTTON, self.OnExit) # title mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add((0, 10)) mainSizer.Add(loginTitle, 0, wx.CENTER | wx.TOP | wx.BOTTOM, 5) mainSizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 5) # ak and sk keySizer = wx.FlexGridSizer(cols=2, hgap=7, vgap=7) keySizer.AddGrowableCol(1) keySizer.Add(accessKeyLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL) keySizer.Add(self.accessKey, 0, wx.EXPAND) keySizer.Add(secretKeyLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL) keySizer.Add(self.secretKey, 0, wx.EXPAND) mainSizer.Add(keySizer, 0, wx.EXPAND | wx.ALL, 5) mainSizer.Add(self.rememberMe, 0, wx.ALL | wx.ALIGN_RIGHT, 5) mainSizer.Add((10, 10)) # some empty space btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add((30, 20)) btnSizer.Add(self.loginBtn,1) btnSizer.Add((30, 20)) btnSizer.Add(self.exitBtn,1) btnSizer.Add((30, 20)) mainSizer.Add(btnSizer, 0, wx.EXPAND | wx.BOTTOM, 10) self.SetSizer(mainSizer)
def __init__(self): wx.Frame.__init__(self, None, -1, u'七牛文件管理('+VERSION+')', size=(800, 640)) self.conf = Config() ak, sk = self.conf.getKeys() self.__auth = qiniu.Auth(ak, sk) self.SetIcon(libs.icons.desktop().GetIcon()) #self.SetWindowStyle((self.GetWindowStyle() | wx.STAY_ON_TOP)) self.createSplitter() self.createMenuBar(self.menuData()) self.createToolBar(self.toolbarData()) self.createStatusBar([-1, 100, 140, 70]) self.createTaskBarIcon(self.taskMenuData()) self.Bind(wx.EVT_CLOSE, self.onHideEvent) self.Center() for bucket in self.conf.getBuckets(): self._bucketPanel.setBucketName(bucket) return
def __init__(self, args): self.args = args self.config = Config() self.config.load('s4config.toml') session = boto3.session.Session(**self.config['aws']['credentials']) self.s3 = session.resource('s3') # Check if bucket exists check = self.check_bucket_access(self.config['aws']['bucket']['name']) if check == BucketAccess.NotFound: print('Configured bucket does not exist.') exit(1) elif check == BucketAccess.Forbidden: print('Error: do not have permission to access configured bucket') print('The following are some known causes of this error:') print(' - User does not have access to S3') print(' - The bucket is owned by another account') exit(1) # Sync files self.sync()
if not self.xbee.connect(): self.stop() while True: try: self.mqtt.loop() except Exception as e: self.log(logging.ERROR, "Error while looping MQTT (%s)" % e) if __name__ == "__main__": def resolve_path(path): return path if path[0] == '/' else os.path.join(os.path.dirname(os.path.realpath(__file__)), path) config_file = resolve_path('config/xbee2mqtt.yaml'); config = Config(config_file) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(config.get('general', 'logging_level', logging.DEBUG)) logger.addHandler(handler) mqtt = MosquittoWrapper(config.get('mqtt', 'client_id', None)) mqtt.host = config.get('mqtt', 'host', 'localhost') mqtt.port = config.get('mqtt', 'port', 1883) mqtt.username = config.get('mqtt', 'username', None) mqtt.password = config.get('mqtt', 'password', None) mqtt.keepalive = config.get('mqtt', 'keepalive', 60)
self.stop() while True: try: self.mqtt.loop() time.sleep(0.5) except Exception as e: self.log(logging.ERROR, "Error while looping MQTT (%s)" % e) if __name__ == "__main__": def resolve_path(path): return path if path[0] == '/' else os.path.join(os.path.dirname(os.path.realpath(__file__)), path) config_file = resolve_path('config/GPIO2MQTT.yaml'); config = Config(config_file) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(config.get('general', 'logging_level', logging.INFO)) logger.addHandler(handler) mqtt = MosquittoWrapper.ConfigureNewWrapper(config) gpio = GPIOWrapper.ConfigureNewWrapper(config) processor = Processor(config.get('processor', 'filters', [])) GPIO2MQTT = GPIO2MQTT(resolve_path(config.get('general', 'pidfile', '/tmp/GPIO2MQTT.pid'))) GPIO2MQTT.stdout = GPIO2MQTT.stderr = resolve_path(config.get('general', 'stdout', '/dev/null'))
"certfile": self.ssl_certificate_file, "keyfile": self.ssl_privatekey_file, } http_server = HTTPServer(WSGIContainer(app), ssl_options = ssl_options) http_server.listen(self.port) IOLoop.instance().start() if __name__ == "__main__": def resolve_path(path): return path if path[0] == '/' else os.path.join(os.path.dirname(os.path.realpath(__file__)), path) config_file = resolve_path('config/Ripcord.yaml'); config = Config(config_file) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(config.get('general', 'logging_level', logging.INFO)) logger.addHandler(handler) BottledTornado = BottledTornado(resolve_path(config.get('general', 'pidfile', '/tmp/BottledTornado.pid'))) BottledTornado.stdout = BottledTornado.stderr = resolve_path(config.get('general', 'stdout', '/dev/null')) BottledTornado.logger = logger BottledTornado.config_file = config_file BottledTornado.ssl_privatekey_file = resolve_path(config.get('app', 'ssl_privatekey_file', '')) BottledTornado.ssl_certificate_file = resolve_path(config.get('app', 'ssl_certificate_file', ''))
def on_message(client, userdata, msg): """ Message received from a subscribed topic """ print "Message received" print("%s %s %s" % (time.asctime(), msg.topic, msg.payload)) if __name__ == "__main__": def resolve_path(path): return path if path[0] == '/' else os.path.join(os.path.dirname(os.path.realpath(__file__)), path) config_file = resolve_path('config/xbee2mqtt.yaml'); config = Config(config_file) host = config.get('mqtt', 'host', 'localhost') port = config.get('mqtt', 'port', 1883) username = config.get('mqtt', 'username', None) password = config.get('mqtt', 'password', None) client = mqtt.Client() client.on_message = on_message if username: client.username_pw_set(username, password) client.connect(host, port, 60) client.subscribe('#', qos=0) while True:
def config(self): if self._config is None: self._config = Config(getcwd() + '/tasks/app.config') return self._config
class BucketConfigPanel(wx.Panel): def __init__(self, parent, buckets, onConfigSuccess): wx.Panel.__init__(self, parent, style=wx.BORDER_SIMPLE) self.frame = parent self.onConfigSuccess = onConfigSuccess self.buckets = buckets self.conf = Config() self.startConfigBucket() def startConfigBucket(self): mainSizer = wx.BoxSizer(wx.VERTICAL) title = wx.StaticText(self, -1, u"配置空间下载域名") title.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD)) mainSizer.Add((0, 10)) mainSizer.Add(title, 0, wx.CENTER | wx.TOP | wx.BOTTOM, 10) mainSizer.Add((0, 10)) mainSizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 5) configBuckets = self.conf.getBuckets() self.bucketsSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=3) for idx, bucket in enumerate(self.buckets): domain = configBuckets.get(bucket) or "" bucketName = wx.StaticText(self, -1, bucket) self.bucketsSizer.Add(bucketName, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL) bucketDomain = wx.TextCtrl(self, -1, domain, size=(160,25)) bucketDomain.SetHint(u"未配置部分功能不可使用") self.bucketsSizer.Add(bucketDomain, 2, wx.EXPAND) bmp = libs.icons.get("/status/question.png").GetBitmap() button = wx.BitmapButton(self, -1, bmp) self.bucketsSizer.Add(button, 0, wx.EXPAND) self.bucketsSizer.AddGrowableCol(1) mainSizer.Add(self.bucketsSizer, 0, wx.EXPAND | wx.ALL, 5) okBtn = wx.Button(self, -1, u"确定") okBtn.Bind(wx.EVT_BUTTON, self.endConfigBucket) exitBtn = wx.Button(self, -1, u"退出") exitBtn.Bind(wx.EVT_BUTTON, self.OnExit) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add((50, 20)) btnSizer.Add(okBtn,1) btnSizer.Add((50, 20)) btnSizer.Add(exitBtn,1) btnSizer.Add((50, 20)) mainSizer.Add(btnSizer, 0, wx.EXPAND | wx.ALL, 10) self.SetSizer(mainSizer) def endConfigBucket(self, event): items = self.bucketsSizer.GetChildren() buffers = {} for idx in range(0, len(items) / 3): if idx * 3 + 1 < len(items): input = items[idx * 3 + 1] bucketName = items[idx*3].GetWindow().GetLabelText() oldDomain = input.GetWindow().GetLabelText() domain = input.GetWindow().GetValue() if oldDomain != domain: print(u"检查【%s】下载地址: http://%s"%(bucketName,domain)) buffers[bucketName] = domain self.conf.setBuckets(buffers) self.onConfigSuccess() def OnExit(self, evt): self.frame.Hide() self.frame.Destroy()
def __init__(self): # Configure logger logFormatter = logging.Formatter(fmt="[%(asctime)-15s][%(levelname)s] %(message)s", datefmt='%d.%m.%Y %H:%M:%S') log = logging.getLogger() log.setLevel(logging.DEBUG) fileName = "logs/"+"sensorshub_{}_".format(datetime.datetime.now().strftime("%d-%m-%Y"))+"{}.log" fileNum = 0 if not os.path.isdir("logs"): os.mkdir("logs") while os.path.isfile(fileName.format(fileNum)): fileNum += 1 fileHandler = logging.FileHandler(fileName.format(fileNum)) fileHandler.setFormatter(logFormatter) log.addHandler(fileHandler) consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setFormatter(logFormatter) log.addHandler(consoleHandler) logging.info("Starting SensorsHub version {}".format(self.VERSION)) # Create databse and tables with sqlite3.connect("db.sqlite") as conn: # # SENSORS # Table for sensors, each sensor has one row. conn.execute( "CREATE TABLE IF NOT EXISTS sensors(" "sid INTEGER PRIMARY KEY AUTOINCREMENT, " # Sensor ID, must be unique "token TEXT, " # Generated string for authentication "title TEXT, " # Title of the sensor, f.eg. Outside "description TEXT, " # Description of the sensor, f.eg. ESP8266 temperature sensor "updated INTEGER, " # Timestamp updated when new reading is received "status INTEGER DEFAULT 0" # Current status (enabled, disabled) ")") # FIELDS conn.execute( "CREATE TABLE IF NOT EXISTS fields(" "fid INTEGER PRIMARY KEY AUTOINCREMENT, " # Field ID, must be unique "sid INTEGER, " # Sensor ID to which this field belong "parent INTEGER" # Parent fid, default None "type INTEGER" # Field type "updated INTEGER, " # Updated time in timestamp format "value FLOAT, " # Current field value "name TEXT, " # Name of the field, f.eg. temperature "display_name TEXT, " # Human friendly name of the field, f.eg. Temperature "color TEXT, " # Color (HEX) of the field without hashtag, f.eg. FF00AA "icon TEXT" # Font awesome icon f.eg. fa-sun-o "unit TEXT)") # Unit of the field, f.eg. °C # # READINGS # Table for readings, each reding must specify field and sensor # # sid - Sensor ID to which this reading belong # fid - Field ID to which this reading belong # updated - When reading has been created in timestamp format # value - New value of the field conn.execute( """CREATE TABLE IF NOT EXISTS readings(sid INTEGER, fid INTEGER, updated INT, value FLOAT)""") # # ACCOUNTS # Table for accounts # # uid - User ID, must be unique # session - Generated string for sessions # user - Unique user login # password - Hashed password using hashlib # lastlogin - Timestamp updated when user logged in # email - User email conn.execute( """CREATE TABLE IF NOT EXISTS accounts(uid INTEGER PRIMARY KEY, session TEXT, user TEXT UNIQUE , password TEXT, lastlogin INTEGER, email TEXT)""") # Load config self.config = Config() self.config.load() # Load lang self.lang = Lang(self) self.lang.load() # Load updater self.updater = Updater(self) if self.updater.check_updates(): if "update" in self.config.args: logging.info("Starting auto update") self.updater.update() else: logging.info("No updates available") # Create and read sensors from database self.sensors = Sensors() self.sensors.load() # Create and load accounts self.accounts = Accounts(self) # Load statistics self.statistics = Statistics(self) # Configure web template engine env = Environment(loader=FileSystemLoader('templates')) env.filters["to_json"] = lambda value: json.dumps(value) def format_datetime(value, format="%d.%m.%Y %H:%M"): if value == None: return "Never" else: try: return datetime.datetime.fromtimestamp(value).strftime(format) except TypeError: return value.strftime(format) env.filters["strftime"] = format_datetime # Configure web server cherrypy_config = { "server.socket_port": self.config.get("port"), "server.socket_host": self.config.get("host"), "checker.check_skipped_app_config": False, "log.screen": False, "log.access_file": '', "log.error_file": '' } cherrypy.config.update(cherrypy_config) cherrypy.tree.mount(WebRoot(self,env),"/", { "/static": { "tools.staticdir.root": os.getcwd(), "tools.staticdir.on": True, "tools.staticdir.dir": "static" } }) cherrypy.tree.mount(WebSettings(self, env), "/settings", { }) # Disable cherrypy loggers logging.info("Starting up web server at {}:{}".format(cherrypy_config["server.socket_host"], cherrypy_config["server.socket_port"])) logging.getLogger("cherrypy").propagate = False #logging.getLogger("cherrypy.error").propagate = False logging.getLogger("cherrypy.access").propagate = False cherrypy.engine.signals.subscribe() cherrypy.engine.start() logging.info("Done loading") Statistics.snooper(1) cherrypy.engine.block()
self.xbee.on_message = self.xbee_on_message self.xbee.log = self.log self.xbee.connect() try: while True: time.sleep(.1) except KeyboardInterrupt: pass self.xbee.disconnect() self.log(logging.INFO, "Exiting") if __name__ == "__main__": config = Config('config/xbee2mqtt.yaml') handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.addHandler(handler) serial = Serial( config.get('radio', 'port', '/dev/ttyUSB0'), config.get('radio', 'baudrate', 9600) ) # Sample data when using SerialMock
server.start() while True: try: time.sleep(1) except Exception as e: self.log(logging.ERROR, "Error while looping") if __name__ == "__main__": def resolve_path(path): return path if path[0] == '/' else os.path.join(os.path.dirname(os.path.realpath(__file__)), path) config_file = resolve_path('config/smsnode2mqtt.yaml'); config = Config(config_file) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(config.get('general', 'logging_level', logging.INFO)) logger.addHandler(handler) mqtt = MosquittoWrapper(config.get('mqtt', 'client_id', None)) mqtt.host = config.get('mqtt', 'host', 'localhost') mqtt.port = config.get('mqtt', 'port', 1883) mqtt.keepalive = config.get('mqtt', 'keepalive', 60) mqtt.clean_session = config.get('mqtt', 'clean_session', False) mqtt.qos = config.get('mqtt', 'qos', 0)
class MainFrame(framework.XFrame): def __init__(self): wx.Frame.__init__(self, None, -1, u'七牛文件管理('+VERSION+')', size=(800, 640)) self.conf = Config() ak, sk = self.conf.getKeys() self.__auth = qiniu.Auth(ak, sk) self.SetIcon(libs.icons.desktop().GetIcon()) #self.SetWindowStyle((self.GetWindowStyle() | wx.STAY_ON_TOP)) self.createSplitter() self.createMenuBar(self.menuData()) self.createToolBar(self.toolbarData()) self.createStatusBar([-1, 100, 140, 70]) self.createTaskBarIcon(self.taskMenuData()) self.Bind(wx.EVT_CLOSE, self.onHideEvent) self.Center() for bucket in self.conf.getBuckets(): self._bucketPanel.setBucketName(bucket) return def bucketMenuData(self): bucketsMenu = [] for bucket in self.conf.getBuckets(): bucketsMenu.append((bucket, bucket, self.onBucketChangedEvent, wx.ITEM_RADIO)) bucketsMenu.append("---") bucketsMenu.append((u"新建空间", u"新建空间",self.onCreateBucketEvent)) return (u"空间", bucketsMenu) def menuData(self): return [ (u"文件", [ (u"上传", u"上传文件到当前空间", self.onUploadFileEvent), "---", (u"最小化", u"最小化到系统托盘", self.onHideEvent), (u"退出", u"退出系统", self.onExitEvent) ]), (u"视图", [ (u"查看方式", [ ([u"详细信息", u"列表", u"大图标", u"小图标"], "", self.onViewChangedEvent, wx.ITEM_RADIO) ]), "---", (u"排序方式", [ ([u"名称",u"大小",u"时间"], "", self.onSortChangedEvent, wx.ITEM_RADIO) ]) ,"---" , (u"系统设置", u"系统运行视图参数设置", self.onConfigEvent) ]), self.bucketMenuData(), (u"关于", [ (u"检查更新", u"连接服务器检测是否更新", self.onUploadEvent), (u"关于软件", u"关于软件简介", self.onAboutSoftEvent), (u"关于作者", u"作者简介", self.onAboutUserEvent) ]) ] def toolbarData(self): return [ (u"上传", u"上传文件到当前空间", "upload.png", self.onUploadFileEvent), ((ID.ID_TOOLBAR_DOWNLOAD, u"下载"), u"下载选中文件", ["download.png","download.dis.png"], self.onDownloadFileEvent, False), "---", ((ID.ID_TOOLBAR_TRASH, u"删除"), u"删除选中文件", ["trash.png","trash.dis.png"], self._bucketPanel.onDeleteEvent, False), "---", ((ID.ID_TOOLBAR_PREV_PAGE, U"上一页"), u"加载上一页文件", ["prev.png", "prev.dis.png"], self._bucketPanel.onPrevPageEvent, False), ((ID.ID_TOOLBAR_NEXT_PAGE, U"下一页"), u"加载下一页文件", ["next.png", "next.dis.png"], self._bucketPanel.onNextPageEvent, False), "---", (u"刷新", u"刷新当前页" , "refresh.png",self._bucketPanel.onRefreshEvent), "---", ((ID.ID_TOOLBAR_LIMIT,u"显示个数:"),["10","20","50","100","200","500"],self._bucketPanel.onPageLimitEvent), "---", ((ID.ID_TOOLBAR_SEARCH_TEXT, u"搜索关键字"), (u"", u"文件前缀"), {wx.EVT_KEY_DOWN:self._bucketPanel.onSearchEvent}), (u"搜索", u"在当前空间搜索", "search.png", self._bucketPanel.onSearchEvent), ] def taskMenuData(self): return [ (u"显示", u"", self.onShowEvent), "-", (u"关于软件", u"关于软件简介", self.onAboutSoftEvent), "-", (u"退出", u"", self.onExitEvent) ] def createSplitter(self): self._splitter = wx.SplitterWindow(self) self._items = self.createBucketsPanel(self._splitter) self._uploadify = wx.Panel(self._splitter, style=wx.BORDER_SIMPLE) self._uploadify.SetSizer(wx.BoxSizer(wx.VERTICAL)) self._splitter.Initialize(self._items) return self._splitter def createBucketsPanel(self, parent): self._bucketPanel = BucketPanel(parent, self.__auth) self.SetDropTarget(FileDropUpLoadTarget(self.uploadFile)) return self._bucketPanel def onScheduleFinally(self, panel=None, status=True): """上传动作结束(正确上传,上传错误,。。。)均会调用""" if status and panel: self._uploadify.GetSizer().Hide(panel) self._uploadify.GetSizer().Remove(panel) self._uploadify.RemoveChild(panel) children = len(self._uploadify.GetChildren()) if children == 0 : self.__switchSplitWindow(False) self._uploadify.Layout() def onUploadFileEvent(self, event): wildcard = u"所有文件 (*.*) | *.*" result = dialogs.fileDialog(parent=self._uploadify, title=u'选择文件', filename='', wildcard=wildcard, style=wx.OPEN) if result.accepted: for file_path in result.paths: if os.path.isdir(file_path) : continue self.uploadFile(file_path) event.Skip() def onDownloadFileEvent(self, event): self.__switchSplitWindow(True) folder = "" results = dialogs.dirDialog(self, u"选择下载位置") if results.accepted: folder = results.path files = self._bucketPanel.getSelectedFiles() for file in files : dnPanel = DownloadPanel(folder, file, self.onScheduleFinally, self._uploadify) boxSizer = self._uploadify.GetSizer() boxSizer.Add(dnPanel, flag=wx.EXPAND) self._uploadify.Layout() event.Skip() else: self.onScheduleFinally(None,False) def uploadFile(self,file_path): self.__switchSplitWindow(True) bucketName = self._bucketPanel.getBucketName() up = UploadifyPanel(self.__auth, bucketName, file_path, self.onScheduleFinally, self._uploadify) boxSizer = self._uploadify.GetSizer() boxSizer.Add(up, flag=wx.EXPAND) #self._uploadify.GetSizer().Fit(self._uploadify) #self._uploadify.GetSizer().SetSizeHints(self._uploadify) self._uploadify.Layout() def __switchSplitWindow(self,open=True): """选择上传下载队列窗口状态""" if open: if not self._splitter.IsSplit() : rect = self.GetScreenRect() self._splitter.SplitVertically(self._items, self._uploadify, rect.width - 370) else: if self._splitter.IsSplit(): self._splitter.Unsplit() #self._bucketPanel.setBucketName(self._bucketPanel.getBucketName()) def onBucketChangedEvent(self, event): item = event.EventObject.FindItemById(event.GetId()) bucketName = item.GetText() self._bucketPanel.setBucketName(bucketName) def onViewChangedEvent(self, event): item = event.EventObject.FindItemById(event.GetId()) text = item.GetText() wx.MessageBox(u"首先感谢您的支持!视图查看功能此版本不包含。该项功能正在加紧开发。",u"抱歉") def onSortChangedEvent(self, event): item = event.EventObject.FindItemById(event.GetId()) text = item.GetText() self._bucketPanel.sortBy(text) def onCreateBucketEvent(self, event): wx.MessageBox(VERSION+u"版暂不支持此功能!",u"抱歉") def onConfigEvent(self, event): from libs.login import BucketConfigPanel class ConfigDialog(wx.Dialog): def __init__(self, parent): wx.Dialog.__init__(self, parent) conf = Config() boxSizer = wx.BoxSizer(wx.HORIZONTAL) b = BucketConfigPanel(self, conf.getBuckets().keys(), self.onOkBtn) boxSizer.Add(b, 1, wx.EXPAND) self.Layout() self.Center() def onOkBtn(self): self.Hide() self.Destroy() ConfigDialog(self).ShowModal() def onUploadEvent(self, event): webbrowser.open_new("http://github.com/ihaiker/QiniuAdminGui") def onAboutUserEvent(self, event): self.onUploadEvent(event) def onAboutSoftEvent(self, event): self.onUploadEvent(event)
def init_config(): config = Config(test=True) base_dir = os.path.abspath('%s/../../db' % __file__) copyfile(os.path.join(base_dir, 'case.db'), os.path.join(base_dir, 'test.db'))
from web.view.config_views import log_layout, config_layout from web.utils import diff_dashtable, dash_date_to_datetime # pylint: disable=invalid-name from web.tools.figurefilter import FigureFilter from web.utils import create_card from libs.config import Config from web.view.control import get_control_tabs EMPTY_DIV = "empty-div" CALLBACK_CREATED = False trips: Trips = Trips() chargings: List[dict] min_date = max_date = min_millis = max_millis = step = marks = cached_layout = None CONFIG = Config() def add_header(el): return dbc.Row([ dbc.Col( dcc.Link(html.H1('My car info'), href=dash_app.requests_pathname_external_prefix, style={"text-decoration": "none"})), dbc.Col( dcc.Link(html.Img(src="assets/images/settings.svg", width="30veh"), href=dash_app.requests_pathname_external_prefix + "config", className="float-end")) ]), el
class BucketPanel(wx.Panel, wx.lib.mixins.listctrl.ColumnSorterMixin): def __init__(self, parent, auth): wx.Panel.__init__(self, parent) self.__frame = self.GetParent().GetParent() self.__auth = auth self.__bucketManger = qiniu.BucketManager(self.__auth) self.__conf = Config() self.__bucketName = "" self.__download_url = None self.__prefix = "" self.__marker = None self.__limit = LIMIT self.__initImages() self.__boxSizer = wx.BoxSizer() self.__dataList = self.__initList() self.__boxSizer.Add(self.__dataList, 1, wx.EXPAND) self.__initPopMenu() self.SetSizer(self.__boxSizer) # init column sorter wx.lib.mixins.listctrl.ColumnSorterMixin.__init__(self, LIMIT) def GetListCtrl(self): return self.__dataList def GetSortImages(self): return (self.down, self.up) def OnSortOrderChanged(self): self.__downloadButtonAndDeleteButtonStatus() def setBucketName(self, bucketName): ## 之所以放在这是因为,在初始化此面板的时候还未初始化toolbar self.__toolbar = self.__frame._toolbar self.__bucketName = bucketName # 当前空间名称 self.__download_url = self.__conf.getBuckets()[self.__bucketName] self.__resetStartLoad() def setPrefix(self, prefix): self.__prefix = prefix self.__enableToolbar(ID.ID_TOOLBAR_SEARCH_BTN,False) self.__enableToolbar(ID.ID_TOOLBAR_SEARCH_TEXT,False) self.__resetStartLoad() def setLimit(self, limit): self.__limit = limit self.__enableToolbar(ID.ID_TOOLBAR_LIMIT,False) self.__resetStartLoad() def getBucketName(self): return self.__bucketName def __resetStartLoad(self): """从头开始重新加载""" self.__marker = None # 下一页marker,加载下一页的时候需要 self.__store = Store() # 保存数据 self.__dataList.DeleteAllItems() AsynchronousThread(self.__loadData).start() def __initImages(self): # load some images into an image list self.__images_16x = wx.ImageList(16, 16, False) self.__icons = [] for types, image in libs.mimetype.typeImage: self.__images_16x.Add(icons.mimeType('16x',image).GetBitmap()) self.__icons.append(image) self.up = self.__images_16x.AddWithColourMask(icons.get("/sorter/up.png").GetBitmap(),"blue") self.down = self.__images_16x.AddWithColourMask(icons.get("/sorter/down.png").GetBitmap(),"blue") def __initList(self): list = wx.ListCtrl(self, -1, style=wx.LC_REPORT | wx.LC_SORT_ASCENDING | wx.BORDER_SUNKEN) # assign the image list to it list.AssignImageList(self.__images_16x, wx.IMAGE_LIST_SMALL) # Add some columns for col, text in enumerate([u"路径", u"类型", u"大小", u"上传时间"]): list.InsertColumn(col, text, wx.CENTER) # set the width of the columns in various ways list.SetColumnWidth(0, 320) list.SetColumnWidth(1, 120) list.SetColumnWidth(2, 80) list.SetColumnWidth(3, 140) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.__onTreeSelected, list) self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.__onTreeSelected, list) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.__onTreeSelected, list) # rename event self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.__onEditNameStart, list) self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.__onEditNameEnd, list) # key up event (rename & delete) list.Bind(wx.EVT_KEY_UP, self.__onListKeyUp) #drop to download, bug bug #self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._startDragEvent, list) return list def _startDragEvent(self, e): # create temp folder # folder = libs.config.WORK_PATH + "/temp" # libs.config.mkdirs(folder) text = self.__dataList.GetItem(e.GetIndex()).GetText() text = text if text[0] == "/" else "/" + text # temp_file = os.path.join(folder, os.path.basename(text if text[0] == "/" else "/" + text)) # Create drag data data = wx.FileDataObject() data.AddFile(text) # Create drop source and begin drag-and-drop. dropSource = wx.DropSource(self.__dataList) dropSource.SetData(data) # Get Source res = dropSource.DoDragDrop(flags=wx.Drag_AllowMove) if res == wx.DragMove or res == wx.DragCopy: ## 下载 print("DragMove & DragCopy") return text def __onTreeSelected(self, event): self.__downloadButtonAndDeleteButtonStatus() def __pageButtonStatus(self): self.__enableToolbar(ID.ID_TOOLBAR_SEARCH_BTN,True) self.__enableToolbar(ID.ID_TOOLBAR_SEARCH_TEXT,True) self.__enableToolbar(ID.ID_TOOLBAR_LIMIT,True) self.__enableToolbar(ID.ID_TOOLBAR_NEXT_PAGE, self.__store.hasNext() or self.__marker != None) self.__enableToolbar(ID.ID_TOOLBAR_PREV_PAGE, self.__store.hasPrev()) self.__updateStatus() self.__downloadButtonAndDeleteButtonStatus() def __downloadButtonAndDeleteButtonStatus(self): selected = self.__dataList.GetSelectedItemCount() > 0 self.__enableToolbar(ID.ID_TOOLBAR_DOWNLOAD, selected and self.__download_url != None and self.__download_url != "") self.__enableToolbar(ID.ID_TOOLBAR_TRASH, selected) def __loadNextData(self): if self.__store.hasNext(): self.__showData(self.__store.next()) self.__pageButtonStatus() elif self.__marker != None: AsynchronousThread(self.__loadData).start() def __loadPrevData(self): if self.__store.hasPrev(): self.__showData(self.__store.prev()) self.__pageButtonStatus() def __loadData(self): ret, eof, info = self.__bucketManger.list(bucket=self.__bucketName, marker=self.__marker,limit=self.__limit, prefix=self.__prefix) if info.ok(): items = ret.get("items") self.__store.add(items) wx.CallAfter(self.__showData,items) if not eof: self.__marker = ret.get("marker") else: self.__marker = None else: if self.__marker != None: self.__enableToolbar(ID.ID_TOOLBAR_NEXT_PAGE, True) wx.MessageBox(info.error) self.__pageButtonStatus() def __showData(self, items): self.itemDataMap = {} for row, item in enumerate(items): name = item.get(u"key") fsize = libs.config.fileSizeShow(item.get(u"fsize")) putTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(round(item.get("putTime") / 10000 / 1000))) mimeType = item.get(u"mimeType") image = libs.mimetype.showType(mimeType, name) index = self.__dataList.InsertStringItem(sys.maxint, name) self.__dataList.SetStringItem(index, 1, mimeType) self.__dataList.SetStringItem(index, 2, fsize) self.__dataList.SetStringItem(index, 3, putTime) self.__dataList.SetItemData(index, row) # sort data self.itemDataMap[index] = (name, mimeType, item.get("fsize"), item.get("putTime")) # 设置图标 self.__dataList.SetItemImage(index, self.__icons.index(image)) def __initPopMenu(self): self.popupMenu = wx.Menu() urlMenu = self.popupMenu.Append(-1, u"复制地址", u"复制地址") self.Bind(wx.EVT_MENU, self.onCopyUrlEvent, urlMenu) self.popupMenu.AppendSeparator() deleteMenu = self.popupMenu.Append(-1, u"删除",u"删除选中文件") self.Bind(wx.EVT_MENU, self.onDeleteEvent, deleteMenu) refreshMenu = self.popupMenu.Append(-1, u"更新", u"强制更新缓存,保证上传的文件可以显示最新") self.Bind(wx.EVT_MENU, self.onRefreshCacheEvent, refreshMenu) renameMenu = self.popupMenu.Append(-1, u"重命名", u"重命名") self.Bind(wx.EVT_MENU, self.onRenameEvent, renameMenu) downloadMenu = self.popupMenu.Append(-1, u"下载", u"下载选中文件") self.Bind(wx.EVT_MENU, self.__frame.onDownloadFileEvent, downloadMenu) self.Bind(wx.EVT_CONTEXT_MENU, self.__onShowPopup) def __onShowPopup(self, event): if len(self.getSelectedFiles()) != 0 : pos = event.GetPosition() pos = self.ScreenToClient(pos) self.PopupMenu(self.popupMenu, pos) else: ##没有选中文件,不可操作 pass def __onPopupItemSelected(self, event): item = self.popupMenu.FindItemById(event.GetId()) text = item.GetText() wx.MessageBox("You selected item '%s'" % text) def __onListKeyUp(self, event): keyCode = event.GetKeyCode() if keyCode == wx.WXK_DELETE: self.onDeleteEvent(event) elif keyCode == wx.WXK_F2: if len(self.getSelectedFiles()) == 1: self.onRenameEvent(event) elif event.ControlDown() and keyCode == 67: self.onCopyUrlEvent(event) elif event.ControlDown() and keyCode == 65: for index in range(self.__dataList.GetItemCount()): self.__dataList.Select(index, True) event.Skip() def __onEditNameStart(self, event): print("重命名开始") def __onEditNameEnd(self, event): print("重命名结束") def getSelectedFiles(self): files = [] index = self.__dataList.GetFirstSelected() while index != -1: item = self.__dataList.GetItem(index) key = item.GetText() mimeType = self.itemDataMap[index][1] fileSize = self.itemDataMap[index][2] base_url = 'http://%s/%s' % (self.__download_url, key) private_url = self.__auth.private_download_url(base_url, expires=3600) files.append((private_url,key,mimeType,fileSize)) index = self.__dataList.GetNextSelected(index) return files def onRefreshEvent(self,event): self.__resetStartLoad() def onNextPageEvent(self, event): self.__dataList.DeleteAllItems() self.__enableToolbar(ID.ID_TOOLBAR_NEXT_PAGE) self.__loadNextData() def onPrevPageEvent(self, event): self.__dataList.DeleteAllItems() self.__enableToolbar(ID.ID_TOOLBAR_PREV_PAGE) self.__loadPrevData() def onCopyUrlEvent(self, event): files = self.getSelectedFiles() value = "" for url, key, mimeType, fileSize in files: value += url + "\n" data = wx.TextDataObject() data.SetText(value) if wx.TheClipboard.Open(): wx.TheClipboard.SetData(data) wx.TheClipboard.Close() else: wx.MessageBox(u"不能打开剪切板!", u"复制错误") def onDeleteEvent(self, event): """删除文件""" self.__enableToolbar(ID.ID_TOOLBAR_TRASH,False) message = u"您确定删除以下文件?\n" files = [] index = self.__dataList.GetFirstSelected() while index != -1: item = self.__dataList.GetItem(index) key = item.GetText() message += key + "\n" files.append(key) index = self.__dataList.GetNextSelected(index) results = dialogs.messageDialog(self,message,"Sure?") if results.accepted : AsynchronousThread((self.deleteSelectedFile,files)).start() else: self.__downloadButtonAndDeleteButtonStatus() def deleteSelectedFile(self,files): ops = build_batch_delete(self.__bucketName, files) ret, info = self.__bucketManger.batch(ops) if info.ok() : wx.CallAfter(wx.MessageBox,u"删除成功",u"提示") wx.CallAfter(self.setBucketName, self.__bucketName) else: wx.CallAfter(wx.MessageBox,info.error) def onRefreshCacheEvent(self, event): """刷新缓存""" files = self.getSelectedFiles() for url,key,mimeType,fileSize in files : self.__bucketManger.prefetch(self.__bucketName, key) wx.MessageBox(u"更新成功",u"Note") def onRenameEvent(self, event): """重命名""" selected = len(self.getSelectedFiles()) if selected == 1: # self.__onEditNameStart(event) index = self.__dataList.GetFirstSelected() key = self.itemDataMap[index][0] results = dialogs.textEntryDialog(self, u"请输入修改的名字", u"重命名", key) if results.accepted : newKey = results.text try: ret, info = self.__bucketManger.rename(self.__bucketName, key, newKey) if info.ok(): wx.MessageBox(u"重命名成功!", u"成功") else: wx.MessageBox(info.error, u"错误") except: wx.MessageBox(u"名字错误,查阅七牛文档!", u"错误") else: wx.MessageBox(u"不能同时重命名多个文件!", u"错误") def onSearchEvent(self, event): if isinstance(event,wx.KeyEvent): keycode = event.GetKeyCode() if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER : pass else: event.Skip() return True textCtrl = self.__frame._toolbar.FindById(ID.ID_TOOLBAR_SEARCH_TEXT).GetControl() self.setPrefix(textCtrl.GetValue()) def onPageLimitEvent(self, event): limit = int(event.EventObject.GetStringSelection(), 10) self.setLimit(limit) event.Skip() def sortBy(self, type): dict = {u"名称": 0, u"大小": 2, u"时间": 3} idx = dict[type] def compare_func(row1, row2): val1 = self.itemDataMap[row1][idx] val2 = self.itemDataMap[row2][idx] if val1 < val2: return -1 elif val1 > val2: return 1 else: return 0 self.__dataList.SortItems(compare_func) def __enableToolbar(self, id, enable=False): """禁用或者启用某个菜单""" self.__toolbar.EnableTool(id, enable) def __updateStatus(self): moreMark = "+" if self.__marker == None: moreMark = "" statusText = (u"空间:%s" % (self.__bucketName)) self.__frame.SetStatusText(statusText, 2) statusText = (u"页码:%d/%d%s" % (self.__store.page(), self.__store.length(),moreMark)) self.__frame.SetStatusText(statusText, 3)
if not self.sqlite.connect(): self.stop() while True: try: self.mqtt.loop() except Exception as e: self.log(logging.ERROR, "Error while looping MQTT (%s)" % e) if __name__ == "__main__": def resolve_path(path): return path if path[0] == '/' else os.path.join(os.path.dirname(os.path.realpath(__file__)), path) config_file = resolve_path('config/MQTT2SQLite.yaml'); config = Config(config_file) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(config.get('general', 'logging_level', logging.INFO)) logger.addHandler(handler) mqtt = MosquittoWrapper.ConfigureNewWrapper(config) sqlite = SQLiteWrapper.ConfigureNewWrapper(config, resolve_path('database.db')) MQTT2SQLite = MQTT2SQLite(resolve_path(config.get('general', 'pidfile', '/tmp/MQTT2SQLite.pid'))) MQTT2SQLite.stdout = MQTT2SQLite.stderr = resolve_path(config.get('general', 'stdout', '/dev/null')) MQTT2SQLite.duplicate_check_window = config.get('general', 'duplicate_check_window', 5)
def main(): config = Config(BASE_DIR + '/configuration/') sqlite = Sqlite(BASE_DIR + '/storage/hsm.db', config.XMLconfiguration) settings = path.abspath( path.join(path.dirname(__file__), '..', 'settings.ini')) pandadb = PandaDB(settings) es = Es(settings) metrics = pandadb.get_db_metrics() dictHarvesterInstnaces = es.get_workers_stats() sqlite.instances_availability(dictHarvesterInstnaces, metrics) instances = sqlite.get_data() for instance in instances: if instance not in list(config.XMLconfiguration.keys()): continue for harvesterhost in instances[instance]: sls_doc = SlsDocument() harvesterhosts_config = list( config.XMLconfiguration[instance].keys()) if harvesterhost not in harvesterhosts_config: continue if harvesterhost != 'none': availability = instances[instance][harvesterhost][ 'availability'] notificated = instances[instance][harvesterhost]['notificated'] contacts = instances[instance][harvesterhost]['contacts'] text = instances[instance][harvesterhost]['errorsdesc'] errors = sqlite.get_history_logs(harvesterid=instance, harvesterhost=harvesterhost) if (availability == 0 or availability == 10 or availability == 50): if len(errors) > 0: mailtext = '' for error in errors: if error['notificated'] == 0: mailtext = mailtext + error['fulltext'] sqlite.update_entry( 'HISTORYLOG', 'notificated', 1, instance, harvesterhost, checkmetrictime=error['checkmetrictime']) sqlite.update_entry( 'HISTORYLOG', 'notificationtime', str(datetime.utcnow()), instance, harvesterhost, checkmetrictime=error['checkmetrictime']) if mailtext != '': email = Notifications( text=mailtext, subject='Service issues on {0} {1}'.format( instance, harvesterhost), to=contacts) email.send_notification_email() sqlite.update_entry('INSTANCES', 'notificated', 1, instance, harvesterhost) email = {} elif availability == 100 and notificated == 1: sqlite.update_entry('INSTANCES', 'notificated', 0, instance, harvesterhost) id = 'PandaHarvester' sls_doc.set_id('%s_%s' % (id, (str(harvesterhost).split('.'))[0])) sls_doc.set_status(availability) sls_doc.set_avail_desc(instance) sls_doc.set_avail_info(text) sls_doc.set_webpage("") sls_doc.set_contact("") try: sls_doc.send_document() except Exception as ex: _logger.error(ex)
while True: try: self.telinf.loop() except Exception as e: self.log(logging.ERROR, "Error while looping -> %s" % (e)) if __name__ == "__main__": def resolve_path(path): return path if path[0] == '/' else os.path.join(os.path.dirname(os.path.realpath(__file__)), path) config_file = resolve_path('config/teleinfo2mqtt.yaml'); config = Config(config_file) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(config.get('general', 'logging_level', logging.INFO)) logger.addHandler(handler) mqtt = MosquittoWrapper(config.get('mqtt', 'client_id', None)) mqtt.host = config.get('mqtt', 'host', 'localhost') mqtt.port = config.get('mqtt', 'port', 1883) mqtt.keepalive = config.get('mqtt', 'keepalive', 60) mqtt.clean_session = config.get('mqtt', 'clean_session', False) mqtt.qos = config.get('mqtt', 'qos', 0)
class MainWin(sqbrowser_xrc.xrcfrmMain): """Represents the main query browser window """ configPath = os.path.join(os.path.dirname(__file__), "app.cfg") def __init__(self): """__init__ """ sqbrowser_xrc.xrcfrmMain.__init__(self, None) self.SetSize((650, 500)) # setup the control events self.btOpenSqlFile.Bind(wx.EVT_BUTTON, self.btOpenSqlFile_Click) self.btOpenSqlDb.Bind(wx.EVT_BUTTON, self.btOpenSqlDb_Click) self.btExecuteFile.Bind(wx.EVT_BUTTON, self.btExecuteFile_Click) self.btCommit.Bind(wx.EVT_BUTTON, self.btCommit_Click) # setup timers self._interval = 2 # seconds self.tmrCheckFile = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.tmrCheckFile_Tick, self.tmrCheckFile) # file operation vars self.file = None self._lastCheckTime = None # status bar self.CreateStatusBar() self.SetStatusText("SQBrowser") # setup sqlengine self._sqlEngine = None # misc setup self.config = Config(self.configPath) self.config.load() self.StartTimer() if self.config.db_path: self.txtSqlDb.SetValue(self.config.db_path) if self.config.src_path: self.txtSqlFile.SetValue(self.config.src_path) ## EVENTS METHODS def OnClose(self, evt): """OnClose @remark: overriden from base class """ if self._sqlEngine: self._sqlEngine.disconnect() # use default close action evt.Skip() def btOpenSqlFile_Click(self, evt): """btOpenSqlFile_Click """ path = self._openFileDialog(msg="Select the query file") if not path: return self.config.src_path = path self.config.save() self.txtSqlFile.SetValue(path) def btOpenSqlDb_Click(self, evt): """btOpenSqlDb_Click """ path = self._openFileDialog(msg="Select the data source") if not path: return self._clearLog() self.config.db_path = path self.config.save() self.txtSqlDb.SetValue(path) def tmrCheckFile_Tick(self, evt): """tmrServer_Tick """ if self.chkMonitorFile.IsChecked(): self.SetStatusText("Monitoring file...") else: self.SetStatusText("SQBrowser") return self.StopTimer() self._executeQueryFile() self.StartTimer() def btExecuteFile_Click(self, evt): """btExecuteFile_Click """ self._executeQueryFile(force_execute=True) def btCommit_Click(self, evt): """btCommit_Click """ if not self._sqlEngine: return self._sqlEngine.commit() self._addLog("Changes committed...") ## MISC METHODS def _executeQueryFile(self, force_execute=False): """Runs the query specified by the opened query file """ path = self.txtSqlFile.GetValue() if not os.path.isfile(path): self._addLog("Not a file: " + path) return dbPath = self.txtSqlDb.GetValue() hasChanged = self._checkFile(path) now = wx.DateTime().Now().Format() if hasChanged: self._addLogSplit() self._addLog("File Changed: " + now) elif not hasChanged: if not force_execute: return # get contents of query file contents = self._readContents(path) # get the query query = self._parseQuery(contents) # setup the engine, determine the query type isJson = query.lstrip()[:2] == "$." if isJson: pass else: self._sqlEngine = sqlbase.SqlBase(dbPath) if not self._sqlEngine.connect(): self._addLog("Unable to connect to: " + dbPath) return self._addLogSplit() # exec all queries, semi-colon separated queries = [query] if EXEC_ALL(query) is not None: queries = query.split(";") # beseech user msg = "Run %d queries?" % len(queries) if wx.MessageBox(message=msg, style=wx.YES | wx.NO) == wx.NO: self._addLog("Multi-query operation aborted.") return self._addLog("Running %d queries..." % len(queries)) if isJson: self._runJson(queries, dbPath) else: self._runSql(queries) def _runJson(self, queries, jsonPath): for query in queries: db = jsondb.from_file(jsonPath) results = db.query(query).values() # output to log, for now self._addLog(pprint.pformat(results)) def _runSql(self, queries): # execute the queries results = {} for query in queries: self._addLog(query.strip()) results = self._sqlEngine.execute_query(query) if not results: self._addLog("SQL ERROR: " + self._sqlEngine.last_error) return self._addLog(results["message"]) ## display the result data in the table # insert columns self._rebuildColumns(results["columns"]) # insert rows for row in results["rows"]: self._addRow(row) self._resizeColumns(results["columns"]) def _parseQuery(self, src): """Parses the src to only show the target query @remark: it stops at the first 'query stop' placeholder @return string the query to execute """ lines = src.split("\n") hasQueryStart = False for start in QUERY_START: if src.find(start) >= 0: hasQueryStart = True break doStart = False query = "" for line in lines: sLine = line.strip() # if flag seen, start grabbing if not hasQueryStart or doStart: # if no starter, then grab until eof query += line + "\n" if sLine in QUERY_START: # start grabbing from next line on doStart = True if not hasQueryStart or doStart: if sLine in QUERY_STOP: # done, return query, remove the query stop query = query.replace(sLine, "") break return query.strip() def _addLogSplit(self): """Adds an output separator to the log """ count = 70 self._addLog("-" * count) def _addLog(self, msg): """Adds a line of text to the output console """ self.txtMessages.AppendText(msg + "\n") def _clearLog(self): """Clears the output log """ self.txtMessages.Clear() def StartTimer(self): self.StopTimer() self.tmrCheckFile.Start(self._interval * 1000) def StopTimer(self): self.tmrCheckFile.Stop() def _openFileDialog(self, msg="Select the file", path=""): """Displays the open file dialog """ path = wx.FileSelector(message=msg, default_path=path, parent=self) return path def _rebuildColumns(self, columns): """Rebuilds the list ctrl @remarks: Deletes all columns and rows """ # remove all cols and rows self.lstResults.ClearAll() # insert the columns into the header for col, text in enumerate(columns): self.lstResults.InsertColumn(col, text) def _resizeColumns(self, columns): """Resizes the columns """ doAutoSize = len(columns) <= AUTOSIZE_COLUMNS # insert the columns into the header if doAutoSize: for col, text in enumerate(columns): self.lstResults.SetColumnWidth(col, wx.LIST_AUTOSIZE) def _addRow(self, row): """addRow """ count = self.lstResults.GetItemCount() idx = 0 for col, col_value in enumerate(row): if col == 0: idx = self.lstResults.InsertStringItem(sys.maxint, str(count)) self.lstResults.SetStringItem(idx, col, unicode(col_value)) ## FILE CHECK METHODS def _checkFile(self, filePath): """Checks the modification date for the specified file path """ if not os.path.isfile(filePath): return False hasFileChanged = False # get file info fileStats = os.stat(filePath) lastMod = time.localtime(fileStats[stat.ST_MTIME]) # create a dictionary to hold file info file_info = { "fname": filePath, "fsize": fileStats[stat.ST_SIZE], # last modified "f_lm": time.strftime("%m/%d/%Y %I:%M:%S %p", lastMod), # last accessed "f_la": time.strftime("%m/%d/%Y %I:%M:%S %p", time.localtime(fileStats[stat.ST_ATIME])), # creation time "f_ct": time.strftime("%m/%d/%Y %I:%M:%S %p", time.localtime(fileStats[stat.ST_CTIME])), } # get the datetime object of the file modification time lastModTime = wx.DateTime() lastModTime.ParseDateTime(file_info["f_lm"]) if self._lastCheckTime is None: self._lastCheckTime = wx.DateTime().Now() # make sure it is after the last checked time if lastModTime.IsLaterThan(self._lastCheckTime): hasFileChanged = True # get the last mod time self._lastCheckTime = lastModTime return hasFileChanged def _readContents(self, path): """read_contents """ if not os.path.isfile(path): return None # get the file contents with codecs.open(path, "r", encoding="utf-8") as fp: contents = fp.read() return contents
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see <http://www.gnu.org/licenses/>. from typing import TypeVar, Optional, Callable import subprocess, time, json, feedparser from datetime import * from libs.config import Config from libs.database import Database import os.path from os import path # pylint: disable=invalid-name T = TypeVar("T") config = Config() def _get_youtube_rss_url(yt_channel_id: str) -> str: return f"https://www.youtube.com/feeds/videos.xml?channel_id={yt_channel_id}" def unpack_optional(elem: Optional[T], default: Callable[[], T]) -> T: if elem is None: return default() return elem def get_unix_time(): d = datetime.now() ut = d.timestamp()
def do_reload(self): self.log(logging.INFO, "Reloading") config = Config(config_file) self.load(config.get('general', 'routes', {})) self.mqtt.subscribe(self._actions.keys())
''' Created on 25 jan. 2016 @author: Dirc ''' import os from libs.config import Config config = Config() print config.getConfig("peassantdef", "food") print config.getConfig("peassantdef", "wood") print config.getConfig("peassantdef", "eat") print config.getConfig("peassantdef", "offense") print config.getConfig("peassantdef", "defense") print config.getConfig("peassantdef", "greating") print #print config.infoConfig() peassantdef = config.getConfig("peassantdef", "eat") print type(peassantdef) print peassantdef
self.mqtt.on_message_cleaned = self.mqtt_on_message self.mqtt.connect() self.runTimers() while True: self.mqtt.loop() if __name__ == "__main__": def resolve_path(path): return path if path[0] == '/' else os.path.join(os.path.dirname(os.path.realpath(__file__)), path) config_file = resolve_path('config/mqttaverage.yaml'); config = Config(config_file) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(config.get('general', 'logging_level', logging.INFO)) logger.addHandler(handler) mqtt = MosquittoWrapper(config.get('mqtt', 'client_id', None)) mqtt.host = config.get('mqtt', 'host', 'localhost') mqtt.port = config.get('mqtt', 'port', 1883) mqtt.keepalive = config.get('mqtt', 'keepalive', 60) mqtt.clean_session = config.get('mqtt', 'clean_session', False) mqtt.qos = config.get('mqtt', 'qos', 0)
class PhotoboothApp(object): config = Config() def __init__(self): self.runtime_id = 0 self._canvas = None self._background = None self._photo_space = None self.target_dir = None self.font = None self._init_camera() self.photos = [] #self.printer = backends.acquire_backend("output", "line_printer", self.config) self._init_gpio() self._get_last_runtime_id() self.get_current_photo_directory() pygame.init() self.clock = pygame.time.Clock() self.limit_cpu_usage() display_mode = pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN self._canvas = pygame.display.set_mode((0, 0), display_mode) self.screen_width = pygame.display.Info().current_w self.screen_height = pygame.display.Info().current_h self._background = self.fill_background() self._photo_space = self.fill_photo_space() self._running = True self.font = pygame.font.Font(self.config.get('font_filename'), self.config.getint('font_size')) pygame.mouse.set_visible(False) def _get_last_runtime_id(self): self.runtime_id = 0 try: f = open(self.config.get("RUNTIME_ID_FILE"), "r") self.runtime_id = int(f.read()) f.close() except (IOError, OSError, ValueError): pass def _acquire_new_runtime_id(self): self.runtime_id += 1 f = open(self.config.get("RUNTIME_ID_FILE"), "w") f.write(str(self.runtime_id)) f.close() def create_valid_photo_directory(self): if not os.path.exists(self.target_dir): os.mkdir(self.target_dir) return True if os.path.isdir(self.target_dir): return not os.listdir(self.target_dir) return False def get_current_photo_directory(self): self.generate_runtime_dirname() while not self.create_valid_photo_directory(): self._acquire_new_runtime_id() self.generate_runtime_dirname() def generate_runtime_dirname(self): base_dir = os.path.expanduser(self.config.get("TARGET_DIR")) runtime_dir = "photos-%04d" % self.runtime_id self.target_dir = os.path.join(base_dir, runtime_dir) def _init_gpio(self): GPIO.setmode(GPIO.BCM) GPIO.setup(self.config.getint("SWITCH_PIN"), GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(self.config.getint("LED_PIN"), GPIO.OUT) self.enable_led(False) def _init_camera(self): self.camera = picamera.PiCamera() self.camera.rotation = 180 self.camera.annotate_text_size = 128 self.camera.led = False self.camera.vflip = True self.camera.resolution = (self.config.getint("picture_width"), self.config.getint("picture_height")) def enable_led(self, mode): GPIO.output(self.config.getint("LED_PIN"), int(not mode)) def wait_for_button(self): while True: button_pressed = GPIO.input(self.config.getint("SWITCH_PIN")) if button_pressed: return pygame.display.flip() time.sleep(0.1) if self.parse_events(): return def fill_background(self): background = pygame.Surface((self.screen_width, self.screen_height)) background_image = pygame.image.load( self.config.get("background_tile_image")).convert() for y in range(0, self.screen_height, background_image.get_height()): for x in range(0, self.screen_width, background_image.get_width()): background.blit(background_image, (x, y)) return background def fill_photo_space(self): all_photos = pygame.Surface((self.screen_width, self.screen_height)) for photo_number in range(1, 5): photo_filename = "/home/photobooth/photobooth/images/sample%d.png" % photo_number self.put_photo_on_surface(all_photos, photo_filename, photo_number) all_photos.set_colorkey(Colors.BLACK) return all_photos def put_photo_on_surface(self, surface, filename, number): gap_percentage = 5 width_gap = int(self.screen_width / 100 * gap_percentage) height_gap = int(self.screen_height / 100 * gap_percentage) frame_width = int((self.screen_width - 3 * width_gap) / 2) frame_height = int((self.screen_height - 3 * height_gap) / 2) frame_x = width_gap if number % 2 != 0 else (2 * width_gap + frame_width) frame_y = height_gap if number <= 2 else (2 * height_gap + frame_height) photo = self.load_and_scale_photo_for_display(filename) surface.blit(photo, (frame_x, frame_y)) def load_and_scale_photo_for_display(self, photo_filename): gap_percentage = 5 width_gap = int(self.screen_width / 100 * gap_percentage) height_gap = int(self.screen_height / 100 * gap_percentage) frame_width = int((self.screen_width - 3 * width_gap) / 2) frame_height = int((self.screen_height - 3 * height_gap) / 2) frame_surface = pygame.Surface((frame_width, frame_height)) frame_surface.fill(Colors.WHITE) photo_surface = pygame.image.load(photo_filename) self.photos.append(photo_surface) photo_width_gap = 0 photo_height_gap = (frame_height / 100 * 8) photo_width = frame_width - 2 * photo_width_gap photo_height = frame_height - 2 * photo_height_gap scaled_surface = pygame.transform.scale(photo_surface, (photo_width, photo_height)) frame_surface.blit(scaled_surface, (photo_width_gap, photo_height_gap)) return frame_surface def take_photo(self, number): self.redraw_background() self.render_text("Bild %d von %d" % (number, 4), Colors.BLACK) pygame.display.flip() time.sleep(2) self.camera.start_preview() self.redraw_background(white_borders=True) for count in range(self.config.getint("countdown_seconds"), 0, -1): self.camera.annotate_text = str(count) time.sleep(1) self.camera.annotate_text = "" photo_filename = '%s/photo_%d.jpg' % (self.config.get("TEMP_DIR"), number) self.camera.stop_preview() self._canvas.fill((255, 255, 255)) pygame.display.flip() self.camera.capture(photo_filename) self.put_photo_on_surface(self._photo_space, photo_filename, number) def parse_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self._running = False self.cleanup() sys.exit(0) if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self._running = False self.cleanup() sys.exit(0) return True return False def limit_cpu_usage(self): self.clock.tick(self.config.getfloat("MAX_FPS")) def render_text(self, text, bg_color): overall_width = 0 overall_height = 0 text_lines = [] for line in text.split('\n'): overall_width = max(overall_width, self.font.size(line)[0]) overall_height += self.font.size(line)[1] text_lines.append(self.font.render(line, True, Colors.WHITE)) top_and_bottom_margin_percentage = 10 background_width = overall_width * ( 100 + top_and_bottom_margin_percentage) / 100 background_height = overall_height * ( 100 + top_and_bottom_margin_percentage) / 100 x = (self.screen_width - background_width) / 2 y = (self.screen_height - background_height) / 2 rounded_rect(self._canvas, (x, y, background_width, background_height), bg_color, radius=0.2) text_margin_percentage = top_and_bottom_margin_percentage / 2 start_height = y + text_margin_percentage * overall_height / 100 for i, line in enumerate(text_lines): label_x = (self.screen_width - line.get_width()) / 2 label_y = start_height + i * line.get_height() self._canvas.blit(line, (label_x, label_y)) def redraw_background(self, white_borders=False): self._canvas.blit(self._background, (0, 0)) self._canvas.blit(self._photo_space, (0, 0)) if white_borders: photo_height = self.config.getint("picture_height") rect_height = int((self.screen_height - photo_height) / 2) rect_size = (self.screen_width, rect_height) border_rect = pygame.Surface(rect_size) border_rect.fill(Colors.WHITE) self._canvas.blit(border_rect, (0, 0)) self._canvas.blit(border_rect, (0, rect_height + photo_height)) pygame.display.flip() def render_and_save_printer_photo(self, photo_filename): dpi = self.config.getfloat("printer_dpi") width = dpi * self.config.getfloat("printer_width_inch") height = dpi * self.config.getfloat("printer_height_inch") print_surface = pygame.Surface((width, height)) print_surface.fill(Colors.WHITE) for number, photo in enumerate(self.photos): gap_percentage = 2 width_gap = int(width / 100 * gap_percentage) height_gap = int(height / 100 * gap_percentage) frame_width = int((width - width_gap) / 2) frame_height = int((height - height_gap) / 2) frame_x = 0 if number % 2 == 0 else (width_gap + frame_width) frame_y = 0 if number < 2 else (height_gap + frame_height) scaled_photo = pygame.transform.scale(photo, (frame_width, frame_height)) scaled_photo = pygame.transform.flip(scaled_photo, True, False) print_surface.blit(scaled_photo, (frame_x, frame_y)) pygame.image.save(print_surface, photo_filename) def generate_photo_filename(self): picture = "%d.jpg" % time.time() filename = os.path.join(self.target_dir, picture) return os.path.normpath(filename) def stage_greeting(self): self.photos = [] self.redraw_background() self.render_text(u"Bereit?\nKnopf drücken!", bg_color=Colors.ORANGE) pygame.display.flip() self.enable_led(True) self.wait_for_button() self.enable_led(False) def stage_farewell(self): time.sleep(2) self.render_text(u"Vielen Dank!\nDrucke... ", bg_color=Colors.ORANGE) pygame.display.flip() photo_filename = self.generate_photo_filename() self.render_and_save_printer_photo(photo_filename) #self.printer.export(photo_filename) self.photos = [] time.sleep(10) self._photo_space = self.fill_photo_space() def stage_photos(self): max = 5 for number in range(1, max): self.take_photo(number) self.redraw_background() if number < max - 1: time.sleep(1.5) self.render_text(u"Nächstes Bild?\nKnopf drücken!", bg_color=Colors.ORANGE) self.wait_for_button() def cleanup(self): GPIO.cleanup() pygame.quit() def launch_app(self): while self._running: self.stage_greeting() self.stage_photos() self.stage_farewell() self.cleanup()
class LoginPanel(wx.Panel): def __init__(self, parent, onLoginSuccess): wx.Panel.__init__(self, parent, style=wx.BORDER_SIMPLE) self.frame = parent self.onLoginSuccess = onLoginSuccess self.conf = Config() accessKey, secretKey = self.conf.getKeys() loginTitle = wx.StaticText(self, -1, u" 登 陆 ") loginTitle.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) accessKeyLabel = wx.StaticText(self, -1, "AccessKey:") self.accessKey = wx.TextCtrl(self, -1, accessKey) secretKeyLabel = wx.StaticText(self, -1, "SecretKey:") self.secretKey = wx.TextCtrl(self, -1, secretKey, style=wx.PASSWORD) self.rememberMe = wx.CheckBox(self, -1, u"记住账号") if accessKey != "" and secretKey != "": self.rememberMe.SetValue(True) self.loginBtn = wx.Button(self, -1, u"登陆") self.loginBtn.Bind(wx.EVT_BUTTON, self.OnLogin) self.exitBtn = wx.Button(self, -1, u"退出") self.exitBtn.Bind(wx.EVT_BUTTON, self.OnExit) # title mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add((0, 10)) mainSizer.Add(loginTitle, 0, wx.CENTER | wx.TOP | wx.BOTTOM, 5) mainSizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 5) # ak and sk keySizer = wx.FlexGridSizer(cols=2, hgap=7, vgap=7) keySizer.AddGrowableCol(1) keySizer.Add(accessKeyLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL) keySizer.Add(self.accessKey, 0, wx.EXPAND) keySizer.Add(secretKeyLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL) keySizer.Add(self.secretKey, 0, wx.EXPAND) mainSizer.Add(keySizer, 0, wx.EXPAND | wx.ALL, 5) mainSizer.Add(self.rememberMe, 0, wx.ALL | wx.ALIGN_RIGHT, 5) mainSizer.Add((10, 10)) # some empty space btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add((30, 20)) btnSizer.Add(self.loginBtn,1) btnSizer.Add((30, 20)) btnSizer.Add(self.exitBtn,1) btnSizer.Add((30, 20)) mainSizer.Add(btnSizer, 0, wx.EXPAND | wx.BOTTOM, 10) self.SetSizer(mainSizer) def onAuth(self): ak = str(self.accessKey.GetLabelText()) sk = str(self.secretKey.GetLabelText()) buckets, info = qiniu.BucketManager(qiniu.Auth(ak, sk)).buckets() if info.ok(): if self.rememberMe.IsChecked(): self.conf.setKeys((ak, sk)) self.onLoginSuccess(buckets) else: self.onAuthError(info.error) def onAuthError(self, errMsg): self.loginBtn.Enable() wx.MessageBox(errMsg, u"错误") def OnLogin(self, event): self.loginBtn.Disable() wxAsynchronousThread(self.onAuth, self.onAuthError).start() def OnExit(self, evt): self.frame.Hide() self.frame.Destroy()