def compile(pathnames, out, err=sys.stderr, externals=None): from spike.compiler.scheck import check, declareBuiltIn, declareExternalSymbols from spike.compiler.symbols import SymbolTable from spike.compiler.cgen import generateCode from spike.compiler.statements import Compound, PragmaSource notifier = Notifier(stream=err) st = SymbolTable() declareBuiltIn(st, notifier) if externals: declareExternalSymbols(externals, st, notifier) tree = Compound() for pathname in pathnames: t = parse(pathname, notifier) if t is None: continue tree.append(PragmaSource(pathname)) tree.extend(t) check(tree, st, notifier) notifier.failOnError() generateCode(tree, out) return
def upload(self, frame): notify = Notifier(self.config['not']['sid'], self.config['not']['token'], self.config['not']['twilio_number'], self.config['not']['usr_number'], self.config['not']['imgur_client_id']) notify.new_msg(frame, self.config['main']['location_name'])
def __init__(self, player1: Player, player2: Player, n_games: int): if n_games % 2 == 0: raise ValueError("Error: number of games in tournament must be an odd number!") # initialize an empty deck and join to the players self.deck = [] player1.deck = self.deck player2.deck = self.deck self.player1 = player1 self.player2 = player2 self.starting_player = player1 self.n_games = n_games self.player1_stats = { 'games_won': 0, 'total_points': 0 } self.player2_stats = { 'games_won': 0, 'total_points': 0 } self.notifier = Notifier()
def main(): citizen = Citizen(13, "Jan", "Kowalski") device_data = input("name, number, state: ") device = Device( device_data.split(' ')[0], device_data.split(' ')[1], States[device_data.split(' ')[2]], citizen) notifier = Notifier() notifier.add_device(device, device.get_state()) f = open("legitnetwork.txt", "r") message = f.read() last_message = None while not message or message.split(' ')[1] != 'EXIT': if message and message.split(' ')[0] == device.get_state( ).name and last_message != message.split(' ', 1)[1]: print(message.split(' ', 1)[1]) last_message = message.split(' ', 1)[1] f.seek(0) message = f.read() f.close()
def main(argv): db_location = '' account = '' token = '' from_num = '' to_num = '' min_down_speed = 100 try: opts, args = getopt.getopt(argv, "ha:t:F:T:d:m:", [ "account=", "token=", "from=", "to=", "db_location=", "min_down_speed=" ]) except getopt.GetoptError: print 'speedavg.py -a <account> -t <token> -F <from> -T <to> -d <db location> -m <min down speed>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'speedavg.py -a <account> -t <token> -F <from> -T <to> -d <db location> -m <min down speed>' sys.exit() elif opt in ("-d", "--dblocation"): db_location = arg elif opt in ("-a", "--account"): account = arg elif opt in ("-t", "--token"): token = arg elif opt in ("-F", "--from"): from_num = arg elif opt in ("-T", "--to"): to_num = arg elif opt in ("-m", "--min_down_speed"): min_down_speed = arg if db_location != '' and account != '' and token != '' and from_num != '' and to_num != '': num_consecutive_slow = 4 cnt_below_threshold = 0 sum_speed = 0 avg_speed = 0 select = "SELECT down_speed FROM speedtestresults ORDER BY id DESC LIMIT " + str( num_consecutive_slow) conn = sqlite3.connect(db_location) cursor = conn.execute(select) for row in cursor: print("DOWN SPEED = ", row[0]) if row[0] < min_down_speed: cnt_below_threshold += 1 sum_speed += row[0] conn.close() avg_speed = sum_speed / num_consecutive_slow if cnt_below_threshold == num_consecutive_slow: print("SENDING NOTIFICATION") notifier = Notifier() dateNow = datetime.datetime.now().strftime("%m-%d-%y %H:%M:%S") msg = str(num_consecutive_slow ) + " CONSECUTIVE SLOW SPEED RESULTS AT " + str( dateNow) + ". AVG SPEED " + str( round(avg_speed, 2)) + "Mbps" notifier.send_sms_alert(msg) else: print("SPEEDS WITHIN ACCEPTABLE RANGE")
def __init__(self, window, level, stage, test = False, log = False): Notifier.__init__(self, [], test, log) self.sender = "*****@*****.**" self.level = level self.stage = stage self.type = type self.setWindow(window)
def __init__(self, name: str): self.deck = [ ] # remaining cards available for the game (32 at the very beginning) self.hand_cards = [ ] # cards in the hand (max 4 according to the rules) self.archive_cards = [] # cards that have been played self.name = name self.score = 0 self.notifier = Notifier()
def notify(self): "send out all the different emails" if self.email is None: return self.post(self.email) Notifier.notify(self) # send all the queued messages out! self.flushQueue() # just in case. If queue is empty, does nothing.
def __init__(self, motionScheduler=None, specification=None, scheduler=None): """ Initializes the SRPCServer object Args passed to this object allow the SRPC server to share these objects All requests are subject to username and password authentication and connection are made over HTTPS. @param motionScheduler @param specification @param scheduler """ if (motionScheduler == None): self.motionScheduler = MotionScheduler.GetInstance() else: self.motionScheduler = motionScheduler if (specification == None): self.specification = Specification.GetInstance() else: self.specification = specification if (scheduler == None): self.scheduler = Scheduler.GetInstance() else: self.scheduler = scheduler self.notifier = Notifier() self.sslmanager = SSLManager() self.server_address = (Setting.get('rpc_server_hostname', '0.0.0.0'), Setting.get('rpc_server_port', 9000)) try: self.server = SecureXMLRPCServer( self.server_address, SecureXMLRpcRequestHandler, Setting.get('rpc_server_log', False), self.sslmanager.key, self.sslmanager.certificate) except (socket.error): old = self.server_address[0] Setting.set('rpc_server_hostname', '0.0.0.0') self.server_address = (Setting.get('rpc_server_hostname', '0.0.0.0'), Setting.get('rpc_server_port', 9000)) self.server = SecureXMLRPCServer( self.server_address, SecureXMLRpcRequestHandler, Setting.get('rpc_server_log', False), self.sslmanager.key, self.sslmanager.certificate) self.notifier.addNotice( 'Unable to bind to RPC Hostname: {}. Reset to 0.0.0.0.'.format( old), 'warning') self.exposed = Exposed(self.specification, self.motionScheduler) self.server.register_instance(self.exposed) self.scheduler.addTask( 'srpc_server', self.serve, 0.2, stopped=(not Setting.get('rpc_autostart', False)))
def select_event(self): ''' Fires whenever a TreeNode selected state is changed. Args: None Returns: None ''' notifier = Notifier() notifier.Notify(lx.symbol.fCMDNOTIFY_CHANGE_ALL)
def __init__(self , periods = [] , futurePeriods = [] , skipEmails = [] , test = False , log = False ): Notifier.__init__(self, skipEmails, test, log) self.periodChanges = PeriodChanges(test = test) self.sender = "*****@*****.**" self.setPeriods(periods, futurePeriods)
def path_event(self): ''' Fired by TreeNode objects whenever the node's path property is changed. Args: None Returns: None ''' self.unsaved_changes = True notifier = Notifier() notifier.Notify(lx.symbol.fCMDNOTIFY_CHANGE_ALL)
def __init__(self, parent=None, name=None, fl=0): MainForm.__init__(self, parent, name, fl) notifymode = 0 if len(sys.argv) > 1 and sys.argv[1] == '-s': notifymode = 1 self.statusFrame.hide() self.sh = HTMLSyntax(self.sourceEditor) self.sourceEditor.setTextFormat(Qt.PlainText) self.current_post = None self.cached_password = None self.cached_atomblog = None self.plugins = PluginFactory(self) tabLayout = QHBoxLayout(self.tab, 11, 6, "tabLayout") tabLayout.setAutoAdd(True) tabLayout2 = QHBoxLayout(self.tab_2, 11, 6, "tabLayout2") tabLayout2.setAutoAdd(True) initToolbar(self, self.plugins) self.notifier = Notifier(self, notifymode) self.bg = BackGround() self.workers = BackGround() self.uChecker = updateCheckWorker(self.notifier) self.aMenu = QPopupMenu() self.aMenu.insertItem("Delete post", 1) self.aMenu.insertItem("Export post", 2) self.bMenu = QPopupMenu() self.bMenu.insertItem("Delete post", 1) self.bMenu.insertItem("Export post", 2) self.connect(self.aMenu, SIGNAL("activated(int)"), self.pubPopup) self.connect(self.bMenu, SIGNAL("activated(int)"), self.savePopup) self.frameCat.hide()
def loadImage(self): fileName = QFileDialog.getOpenFileName(QFileDialog(), "Load Image", "", "Image (*.png, *.jpg)") if fileName[0] == '': Notifier.Alert(message="No image selected!") return self.imageViewer.setPixmap(QPixmap(fileName[0]))
def __init__(self, motionScheduler = None, specification = None, scheduler = None): if(motionScheduler == None): self.motionScheduler = MotionScheduler() else: self.motionScheduler = motionScheduler if(specification == None): self.specification = Specification() else: self.specification = specification if(scheduler == None): self.scheduler = Scheduler() else: self.scheduler = scheduler self.notifier = Notifier() self.sslmanager = SSLManager() self.server_address = (Setting.get('rpc_server_hostname', 'localhost'), Setting.get('rpc_server_port', 9000)) try: self.server = SecureXMLRPCServer(self.server_address, SecureXMLRpcRequestHandler, Setting.get('rpc_server_log', False), self.sslmanager.key, self.sslmanager.certificate) except (socket.error): old = self.server_address[0] Setting.set('rpc_server_hostname', 'localhost') self.server_address = (Setting.get('rpc_server_hostname', 'localhost'), Setting.get('rpc_server_port', 9000)) self.server = SecureXMLRPCServer(self.server_address, SecureXMLRpcRequestHandler, Setting.get('rpc_server_log', False), self.sslmanager.key, self.sslmanager.certificate) self.notifier.addNotice('Unable to bind to RPC Hostname: {}. Reset to localhost.'.format(old), 'warning') self.exposed = Exposed(self.specification, self.motionScheduler) self.server.register_instance(self.exposed) self.scheduler.addTask('srpc_server', self.serve, 0.2, stopped=(not Setting.get('rpc_autostart', False)))
def main(): import optparse parser = optparse.OptionParser(version=info.VERSION) parser.add_option('-d', '--debug', action='store_true', default=False) parser.add_option('-i', '--inital-check', action='store', dest='initial_check', type='int', default=30, metavar='N', help='number of seconds before initial check is performed',) (options, args) = parser.parse_args() if options.debug: Debug.DEBUGGING = True conf = Config(GCONF_PATH) notifier = Notifier(conf, options.initial_check) try: gtk.main() except KeyboardInterrupt: notifier.destroy()
def __init__(self, *, debug_show=False): self.car_op = CarOp() self.auto_nav_er = AutoNav(self.car_op) # self.orbslam2_connect = OrbSlam2Connector() self.debug_show = debug_show self.human_detect = Yolov3HumanDetector() self.auto_watch_human = AutoWatchHuman(self.car_op) self.recorder = Recorder() self.notifier = Notifier(self.recorder) self.work_thread = Thread(target=self.work_run) self.work_thread.start() self.record_thread = Thread(target=self.record_run) self.record_thread.start()
def __init__(self, configPath, logger): ''' Pyibber ctor ''' self.loadConfig(configPath) self.logger = logger self.Commandx = Commandx(self) self.Notifier = Notifier(self) self.DccManager = Dcc.Manager.Manager(self) self.event_loop = EventLoop()
def __init__(self, parent=None, name=None, modal=0, fl=0): ImageForm.__init__(self, parent, name, modal, fl) self.comboAlign.insertItem('None') self.notifier = Notifier(parent, 1, args=[self.progressBar]) self.alignList['Left'] = 'left' self.alignList['Right'] = 'right' self.alignList['Center'] = 'center' self.btnUpload.setEnabled(False) self.buttonOk.setEnabled(False) self.http = QHttp() self.connect(self.http, SIGNAL("done(bool)"), self.httpDone) self.connect(self.http, SIGNAL("dataSendProgress (int, int)"), self.httpProgress) self.http2 = QHttp() self.connect(self.http2, SIGNAL("done(bool)"), self.http2Done) self.connect(self.http2, SIGNAL("dataSendProgress (int, int)"), self.httpProgress) for key in self.alignList.keys(): self.comboAlign.insertItem(key)
def notify(self): "send out all the different emails" # notify the obs; subject = "Your GBT Project has been # scheduled..." Because each observer will get a custom # 'subject' line with the pcode appended, each must get a # separate email. for i in self.getAddresses("observer"): try: pcodes = " - ".join(self.emailProjectMap[i]) except KeyError: # You WILL get a key error if scheduler # changes observer email addresses pcodes = None email = self.cloneTemplate("observer") if pcodes: subject = "%s (%s)" % (email.GetSubject(), pcodes) else: subject = email.GetSubject() email.SetRecipients(i) email.SetSubject(subject) self.post(email) # now let the people who aren't observing know, but who # might have been in scheduled in the past if len(self.getAddresses("changed")) != 0: email = self.cloneTemplate("changed") self.post(email) # now let the staff know - "GBT schedule for ..." if len(self.getAddresses("staff")) != 0: email = self.cloneTemplate("staff") self.post(email) Notifier.notify(self) # send all the queued messages out! self.flushQueue() # just in case. If queue is empty, does nothing.
def __init__(self, cam_id=0, *, debug_show=False): ''' 初始化函数 :param cam_id: 当cam_id为-1时,将会使用IP摄像机,如果为其他值,例如1,将会使用本机的1号摄像头 :param debug_show: 是否启动调试输出,为True时,将会启动debug模式,并且会显示所有子模块的处理情况的显示输出 ''' self.debug_show = debug_show print('initing cam') self.cam_id = cam_id if cam_id == -1: # 使用IP摄像头 self.smart_cam = smart_cam_receiver() else: # 打开本地摄像头失败时,将会抛出异常 self.cam = imageio.get_reader('<video%d>' % cam_id, fps=self.fps) print('open cam complete') print('load detector') # 载入各种检测器 self.fire_detector = FireDetector(debug_show=debug_show) self.smoke_detector = SmokeDetector() self.diff_move_detector = DiffMoveDetector(debug_show=debug_show) self.human_detector = HumanDetector(const_define.yolo_net_file, const_define.yolo_weights_file, debug_show=debug_show) self.recoder = Recorder(const_define.record_path) self.notifier = Notifier(self.recoder) print('load detector complete') # 初始化第一帧为全黑图像 self.frame = np.zeros([*self.frame_hw, 3], np.uint8) # 初始化各个检测器的工作线程 self.fire_detect_thread = threading.Thread(target=self.fire_detect_run) self.smoke_detect_thread = threading.Thread(target=self.smoke_detect_run) self.human_detect_thread = threading.Thread(target=self.human_detect_run) self.move_detect_thread = threading.Thread(target=self.move_detect_run) if self.cam_id == -1: self.smart_cam.ctrl_framehw(self.frame_hw) self.smart_cam.ctrl_fps(self.fps)
def dispatch_from_params(self, argv): main_help = 'jmake is a primary tool for JIRA devs.' parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter) self.__register_submodules(parser, MainModule(parser).get_submodules()) self.__discover_help(main_help, parser) if argv[1:]: args = parser.parse_args( [arg for arg in argv[1:] if arg != 'clean' or argv[1] == arg or argv[1] == 'auto-complete']) args.mvn_clean = 'clean' in argv[2:] if args.func.check_branch and not 'JMAKE_DRY' in os.environ: git_branch = GitBranchDiscovery() self.executor.append(git_branch) if not args.mvn_clean: self.executor.append(BranchInconsistencyCheck(git_branch)) self.executor.append_post(BranchInconsistencyMarker(git_branch)) try: args.func(args, self.executor) except Exception as e: self.executor.commands = [ lambda logger : logger.error('Exception occurred during preparing executor: %s' % str(e)) or Callable.success] self.executor.post_commands = [] traceback.print_exc() return self.executor.execute() if args.log_level: try: getattr(LOG, 'set_' + args.log_level)() except AttributeError: LOG.error('Cannot set log level to %s' % args.log_level) return Callable.failure if args.silent: args.func.prevent_post_commands = True if not args.func.prevent_post_commands: timer = ExecutionTimeCallable() self.executor.append_post(timer) if os.getenv('JMAKE_STFU') is None: self.executor.append_post(Notifier(timer)) if args.func.prevent_console_reset: self.executor.perform_console_reset = False if not args.func.prevent_post_diagnostics: self.__append_post_diagnostics() else: parser.print_help() self.__append_post_diagnostics() return self.executor.execute()
def __init__(self, parent=None, name=None, modal=0, fl=0): ImageForm.__init__(self, parent, name, modal, fl) self.comboAlign.insertItem("None") self.notifier = Notifier(parent, 1, args=[self.progressBar]) self.alignList["Left"] = "left" self.alignList["Right"] = "right" self.alignList["Center"] = "center" self.btnUpload.setEnabled(False) self.buttonOk.setEnabled(False) self.http = QHttp() self.connect(self.http, SIGNAL("done(bool)"), self.httpDone) self.connect(self.http, SIGNAL("dataSendProgress (int, int)"), self.httpProgress) self.http2 = QHttp() self.connect(self.http2, SIGNAL("done(bool)"), self.http2Done) self.connect(self.http2, SIGNAL("dataSendProgress (int, int)"), self.httpProgress) for key in self.alignList.keys(): self.comboAlign.insertItem(key)
def init(self): debug("GoogleTranslatorApplet: init().") BasePlasmoid.init(self) self._widget = None self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.notifier = Notifier(self) self.nwmon = NetworkMonitor() if self.nwmon.connected(): self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self.nwmon.status_changed.connect(self.netstate_changed) # Main widget debug("GoogleTranslatorApplet: Creating main widget.") self._widget = GoogleTranslator(self) self._widget.init() self.setGraphicsWidget(self._widget) self.setPopupIcon(self.metadata.pluginName()) self.setGraphicsWidget(self._widget) # Tool tip for panel self.metadata = self.package().metadata() self.tooltipdata = Plasma.ToolTipContent() self.tooltipdata.setMainText(self.metadata.name()) self.tooltipdata.setSubText(self.metadata.description()) self.tooltipdata.setImage(KIcon(self.metadata.pluginName())) Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata) # Only register the tooltip in panels #if (self.formFactor() != Plasma.Planar): if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)): print("GoogleTranslatorApplet: In Panel") Plasma.ToolTipManager.self().registerWidget(self.applet) else: Plasma.ToolTipManager.self().unregisterWidget(self.applet) print("GoogleTranslatorApplet: Not in Panel") self.configChanged()
def _run_application(self): #print 'logic _run_application' #call functions to start up app from here self.load_config() self.set_status_icon() self.connect_to_harvest() self.center_windows(self.timetracker_window, self.preferences_window) self.start_elapsed_timer() if sys.platform != "win32": self._status_button = StatusButton() self._notifier = Notifier('TimeTracker', gtk.STOCK_DIALOG_INFO, self._status_button) self.about_dialog.set_logo(gtk.gdk.pixbuf_new_from_file(media_path + "logo.svg")) return self
def init(self): base.BaseApplet.init(self, needsversion="4.5") if self.hasFailedToLaunch(): return KGlobal.locale().insertCatalog(self.metadata.pluginName()) lang = KGlobal.locale().language() print "Language:", lang print "Translated?", KGlobal.locale().isApplicationTranslatedInto(lang) self._widget = None self.dialog = None self.has_tooltip = False self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.notifier = Notifier(self) self.nwmon = NetworkMonitor() if self.nwmon.connected(): self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self.nwmon.status_changed.connect(self.netstate_changed) # Main widget print("CurrencyConverterApplet: Creating main widget.") self._widget = CurrencyConverter(self) self._widget.init() self.setGraphicsWidget(self._widget) self.setPopupIcon(self.metadata.pluginName()) self.setGraphicsWidget(self._widget) #self.setup_tooltip() self.configChanged() self._widget.updated.connect(self.setup_tooltip)
def __init__(self, elective, test = False, log = False): Notifier.__init__(self, [], test, log) self.sender = "*****@*****.**" self.type = type self.setElective(elective)
def __init__(self, db, table_name): self._db = db self.table_name = table_name self.notifier = Notifier.getInstance()
class SmartCar: # 自动模式 auto_mode = True current_status = '' jpeg_quality = 80 _human_boxes = [] draw_human_boxes = True def __init__(self, *, debug_show=False): self.car_op = CarOp() self.auto_nav_er = AutoNav(self.car_op) # self.orbslam2_connect = OrbSlam2Connector() self.debug_show = debug_show self.human_detect = Yolov3HumanDetector() self.auto_watch_human = AutoWatchHuman(self.car_op) self.recorder = Recorder() self.notifier = Notifier(self.recorder) self.work_thread = Thread(target=self.work_run) self.work_thread.start() self.record_thread = Thread(target=self.record_run) self.record_thread.start() def work_run(self): while True: time.sleep(1 / 3) img = self.get_current_img(only_left=True) if img is None: continue self.human_detect.push_frame(img) boxes = self.human_detect.detect() if len(boxes) > 0: boxes = np.array(boxes, np.float32) self._human_boxes = boxes.copy() self.auto_watch_human.detect(img, boxes) self.notifier.notice(notify_type.type_human, '发现人') self.notifier.do_interest_mark() else: self._human_boxes = [] if self.debug_show: img = self.get_current_img(only_left=True, draw_box=True) img2 = img[:, :, ::-1] cv2.imshow('viewerL', img2) cv2.waitKey(1000 // 60) def record_run(self): while True: time.sleep(1 / 20) img = self.get_current_img(only_left=True) if img is None: continue if self.notifier.can_record: self.recorder.start_video_record(20) else: self.recorder.stop_video_record() self.recorder.next_frame(img) def what_i_need_do(self): p = np.random.uniform(0, 1) if p < 0.1: a = 'patrol' elif p > 0.9: a = 'stop' else: a = 'idle' return a def ctrl_auto_mode(self, b=None): ''' 开启与关闭自动模式 :param b: :return: ''' if b is not None: self.auto_mode = b if self.auto_mode: self.auto_nav_er.start() else: self.auto_nav_er.stop() self.car_op.move_stop() return self.auto_mode def handle_motion_system(self, action=''): if self.auto_mode: print('please close auto mode to use handle mode') return if action == 'forward': self.car_op.move_forward() elif action == 'back': self.car_op.move_back() elif action == 'left': self.car_op.move_left() elif action == 'right': self.car_op.move_right() elif action == 'stop': self.car_op.move_stop() def handle_servohead(self, action=''): if self.auto_mode: print('please close auto mode to use handle mode') return if action == 'turn_left': self.car_op.ctrl_servohead('turn_left') elif action == 'turn_right': self.car_op.ctrl_servohead('turn_right') elif action == 'turn_up': self.car_op.ctrl_servohead('turn_up') elif action == 'turn_down': self.car_op.ctrl_servohead('turn_down') elif action == 'watch_forward': self.car_op.ctrl_servohead('forward') elif action == 'watch_left': self.car_op.ctrl_servohead('left') elif action == 'watch_right': self.car_op.ctrl_servohead('right') elif action == 'watch_top': self.car_op.ctrl_servohead('top') def run(self): while True: time.sleep(1.) # if imgLR is not None: # self.orbslam2_connect.get_pos(imgLR) if self.car_op.offline: print('offline...') continue if not self.auto_mode: print('handling...') continue # 自动控制 cmd_id = self.what_i_need_do() if self.current_status != cmd_id: self.current_status = cmd_id if cmd_id == 'idle': print('idle...') elif cmd_id == 'patrol': print('patrol...') self.auto_nav_er.start() self.auto_nav_er.to('any') elif cmd_id == 'stop': print('stop...') self.auto_nav_er.to('neighbor') else: raise AttributeError('Please check cmd code !') def get_current_img(self, only_left=True, draw_box=False): ''' 返回当前图像,如果没有初始化成功,返回None :return: np.array ''' img = self.car_op.get_cam_img() if img is None: return None if only_left: img = np.split(img, 2, 1)[0] if draw_box: human_boxes = self._human_boxes.copy() for box in human_boxes: cv2.rectangle(img, tuple(box[:2]), tuple(box[2:]), (0, 255, 0)) return img def get_current_jpg(self, only_left=True): ''' 返回当前图像的JPEG编码格式的字节串,如果没有初始化成功,返回None :return: None or bytes ''' img = self.get_current_img(only_left, draw_box=self.draw_human_boxes) if img is not None: img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) _, data = cv2.imencode( '.jpg', img, (cv2.IMWRITE_JPEG_QUALITY, self.jpeg_quality)) return bytes(data) return None
def refresh(self, json): self.thread = json try: debug = DebugLog("debug.log") except: raise for posts in self.thread['posts']: try: # skip if record found in dictionary no = posts['no'] # Post is OP try: if posts['resto'] is 0: self.tdict['OP'] = {'no': posts['no'], 'sub': posts['sub'].encode('utf-8'), 'semantic_url': posts['semantic_url'].encode('utf-8')} except Exception as e: debug.msg("Exception:" + e.msg() + "\n") raise if no in self.tdict: continue name = posts['name'] time = datetime.datetime.fromtimestamp(posts['time']).strftime('%H:%M') except: continue curses.use_default_colors() for i in range(0, curses.COLORS): # @UndefinedVariable curses.init_pair(i + 1, i, -1) # assign color to post number color = randint(2, 255) try: country = posts['country'] except: country = "" try: com = posts['com'] com = re.sub('<br>', ' ', com) refposts = "" refposts = re.findall('>>(\d+)', com) com = re.sub('>>(\d+)', '\g<1> ', com) com = re.sub(''', '\'', com) com = re.sub('>', '>', com) com = re.sub('<', '<', com) com = re.sub('"', '"', com) com = re.sub('<[^<]+?>', '', com) except: com = "[File only]" try: trip = posts['trip'] except: trip = "" self.tdict[no] = {'country':country, 'name':name, 'time':time, 'com':com, 'trip':trip, 'color':color} # try: # line = u' '.join((time, ">>" + str(no), country, "<" + name + ">", com)).encode('utf-8') # except: # raise try: self.bp.addstr("", curses.color_pair(color)) self.bp.addstr(time) self.bp.addstr(" >>" + str(no), curses.color_pair(color)) self.bp.addstr(" " + country) if re.match(self.nickname, name) is not None: self.bp.addstr(" <" + self.nickname + "> ", curses.A_BOLD) else: self.bp.addstr(" <" + name.encode('utf8') + "> ") #self.bp.addstr(com.encode('utf8')) comlist = com.split() try: for word in comlist: if word not in refposts: self.bp.addstr(u''.join((word + " ")).encode('utf8')) else: # Comment and reference color encoding try: refcolor = self.tdict[int(word)]['color'] self.bp.addstr(">>" + word + " ", curses.color_pair(refcolor)) # if reference points to nickname, higligt the name if re.match(self.tdict[int(word)]['name'], self.nickname): self.bp.addstr("(You) ", curses.A_BOLD | curses.color_pair(221)) Notifier.send(com) # if re.match(word, threadno): # self.bp.addstr("(OP) ", curses.A_BOLD | curses.color_pair(197)) except: self.bp.addstr(word) except: self.bp.addstr("[File only]") except: raise self.bp.addstr("\n") try: self.title = self.tdict['OP']['sub'] except Exception as e: debug.msg("Couldn't set title" + str(e) + "\n") pass
def __init__(self, cnf): Notifier.__init__(self, {'filename': '%Y-%m-%d.log', 'mode': 'a'}) self.C.update(cnf) self.file = self.name = None
class ImageForm_Impl(ImageForm): alignList = {} def __init__(self, parent=None, name=None, modal=0, fl=0): ImageForm.__init__(self, parent, name, modal, fl) self.comboAlign.insertItem("None") self.notifier = Notifier(parent, 1, args=[self.progressBar]) self.alignList["Left"] = "left" self.alignList["Right"] = "right" self.alignList["Center"] = "center" self.btnUpload.setEnabled(False) self.buttonOk.setEnabled(False) self.http = QHttp() self.connect(self.http, SIGNAL("done(bool)"), self.httpDone) self.connect(self.http, SIGNAL("dataSendProgress (int, int)"), self.httpProgress) self.http2 = QHttp() self.connect(self.http2, SIGNAL("done(bool)"), self.http2Done) self.connect(self.http2, SIGNAL("dataSendProgress (int, int)"), self.httpProgress) for key in self.alignList.keys(): self.comboAlign.insertItem(key) def ImageArkPostData(sel, filename): return ( [("MAX_FILE_SIZE", "512000")], [("userfile", os.path.basename(filename), open(filename, "rb").read())], "www.imageark.net", "/upload.php", "http://www.imageark.net", ) def ImageShackPostData(self, filename): return ( [], [("fileupload", os.path.basename(filename), open(filename, "rb").read())], "imageshack.us", "/index2.php", "http://imageshack.us/index2.php", ) def BeginImageUpload(self, filename, GetPostData, http): (fields, files, host, path, referer) = GetPostData(filename) content_type, body = encode_multipart_formdata(fields, files) Req = QHttpRequestHeader("POST", path) Req.setContentType(content_type) Req.setValue("Host", host) Req.setValue("Content-Length", str(len(body))) Req.setValue("Referer", referer) http.setHost(host) http.request(Req, body) def httpProgress(self, done, total): self.notifier.progress(done, total) def http2Done(self, error): qs = QString(self.http2.readAll()) match = self.imgre.search(unicode(qs)) if error: QMessageBox.warning(self, "Warning", "Cannot upload! Error:" + self.http2.error()) else: if match: self.editUrl.setText(self.image) self.editThumb.setText(match.group(1)) QMessageBox.information(self, "Info", "Image successfully uploaded!") else: QMessageBox.warning(self, "Warning", "Cannot upload the thumbnail image file!") self.http2.closeConnection() def httpDone(self, error): qs = QString(self.http.readAll()) match = self.imgre.search(unicode(qs)) if error: QMessageBox.warning(self, "Warning", "Cannot upload! Error:" + self.http.error()) else: if match: self.image = match.group(1) if self.thumbfile: # do second upload if self.chkShack.isChecked(): self.BeginImageUpload(self.thumbfile, self.ImageShackPostData, self.http2) elif self.chkArk.isChecked(): self.BeginImageUpload(self.thumbfile, self.ImageArkPostData, self.http2) else: # no need to upload second QMessageBox.information(self, "Info", "Image successfully uploaded!") self.editUrl.setText(self.image) else: if self.thumbfile: os.unlink(thumbfile) QMessageBox.warning(self, "Warning", "Cannot upload the image file!") self.http.closeConnection() def imagetag(self): imagetag = "" image = str(self.editUrl.text()) thumb = str(self.editThumb.text()) title = str(self.editTitle.text()) if str(self.editWidth.text()): width = int(str(self.editWidth.text())) else: width = None if str(self.editBorder.text()): border = int(str(self.editBorder.text())) else: border = None if str(self.editHeight.text()): height = int(str(self.editHeight.text())) else: height = None if not image: return None else: if thumb: imagetag += "<a href='%s'><img src='%s'" % (image, thumb) else: imagetag += "<img src='%s'" % image if width: imagetag += " width='%d'" % width if height: imagetag += " height='%d'" % height if border: imagetag += " border='%d'" % border if title: imagetag += " alt='%s'" % title if self.alignList.has_key("%s" % self.comboAlign.currentText()): align = self.alignList["%s" % self.comboAlign.currentText()] imagetag += " align='%s'" % align imagetag += ">" if thumb: imagetag += "</a>" return imagetag def btnRefresh_clicked(self): if str(self.editUrl.text()): try: img = urllib2.urlopen(str(self.editUrl.text())).read() pic = QPixmap() pic.loadFromData(img) if not str(self.editWidth.text()): self.editWidth.setText(str(pic.width())) if not str(self.editHeight.text()): self.editHeight.setText(str(pic.height())) self.previewImage.setPixmap(pic) except: QMessageBox.warning(self, "Warning", "Cannot open the image url!") def editUrl_textChanged(self, a0): self.buttonOk.setEnabled(str(self.editUrl.text()) != "") def chk_stateChanged(self, a0): if self.chkUrl.isChecked(): self.widgetStack2.raiseWidget(self.pageUrl) self.buttonOk.setEnabled(str(self.editUrl.text()) != "") else: self.widgetStack2.raiseWidget(self.pageUpload) self.buttonOk.setEnabled(False) def chkThumb_toggled(self, a0): pass imgre = re.compile("\[img\](.*?)\[/img\]", re.IGNORECASE) def __generateThumb(self, filename): if not self.chkThumb.isChecked(): return None try: p = self.previewImage import tempfile fn = tempfile.mkstemp("%s" % os.path.basename(filename))[1] w = p.width() h = p.height() if w > 120: w = 120 if h > 120: h = 120 # if the image is smaller than the thumb, don't create the thumb if h < 120 and w < 120: return None os.system("convert -geometry %dx%d %s %s" % (w, h, filename, fn)) if os.path.exists(fn): return fn except: return None def btnUpload_clicked(self): self.image = None self.thumbfile = self.__generateThumb(str(self.editFile.text())) if self.chkShack.isChecked(): self.BeginImageUpload(str(self.editFile.text()), self.ImageShackPostData, self.http) elif self.chkArk.isChecked(): self.BeginImageUpload(str(self.editFile.text()), self.ImageArkPostData, self.http) def __open(self, txt, btn): filename = str( QFileDialog.getOpenFileName( None, "Images (*.png *.jpg *.gif)", self, "open image file", "Choose a file to open" ) ) txt.setText(filename) ok = False try: pic = QPixmap() if pic.loadFromData(open(filename, "rb").read()): ok = True if not str(self.editWidth.text()): self.editWidth.setText(str(pic.width())) if not str(self.editHeight.text()): self.editHeight.setText(str(pic.height())) self.previewImage.setPixmap(pic) btn.setEnabled(True) except: ok = False if not ok: QMessageBox.warning(self, "Warning", "Cannot open the image file!") self.previewImage.setPixmap(QPixmap()) btn.setEnabled(False) def editFile_textChanged(self, a0): self.btnUpload.setEnabled(os.path.exists(str(a0))) def btnOpen_clicked(self): self.__open(self.editFile, self.btnUpload)
except ValueError, err: print "Error: %s" % (err) sys.exit(1) except: print "notify: Error loading configuration." sys.exit(1) for apath in CONF['path'].split(':'): if os.path.isdir(apath): sys.path.append(apath) from Notifier import Notifier recp = '' if dryrun else args[0] msg = " ".join(args[1:]) for name in set(re.split('[\s,]+', CONF['notifier'])): try: cnf = CONF[name] klass = cnf['class'] if 'class' in cnf else name notifier = Notifier.new(klass, cnf) resp = 'Test success' if dryrun else notifier.notify(recp, msg) if debug: print("%s('%s', '%s') = %s\n" % (name, recp, msg, resp)) except Exception as ex: # Call all exceptions so that every configured notifier is visited. err = "%s %s = %s -- message = %s" % (time.strftime( "%Y-%m-%dT%H:%M:%S"), ex.__class__.__name__, str(ex), msg) try: flog = Notifier.new("Logfile", CONF['errorlog']) flog.notify(recp, err) except Exception as ex: sys.stderr.write("%s\n" % (err)) sys.exit(0)
CONF.update(json.load(open(conf, 'r'), 'utf-8')) except ValueError, err: print "Error: %s" % (err) sys.exit(1) except: print "notify: Error loading configuration." sys.exit(1) for apath in CONF['path'].split(':'): if os.path.isdir(apath): sys.path.append(apath) from Notifier import Notifier recp = '' if dryrun else args[0] msg = " ".join(args[1:]) for name in set(re.split('[\s,]+', CONF['notifier'])): try: cnf = CONF[name] klass = cnf['class'] if 'class' in cnf else name notifier = Notifier.new(klass, cnf) resp = 'Test success' if dryrun else notifier.notify(recp, msg) if debug: print("%s('%s', '%s') = %s\n" % (name, recp, msg, resp)) except Exception as ex: # Call all exceptions so that every configured notifier is visited. err = "%s %s = %s -- message = %s" % (time.strftime("%Y-%m-%dT%H:%M:%S"), ex.__class__.__name__, str(ex), msg) try: flog = Notifier.new("Logfile", CONF['errorlog']) flog.notify(recp, err) except Exception as ex: sys.stderr.write("%s\n" % (err)) sys.exit(0)
print lectura ch = p.check() print ch t = Text("/home/oscargcervantes/Issues_Servers/AIX 5.3 Upgrades") rd = t.read() print rd r = Dir_Reader("/home/oscargcervantes/Issues_Servers") files_found = r.read() print files_found time.sleep(5) #Notifier Threads n = Notifier("1","Thread-1","/home/oscargcervantes/Issues_Servers") #n.setDaemon(True) n.start() m = Notifier("2","Thread-2","/home/oscargcervantes/CourseInformation") #m.setDaemon(True) m.start() time.sleep(5) m._Thread__stop() n._Thread__stop() print "Ending Main Process" from ODSReader import *
class SmartCam: # 帧大小 frame_hw = [480, 640] # 帧速率 fps = 30 # 图像质量 jpeg_quality = 80 need_quit = False # 快速变量,如果发现xx将会设定以下变量为True,没有则False has_move = False has_smoke = False has_fire = False has_human = False _is_start = False _recording_frame_hw = None _human_boxes = [] draw_human_boxes = True def __init__(self, cam_id=0, *, debug_show=False): ''' 初始化函数 :param cam_id: 当cam_id为-1时,将会使用IP摄像机,如果为其他值,例如1,将会使用本机的1号摄像头 :param debug_show: 是否启动调试输出,为True时,将会启动debug模式,并且会显示所有子模块的处理情况的显示输出 ''' self.debug_show = debug_show print('initing cam') self.cam_id = cam_id if cam_id == -1: # 使用IP摄像头 self.smart_cam = smart_cam_receiver() else: # 打开本地摄像头失败时,将会抛出异常 self.cam = imageio.get_reader('<video%d>' % cam_id, fps=self.fps) print('open cam complete') print('load detector') # 载入各种检测器 self.fire_detector = FireDetector(debug_show=debug_show) self.smoke_detector = SmokeDetector() self.diff_move_detector = DiffMoveDetector(debug_show=debug_show) self.human_detector = HumanDetector(const_define.yolo_net_file, const_define.yolo_weights_file, debug_show=debug_show) self.recoder = Recorder(const_define.record_path) self.notifier = Notifier(self.recoder) print('load detector complete') # 初始化第一帧为全黑图像 self.frame = np.zeros([*self.frame_hw, 3], np.uint8) # 初始化各个检测器的工作线程 self.fire_detect_thread = threading.Thread(target=self.fire_detect_run) self.smoke_detect_thread = threading.Thread(target=self.smoke_detect_run) self.human_detect_thread = threading.Thread(target=self.human_detect_run) self.move_detect_thread = threading.Thread(target=self.move_detect_run) if self.cam_id == -1: self.smart_cam.ctrl_framehw(self.frame_hw) self.smart_cam.ctrl_fps(self.fps) def load(self, path=const_define.main_config_path): ''' 载入配置函数,可以动态载入,载入配置时将会马上使用新的配置 :param path: :return: ''' print('loading config') # 载入配置时,应当暂停部分操作 cfg = json.load(open(path, 'r')) self.frame_hw = cfg['frame_hw'] self.fps = cfg['fps'] self.jpeg_quality = cfg['jpeg_quality'] self.fire_detector.load(cfg['FireDetector']) self.smoke_detector.load(cfg['SmokeDetector']) self.diff_move_detector.load(cfg['DiffMoveDetector']) self.human_detector.load(cfg['HumanDetector']) self.notifier.load(cfg['Notifier']) if self.cam_id == -1: self.smart_cam.load(cfg['cam']) self.smart_cam.ctrl_framehw(self.frame_hw) self.smart_cam.ctrl_fps(self.fps) self.smart_cam.ctrl_jpeg_quality(self.jpeg_quality) print('load config success') def save(self, path='config.json'): ''' 保存配置到指定文件,格式为json :param path: 要保存到的配置文件路径 :return: 同时也会返回一份配置文件字典,类型为dict ''' print('saving config') cfg = { 'frame_hw': self.frame_hw, 'fps': self.fps, 'jpeg_quality': self.jpeg_quality, 'FireDetector': self.fire_detector.save(), 'SmokeDetector': self.smoke_detector.save(), 'DiffMoveDetector': self.diff_move_detector.save(), 'HumanDetector': self.human_detector.save(), 'Notifier': self.notifier.save() } if self.cam_id == -1: cfg.update({'cam': self.smart_cam.save()}) json.dump(cfg, open(path, 'w')) print('save config success') return cfg def fire_detect_run(self): ''' 火焰监测线程 :return: ''' while not self.need_quit: self.fire_detector.push_frame(self.frame) bboxes = self.fire_detector.detect() if len(bboxes) > 0: self.notifier.notice(notify_type.type_fire, 'found fire') self.has_fire = True else: self.has_fire = False time.sleep(1/self.fps) def smoke_detect_run(self): ''' 烟雾检测线程 :return: ''' if self.cam_id == -1: while not self.need_quit: b = self.smart_cam.found_smoke if b: self.notifier.notice(notify_type.type_smoke, 'found smoke') self.has_smoke = True else: self.has_smoke = False time.sleep(1 / self.fps) else: self.smoke_detector.start() while not self.need_quit: b = self.smoke_detector.detect() if b: self.notifier.notice(notify_type.type_smoke, 'found smoke') self.has_smoke = True else: self.has_smoke = False time.sleep(1 / self.fps) self.smoke_detector.stop() self.smoke_detector.cleanup() def move_detect_run(self): ''' 画面变动检测线程 :return: ''' while not self.need_quit: self.diff_move_detector.push_frame(self.frame) bboxes = self.diff_move_detector.detect() if len(bboxes) > 0: self.notifier.notice(notify_type.type_move, 'found move') self.has_move = True else: self.has_move = False time.sleep(1 / self.fps) def human_detect_run(self): ''' 人类检测线程 :return: ''' while not self.need_quit: self.human_detector.push_frame(self.frame) bboxes = self.human_detector.detect() if len(bboxes) > 0: self._human_boxes = bboxes self.notifier.notice(notify_type.type_human, 'found human') self.has_human = True else: self._human_boxes = [] self.has_human = False time.sleep(1 / self.fps) # def noise_detect_run(self): # while not self.need_quit: # # 尚未完成异常噪音检测 # time.sleep(1 / self.fps) def cleanup(self): ''' 退出程序时调用,安全清理内存 :return: ''' self.need_quit = True self.fire_detect_thread.join() self.smoke_detect_thread.join() self.human_detect_thread.join() self.move_detect_thread.join() self.smart_cam.cleanup() self.notifier.cleanup() def run(self): ''' 主消息循环,需要手动调用,此循环不会退出 :return: ''' print('start watch') while not self.need_quit: # 检查摄像机id,如果是-1代表使用远程摄像头 if self.cam_id == -1: # 从IP相机获得图像数据 if self.smart_cam.offline: print('camera offline') time.sleep(1) img = self.smart_cam.get_cam_img() if img is not None: # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.frame = img else: # 从本地相机获取图像数据 img = self.cam.get_next_data() self.frame = img # 第一次循环时,将会启动各个探测模块的线程,然后会设定 _is_start 标志,避免再次进入 if not self._is_start: self._is_start = True self.fire_detect_thread.start() self.smoke_detect_thread.start() self.human_detect_thread.start() self.move_detect_thread.start() # 是否可以录像由 notifier 模块的 can_record 变量控制 # 为 True 时代表可以开始录像,为 False 时代表应停止录像 if self.notifier.can_record: # 如果录像中途切换了分辨率,关闭上一个录像后,再次启动 if self._recording_frame_hw != self.frame_hw: self.recoder.stop_video_record() self._recording_frame_hw = self.frame_hw self.recoder.start_video_record(self.fps) self.recoder.next_frame(self.frame) else: self.recoder.stop_video_record() # 如果是debug模式,则显示相关信息 if not self.debug_show: time.sleep(1 / self.fps) else: cv2.imshow('main', sc.frame) cv2.waitKey(1000 // self.fps) def cam_turn_left(self): ''' 每次调用此函数时,将会使IP相机的云台向左旋转0.5个单位 如果没有连接IP相机,此函数将会无效 :return: ''' if self.cam_id == -1: self.smart_cam.ctrl_cam_angle('left') else: print('Unsupport normal cam') def cam_turn_right(self): ''' 每次调用此函数时,将会使IP相机的云台向右旋转0.5个单位 如果没有连接IP相机,此函数将会无效 :return: ''' if self.cam_id == -1: self.smart_cam.ctrl_cam_angle('right') else: print('Unsupport normal cam') def get_current_img(self): ''' 返回当前图像,如果没有初始化成功,返回None :return: np.array ''' return self.frame.copy() def get_current_jpg(self): ''' 返回当前图像的JPEG编码格式的字节串,如果没有初始化成功,返回None :return: None or bytes ''' img = self.get_current_img() human_boxes = self._human_boxes.copy() if img is not None: if self.draw_human_boxes: for box in human_boxes: cv2.rectangle(img, tuple(box[:2]), tuple(box[2:]), (0, 255, 0)) img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) _, data = cv2.imencode('.jpg', img, (cv2.IMWRITE_JPEG_QUALITY, self.jpeg_quality)) return bytes(data) return None def get_recent_msg(self): return list(self.notifier.get_recent_msg())
def __init__(self, session, test = False, log = False): Notifier.__init__(self, [], test, log) self.sender = "*****@*****.**" self.type = type self.setFixed(session)
def __init__(self, config, logger): super(MainWidget, self).__init__() self.config = config self.logger = logger self.imageDir = self.config.get("display", "image_dir", fallback="images") self.alarm = None self.route = ([], None, None) self.seenPager = False self.seenXml = False self.seenJson = False self.reportDone = False self.alarmDateTime = None self.forwarder = Forwarder(config, logger) self.notifier = Notifier(config, logger) self.sound = Sound(config, logger) self.gpioControl = GpioControl(config, logger) self.tts = TextToSpeech(config, logger) self.reportTimer = QTimer(self) self.reportTimer.setInterval( \ self.config.getint("report", "timeout", fallback = 60) * 1000) self.reportTimer.setSingleShot(True) self.reportTimer.timeout.connect(self.generateReport) self.simTimer = QTimer(self) self.simTimer.setInterval(10000) self.simTimer.setSingleShot(True) self.simTimer.timeout.connect(self.simTimeout) #self.simTimer.start() self.idleTimer = QTimer(self) idleTimeout = self.config.getint("display", "idle_timeout", fallback=30) self.idleTimer.setInterval(idleTimeout * 60000) self.idleTimer.setSingleShot(True) self.idleTimer.timeout.connect(self.idleTimeout) self.screenTimer = QTimer(self) screenTimeout = self.config.getint("display", "screen_timeout", fallback=0) self.screenTimer.setInterval(screenTimeout * 60000) self.screenTimer.setSingleShot(True) self.screenTimer.timeout.connect(self.screenTimeout) if self.screenTimer.interval() > 0: self.screenTimer.start() # Presence ----------------------------------------------------------- self.presenceTimer = QTimer(self) self.presenceTimer.setInterval(1000) self.presenceTimer.setSingleShot(False) self.presenceTimer.timeout.connect(self.checkPresence) self.presenceTimer.start() self.switchOnTimes = [] self.switchOffTimes = [] if self.config.has_section('presence'): onRe = re.compile('on[0-9]+') offRe = re.compile('off[0-9]+') for key, value in self.config.items('presence'): ma = onRe.fullmatch(key) if ma: tup = self.parsePresence(key, value) if tup: self.switchOnTimes.append(tup) continue ma = offRe.fullmatch(key) if ma: tup = self.parsePresence(key, value) if tup: self.switchOffTimes.append(tup) continue self.updateNextSwitchTimes() # Appearance --------------------------------------------------------- self.logger.info('Setting up X server...') subprocess.call(['xset', 's', 'off']) subprocess.call(['xset', 's', 'noblank']) subprocess.call(['xset', 's', '0', '0']) subprocess.call(['xset', '-dpms']) self.move(0, 0) self.resize(1920, 1080) self.setWindowTitle('Alarmdisplay') self.setStyleSheet(""" font-size: 60px; background-color: rgb(0, 34, 44); color: rgb(2, 203, 255); font-family: "DejaVu Sans"; """) # Sub-widgets -------------------------------------------------------- layout = QVBoxLayout(self) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) self.stackedWidget = QStackedWidget(self) layout.addWidget(self.stackedWidget) self.idleWidget = IdleWidget(self) self.idleWidget.start() self.stackedWidget.addWidget(self.idleWidget) self.alarmWidget = AlarmWidget(self) self.stackedWidget.addWidget(self.alarmWidget) self.errorWidget = QLabel(self) self.errorWidget.setGeometry(self.contentsRect()) self.errorWidget.setAlignment(Qt.AlignCenter | Qt.AlignVCenter) self.errorWidget.setStyleSheet(""" background-color: transparent; font-size: 20px; color: red; """) # Shortcuts ---------------------------------------------------------- action = QAction(self) action.setShortcut(QKeySequence("1")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleJugend) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("2")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleEngels) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("3")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleSack) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("4")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleWolfsgrabenPager) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("5")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleWolfsgrabenMail) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("6")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleWald) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("7")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleStadtwerkePager) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("8")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleLebenshilfe) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("9")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleHuissen) self.addAction(action) # Threads ------------------------------------------------------------ self.receiverThread = QThread() self.alarmReceiver = AlarmReceiver(self.config, self.logger) self.alarmReceiver.receivedAlarm.connect(self.receivedPagerAlarm) self.alarmReceiver.finished.connect(self.receiverThread.quit) self.alarmReceiver.errorMessage.connect(self.receiverError) self.alarmReceiver.moveToThread(self.receiverThread) self.receiverThread.started.connect(self.alarmReceiver.receive) self.receiverThread.start() self.websocketReceiverThread = QThread() self.websocketReceiver = WebsocketReceiver(self.config, self.logger) self.websocketReceiver.receivedAlarm.connect( \ self.receivedWebsocketAlarm) self.websocketReceiver.finished.connect( \ self.websocketReceiverThread.quit) self.websocketReceiver.moveToThread(self.websocketReceiverThread) self.websocketReceiverThread.started.connect( \ self.websocketReceiver.receive) self.websocketReceiverThread.start() if self.websocketReceiver.status: self.statusWidget = StatusWidget(self) layout.addWidget(self.statusWidget) self.websocketReceiver.receivedStatus.connect( \ self.statusWidget.setStatus) if self.config.has_section('email') and \ self.config.get("email", "imap_host", fallback = ''): from ImapMonitor import ImapMonitor self.imapThread = QThread() self.imapMonitor = ImapMonitor(self.config, self.logger) self.imapMonitor.receivedAlarm.connect(self.receivedXmlAlarm) self.imapMonitor.moveToThread(self.imapThread) self.imapMonitor.finished.connect(self.imapThread.quit) self.imapThread.started.connect(self.imapMonitor.start) self.imapThread.start() self.socketListener = SocketListener(self.logger) self.socketListener.pagerAlarm.connect(self.receivedPagerAlarm) self.socketListener.xmlAlarm.connect(self.receivedXmlAlarm) self.cecThread = QThread() self.cecThread.start() self.cecCommand = CecCommand(self.logger) self.cecCommand.moveToThread(self.cecThread) self.report = AlarmReport(self.config, self.logger) try: self.notifier.startup() except: self.logger.error('Startup notification failed:', exc_info=True) self.logger.info('Setup finished.')
class MainWidget(QWidget): def __init__(self, config, logger): super(MainWidget, self).__init__() self.config = config self.logger = logger self.imageDir = self.config.get("display", "image_dir", fallback="images") self.alarm = None self.route = ([], None, None) self.seenPager = False self.seenXml = False self.seenJson = False self.reportDone = False self.alarmDateTime = None self.forwarder = Forwarder(config, logger) self.notifier = Notifier(config, logger) self.sound = Sound(config, logger) self.gpioControl = GpioControl(config, logger) self.tts = TextToSpeech(config, logger) self.reportTimer = QTimer(self) self.reportTimer.setInterval( \ self.config.getint("report", "timeout", fallback = 60) * 1000) self.reportTimer.setSingleShot(True) self.reportTimer.timeout.connect(self.generateReport) self.simTimer = QTimer(self) self.simTimer.setInterval(10000) self.simTimer.setSingleShot(True) self.simTimer.timeout.connect(self.simTimeout) #self.simTimer.start() self.idleTimer = QTimer(self) idleTimeout = self.config.getint("display", "idle_timeout", fallback=30) self.idleTimer.setInterval(idleTimeout * 60000) self.idleTimer.setSingleShot(True) self.idleTimer.timeout.connect(self.idleTimeout) self.screenTimer = QTimer(self) screenTimeout = self.config.getint("display", "screen_timeout", fallback=0) self.screenTimer.setInterval(screenTimeout * 60000) self.screenTimer.setSingleShot(True) self.screenTimer.timeout.connect(self.screenTimeout) if self.screenTimer.interval() > 0: self.screenTimer.start() # Presence ----------------------------------------------------------- self.presenceTimer = QTimer(self) self.presenceTimer.setInterval(1000) self.presenceTimer.setSingleShot(False) self.presenceTimer.timeout.connect(self.checkPresence) self.presenceTimer.start() self.switchOnTimes = [] self.switchOffTimes = [] if self.config.has_section('presence'): onRe = re.compile('on[0-9]+') offRe = re.compile('off[0-9]+') for key, value in self.config.items('presence'): ma = onRe.fullmatch(key) if ma: tup = self.parsePresence(key, value) if tup: self.switchOnTimes.append(tup) continue ma = offRe.fullmatch(key) if ma: tup = self.parsePresence(key, value) if tup: self.switchOffTimes.append(tup) continue self.updateNextSwitchTimes() # Appearance --------------------------------------------------------- self.logger.info('Setting up X server...') subprocess.call(['xset', 's', 'off']) subprocess.call(['xset', 's', 'noblank']) subprocess.call(['xset', 's', '0', '0']) subprocess.call(['xset', '-dpms']) self.move(0, 0) self.resize(1920, 1080) self.setWindowTitle('Alarmdisplay') self.setStyleSheet(""" font-size: 60px; background-color: rgb(0, 34, 44); color: rgb(2, 203, 255); font-family: "DejaVu Sans"; """) # Sub-widgets -------------------------------------------------------- layout = QVBoxLayout(self) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) self.stackedWidget = QStackedWidget(self) layout.addWidget(self.stackedWidget) self.idleWidget = IdleWidget(self) self.idleWidget.start() self.stackedWidget.addWidget(self.idleWidget) self.alarmWidget = AlarmWidget(self) self.stackedWidget.addWidget(self.alarmWidget) self.errorWidget = QLabel(self) self.errorWidget.setGeometry(self.contentsRect()) self.errorWidget.setAlignment(Qt.AlignCenter | Qt.AlignVCenter) self.errorWidget.setStyleSheet(""" background-color: transparent; font-size: 20px; color: red; """) # Shortcuts ---------------------------------------------------------- action = QAction(self) action.setShortcut(QKeySequence("1")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleJugend) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("2")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleEngels) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("3")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleSack) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("4")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleWolfsgrabenPager) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("5")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleWolfsgrabenMail) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("6")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleWald) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("7")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleStadtwerkePager) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("8")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleLebenshilfe) self.addAction(action) action = QAction(self) action.setShortcut(QKeySequence("9")) action.setShortcutContext(Qt.ApplicationShortcut) action.triggered.connect(self.exampleHuissen) self.addAction(action) # Threads ------------------------------------------------------------ self.receiverThread = QThread() self.alarmReceiver = AlarmReceiver(self.config, self.logger) self.alarmReceiver.receivedAlarm.connect(self.receivedPagerAlarm) self.alarmReceiver.finished.connect(self.receiverThread.quit) self.alarmReceiver.errorMessage.connect(self.receiverError) self.alarmReceiver.moveToThread(self.receiverThread) self.receiverThread.started.connect(self.alarmReceiver.receive) self.receiverThread.start() self.websocketReceiverThread = QThread() self.websocketReceiver = WebsocketReceiver(self.config, self.logger) self.websocketReceiver.receivedAlarm.connect( \ self.receivedWebsocketAlarm) self.websocketReceiver.finished.connect( \ self.websocketReceiverThread.quit) self.websocketReceiver.moveToThread(self.websocketReceiverThread) self.websocketReceiverThread.started.connect( \ self.websocketReceiver.receive) self.websocketReceiverThread.start() if self.websocketReceiver.status: self.statusWidget = StatusWidget(self) layout.addWidget(self.statusWidget) self.websocketReceiver.receivedStatus.connect( \ self.statusWidget.setStatus) if self.config.has_section('email') and \ self.config.get("email", "imap_host", fallback = ''): from ImapMonitor import ImapMonitor self.imapThread = QThread() self.imapMonitor = ImapMonitor(self.config, self.logger) self.imapMonitor.receivedAlarm.connect(self.receivedXmlAlarm) self.imapMonitor.moveToThread(self.imapThread) self.imapMonitor.finished.connect(self.imapThread.quit) self.imapThread.started.connect(self.imapMonitor.start) self.imapThread.start() self.socketListener = SocketListener(self.logger) self.socketListener.pagerAlarm.connect(self.receivedPagerAlarm) self.socketListener.xmlAlarm.connect(self.receivedXmlAlarm) self.cecThread = QThread() self.cecThread.start() self.cecCommand = CecCommand(self.logger) self.cecCommand.moveToThread(self.cecThread) self.report = AlarmReport(self.config, self.logger) try: self.notifier.startup() except: self.logger.error('Startup notification failed:', exc_info=True) self.logger.info('Setup finished.') #------------------------------------------------------------------------- def parsePresence(self, key, value): dateRe = re.compile('(\S+)\s(\d+):(\d+)') ma = dateRe.fullmatch(value) if not ma: logger.error("Invalid date spec for %s: %s", key, value) return hour = int(ma.group(2)) if hour >= 24: logger.error("Invalid hour in %s: %s", key, hour) return minute = int(ma.group(3)) if minute >= 60: logger.error("Invalid minute in %s: %s", key, minute) return try: tm = time.strptime(ma.group(1), '%a') except: logger.error("Invalid week day in %s: %s", key, ma.group(1)) return weekDay = tm.tm_wday return (weekDay, hour, minute) def updateNextSwitchTimes(self): self.nextSwitchOn = self.findNextEvent(self.switchOnTimes) self.logger.info("Next switch on: %s", self.nextSwitchOn) self.nextSwitchOff = self.findNextEvent(self.switchOffTimes) self.logger.info("Next switch off: %s", self.nextSwitchOff) def findNextEvent(self, tups): nextDt = None now = datetime.datetime.now() for tup in tups: date = now.date() dayDiff = (tup[0] - date.weekday() + 7) % 7 date = date + datetime.timedelta(days=dayDiff) dt = datetime.datetime(date.year, date.month, date.day, tup[1], tup[2]) if dt < now: dt = dt + datetime.timedelta(days=7) if not nextDt or nextDt > dt: nextDt = dt return nextDt def checkPresence(self): now = datetime.datetime.now() update = False if self.nextSwitchOn and now >= self.nextSwitchOn: update = True self.cecCommand.switchOn() elif self.nextSwitchOff and now >= self.nextSwitchOff: update = True # only switch off, if no alarm active alarm = self.idleTimer.isActive() or self.screenTimer.isActive() if not alarm: self.cecCommand.switchOff() if update: self.updateNextSwitchTimes() #------------------------------------------------------------------------- def receivedPagerAlarm(self, pagerStr): self.logger.info('Received pager alarm: %s', repr(pagerStr)) alarm = Alarm(self.config) alarm.fromPager(pagerStr, self.logger) try: self.notifier.pager(pagerStr) except: self.logger.error('Pager notification failed:', exc_info=True) self.processAlarm(alarm) #------------------------------------------------------------------------- def receiverError(self, errorMessage): self.errorWidget.setText(errorMessage) #------------------------------------------------------------------------- def receivedWebsocketAlarm(self, data): self.logger.info('Received websocket alarm: %s', repr(data)) alarm = Alarm(self.config) try: alarm.fromAlamos(data, self.logger) except: self.logger.error('Failed to process websocket alarm:', exc_info=True) return self.processAlarm(alarm) #------------------------------------------------------------------------- def receivedXmlAlarm(self, xmlContent): self.logger.info('Received XML alarm.') alarm = Alarm(self.config) try: alarm.fromXml(xmlContent, self.logger) except: self.logger.error('Failed to parse XML:', exc_info=True) return self.processAlarm(alarm) #------------------------------------------------------------------------- def processAlarm(self, newAlarm): self.alarmWidget.setHourGlass(True) try: newAlarm.save() except: self.logger.error('Failed to save alarm:', exc_info=True) try: self.forwarder.forward(newAlarm) except: self.logger.error('Failed to forward alarm:', exc_info=True) if not self.alarm or not self.alarm.matches(newAlarm): self.logger.info("Processing new alarm.") self.startTimer() self.alarm = newAlarm self.route = ([], None, None) self.seenPager = False self.seenXml = False self.seenJson = False self.reportDone = False self.reportTimer.start() self.sound.start() self.tts.clear() self.tts.start() self.gpioControl.trigger() self.report.wakeupPrinter() else: self.alarm.merge(newAlarm, self.logger) if newAlarm.source == 'pager': self.seenPager = True elif newAlarm.source == 'xml': self.seenXml = True elif newAlarm.source == 'json': self.seenJson = True self.logger.info('Sources: %s', self.alarm.sources) self.idleWidget.stop() self.stackedWidget.setCurrentWidget(self.alarmWidget) self.alarmWidget.processAlarm(self.alarm) QApplication.processEvents() self.alarmWidget.setRoute(self.route) if not self.route[0]: QApplication.processEvents() self.logger.info('Route query...') self.route = getRoute(self.alarm.lat, self.alarm.lon, self.config, self.logger) self.alarmWidget.setRoute(self.route) self.logger.info('Route ready.') self.tts.setText(self.alarm.spoken()) if (self.seenJson or (self.seenPager and self.seenXml)) \ and not self.reportDone: self.reportTimer.stop() QApplication.processEvents() self.generateReport() self.alarmWidget.setHourGlass(False) def generateReport(self): if self.reportDone: self.logger.info('Report already done.') return self.reportDone = True self.alarmWidget.setHourGlass(True) self.logger.info('Report...') try: self.report.generate(self.alarm, self.route) except: self.logger.error('Report failed:', exc_info=True) self.reportDone = False self.logger.info('Finished.') self.alarmWidget.setHourGlass(False) def startTimer(self): self.alarmDateTime = QDateTime.currentDateTime() if self.idleTimer.interval() > 0: self.idleTimer.start() if self.screenTimer.interval() > 0: self.screenTimer.start() self.alarmWidget.startTimer(self.alarmDateTime) self.logger.info('Alarm at %s', self.alarmDateTime) self.cecCommand.switchOn() def simTimeout(self): self.exampleJugend() def idleTimeout(self): self.stackedWidget.setCurrentWidget(self.idleWidget) self.idleWidget.start() def screenTimeout(self): self.cecCommand.switchOff() #------------------------------------------------------------------------- def exampleJugend(self): alarm = Alarm(self.config) alarm.source = 'xml' alarm.sources.add(alarm.source) alarm.number = '40001' now = datetime.datetime.now() local_tz = get_localzone() alarm.datetime = local_tz.localize(now) alarm.art = 'B' alarm.stichwort = '3' alarm.diagnose = 'Wohnungsbrand' alarm.strasse = 'St.-Anna-Berg' alarm.ort = 'Kleve' alarm.hausnummer = '5' alarm.objektname = 'Jugendherberge' alarm.besonderheit = 'lt. Betreiber 34 Personen gemeldet' alarm.objektnummer = 'KLV 02/140' alarm.lat = 51.78317 alarm.lon = 6.10695 self.processAlarm(alarm) def exampleEngels(self): alarm = Alarm(self.config) alarm.source = 'xml' alarm.sources.add(alarm.source) alarm.number = '40002' now = datetime.datetime.now() local_tz = get_localzone() alarm.datetime = local_tz.localize(now) alarm.art = 'H' alarm.stichwort = '1' alarm.diagnose = 'Tierrettung' alarm.ort = 'Kleve' alarm.ortsteil = 'Reichswalde' alarm.strasse = 'Engelsstraße' alarm.hausnummer = '5' alarm.ort = 'Kleve' alarm.besonderheit = 'Katze auf Baum' alarm.sondersignal = '0' alarm.lat = 51.75065 alarm.lon = 6.11170 self.processAlarm(alarm) def exampleSack(self): self.logger.info('Example Sackstrasse') alarm = Alarm(self.config) alarm.source = 'xml' alarm.sources.add(alarm.source) alarm.number = '40003' now = datetime.datetime.now() local_tz = get_localzone() alarm.datetime = local_tz.localize(now) alarm.art = 'B' alarm.stichwort = '2' alarm.diagnose = 'Garagenbrand' alarm.strasse = 'Sackstraße' alarm.hausnummer = '173' alarm.ort = 'Kleve' alarm.besonderheit = 'Kfz brennt unter Carport' alarm.lat = 51.77190 alarm.lon = 6.12305 self.processAlarm(alarm) def exampleWolfsgrabenPager(self): pagerStr = '21-12-17 11:55:10 LG Reichswalde Geb{udesteuerung' + \ ' #K01;N5175638E0611815; *40004*B2 Kaminbrand**Kleve*' + \ 'Reichswalde*Wolfsgraben*11**' alarm = Alarm(self.config) alarm.fromPager(pagerStr, self.logger) self.processAlarm(alarm) def exampleWolfsgrabenMail(self): alarm = Alarm(self.config) alarm.source = 'xml' alarm.sources.add(alarm.source) now = datetime.datetime.now() local_tz = get_localzone() alarm.datetime = local_tz.localize(now) alarm.art = 'B' alarm.stichwort = '2' alarm.diagnose = 'Kaminbrand' alarm.besonderheit = 'keine Personen mehr im Gebäude' alarm.ortsteil = 'Reichswalde' alarm.strasse = 'Wolfsgraben' alarm.hausnummer = '11' alarm.ort = 'Kleve' alarm.lat = 51.75638 alarm.lon = 6.11815 alarm.meldender = 'Müller' alarm.rufnummer = '0179 555 364532' alarm.number = '1170040004' alarm.sondersignal = '1' em = EinsatzMittel('FW', 'KLV', '05', 'LF10', '1', '') alarm.einsatzmittel.add(em) em = EinsatzMittel('FW', 'KLV', '02', 'LF20', '1', '') alarm.einsatzmittel.add(em) self.processAlarm(alarm) def exampleWald(self): pagerStr = '16-12-17 18:55:10 LG Reichswalde Gebäudesteuerung' + \ ' #K01;N5173170E0606900; *40005*H1 Hilfeleistung*' + \ 'Eichhörnchen auf Baum*Kleve*Reichswalde*' + \ 'Grunewaldstrasse***Waldweg C' alarm = Alarm(self.config) alarm.fromPager(pagerStr, self.logger) self.processAlarm(alarm) def exampleStadtwerkePager(self): pagerStr = '21-12-17 11:55:10 LG Reichswalde Gebäudesteuerung' + \ ' #K01;N5179473E0613985; *40006*B3 Brand Bürogebäude*' + \ 'Stadtwerke Kleve GmbH*Kleve*Kleve*Flutstraße*36**' alarm = Alarm(self.config) alarm.fromPager(pagerStr, self.logger) self.processAlarm(alarm) def exampleLebenshilfe(self): pagerStr = '22-03-17 10:12:38 LG Reichswalde Gebäudesteuerung' + \ ' #K01;N5177287E0611253;*40007*B2 Brandmeldeanlage 2' + \ ' **Kleve*Materborn*Dorfstrasse*27*KLV 02/103' + \ '*Materborner Allee - Saalstrasse' alarm = Alarm(self.config) alarm.fromPager(pagerStr, self.logger) self.processAlarm(alarm) def exampleHuissen(self): f = open("alarm_db/2018-06-24-04-13-11.xml", "rb") xmlContent = f.read() f.close() alarm = Alarm(self.config) try: alarm.fromXml(xmlContent, self.logger) except: self.logger.error('Failed to parse XML:', exc_info=True) return self.processAlarm(alarm)
def __init__(self, cnf): Notifier.__init__(self, { 'filename': '%Y-%m-%d.log', 'mode': 'a' }) self.C.update(cnf) self.file = self.name = None
from WebScraper import WebScraper from Notifier import Notifier from time import sleep from datetime import datetime, timedelta import os CHECKING_INTERVAL = 60 * 1 sender_login = ############# TODO # mail account sender_password = ############# TODO notifier = Notifier(sender_login, sender_password) notifier.add_receiver() #to do web_scraper = WebScraper() work_start_hour = 9 work_end_hour = 18 while True: datetime_cur = datetime.today() print("\nNow", datetime_cur.strftime("%Y/%m/%d - %H.%M.%S")) if not (work_start_hour < datetime_cur.hour < work_end_hour): if datetime_cur.hour > work_end_hour: work_start_datetime = datetime_cur.replace(hour=work_start_hour, minute=0, second=0)\ + timedelta(days=1) else: work_start_datetime = datetime_cur.replace(hour=work_start_hour, minute=0, second=0) work_brake = (work_start_datetime - datetime_cur).seconds
def __init__(self, unknown, test = False, log = False, type = "dss_team", flag = "enabled"): Notifier.__init__(self, [], test, log) self.sender = "*****@*****.**" self.type = type self.setUnknown(unknown, flag)
class CurrencyConverterApplet(base.BaseApplet): def __init__(self,parent,args=None): base.BaseApplet.__init__(self,parent) def init(self): base.BaseApplet.init(self, needsversion="4.5") if self.hasFailedToLaunch(): return KGlobal.locale().insertCatalog(self.metadata.pluginName()) lang = KGlobal.locale().language() print "Language:", lang print "Translated?", KGlobal.locale().isApplicationTranslatedInto(lang) self._widget = None self.dialog = None self.has_tooltip = False self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.notifier = Notifier(self) self.nwmon = NetworkMonitor() if self.nwmon.connected(): self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self.nwmon.status_changed.connect(self.netstate_changed) # Main widget print("CurrencyConverterApplet: Creating main widget.") self._widget = CurrencyConverter(self) self._widget.init() self.setGraphicsWidget(self._widget) self.setPopupIcon(self.metadata.pluginName()) self.setGraphicsWidget(self._widget) #self.setup_tooltip() self.configChanged() self._widget.updated.connect(self.setup_tooltip) def createConfigurationInterface(self, dialog): self.ui = CurrencyConverterConfig(self.dialog) p = dialog.addPage(self.ui, i18n("General") ) p.setIcon( KIcon("currency-converter") ) #self.notify_widget = KCModuleProxy("kcmnotify", dialog, ["currency-converter",]) #real_module = self.notify_widget.realModule() ##print "Module:", real_module #p = dialog.addPage(self.notify_widget, i18n("Notifications") ) #p.setIcon( KIcon("dialog-information") ) dialog.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel | KDialog.Apply))) dialog.showButton(KDialog.Apply, False) #self.connect(dialog, SIGNAL("applyClicked()"), self, SLOT("configAccepted()")) #self.connect(dialog, SIGNAL("okClicked()"), self, SLOT("configAccepted()")) dialog.applyClicked.connect(self.configAccepted) dialog.okClicked.connect(self.configAccepted) self.ui.update_interval.setValue(self._widget.update_interval) #@pyqtSignature("configAccepted()") @pyqtSlot(name="configAccepted") def configAccepted(self): print "CurrencyConverterApplet::configAccepted" self._widget.update_interval = self.ui.update_interval.value() self.cfg.writeEntry("update_interval", QVariant(self._widget.update_interval)) self.constraintsEvent(Plasma.SizeConstraint) self.update() self._widget.start_timer() self.emit(SIGNAL("configNeedsSaving()")) #self.configNeedsSaving.emit() def contextualActions(self): # Add custom context menus print "CurrencyConverterApplet::contextualActions" actions = [] ac_update = QAction(KIcon("view-refresh"), i18n("Update now"), self) #checkNow = QAction(KIcon(self.package().path() + "contents/icons/check.svg"), "Check email now", self) #self.connect(ac_update, SIGNAL("triggered()"), self._widget.do_convert) if hasattr(self, '_widget') and self._widget is not None: ac_update.triggered.connect(self._widget.do_convert) actions.append(ac_update) print actions return actions # Never called..? def updateToolTipContent(self): print "CurrencyConverterApplet::updateToolTipContent" @QtCore.pyqtSlot(name="setup_tooltip") def setup_tooltip(self): print "setup_tooltip: Last updated:", self._widget.lastUpdated() # Tool tip for panel if self.has_tooltip: Plasma.ToolTipManager.self().clearContent(self.applet) self.metadata = self.package().metadata() self.tooltipdata = Plasma.ToolTipContent() self.tooltipdata.setAutohide(False) self.tooltipdata.setMainText(self.metadata.name()) #self.tooltipdata.setSubText(self.metadata.description()) tooltip_txt = str(i18nc("From code From Amount = To code To Amount - Last updated", "%s %s = %s %s<br /><br />Last updated:<br />%s")) tooltip_txt= tooltip_txt % (self._widget.fromCurrency(), self._widget.fromAmount(), self._widget.toCurrency(), self._widget.toAmount(), self._widget.lastUpdated()) #print tooltip_txt self.tooltipdata.setSubText(tooltip_txt) self.tooltipdata.setImage(KIcon(self.metadata.pluginName())) Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata) # Only register the tooltip in panels #if (self.formFactor() != Plasma.Planar): if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)): #print("CurrencyConverterApplet: In Panel") Plasma.ToolTipManager.self().registerWidget(self.applet) self.has_tooltip = True else: Plasma.ToolTipManager.self().clearContent(self.applet) Plasma.ToolTipManager.self().unregisterWidget(self.applet) #print("CurrencyConverterApplet: Not in Panel") self.has_tooltip = False def configChanged(self): print("CurrencyConverterApplet: configChanged") # TODO: # Clear ComboBoxes # Add currencies # Select currencies # Convert @QtCore.pyqtSlot(bool, name="netstate_changed") def netstate_changed(self, connected): print "CurrencyConverterApplet: Network status changed!", connected if connected: print("CurrencyConverterApplet: Connected!") self._widget.setEnabled(True) self._widget.start_timer() self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self._widget.setEnabled(False) print("CurrencyConverterApplet: Not connected!") self.setBusy(True) # Whys isn't this called? @QtCore.pyqtSlot(name="toolTipAboutToShow") def toolTipAboutToShow(self): print "CurrencyConverterApplet:toolTipAboutToShow"
from Notifier import Notifier from State import States from Notification import Notification notifier = Notifier() def main(): notification = Notification() command = input() while command.split(' ')[0] != 'EXIT': if command.split(' ')[0] == 'SEND': notification.set_message(command.split(' ', 2)[2]) notification.set_state(States[command.split(' ')[1]]) notifier.send_message(notification, States[command.split(' ')[1]]) command = input() notification.set_message(command) notifier.send_message(notification, 0) open("legitnetwork.txt", "w").close() main()
from urllib.parse import urlparse from Notifier import Notifier from ListManager import ListManager from Manga import Manga # instantiate a chrome options object so you can set the size and headless preference chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--window-size=1920x1080") driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='./chromedriver') time.sleep(1) # Notifier to notify the user when a new chapter of a manga is downloaded notifier = Notifier() liste_manager = ListManager() for entry in liste_manager.lirescan_list: manga = Manga(entry["name"], entry["url"], entry["last_chapter"]) driver.get(manga.url) # TODO appeler le bon scrapper correspondant au site du manga actuel # check if manga dir exist, if not, creates it dir_name = './images/' + manga.dir_name + '/' if not os.path.isdir(dir_name): os.mkdir(dir_name) is_last_chapter = False previous_chapter = manga.chapter
# parameters to the scanner facilityID = jRocksCamp.getFacilityID() startDate = "01/05/2020" endDate = "01/07/2020" scanner = CampScanner(facilityID, startDate, endDate) # keep scanning until an available campsite is found. while (True): scanner.scanCampground() if scanner.getAvailableCampSites(): break time.sleep(900) # wait 900 secs/15 mins before scanning again print("Campsites Available. Sending notification...") # parameters to Notifier password = "******" # put sending email password here sEmailAddr = "*****@*****.**" # sending email address here rEmailAddr = "*****@*****.**" # receiving email address to send to here subject = "Available Sites!" emailMsgBdy = ("Campsites are available at " + facilityName + ". Navigate to " "https://www.recreation.gov/camping/campgrounds/" + facilityID + "/availability" " to view the availability table.") notifier = Notifier(password, sEmailAddr, rEmailAddr, subject, emailMsgBdy) notifier.buildMessage() notifier.send()
def refresh(self, jsonobj, jsonpages=None): self.thread = jsonobj self.pages = jsonpages #self.tdict['OP'] = {'no': 213, 'com': 'unset', 'sub': 'unset'.encode('utf-8'), 'semantic-url': 'unset'.encode('utf-8')} # Get some information about the thread (post count, reply count, etc) from the first post self.bp.stdscr.noutrefresh() try: self.originalpost.update({'no': self.thread['posts'][0]['no']}) try: self.originalpost.update( {'replies': self.thread['posts'][0]['replies']}) self.originalpost.update( {'images': self.thread['posts'][0]['images']}) self.originalpost.update( {'bumplimit': self.thread['posts'][0]['bumplimit']}) self.originalpost.update( {'imagelimit': self.thread['posts'][0]['imagelimit']}) try: self.originalpost.update( {'archived': self.thread['posts'][0]['archived']}) except KeyError: self.originalpost['archived'] = 0 self.bp.tb.bumplimit = self.originalpost['bumplimit'] self.bp.tb.imagelmit = self.originalpost['imagelimit'] self.bp.tb.images = self.originalpost['images'] self.bp.tb.replies = self.originalpost['replies'] try: self.originalpost.update( {'unique_ips': self.thread['posts'][0]['unique_ips']}) if int(self.originalpost['unique_ips']) > int( self.bp.tb.unique_ips ) and self.bp.tb.unique_ips != 0: self.bp.tb.unique_ips_changed = True else: self.bp.tb.unique_ips_changed = False self.bp.tb.unique_ips = self.originalpost['unique_ips'] # Archived threads do not set unique_ips except: self.bp.tb.unique_ips = "?" # Look up catalog page the thread is currently in self.refresh_pages(jsonpages) except Exception as e: self.dlog.warn(e, logLevel=3, msg=">>>in DictOutput.refresh() -> OP") try: self.originalpost.update({ 'semantic_url': self.thread['posts'][0]['semantic_url'].encode('utf-8') }) except: pass try: com = self.clean_html(self.thread['posts'][0]['com']) self.originalpost.update({'com': com.encode('utf-8')}) self.title = self.originalpost['com'] except: pass try: sub = self.clean_html(self.thread['posts'][0]['sub']) self.originalpost.update({'sub': sub.encode('utf-8')}) self.title = self.originalpost['sub'] except: pass except Exception as e: self.dlog.warn(e, msg=">>>in DictOutput.refresh()", cn=self.__class__.__name__) raise db_posts = [] try: # Array containing posts from previous sessions db_posts = self.db.get_postno_from_threadno( self.originalpost['no']) except Exception as e: self.dlog.excpt(e, msg=">>>in refresh() -> db_posts", cn=self.__class__.__name__) for posts in self.thread['posts']: # skip post if base data can't be processed try: no = posts['no'] # skip post if it was already processed if no in self.tdict: continue self.no_abs_to_rel_dict[no] = self.no_rel name = posts['name'][:16] time = datetime.datetime.fromtimestamp( posts['time']).strftime('%H:%M') except: continue #color = randint(11, 240) color = self.no_rel % 244 + 11 # re-assign black color # TODO is this term/color-independent? if color % 244 == 26: color = 11 refposts = "" # posts referenced in a reply try: country = posts['country'] except: country = "" try: com = posts['com'] com = re.sub('<br>', ' ', com) # save all post quotes in a list (without >>) refposts = re.findall('>>(\d+)', com) # remove >> from quotes for now com = re.sub('>>(\d+)', '\g<1>', com) #com = re.sub(''', '\'', com) #com = re.sub('>', '>', com) #com = re.sub('<', '<', com) #com = re.sub('"', '"', com) #com = re.sub('<[^<]+?>', '', com) com = self.clean_html(com) except: com = "[File only]" # @UndefinedVariable try: trip = posts['trip'] except: trip = "" try: filename = self.clean_html(posts['filename']) except: filename = "" try: fsize = posts['fsize'] except: fsize = 0 try: tim = posts['tim'] except: tim = "" try: ext = self.clean_html(posts['ext']) file_ext_short = ext[1:2].upper() except: ext = "" file_ext_short = " " # Compare comment content to recently posted comment try: marked = False if self.comment_tbm_timeout > 0: self.dlog.msg( "comment wrote: " + str(com) + " comment to be matched: " + str(self.comment_tbm), 4) # TODO regex match with n percentage accuracy should work better if com == self.comment_tbm: marked = True self.comment_tbm = None self.comment_tbm_timeout = 0 self.bp.update_db(no) self.bp.threadFetcher.update_n = 3 self.comment_tbm_timeout -= 1 if no in db_posts: marked = True except: pass try: # TODO maybe just use the structure from 4chan's json. Maybe. self.tdict[no] = { 'country': country, 'name': name, 'time': time, 'com': com, 'trip': trip, 'color': color, 'filename': filename, 'tim': tim, 'ext': ext, 'marked': marked, 'refposts': refposts, 'fsize': fsize } def filter_scan(filterdict): filter_matched = False for rule in json.loads(filterdict): for section in json.loads(rule['filter']): try: test = json.loads(rule['filter']) except: pass if self.tdict[no][section] in test[ section] and self.tdict[no][section]: self.dlog.msg( "--Matched: " + str(self.tdict[no][section]) + " in " + str(test[section]), 4) filter_matched = True elif self.tdict[no][section] not in test[section]: self.dlog.msg( "--Not matched: " + str(self.tdict[no][section]) + " in " + str(test[section]), 4) filter_matched = False break else: self.dlog.msg( "--Not matched (section does not exist): " + str(section), 4) filter_matched = False break self.dlog.msg( "--Matched (" + str(rule) + "): " + str(filter_matched), 4) return filter_matched # Scan for matched filters filter_matched = False if self.cfg.get('filter.ignore.list') and filter_scan( self.cfg.get('filter.ignore.list')): filter_matched = True if self.cfg.get('filter.except.list') and filter_scan( self.cfg.get('filter.except.list')): filter_matched = False # ####### FIXME: Remove. This is to test filtering # pattern = re.compile(ur'Japanese', re.UNICODE) # filter_matched = False # if country in ["DE", "TH"] and self.bp.board == "int" and name == "Anonymous" \ # and trip == "" and pattern.search(self.originalpost['com']): # # filter_matched = True # # # Exception for filter # for letter in com: # if unicodedata.east_asian_width(letter) in ['W', 'F']: # filter_matched = False # break # elif country == "US" and name == "Anonymous": # filter_matched = True if filter_matched: self.dlog.msg("--FILTER TEST: Skipping comment: " + str(no)) continue except Exception as err: self.dlog.warn(err, msg=">>>in DictOutput.refresh() (-> filter)") try: #if filter_matched: # # continue ####### End of filter test ########### # Write [TIME] <Name> self.bp.addstr("", curses.color_pair(color)) # @UndefinedVariable self.bp.addstr(time) if self.cfg.get("board.postno.style") is 'relative': self.bp.addstr( " >>" + str(self.no_rel).zfill(3), curses.color_pair(color)) # @UndefinedVariable else: self.bp.addstr( " >>" + str(no), curses.color_pair(color)) # @UndefinedVariable # Add country code self.bp.addstr(" " + country) # Count of characters that are in every new BoardPad line (for indentation on nl in bp) indent = len(time) + len(str(no)) + len(country) + 4 # Make own nickname bold if re.match(str(self.nickname), name) or marked: # if not self.nickname: # nick = "Anonymous" # else: # nick = self.nickname self.bp.addstr(" <" + file_ext_short + name + "> ", curses.A_BOLD) # @UndefinedVariable # Make name decoration stand out if file is attached else: self.bp.addstr( " <", curses.color_pair(250)) # @UndefinedVariable self.bp.addstr(file_ext_short, curses.color_pair(250) | curses.A_BOLD) # @UndefinedVariable self.bp.addstr(name.encode('utf8'), curses.A_DIM) # @UndefinedVariable if self.cfg.get("board.postno.style") is 'hybrid': self.bp.addstr( "-" + str(self.no_rel).zfill(3), curses.color_pair(color)) # @UndefinedVariable self.bp.addstr( "> ", curses.color_pair(250)) # @UndefinedVariable # width of name including unicode east asian characters + len("< > ") == 5 indent += self.bp.calcline(name.encode('utf8')) + 5 comlist = com.split() try: # # Post filename if exists # try: # if filename: # self.bp.addstr("[", curses.A_BOLD) # @UndefinedVariable # self.bp.addstr(filename[:12]) # self.bp.addstr("] ", curses.A_BOLD) # @UndefinedVariable # except: # pass # Iterate over every word in a comment for word in comlist: # refposts contains all >>(\d+) in a comment if word not in refposts: # Output non-reference self.bp.addstr(u''.join( (word + " ")).encode('utf8'), curses.A_NORMAL, indent) # @UndefinedVariable # Handle references (>>(\d+)) else: # Comment and reference color encoding try: refcolor = self.tdict[int(word)]['color'] if self.cfg.get("board.postno.style" ) is not 'absolute': self.bp.addstr( ">>" + str(self.no_abs_to_rel_dict[int(word)]) + " ", curses.color_pair(refcolor), indent) # @UndefinedVariable else: self.bp.addstr( ">>" + word + " ", curses.color_pair(refcolor), indent) # @UndefinedVariable # Add (You) to referenced posts written by self.nickname if re.match(self.tdict[int(word)]['name'], str(self.nickname)) or self.tdict[ int(word)]['marked'] == True: self.bp.addstr( "(You) ", curses.A_BOLD | curses.color_pair(221), indent, mentioned=True) # @UndefinedVariable try: Notifier.send(name, com) except Exception as e: self.dlog.excpt( e, msg=">>>in DictOutput.refresh()", cn=self.__class__.__name__) raise # highlight OP reference if re.match(word, str(self.originalpost['no'])): try: self.bp.addstr( "(OP) ", curses.A_BOLD | curses.color_pair(4), indent) # @UndefinedVariable except: raise except KeyError: self.bp.addstr(word + " ", curses.A_DIM, indent) # @UndefinedVariable except Exception as err: self.dlog.excpt( err, msg=">>>in DictOutput.filter_scan()", cn=self.__class__.__name__) except: self.bp.addstr("[File only]", curses.A_DIM, indent) # @UndefinedVariable except: raise self.bp.addstr("\n", curses.A_NORMAL, indent) # @UndefinedVariable self.no_rel += 1 try: if self.bp.subtitle.append_to_subfile: self.bp.subtitle.subfile_append(com) except AttributeError: pass # refetch entire thread on post count mismatch try: if len(self.tdict) != int(self.thread['posts'][0]['replies']) + 1: self.bp.update_thread(notail=True) except Exception as e: self.dlog.excpt(e, msg=">>>in DictOutput.refresh() ->refetch", cn=self.__class__.__name__) if self.originalpost['archived']: self.bp.threadFetcher.stop() self.bp.sb.setStatus("ARCHIVED") curses.doupdate() # @UndefinedVariable
class GoogleTranslatorApplet(BasePlasmoid): def __init__(self,parent,args=None): self.parent = parent BasePlasmoid.__init__(self, parent) def init(self): debug("GoogleTranslatorApplet: init().") BasePlasmoid.init(self) self._widget = None self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.notifier = Notifier(self) self.nwmon = NetworkMonitor() if self.nwmon.connected(): self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self.nwmon.status_changed.connect(self.netstate_changed) # Main widget debug("GoogleTranslatorApplet: Creating main widget.") self._widget = GoogleTranslator(self) self._widget.init() self.setGraphicsWidget(self._widget) self.setPopupIcon(self.metadata.pluginName()) self.setGraphicsWidget(self._widget) # Tool tip for panel self.metadata = self.package().metadata() self.tooltipdata = Plasma.ToolTipContent() self.tooltipdata.setMainText(self.metadata.name()) self.tooltipdata.setSubText(self.metadata.description()) self.tooltipdata.setImage(KIcon(self.metadata.pluginName())) Plasma.ToolTipManager.self().setContent(self.applet, self.tooltipdata) # Only register the tooltip in panels #if (self.formFactor() != Plasma.Planar): if ((self.formFactor() == Plasma.Horizontal) or (self.formFactor() == Plasma.Vertical)): print("GoogleTranslatorApplet: In Panel") Plasma.ToolTipManager.self().registerWidget(self.applet) else: Plasma.ToolTipManager.self().unregisterWidget(self.applet) print("GoogleTranslatorApplet: Not in Panel") self.configChanged() def configChanged(self): debug("GoogleTranslator: configChanged") # TODO: # Clear ComboBoxes # Add languages # Select languages # Translate defaultSize = QVariant(QSize (0,0)) size = self.cfg.readEntry("size", defaultSize ).toSize() if (size != defaultSize) : self._widget.setPreferredSize(size.width(), size.height()) else: self._widget.setPreferredSize(400 ,200) self.connect(self._widget, SIGNAL("resized()"), self.dialog_resized) @QtCore.pyqtSlot(name="dialog_resized") def dialog_resized(self): if self.isPopupShowing(): self.config().writeEntry("size", QVariant(self.widget.size())) @QtCore.pyqtSlot(bool, name="netstate_changed") def netstate_changed(self, connected): print "GoogleTranslatorApplet: Network status changed! %i" % connected if connected: debug("GoogleTranslatorApplet: Connected!") self._widget.setEnabled(True) self.setBusy(False) else: self.notifier.notify("waiting-for-network", i18n("Waiting for network connection.")) self._widget.setEnabled(False) debug("GoogleTranslatorApplet: Not connected!") self.setBusy(True)
class ImageForm_Impl(ImageForm): alignList = {} def __init__(self, parent=None, name=None, modal=0, fl=0): ImageForm.__init__(self, parent, name, modal, fl) self.comboAlign.insertItem('None') self.notifier = Notifier(parent, 1, args=[self.progressBar]) self.alignList['Left'] = 'left' self.alignList['Right'] = 'right' self.alignList['Center'] = 'center' self.btnUpload.setEnabled(False) self.buttonOk.setEnabled(False) self.http = QHttp() self.connect(self.http, SIGNAL("done(bool)"), self.httpDone) self.connect(self.http, SIGNAL("dataSendProgress (int, int)"), self.httpProgress) self.http2 = QHttp() self.connect(self.http2, SIGNAL("done(bool)"), self.http2Done) self.connect(self.http2, SIGNAL("dataSendProgress (int, int)"), self.httpProgress) for key in self.alignList.keys(): self.comboAlign.insertItem(key) def ImageArkPostData(sel, filename): return ([("MAX_FILE_SIZE", "512000")], [ ("userfile", os.path.basename(filename), open(filename, "rb").read()) ], "www.imageark.net", "/upload.php", "http://www.imageark.net") def ImageShackPostData(self, filename): return ( [], [("fileupload", os.path.basename(filename), open(filename, "rb").read())], "imageshack.us", "/index2.php", "http://imageshack.us/index2.php", ) def BeginImageUpload(self, filename, GetPostData, http): (fields, files, host, path, referer) = GetPostData(filename) content_type, body = encode_multipart_formdata(fields, files) Req = QHttpRequestHeader("POST", path) Req.setContentType(content_type) Req.setValue("Host", host) Req.setValue("Content-Length", str(len(body))) Req.setValue("Referer", referer) http.setHost(host) http.request(Req, body) def httpProgress(self, done, total): self.notifier.progress(done, total) def http2Done(self, error): qs = QString(self.http2.readAll()) match = self.imgre.search(unicode(qs)) if error: QMessageBox.warning(self, "Warning", "Cannot upload! Error:" + self.http2.error()) else: if match: self.editUrl.setText(self.image) self.editThumb.setText(match.group(1)) QMessageBox.information(self, "Info", "Image successfully uploaded!") else: QMessageBox.warning(self, "Warning", "Cannot upload the thumbnail image file!") self.http2.closeConnection() def httpDone(self, error): qs = QString(self.http.readAll()) match = self.imgre.search(unicode(qs)) if error: QMessageBox.warning(self, "Warning", "Cannot upload! Error:" + self.http.error()) else: if match: self.image = match.group(1) if self.thumbfile: # do second upload if self.chkShack.isChecked(): self.BeginImageUpload(self.thumbfile, self.ImageShackPostData, self.http2) elif self.chkArk.isChecked(): self.BeginImageUpload(self.thumbfile, self.ImageArkPostData, self.http2) else: # no need to upload second QMessageBox.information(self, "Info", "Image successfully uploaded!") self.editUrl.setText(self.image) else: if self.thumbfile: os.unlink(thumbfile) QMessageBox.warning(self, "Warning", "Cannot upload the image file!") self.http.closeConnection() def imagetag(self): imagetag = '' image = str(self.editUrl.text()) thumb = str(self.editThumb.text()) title = str(self.editTitle.text()) if str(self.editWidth.text()): width = int(str(self.editWidth.text())) else: width = None if str(self.editBorder.text()): border = int(str(self.editBorder.text())) else: border = None if str(self.editHeight.text()): height = int(str(self.editHeight.text())) else: height = None if not image: return None else: if thumb: imagetag += "<a href='%s'><img src='%s'" % (image, thumb) else: imagetag += '<img src=\'%s\'' % image if width: imagetag += ' width=\'%d\'' % width if height: imagetag += ' height=\'%d\'' % height if border: imagetag += ' border=\'%d\'' % border if title: imagetag += ' alt=\'%s\'' % title if self.alignList.has_key('%s' % self.comboAlign.currentText()): align = self.alignList['%s' % self.comboAlign.currentText()] imagetag += ' align=\'%s\'' % align imagetag += '>' if thumb: imagetag += '</a>' return imagetag def btnRefresh_clicked(self): if str(self.editUrl.text()): try: img = urllib2.urlopen(str(self.editUrl.text())).read() pic = QPixmap() pic.loadFromData(img) if not str(self.editWidth.text()): self.editWidth.setText(str(pic.width())) if not str(self.editHeight.text()): self.editHeight.setText(str(pic.height())) self.previewImage.setPixmap(pic) except: QMessageBox.warning(self, "Warning", "Cannot open the image url!") def editUrl_textChanged(self, a0): self.buttonOk.setEnabled(str(self.editUrl.text()) != '') def chk_stateChanged(self, a0): if self.chkUrl.isChecked(): self.widgetStack2.raiseWidget(self.pageUrl) self.buttonOk.setEnabled(str(self.editUrl.text()) != '') else: self.widgetStack2.raiseWidget(self.pageUpload) self.buttonOk.setEnabled(False) def chkThumb_toggled(self, a0): pass imgre = re.compile('\[img\](.*?)\[/img\]', re.IGNORECASE) def __generateThumb(self, filename): if not self.chkThumb.isChecked(): return None try: p = self.previewImage import tempfile fn = tempfile.mkstemp('%s' % os.path.basename(filename))[1] w = p.width() h = p.height() if w > 120: w = 120 if h > 120: h = 120 # if the image is smaller than the thumb, don't create the thumb if h < 120 and w < 120: return None os.system("convert -geometry %dx%d %s %s" % (w, h, filename, fn)) if os.path.exists(fn): return fn except: return None def btnUpload_clicked(self): self.image = None self.thumbfile = self.__generateThumb(str(self.editFile.text())) if self.chkShack.isChecked(): self.BeginImageUpload(str(self.editFile.text()), self.ImageShackPostData, self.http) elif self.chkArk.isChecked(): self.BeginImageUpload(str(self.editFile.text()), self.ImageArkPostData, self.http) def __open(self, txt, btn): filename = str(QFileDialog.getOpenFileName(None , \ "Images (*.png *.jpg *.gif)", \ self, \ "open image file", \ "Choose a file to open" )) txt.setText(filename) ok = False try: pic = QPixmap() if pic.loadFromData(open(filename, "rb").read()): ok = True if not str(self.editWidth.text()): self.editWidth.setText(str(pic.width())) if not str(self.editHeight.text()): self.editHeight.setText(str(pic.height())) self.previewImage.setPixmap(pic) btn.setEnabled(True) except: ok = False if not ok: QMessageBox.warning(self, "Warning", "Cannot open the image file!") self.previewImage.setPixmap(QPixmap()) btn.setEnabled(False) def editFile_textChanged(self, a0): self.btnUpload.setEnabled(os.path.exists(str(a0))) def btnOpen_clicked(self): self.__open(self.editFile, self.btnUpload)
def main_machine(patient_id, peristaltic_pump, flags, DB_FILE): """ :param patient_id: patient identifier to assign the machine to someone else :param peristaltic_pump: peristaltic_pump by the system :param flags: flags defined by the system :return: """ logging.info("thread of the machine starts") # definition button_listener for on/off thread_machine_on = threading.Thread( name='on_off_button', target=power_button.thread_button_pressed, args=(flags.flag_exit, ), daemon=False) # definition request dose for on/off thread_dose_request = threading.Thread( name='request dose button', target=request_button.thread_button_pressed, args=(flag_request_dose, flag_stop_request, flags.flag_exit), daemon=False) # definition glass IR thread_glass = threading.Thread(name='check glass', target=ir_glass.thread_check_object, args=(flags.flag_glass, flags.flag_exit), daemon=False) # definition juice IR thread_juice = threading.Thread(name='check juice box', target=ir_juice.thread_check_object, args=(flags.flag_juice, flags.flag_exit), daemon=False) # no error at the beginning errors = False counter_error = 0 # starting the listener for pressing the exit button thread_machine_on.start() # starting the thread for pressing the dose request thread_dose_request.start() # todo: uncomment the next lines # starting the thread for check the glass thread_glass.start() # starting the thread for check the juice # thread_juice.start() # define the display used for notify data display = Notifier(PORT_DISPLAY) # infinite loop wait for shutdown button while not flags.flag_exit.is_set(): db = Database(DB_FILE) patient = db.pull_patient(patient_id) logging.info(patient) source_cgm = Nightscout(patient) flag_request_dose.clear() flag_stop_request.clear() flags.flag_juice.set() # todo: remove it #flags.flag_glass.set() # todo: remove it try: # retrieve the glucose value -> with management of error cgm = source_cgm.get_cgm( ) # retrieve data from Nightscout (based on patient settings) except urllib.error.HTTPError: logging.warning('HTTP ERROR') errors = True # turn on the flag of errors request_led.turn_off() # turn off the led for dose request flags.flag_dose_may_be_required.clear() display.notify_error_connection( "HTTP ERROR!", True) # display the head of the error except urllib.error.URLError: # this error include content to short logging.warning('URL ERROR') errors = True request_led.turn_off() # turn off the led for dose request flags.flag_dose_may_be_required.clear() display.notify_error_connection( "URL ERROR!", True) # display the head of the error # todo: except the invalid data except Exception as e: logging.warning('Checkout this error', e) errors = True request_led.turn_off() # turn off the led for dose request flags.flag_dose_may_be_required.clear() display.notify_error_connection( "NO DATA!", True) # display the head of the error else: # no errors are detected errors = False # reset any error from previous counter_error = 0 # reset error counter db.push_unique_cgm(cgm) # store the glucose value anomaly = source_cgm.eval_cgm( cgm) # eval data value based on the threshold recent = source_cgm.is_recent( cgm, THRESHOLD.sec_recent) # eval data recent or not last_dose = db.pull_last_dose( patient.id) # retrieve the last dose received from the patient treatment_ingoing = source_cgm.under_treatment( last_dose, cgm, THRESHOLD.sec_dose) cgm_increased = source_cgm.rising_glucose(cgm) # case 1: data recent and hypoglycemia is detected if (not cgm_increased and not treatment_ingoing ) and anomaly == AnomalousSgv.HYPO and recent: request_led.turn_off() # turn off the led for dose request flags.flag_dose_may_be_required.clear() # eval the hypoglycemia (severe = 20 grams, not_severe = 15 grams) last_hour_date_time = datetime.now(tz=None) - timedelta( hours=2) last_hour_date_time = int(last_hour_date_time.timestamp()) other_cgm = db.pull_cgm_from(patient.id, last_hour_date_time) severe_hypo = source_cgm.eval_severe_hypoglycemia( cgm, other_cgm) # try to deliver the juice (if it's possible) result = manager_hypo(db, severe_hypo, patient.id, display, flags, peristaltic_pump) if not result: # the distribution failed # display data and wait another iteration display.notify_value(anomaly, treatment_ingoing, cgm) # todo: verify the feedback flags.flag_exit.wait( THRESHOLD.sec_investigation / 2 ) # in case of not successful distribution display data # case 2: data recent and the patient may ask for a dose elif (not cgm_increased and not treatment_ingoing ) and anomaly == AnomalousSgv.TO_INVESTIGATE and recent: request_led.turn_on() flags.flag_dose_may_be_required.set() display.notify_value(anomaly, treatment_ingoing, cgm) # display data flag_stop_request.wait(THRESHOLD.sec_investigation) # case 2.1 the patient request a dose (he press the button) or use the bot if flag_request_dose.is_set( ) or flags.flag_bot_request_dose.is_set(): request_led.turn_off() flags.flag_dose_may_be_required.clear() severe_hypo = True success = manager_hypo(db, severe_hypo, patient.id, display, flags, peristaltic_pump) # when the bot request a dose, it it early insert into the system if flags.flag_bot_request_dose.is_set() and not success: fail_dose = db.pull_last_dose(patient.id) db.remove_dose(fail_dose) flags.flag_bot_request_dose.clear() # treatment_ingoing = manager_hypo(db, severe_hypo, patient.id, display, flags) # display.notify_value(anomaly, treatment_ingoing, cgm) # case 3: data are recent and into a normal range, no hurry to evaluate them elif anomaly == AnomalousSgv.NORMAL and recent: # todo: add arrow down request_led.turn_off() flags.flag_dose_may_be_required.clear() request_timing = THRESHOLD.sec_fetch if request_timing > 60: refresh = request_timing / 60 count = 1 while count <= refresh: display.notify_value(anomaly, treatment_ingoing, cgm) flags.flag_exit.wait(60) count = count + 1 # case others: display data and update them (no error was detected) else: request_led.turn_off() # turn off the led for dose request flags.flag_dose_may_be_required.clear() display.notify_value(anomaly, treatment_ingoing, cgm) flags.flag_exit.wait(THRESHOLD.sec_investigation) finally: # close the connection with the db in this way the update from the bot may be performed db.close() # something went wrong if errors: counter_error = counter_error + 1 if counter_error <= MAX_TRIES: display.notify_error_connection( "err: " + str(counter_error) + " on " + str(MAX_TRIES), False) flags.flag_exit.wait(THRESHOLD.sec_error) else: logging.warning( 'Too many error the machine will be turned off') display.notify_error('Too many errors!\nMachine OFF') flags.flag_exit.wait( 10) # give the user the possibility to see the message flags.flag_exit.set() # stop the main and kill the machine break # todo add a reminder for glass and juice # out from the loop request_led.turn_off() flags.flag_dose_may_be_required.clear() display.turn_off() logging.info("the thread of the machine arrives at the end")
desktop = desktopparser.parse( file ) if desktop == None: syslog.syslog( syslog.LOG_NOTICE, "File '%s' could not be parsed, corrupted content or encoding ." % file ) else: menu.findOwnerAndAdd(desktop) desktopparser.reset() menu.removeEmptyItems() fd = codecs.open( BBFlux.FLUXBOX_MENU, 'w+', 'UTF-8' ) fd.write( menu.toFluxBox() ) fd.close() updated = abs(current - last) message = "BBFlux daemon succesfully updated %d item%s in FluxBox menu." % ( updated, "s" if updated > 1 else "" ) syslog.syslog( message ) Notifier.getInstance().notify( message ) prev = files sleep( BBFlux.WAIT_DELAY ) except KeyboardInterrupt: syslog.syslog( 'User interrupted BBFlux daemon with a keyboard interrupt.' ) except Exception as e: syslog.syslog( syslog.LOG_ERR, str(e) )