Ejemplo n.º 1
0
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()
Ejemplo n.º 2
0
    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()
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
 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'])
Ejemplo n.º 5
0
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")
Ejemplo n.º 6
0
 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()
Ejemplo n.º 7
0
 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()
Ejemplo n.º 8
0
 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()
Ejemplo n.º 9
0
    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)))
Ejemplo n.º 10
0
    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)
Ejemplo n.º 11
0
    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)
Ejemplo n.º 12
0
    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()
Ejemplo n.º 13
0
    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()
Ejemplo n.º 14
0
    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)
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
    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)
Ejemplo n.º 17
0
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()
Ejemplo n.º 18
0
    # 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()
Ejemplo n.º 19
0
from Notifier import Notifier
import bs4 as bs
import urllib.request
import time
import math
over = 0
over1 = 0
url = "https://www.cricbuzz.com/live-cricket-scores/22460/rajasthan-vs-chennai-25th-match-indian-premier-league-2019"
n = Notifier()
while True:
    sp = urllib.request.urlopen(url).read()
    soup = bs.BeautifulSoup(sp, 'lxml')
    hd = soup.find('h1', {"class": "cb-nav-hdr cb-font-18 line-ht24"})
    header = hd.text.split(",", 1)
    link = "cb-font-20 text-bold"
    span = soup.find_all('span', {"class": link})
    try:
        print(span[0].text)
        s = span[0].text
        s = s[s.find("(") + 1:s.find(")")]
        over1 = over
        over = s.split(" ", 1)[0]
    except Exception as e:
        print('Exception occured')
        time.sleep(5)
        continue
    if (math.ceil(float(over)) - (float(over)) == 0 and over != over1):
        n.show_toast("Match Info-" + str(header[0]), span[0].text, 6)
    time.sleep(10)
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
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")
Ejemplo n.º 22
0
    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.')