def trigger(self):
        if self.ui.AScheckbox.isChecked():
            self.flag = 1
            a = Notification()
            a.parser(self.list, self.flag)
        else:

            self.list.append(self.ui.CBstate1.currentText())
            self.list.append(self.ui.CBstate2.currentText())
            self.list.append(self.ui.CBstate3.currentText())
            a = Notification()
            a.parser(self.list, self.flag)
    def run(self):
        for raw_notification in self._consumer:
            partition = raw_notification[0]
            offset = raw_notification[1].offset
            message = raw_notification[1].message.value

            notification_data = json.loads(message)

            ntype = notification_data['type']
            name = notification_data['name']
            addr = notification_data['address']
            period = notification_data['period']

            notification = Notification(ntype, partition, offset, name, addr,
                                        period,
                                        notification_data['retry_count'],
                                        notification_data['raw_alarm'])

            if self._keep_sending(notification.alarm_id, notification.state):
                wait_duration = period - (
                    time.time() - notification_data['notification_timestamp'])

                if wait_duration > 0:
                    time.sleep(wait_duration)

                notification.notification_timestamp = time.time()

                self._notifier.send([notification])
                self._producer.publish(self._topic_name,
                                       [notification.to_json()])

            self._consumer.commit()
Esempio n. 3
0
 def new_notification(self,
                      msg: str,
                      urgency: Optional[Notify.Urgency] = None,
                      listen_closed_event: bool = False) -> Notification:
     # TODO: replace with NotificationFactory (Factory Pattern)
     return Notification('Speaking Eye', msg, self.active_icon, urgency,
                         listen_closed_event)
Esempio n. 4
0
def lambda_handler(event, context):
    # This is the function that is called by Lambda (like a Main function)

    # Fetch all records from the last week
    dynamoService = database.DynamoService()
    now = int(time.time())
    oneWeekAgo = now - (7 * 24 * 60 * 60)
    print("Getting items")
    identifierList = dynamoService.getItemIdentifiersAfterTimestamp(oneWeekAgo)

    # Get nutrition data on all food
    nutritionService = NutritionService()
    nutrition = nutritionService.getMockNutritionData()
    print("Querying for nutrition")
    for identifiers in identifierList:
        n = nutritionService.getNutritionByIdentifiers(identifiers)
        if n is not None:
            nutrition.append(n)

    # Generate HTML report
    nutritionReport = NutrtritionReport()
    url = nutritionReport.getHTML(nutrition)

    # Send user notification
    notificationService = Notification()
    message = "Your weekly Nutrition Report is ready. Download here: " + str(
        url)
    notificationService.sendNotification(message)
    return message
Esempio n. 5
0
 def main(self):
     sense = SenseEnvironment()
     notify = Notification()
     while True:
         # to get all devices which are paired with raspberry pi.
         p = sp.Popen(["bt-device", "--list"],
                      stdin=sp.PIPE,
                      stdout=sp.PIPE,
                      close_fds=True)
         (stdout, stdin) = (p.stdout, p.stdin)
         data = stdout.readlines()
         # Get the mac address as a string
         str_mac = str(data)
         str_mac = str(re.findall("\((.*?)\)", str_mac))
         str_mac = str_mac[2:len(str_mac) - 2]
         # searching for surrounding Bluetooth devices
         nearbyDevices = bluetooth.discover_devices()
         for macAddress in nearbyDevices:
             # checking if the mac address founded is matching the one already paired.
             if macAddress == str_mac:
                 if self.isInOneHour(macAddress) is False:
                     temp = sense.senseTmp()
                     hum = sense.senseHum()
                     notify.send_notification_via_pushbullet(
                         "",
                         " The temperature is {} and the humidity is {}".
                         format(temp, hum))
                     self.db.insert(str_mac)
         # 20 sec before next scanning
         time.sleep(20)
Esempio n. 6
0
 def read(self, mac):
     result = {}
     try:
         conn = Connector(mac)
         conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         if (mac in globals.KNOWN_DEVICES
                 and globals.KNOWN_DEVICES[mac]['model']
                 == 'xiaomiht/xiaomiht_cleargrass'):
             Firm = bytearray(conn.readCharacteristic('0x2a'))
         else:
             Firm = bytearray(conn.readCharacteristic('0x24'))
             batt = bytearray(conn.readCharacteristic('0x18'))
             battery = batt[0]
             result['battery'] = battery
         firmware = "".join(map(chr, Firm))
         result['firmware'] = firmware
         notification = Notification(conn, XiaomiHT)
         conn.writeCharacteristic('0x10', '0100', response=True)
         notification.subscribe(2)
         result['id'] = mac
         logging.debug('XIAOMIHT------' + str(result))
         return result
     except Exception as e:
         logging.error(str(e))
     return result
Esempio n. 7
0
 def action(self, message):
     mac = message['device']['id']
     handle = message['command']['handle']
     value = message['command']['value']
     conn = Connector(mac)
     conn.connect()
     if not conn.isconnected:
         conn.connect()
         if not conn.isconnected:
             return
     try:
         if 'key' in message['command']:
             conn.writeCharacteristic('0x19',
                                      message['command']['key'],
                                      response=True)
         if handle == '0x4e':
             conn.writeCharacteristic(handle, value, response=True)
             conn.connect()
             if not conn.isconnected:
                 conn.connect()
                 if not conn.isconnected:
                     return
             conn.writeCharacteristic('0x51', '04')
             notification = Notification(conn, Miband)
             notification.subscribe(20)
             conn.writeCharacteristic('0x4c', '0100', response=True)
         else:
             conn.writeCharacteristic(handle, value)
             if value == '02':
                 time.sleep(10)
             conn.disconnect()
     except Exception as e:
         logging.error(str(e))
         conn.disconnect()
     return
Esempio n. 8
0
 def read(self, mac):
     global result
     result = {}
     try:
         if mac in globals.KEEPED_CONNECTION:
             logging.debug('Already a connection for ' + mac + ' use it')
             conn = globals.KEEPED_CONNECTION[mac]
         else:
             logging.debug('Creating a new connection for ' + mac)
             conn = Connector(mac)
             globals.KEEPED_CONNECTION[mac] = conn
             conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         notification = Notification(conn, Smartplug)
         conn.writeCharacteristic('0x2b', '0f050400000005ffff')
         notification.subscribe(2)
         return
     except Exception as e:
         try:
             conn.disconnect()
         except Exception as e:
             pass
         logging.error(str(e))
     return
Esempio n. 9
0
def archifPullLastUpdates():
    archifStr = requests.get("https://meddl.center/archif").content.decode("utf8")

    soup = BeautifulSoup(archifStr, 'html.parser')
    ul = soup.select_one('ul.archif')

    notificationArray = []
    counter = 0
    for li in ul:
        id = counter
        epoch = datetime.now()
        source = "meddl.center"
        topic = li.findAll('a')[0].next
        description = ""
        if len(li.findAll('a')) > 0:
            if len(li.findAll('a')[0].findAll('i')) > 0:
                description = li.findAll('a')[0].findAll('i')[0].next
        notificationArray.append(Notification(id, epoch, source, topic, description))
        counter += 1
        if counter > 29:
            break

    counter = 0
    for notification in notificationArray:
        tmpEpoch = notificationArray[29 - counter].epoch
        notificationArray[29 - counter].epoch = notification.epoch
        notification.epoch = tmpEpoch
        counter += 1
        if counter == 15:
            break

    return notificationArray
Esempio n. 10
0
 def getStatus(self, mac):
     logging.debug('STATUS BLPNR')
     try:
         conn = Connector(mac)
         if not conn.isconnected:
             conn.connect(type='random')
             if not conn.isconnected:
                 return
         conn.writeCharacteristic('0x000f', '2902')
         conn.disconnect()
     except Exception as e:
         logging.error(str(e))
     try:
         conn = Connector(mac)
         if not conn.isconnected:
             conn.connect(type='random')
             if not conn.isconnected:
                 return
         logging.debug('READ notif BLPNR')
         notification = Notification(conn, Blpnr)
         #notification.subscribe(10,disconnect=True)
         notification.subscribe()
         conn.writeCharacteristic('0x0011', '0d00000d00')
     except Exception as e:
         logging.error(str(e))
    def event_listener_thread(self):

        ws = create_connection("ws://localhost:6789/websocket")
        while (self.stopped == False):
            result = ws.recv()
            notification = Notification(result)
            self.event_handler(notification)
Esempio n. 12
0
 def read(self, mac):
     result = {}
     try:
         conn = Connector(mac)
         conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         batteryFirm = bytearray(conn.readCharacteristic('0x38'))
         conn.writeCharacteristic('0x33', 'a01f', response=True)
         battery = batteryFirm[0]
         firmware = "".join(map(chr, batteryFirm[2:]))
         notification = Notification(conn, Miflora)
         conn.writeCharacteristic('0x36', '0100', response=True)
         result['battery'] = battery
         result['firmware'] = firmware
         result['id'] = mac
         received = bytearray(conn.readCharacteristic('0x35'))
         temperature = float(received[1] * 256 + received[0]) / 10
         if temperature > 3276.8:
             temperature = 0 - (6553.6 - temperature)
         sunlight = received[4] * 256 + received[3]
         moisture = received[7]
         fertility = received[9] * 256 + received[8]
         result['sunlight'] = sunlight
         result['moisture'] = moisture
         result['fertility'] = fertility
         result['temperature'] = temperature
         result['source'] = globals.daemonname
         logging.debug(str(result))
         globals.JEEDOM_COM.add_changes('devices::' + conn.mac, result)
         return result
     except Exception, e:
         logging.error(str(e))
Esempio n. 13
0
 def _mail_log_action(self, subject, body):
     ses_settings = self._config['ses_settings']
     notif = Notification(aws_access_key=ses_settings['aws_access_key'],
                          aws_secret_key=ses_settings['aws_secret_key'],
                          region=ses_settings['region'])
     html_body = format_html_mail_body(self.app, self.job, self._config)
     log_path = self._get_log_path()
     log = {
         'original_log_path': log_path,
         'filename': os.path.basename(log_path),
     }
     try:
         for log_notif in self.app.get('log_notifications', []):
             mail = log_notif.get('email')
             if (mail and
                 (self.job['status'] in log_notif.get('job_states', [])
                  or ''.join(log_notif.get('job_states', [])) == '*')):
                 notif.send_mail(From=ses_settings.get(
                     'mail_from', MAIL_LOG_FROM_DEFAULT),
                                 To=mail,
                                 subject=subject,
                                 body_text=body,
                                 body_html=html_body,
                                 attachments=[log],
                                 sender_name='Cloud Deploy')
             pass
     except:
         self._init_log_file()
         logging.exception(
             "An exception occurred when trying to send the Job mail notification."
         )
         traceback.print_exc()
         self._close_log_file()
Esempio n. 14
0
 def read(self, mac):
     result = {}
     #account verify : 0x29
     #realtimedata : 0x30
     #settings : 0x34
     #settingsresult : 0x25
     #historydata : 0x2c
     #
     #credentials :  0x21, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0xb8, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00
     #
     #enablerealtime : 0x0B, 0x01, 0x00, 0x00, 0x00, 0x00
     #
     #units celcisu : 0x02, 0x00, 0x00, 0x00, 0x00, 0x00
     # defini seuil : dans 0x34 ecrire 010X48f4YYYY  avec x numero de sonde (commencant a 0) et y temperature x10 inverse
     #
     #0x31 0100 activer notif temp
     #batterie 0x34 082400000000
     try:
         conn = Connector(mac)
         conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         conn.writeCharacteristic('0x29',
                                  '2107060504030201b8220000000000',
                                  response=True)
         notification = Notification(conn, Ibbq6)
         conn.writeCharacteristic('0x26', '0100', response=True)
         conn.writeCharacteristic('0x34', '082400000000', response=True)
         notification.subscribe(10)
         return result
     except Exception as e:
         logging.error(str(e))
     return result
def parsing_notification(file_content):
    '''
    Pre-process notifications.

    :param file_content: file content
    :returns: array of notification objects
    :raise TypeError: unexpected data structure
    :raise ValueError: invalid timestamp
    '''
    notifications = []
    for line in file_content:
        # Trim whitespace
        line = line.strip()
        # Seperate elements by spaces
        elements = line.split(" ")
        try:
            # Store new notification object into array
            notifications.append(Notification(*elements))
        except TypeError:
            print "Unexpected data structure: " + line
            print "Exiting..."
            sys.exit()
        except ValueError:
            print "Invalid timestamp: " + line
            print "Exiting..."
            sys.exit()
    return notifications
Esempio n. 16
0
    def read(self, mac):
        result = {}
        try:
            conn = Connector(mac)
            conn.connect()
            if not conn.isconnected:
                conn.connect()
                if not conn.isconnected:
                    return

            logging.debug('read batteryFirm')
            batteryFirm = bytearray(conn.readCharacteristic('0x18'))
            battery = batteryFirm[0]
            firmware = "".join(map(chr, batteryFirm[2:]))
            notification = Notification(conn, Mithermaff)
            logging.debug('write 0x10 0100 to get sensor values')
            conn.writeCharacteristic('0x10', '0100', response=True)
            notification.subscribe(2)
            result['battery'] = battery
            result['firmware'] = firmware
            result['id'] = mac
            logging.debug(str(result))
            return result
        except Exception, e:
            logging.error(str(e))
Esempio n. 17
0
 def _test_notification(self):
     print "%i F" % (self.current_value)
     time.sleep(1)
     print "target %i F" % (self.current_value + 2)
     self.set_target(self.current_value + 2)
     self.add_notification(Notification("*****@*****.**"))
     self.current_value = self.current_value + 3
     self.check_target()
Esempio n. 18
0
 def __to_notification(self, notif_dict: Dict[str, str]) -> Notification:
     return Notification(
         id=uuid.UUID(notif_dict.get("_id")),
         title=notif_dict.get("title"),
         message=notif_dict.get("message"),
         start_time=dateutil.parser.parse(notif_dict.get("start_time")),
         end_time=dateutil.parser.parse(notif_dict.get("end_time")),
         source=notif_dict.get("source"),
     )
Esempio n. 19
0
    def msg(self, msg):
        # self.system_tray_icon.showMessage("Ufs system", msg, 20000)
        try:
            self.notification_window = Notification()
        except:
            import traceback

            traceback.print_exc()
        self.notification_window.noti(msg)
Esempio n. 20
0
def monitor(app):
	try:
		while(1):
			rules = start(app)
			process(rules)
			logger.info('sleep 120s')
			time.sleep(120)
	except Exception,e:
		print traceback.print_exc()
		Notification('WAM run error').notification(str(e))
Esempio n. 21
0
    def create_report(report_duration, interval, image_path, log_path, percentage, threshold, person_detected, frame):
        elapsed_time = time.time() - starting_time_system
        notification = Notification()
        if threshold < percentage:
            if report_duration <= elapsed_time:
                report_duration = elapsed_time + interval
                notification.send_notification()
                Report.save_crowd_image(image_path, frame)
                Report.write_log(log_path, percentage, person_detected)

        return report_duration
Esempio n. 22
0
    def __init__(self, setting_name):
        setup_logger()
        logging.info('Shit_Happened initializing...')
        self.storage_name = None
        self.notification = Notification()
        self.change_checker = Change_checker()
        self.profile_dict = dict()
        self.site_dict = dict()

        logging.info('Reading settings...')
        self._read_setting(setting_name)
Esempio n. 23
0
 def add_new_reservation(self, hotel_name, customer_name):
     print("---add new reservation---")
     if self.reserve_room(hotel_name):
         self.reservation_list.append([hotel_name, customer_name])
         for customer in Customer.customers_list:
             if customer_name == customer[0]:
                 print(customer_name)
                 Notification("message", customer[1]).send_text_message()
         print "confirmation"
     else:
         print "sorry no rooms available"
     print("---end add new reservation---")
def selectNotificationsBySource(conn, sourceName):
    cur = conn.cursor()
    cur.execute("SELECT * FROM notifications WHERE source='" + sourceName +
                "'")

    rows = cur.fetchall()
    notificationsDict = {}
    for row in rows:
        notificationsDict[str(row[2]) + str(row[3])] = Notification(
            row[0], row[1], row[2], row[3], row[4])

    return notificationsDict
def selectNotifications(conn):
    cur = conn.cursor()
    cur.execute("SELECT * FROM notifications")

    rows = cur.fetchall()

    notificationsDict = {}
    for row in rows:
        notificationsDict[str(row[2]) + str(row[3])] = Notification(
            row[0], row[1], row[2], row[3], row[4])

    return notificationsDict
Esempio n. 26
0
    def _callback_notes(self, instance):
        if instance.is_canceled():
            return

        s_message = 'Pressed button: %s\n\n' % instance.button_pressed
        s_message += str(instance.lines)
        Logger.warning(msg=s_message)
        from notification import Notification
        Notification(text=s_message,
                     show_time=3,
                     size_hint=(0.8, 0.4),
                     title='Notes demo ( will disappear after 3 seconds ):')
Esempio n. 27
0
 def notify_self(self):
     from notification import Notification
     from follower import Follower
     follower = Follower.query.filter(
         and_(Follower.Type == self.Type,
              Follower.ParentID == self.ParentID,
              Follower.UserID == self.UserID)).first()
     if follower:
         note = Notification(UserID=self.UserID,
                             Type="Comments",
                             ParentID=self.CommentID,
                             FollowerID=follower.FollowerID)
         note.save()
Esempio n. 28
0
    def load_notifications(self):
        notification_rows = self.database.get_notifications()
        for notification_row in notification_rows:
            notification_id = notification_row[0]
            notification_content = notification_row[1]
            date_issued = notification_row[2]
            incident = self.get_incident(notification_row[3])

            notification = Notification(incident, notification_content)
            notification.id = notification_id
            notification.date_issued = date_issued

            self.notifications[notification.id] = notification
Esempio n. 29
0
	def __init__(self, authtoken):
		self.server = 'https://api.rach.io/1/public/'
		self.headers = {
			'Content-Type': 'application/json',
			'Authorization': 'Bearer %s' % authtoken
			}
		self.h = httplib2.Http('.cache')

		self.person = Person(self)
		self.device = Device(self)
		self.zone = Zone(self)
		self.schedulerule = Schedulerule(self)
		self.flexschedulerule = FlexSchedulerule(self)
		self.notification = Notification(self)
Esempio n. 30
0
 def parse(self, data, mac, name, manuf):
     result = {}
     result['present'] = 1
     try:
         conn = Connector(mac)
         conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         notification = Notification(conn, LogiSwitch)
         notification.subscribe(2)
     except Exception, e:
         logging.error(str(e))