Ejemplo n.º 1
0
def send_message(message):
    client = Client(po_key, api_token=po_token)
    client.send_message(message, title="Docker Event")
    ##    global pb_key
    ##    pb = Pushbullet(pb_key)
    ##    pb.push_note("Docker Event", message)
    pass
def check(push, show):
    header = {'Authorization': 'Token ' + API_TOKEN}
    session = requests.Session()
    url = "https://api.dusti.xyz/v1/node/"
    r = session.get(url, headers=header)
    if push:
        client = Client(PUSHOVER_CLIENT_TOKEN, api_token=PUSHOVER_API_TOKEN)
    for node in r.json():
        if node.get("last_data_push"):
            last_data_push = datetime.datetime.strptime(node.get("last_data_push")[:19],
                                                        "%Y-%m-%dT%H:%M:%S")
            sensor_id = node.get('sensors', [{}])[0].get('id')
            last_check_timestamp = check_file(sensor_id)
            uid = node.get('uid')
            description = node.get('sensors', [{}])[0].get('description')
            if (last_data_push < datetime.datetime.utcnow() - datetime.timedelta(minutes=LAST_N_MINUTES) and
                last_data_push > datetime.datetime.utcnow() - datetime.timedelta(hours=LAST_N_HOURS)):
                if show:
                    click.echo("{} | {:>35} | {}".format(last_data_push, uid, description))
                if not last_check_timestamp:
                    if push:
                        client.send_message("sensor: {}\ndescription: {}".format(uid, description),
                                            title="Sensor hasn't pushed in the last {} minutes!".format(LAST_N_MINUTES))
                        # FIXME: calculate moment of last push and add into message
                update_file(sensor_id, last_data_push)
            elif last_check_timestamp:
                delete_file(sensor_id)
                if push:
                    client.send_message("RESTORED sensor: {}\ndescription: {}".format(uid, description),
                                        title="Sensor is back again!")
Ejemplo n.º 3
0
class PushMessenger(object):
    def __init__(self, name, init, messager):
        self.name = name
        self.state = {}
        # for push notifications
        self.pb_key = os.environ.get('PB_TOKEN')
        self.pb_api_key = os.environ.get('PB_API_TOKEN')
        self.client = Client(self.pb_key, api_token=self.pb_api_key)

        #self.client.send_message("Iniciando sistema", title="Notificación")
        #self.children = init['children']
        self.messager = messager
        self.polling = 120
        self.last_check = 0
        self.place = init['place']

    def parse(self, message):
        parsed_m = []
        return parsed_m

    def send_message(self, command, state):
        try:
            self.client.send_message(command['value'], title="Notificación")
        except:
            print("Pushover no disponible")

        return

    def update(self, global_state):
        if (global_state['timestamp'] - self.last_check > self.polling):
            pass
            self.last_check = time.time()
        return
Ejemplo n.º 4
0
def send_push_request_accepted_if_token(pickUpRequest, user):
    if user.profile.pushover:
        client = Client(user.profile.pushover, api_token="ad9ohz7ege8sr2ejv3t3asfcnszyr9")
        client.send_message("Your PickUp Request to "+str(pickUpRequest.destination.title)+" was accepted. " +
                            "The drivers phone number is " + pickUpRequest.ride.user.profile.phone,
                            title="PickUp Request accepted",
                            url="https://hitchcar.pillo.ch/#/home", url_title="Open Hitchcar")
Ejemplo n.º 5
0
 def __init__(self, user_key, api_token):
     # pylint: disable=no-name-in-module, unused-variable
     from pushover import Client
     self._user_key = user_key
     self._api_token = api_token
     self.pushover = Client(
         self._user_key, api_token=self._api_token)
Ejemplo n.º 6
0
 def __init__(self, config, packpub_info, upload_info):
     self.__config = config
     self.__packpub_info = packpub_info
     self.__client = Client(self.__config.get('pushover',
                                              'pushover.user_key'),
                            api_token=self.__config.get(
                                'pushover', 'pushover.api_key'))
Ejemplo n.º 7
0
def send_notification(shop, url):
    try:
        for user in users:
            print("Message to: "+user, flush=True)
            client = Client(users[user],
                            api_token=Config.PUSHOVERTOKEN)
            client.send_message('PS5 beschikbaar bij {}. Click link:'.format(shop),
                                title="PS5 in Stock!", url=url)
    except:
        print("Error trying to send push notification")

    try:
        email = "*****@*****.**"
        password = Config.EMAILPW
        subject = "PS5 op voorraad bij {}".format(shop)
        message = "Link {}".format(url)

        msg = MIMEMultipart()
        msg["From"] = email
        msg["To"] = ", ".join(send_to_email)
        msg["Subject"] = subject

        msg.attach(MIMEText(message, 'plain'))

        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(email, password)
        text = msg.as_string()
        server.sendmail(email, send_to_email, text)
        server.quit()
    except:
        print("Failed to send email")
def send_notification(notification):
    if not API_TOKEN:
        print 'No Pushover API token set'
        return

    client = Client(USER_KEY, api_token=API_TOKEN)
    client.send_message(notification.body, title=notification.title)
Ejemplo n.º 9
0
class Pushover(object):
    """
    """
    def __init__(self, config, packpub_info, upload_info):
        self.__config = config
        self.__packpub_info = packpub_info
        self.__client = Client(self.__config.get('pushover',
                                                 'pushover.user_key'),
                               api_token=self.__config.get(
                                   'pushover', 'pushover.api_key'))

    def send(self):
        self.__client.send_message(
            self.__packpub_info['description'].encode('utf-8'),
            title="New book downloaded from Packt: " +
            self.__packpub_info['title'].encode('utf-8'),
            url="https://www.packtpub.com/packt/offers/free-learning",
            url_title="See more")
        log_success('[+] notification sent to pushover')

    def sendError(self, exception, source):
        self.__client.send_message(
            repr(exception),
            title='packtpub-crawler {source}: Could not download ebook'.format(
                source=source))
        log_success('[+] error notification sent to pushover')
Ejemplo n.º 10
0
class PushoverNotifier(object):
    """ Notifier class for Pushover """
    def __init__(self, cfg):
        """ Constructor

        :param cfg: Config object
        :type cfg: Config (namedtuple)
        """
        self._config = cfg
        self._apikey = cfg.pushover_apikey
        self._userkey = cfg.pushover_userkey

    def init(self):
        """ Initializes the notification.

        :return: None
        :rtype: None
        """
        self._client = Client(self._userkey, api_token=self._apikey)

    def send(self, current_ip):
        """ Sends the notification

        :param current_ip: Current IP address
        :type current_ip: str
        :return: None
        :rtype: None
        """
        self._client.send_message(f"New home IP address: {current_ip}")
Ejemplo n.º 11
0
class PushoverNotificationService(BaseNotificationService):
    """Implement the notification service for Pushover."""
    def __init__(self, user_key, api_token):
        """Initialize the service."""
        from pushover import Client
        self._user_key = user_key
        self._api_token = api_token
        self.pushover = Client(self._user_key, api_token=self._api_token)

    def send_message(self, message='', **kwargs):
        """Send a message to a user."""
        from pushover import RequestError

        # Make a copy and use empty dict if necessary
        data = dict(kwargs.get(ATTR_DATA) or {})

        data['title'] = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)

        targets = kwargs.get(ATTR_TARGET)

        if not isinstance(targets, list):
            targets = [targets]

        for target in targets:
            if target is not None:
                data['device'] = target

            try:
                self.pushover.send_message(message, **data)
            except ValueError as val_err:
                _LOGGER.error(str(val_err))
            except RequestError:
                _LOGGER.exception("Could not send pushover notification")
Ejemplo n.º 12
0
    def init(self):
        """ Initializes the notification.

        :return: None
        :rtype: None
        """
        self._client = Client(self._userkey, api_token=self._apikey)
Ejemplo n.º 13
0
class PushoverNotificationService(BaseNotificationService):
    """Implement the notification service for Pushover."""

    def __init__(self, user_key, api_token):
        """Initialize the service."""
        from pushover import Client
        self._user_key = user_key
        self._api_token = api_token
        self.pushover = Client(
            self._user_key, api_token=self._api_token)

    def send_message(self, message='', **kwargs):
        """Send a message to a user."""
        from pushover import RequestError

        # Make a copy and use empty dict if necessary
        data = dict(kwargs.get(ATTR_DATA) or {})

        data['title'] = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)

        targets = kwargs.get(ATTR_TARGET)

        if not isinstance(targets, list):
            targets = [targets]

        for target in targets:
            if target is not None:
                data['device'] = target

            try:
                self.pushover.send_message(message, **data)
            except ValueError as val_err:
                _LOGGER.error(str(val_err))
            except RequestError:
                _LOGGER.exception("Could not send pushover notification")
Ejemplo n.º 14
0
class Push:
    """Send push notifications using Pushover service."""

    def __init__(self, settings):
        """Construct the object based on settings."""
        self.client = Client(
            settings["pushover_user_key"], api_token=settings["pushover_api_token"]
        )
        if settings["pushover-enabled"]:
            self.enabled = True
        else:
            self.enabled = False

    @func_log
    def send_pushover_message(self, message: PushMessage):
        """Send a message, if push is enabled."""
        if self.enabled:
            logger.debug("Sending push message")
            self.client.send_message(message=message.message, title=message.title)
        else:
            print(
                "Push messages not enabled! [Title: {} Message: {}]".format(
                    message.title, message.message
                )
            )
Ejemplo n.º 15
0
 def __init__(self, user_key, api_token):
     """Initialize the service."""
     from pushover import Client
     self._user_key = user_key
     self._api_token = api_token
     self.pushover = Client(
         self._user_key, api_token=self._api_token)
Ejemplo n.º 16
0
 def __init__(self, user_key, api_token, is_allowed_path, local_www_path):
     """Initialize the service."""
     from pushover import Client
     self._user_key = user_key
     self._api_token = api_token
     self._is_allowed_path = is_allowed_path
     self._local_www_path = local_www_path
     self.pushover = Client(self._user_key, api_token=self._api_token)
Ejemplo n.º 17
0
def alert(text, **kwargs):
    """
    >>> alert("Doctest",title="Title", sound="magic",url="https://school4one.com/",attachment=genimage(),url_title="School 4 One Link")
    'OK'
    """
    client = Client(user, api_token=token)
    client.send_message(text, html=1, **kwargs)
    return 'OK'
Ejemplo n.º 18
0
    def act(item):
        webbrowser.open(item.url)

        engine = pyttsx3.init()
        engine.say("It's there!")
        engine.runAndWait()

        client = Client("<PUSHOVER CLIENT API>", api_token="<API TOKEN>")
        client.send_message(item.url, title=item.name + ": " + item.price)
Ejemplo n.º 19
0
def PONotif(chapter, series):
  global xml_list

  PO_token = re.search('<PO_token>(.*?)</PO_token>', xml_list, re.DOTALL|re.MULTILINE).group(1).strip()
  PO_user = re.search('<PO_user>(.*?)</PO_user>', xml_list, re.DOTALL|re.MULTILINE).group(1).strip()

  client = Client(PO_user, api_token=PO_token)

  client.send_message('Series: \"{}\"\nChapter: {}\n\n'.format(series, '{:3.1f}'.format(chapter['num']).zfill(5)), title="New manga chapter downloaded")
Ejemplo n.º 20
0
    def __init__(self):
        # public:
        self.config = configparser.ConfigParser()
        self.config.read('/etc/shannon.conf')
        self.token = self.config["PUSH"]["Token"]
        self.user_id = self.config["PUSH"]["UserId"]

        # private:
        self.__client = Client(self.user_id, api_token=self.token)
Ejemplo n.º 21
0
 def __init__(self, settings):
     """Construct the object based on settings."""
     self.client = Client(
         settings["pushover_user_key"], api_token=settings["pushover_api_token"]
     )
     if settings["pushover-enabled"]:
         self.enabled = True
     else:
         self.enabled = False
Ejemplo n.º 22
0
class PushOverPush:
    def __init__(self, user_key=PUSHOVER_USER_KEY, api_key=PUSHOVER_API_KEY):
        self.client = Client(user_key, api_token=api_key)

    def send_msg(self, title, url):
        self.client.send_message(url, title=title)

    def send_messages(self, entries):
        for i in entries:
            self.send_msg(i.title, i.link)
Ejemplo n.º 23
0
def pushover(app_key, ptitle, message):
    try:
        client = Client(config.get('pushover', 'user_key'), api_token=app_key)
        client.send_message(message, title=ptitle)
    except Exception as e:
        log.error('Pushover notification failed. Error: %s' % str(e))
        return False
    else:
        log.debug('Pushover notification sent. Title: {}'.format(ptitle))
        return True
Ejemplo n.º 24
0
 def __init__(self, config):
     self.logger = logging.getLogger("pushover")
     self.config = config
     self.pushover_api = Client(config['user-key'],
                                api_token=config['api-token'])
     self.last_time = int(time.time()) - self.config['timeout'] * 2
     if 'lock-file' not in self.config:
         self.config['lock-file'] = 'pushover.disable'
     self.config['lock-file'] = os.path.join(os.getcwd(),
                                             self.config['lock-file'])
Ejemplo n.º 25
0
def SendMessage(apiKey, clientkey, tit, mess, pri):
    init(apiKey)
    if pri == 2 or pri == "2":
        Client(clientKey).send_message(mess,
                                       title=tit,
                                       priority=pri,
                                       expire=120,
                                       retry=60)
    else:
        Client(clientKey).send_message(mess, title=tit, priority=pri)
Ejemplo n.º 26
0
 def __init__(self, apitoken, cache_path, pushover_apikey,
              pushover_userkey):
     """ init method, run at class creation """
     logger.debug("Connecting to GitHub")
     self._gh = login(token=apitoken)
     logger.info("Connected to GitHub API")
     self._cache_path = os.path.abspath(os.path.expanduser(cache_path))
     self._cache = self._get_cache()
     self._pushover = Client(pushover_userkey, api_token=pushover_apikey)
     logger.info('Connected to Pushover for user %s', pushover_userkey)
Ejemplo n.º 27
0
def send_pushover(title, message):
    if USER_KEY is None or API_TOKEN is None:
        print("missing pushover credentials")
        return -1
    global PUSHOVER_CLIENT
    if PUSHOVER_CLIENT is None:
        PUSHOVER_CLIENT = Client(USER_KEY, api_token=API_TOKEN)

    PUSHOVER_CLIENT.send_message(f"{message}", title=f"{title}")
    print("sent pushover")
def notify_pushover(is_success, status, stack_name):
    """ send notification via pushover """
    msg = 'Operation on stack {n} finished with status {s}'.format(n=stack_name,
                                                                   s=status)
    title = '{n}: {s}'.format(n=stack_name,
                              s=status)
    if is_success:
        req = Client().send_message(msg, title=title, priority=0)
    else:
        req = Client().send_message(msg, title=title, priority=0, sound='falling')
def PushNotification(push):
    try:
        if push_notification == "true":
            client = Client(push_user_key, api_token=push_api_token)
            client.send_message(time.strftime("%H:%M ") + push,
                                title="SolarPowerDiversion")
            return
        return
    except:
        print("PushNotification: failed")
Ejemplo n.º 30
0
class SonosUpdateHandler(FileSystemEventHandler):
	def __init__(self, system=SonosSystem(), interval=5.0,
		     api_key=None, user_key=None):
		super(SonosUpdateHandler, self).__init__()
		assert isinstance(system, SonosSystem)
		self.system = system
		self.interval = interval
		self.timer = None

		self.client = Client(user_key, api_token=api_key) \
			if api_key and user_key else None

		self.albuminfo = None

		syslog.syslog('Created SonosUpdateHandler: Interval {}'.format(
			self.interval))

	def on_moved(self, event):
		syslog.syslog('File moved event -> {}'.format(event.dest_path))
		
		file_path, filename = path.split(event.dest_path)
		file_path, album = path.split(file_path)
		file_path, artist = path.split(file_path)

		self.albuminfo = artist, album
		self._handle_valid_event(event)

	def on_deleted(self, event):
		syslog.syslog('File deleted event -> {}'.format(event.src_path))
		self._handle_valid_event(event)

	def _handle_valid_event(self, event):
		if self.timer:
			self.timer.cancel()

		self.timer = Timer(self.interval,
				   self._update_sonos)

		self.timer.start()

	def _update_sonos(self):
		self.timer = None

		syslog.syslog('Updating Sonos Library ...')
		self.system.update()

		if self.albuminfo and self.client:
			syslog.syslog('Sending pushover notification ...')
			artist, album = self.albuminfo
			self.albuminfo = None

			self.client.send_message(
				'{} - {}'.format(artist, album),
				title='Album Downloaded')
Ejemplo n.º 31
0
def WriteAudit(AuditMessage):
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H:%M:%S')
    Logger.info(st+'\t'+AuditMessage)
    with open(config.get('Files','auditlog'), "a") as auditfile:
       auditfile.write(st+'\t'+AuditMessage+'\n')
    auditfile.close()

    if config.getboolean('Pushover','enabled'):
        Pushover_client = Client(config.get('Pushover','user_key'),api_token=config.get('Pushover','api_token'))
        Pushover_client.send_message(st+'  '+AuditMessage, title=LANGUAGES_DICT[config.get('Defaults','language')]['doorbell_title'])
Ejemplo n.º 32
0
def pushover(title, message):
    user = "******"
    api = "avfytsyktracxood45myebobtry6yd"
    client = Client(user, api_token=api)
    client.send_message(message, title=title)
    
#from nipype.interfaces.ants import N4BiasFieldCorrection
#correct = N4BiasFieldCorrection()
#correct.inputs.input_image = in_file
#correct.inputs.output_image = out_file
#done = correct.run()
#img done.outputs.output_image
Ejemplo n.º 33
0
class PushConnection():
    def __init__(self):
        # public:
        self.config = configparser.ConfigParser()
        self.config.read('/etc/shannon.conf')
        self.token = self.config["PUSH"]["Token"]
        self.user_id = self.config["PUSH"]["UserId"]

        # private:
        self.__client = Client(self.user_id, api_token=self.token)

    def send_message(self, title: str, message: str):
        self.__client.send_message(message, title=title)
Ejemplo n.º 34
0
def PONotif(chapter, series):
    global xml_list

    PO_token = re.search('<PO_token>(.*?)</PO_token>', xml_list,
                         re.DOTALL | re.MULTILINE).group(1).strip()
    PO_user = re.search('<PO_user>(.*?)</PO_user>', xml_list,
                        re.DOTALL | re.MULTILINE).group(1).strip()

    client = Client(PO_user, api_token=PO_token)

    client.send_message('Series: \"{}\"\nChapter: {}\n\n'.format(
        series, '{:3.1f}'.format(chapter['num']).zfill(5)),
                        title="New manga chapter downloaded")
Ejemplo n.º 35
0
def notify(cfg):

    fitbit_tokens = cfg['fitbit_tokens']
    pushover_tokens = cfg['pushover_tokens']

    po = Client(pushover_tokens['id'], api_token=pushover_tokens['api_token'])

    authd_client = fitbit.Fitbit(fitbit_tokens['client'],
                                 fitbit_tokens['secret'],
                                 access_token=fitbit_tokens['access_token'],
                                 refresh_token=fitbit_tokens['refresh_token'])

    po.send_message(formatMsg(getMissingSteps(authd_client)), title="FitBit")
Ejemplo n.º 36
0
 def __init__(self, user_key, api_token):
     """Initialize the service."""
     from pushover import Client
     self._user_key = user_key
     self._api_token = api_token
     self.pushover = Client(
         self._user_key, api_token=self._api_token)
Ejemplo n.º 37
0
class Pushover(object):
    """
    """

    def __init__(self, config, packpub_info, upload_info):
        self.__config = config
        self.__packpub_info = packpub_info
        self.__client = Client(self.__config.get('pushover', 'pushover.user_key'), api_token=self.__config.get('pushover', 'pushover.api_key'))


    def send(self):
        self.__client.send_message(self.__packpub_info['description'].encode('utf-8'), title="New book downloaded from Packt: " + self.__packpub_info['title'].encode('utf-8'), url="https://www.packtpub.com/packt/offers/free-learning", url_title="See more")
        log_success('[+] notification sent to pushover')

    def sendError(self, exception, source):
        self.__client.send_message(repr(exception), title='packtpub-crawler {source}: Could not download ebook'.format(source=source))
        log_success('[+] error notification sent to pushover')
Ejemplo n.º 38
0
 def __init__(self, config):
     init(config.get("settings", "pushover_api_token"))
     self.client = Client(config.get("settings", "pushover_user_key"))
     self.btrfs_mount_points = [path for key, path in config.items("btrfs_mount_points")]
     self.data_dir = config.get("settings", "data_directory")
     self.suppression_window = config.getint("settings", "suppression_window")
     self.btrfs_enabled = config.getboolean("settings", "btrfs_enabled")
     self.zfs_enabled = config.getboolean("settings", "zfs_enabled")
 def __init__(self, apitoken, cache_path, pushover_apikey, pushover_userkey):
     """ init method, run at class creation """
     logger.debug("Connecting to GitHub")
     self._gh = login(token=apitoken)
     logger.info("Connected to GitHub API")
     self._cache_path = os.path.abspath(os.path.expanduser(cache_path))
     self._cache = self._get_cache()
     self._pushover = Client(pushover_userkey, api_token=pushover_apikey)
     logger.info('Connected to Pushover for user %s', pushover_userkey)
Ejemplo n.º 40
0
class PushoverNotificationService(BaseNotificationService):
    """ Implements notification service for Pushover. """

    def __init__(self, user_key, api_token):
        from pushover import Client
        self._user_key = user_key
        self._api_token = api_token
        self.pushover = Client(
            self._user_key, api_token=self._api_token)

    def send_message(self, message="", **kwargs):
        """ Send a message to a user. """
        from pushover import RequestError

        try:
            self.pushover.send_message(message, title=kwargs.get(ATTR_TITLE))
        except RequestError:
            _LOGGER.exception("Could not send pushover notification")
Ejemplo n.º 41
0
def main():
  init(PUSHOVER_TOKEN)
  pushover = Client(PUSHOVER_KEY)
  tz = pytz.timezone(TIMEZONE)
  now = tz.normalize(datetime.utcnow().replace(tzinfo=pytz.utc))
  card_number = os.getenv('CARD_NUMBER')
  db = Database(DATABASE_URL)
  current_value = db.get_balance()
  edenred_value = balance(int(card_number))
  print '{0}\t{1}\t{2}'.format(now, current_value, edenred_value)
  if current_value != edenred_value:
    delta = edenred_value - current_value
    db.add_balance(edenred_value)
    message = 'Edenred {3}. Previous {0}. Current {1}. Delta {2}.'.format(
      current_value,
      edenred_value,
      delta,
      now.strftime('%Y-%m-%d %H:%M:%S'))
    pushover.send_message(message, title='Edenred')
 def __init__(self, pokemon, bot):
     self.pokemon = pokemon
     self.api = bot.api
     self.bot = bot
     self.position = bot.position
     self.config = bot.config
     self.pokemon_list = bot.pokemon_list
     self.item_list = bot.item_list
     self.inventory = bot.inventory
     self.client = Client(self.config.pushover_user_key, api_token=self.config.pushover_api_token)
def main():
    client = Client("<user-key>", api_token="<api-token>")
    while 1:
        # transition from ACKNOWLEDGED to READY
        write_stdout('READY\n')

        # read header line and print it to stderr
        line = sys.stdin.readline()
        # read event payload and print it to stderr
        headers = dict([ x.split(':') for x in line.split() ])
        data = sys.stdin.read(int(headers['len']))
        data_dic = dict([ x.split(':') for x in data.split()])
        group_name = data_dic.get('groupname')
        process_name = data_dic.get('processname')
        pid = data_dic.get('pid')
        from_state = data_dic.get('from_state')
        message = "{} with the pid {} just stopped.".format(process_name, pid)
        client.send_message(message, title=group_name)

        # transition from READY to ACKNOWLEDGED
        write_stdout('RESULT 2\nOK')
Ejemplo n.º 44
0
class PushoverClient(PushNotificationClient):

    _client = None
    _api_token = "aYBH7B28vQCKopoJXGCnwQ5NhPTG9w"

    def get_name(self):
        return "Pushover"

    def set_api_key(self, api):
        try:
            self._client = Client(user_key=api, api_token=self._api_token)
        except Exception as e:
            self._logger.exception(str(e))

    def send_message(self, title, msg):
        try:
            self._client.send_message(title=title, message=msg)
        except Exception as e:
            self._logger.exception(str(e))

    def set_logger(self, logger):
        pass
Ejemplo n.º 45
0
	def __init__(self, system=SonosSystem(), interval=5.0,
		     api_key=None, user_key=None):
		super(SonosUpdateHandler, self).__init__()
		assert isinstance(system, SonosSystem)
		self.system = system
		self.interval = interval
		self.timer = None

		self.client = Client(user_key, api_token=api_key) \
			if api_key and user_key else None

		self.albuminfo = None

		syslog.syslog('Created SonosUpdateHandler: Interval {}'.format(
			self.interval))
Ejemplo n.º 46
0
def send_to_pushover(astring):
	client = Client(USER_KEY, api_token = API_TOKEN)
	astring = "***Coastalwatch Report***\n" + astring
	client.send_message(astring)
class GithubPushoverIssueNotifier(object):

    def __init__(self, apitoken, cache_path, pushover_apikey, pushover_userkey):
        """ init method, run at class creation """
        logger.debug("Connecting to GitHub")
        self._gh = login(token=apitoken)
        logger.info("Connected to GitHub API")
        self._cache_path = os.path.abspath(os.path.expanduser(cache_path))
        self._cache = self._get_cache()
        self._pushover = Client(pushover_userkey, api_token=pushover_apikey)
        logger.info('Connected to Pushover for user %s', pushover_userkey)

    def _get_cache(self):
        logger.debug('Reading state cache from: %s', self._cache_path)
        if not os.path.exists(self._cache_path):
            logger.debug('State cache does not exist.')
            return {}
        with open(self._cache_path, 'r') as fh:
            raw = fh.read()
        cache = json.loads(raw)
        logger.debug('State cache: %s', cache)
        return cache

    def _write_cache(self):
        logger.debug('Writing state cache to: %s', self._cache_path)
        with open(self._cache_path, 'w') as fh:
            fh.write(json.dumps(self._cache))
        logger.debug('State written.')

    def run(self, issues):
        """check the issues, notify if needed"""
        logger.info('Checking issues: %s', [i['url'] for i in issues])
        for i in issues:
            try:
                self._do_issue(i['user'], i['repo'], i['num'], i['url'])
            except Exception:
                logger.error('Unable to get issue %s/%s #%d', user,
                             repo, num, exc_info=True)
        logger.debug('Done with issues.')
        self._write_cache()

    def _send(self, title, body):
        logger.debug('Sending via pushover: title="%s" body="%s"', title, body)
        try:
            self._pushover.send_message(body, title=title)
        except Exception:
            logger.error('Error sending Pushover notification', exc_info=True)

    def _do_issue(self, user, repo, num, url):
        logger.debug('Checking issue: %s/%s #%d', user, repo, num)
        issue = self._gh.issue(user, repo, num)
        closed = issue.is_closed()
        num_comments = 0
        for comment in issue.comments():
            num_comments += 1
        updated = mktime(issue.updated_at.timetuple())
        logger.debug('Issue %s/%s #%d: closed=%s, %d comments, updated at %s',
                     user, repo, num, closed, num_comments, updated)
        if url not in self._cache:
            logger.info('Issue %s/%s %#d not in cache yet', user, repo, num)
            self._cache[url] = {
                'closed': closed,
                'num_comments': num_comments,
                'updated': updated
            }
            return
        cached = self._cache[url]
        logger.debug('Cached issue info: %s', cached)
        msg = None
        if closed != cached['closed']:
            logger.debug('closed status has changed from %s to %s',
                         cached['closed'], closed)
            if closed:
                msg = 'closed'
            else:
                msg = 'reopened'
        elif num_comments != cached['num_comments']:
            logger.debug('num_comments has changed from %d to %d',
                         cached['num_comments'], num_comments)
            msg = 'has %d new comments' % (
                num_comments - cached['num_comments']
            )
        elif updated != cached['updated']:
            logger.debug('updated has changed from %s to %s',
                         cached['updated'], updated)
            msg = 'updated'
        if msg is None:
            logger.debug('No changes for issue %s/%s #%d', user, repo, num)
            return
        title = 'GitHub issue %s/%s #%d %s' % (
            user, repo, num, msg
        )
        self._send(title, url)
        self._cache[url] = {
            'closed': closed,
            'num_comments': num_comments,
            'updated': updated
        }
def notify(message):
    init(cfg['pushover_api'])
    client = Client(cfg['pushover_user'])
    client.send_message(message, title="Cat Alert")
Ejemplo n.º 49
0
def send_msg(msg):
    client = Client("uyxKeBztgT4H5hzjHfiuQhUUnECDHj", api_token="aqzv1irjog4tcp53ove7stsuedxiut", device="motog3renan")
    client.send_message(msg, title="Alert Aqua Temp")
Ejemplo n.º 50
0
# -*- coding: utf-8 -*-
from pushover import Client
 
client = Client("uaP3kPqNsnccmJhjvwRzGK3Hbsh1K5", api_token="aaFWwMm1G3YP2iPKNPjTsHa3QEc6tS")
client.send_message("Test Mesaji", title="Test Basligi")
client.send_message("Deneme Mesajı", title="DENEME BAŞLIĞIS")
Ejemplo n.º 51
0
 def __init__(self, config, packpub_info, upload_info):
     self.__config = config
     self.__packpub_info = packpub_info
     self.__client = Client(self.__config.get('pushover', 'pushover.user_key'), api_token=self.__config.get('pushover', 'pushover.api_key'))
Ejemplo n.º 52
0
 def __init__(self, user_key, api_token):
     from pushover import Client
     self._user_key = user_key
     self._api_token = api_token
     self.pushover = Client(
         self._user_key, api_token=self._api_token)
Ejemplo n.º 53
0
 def set_api_key(self, api):
     try:
         self._client = Client(user_key=api, api_token=self._api_token)
     except Exception as e:
         self._logger.exception(str(e))
Ejemplo n.º 54
0
import time
from pushover import Client

start_time = time.time()  # 初始时间戳
now = time.strftime("%Y%m%d", time.localtime())  # 当前日期戳
file_name = 'PushOver'  # 文件名
path_prefix = '/Users/alicewish/我的坚果云/'  # 文件地址前缀
txt_file_path = path_prefix + file_name + '.txt'  # TXT文件名
# ================按行读取文本:with open(更好)================
text_readline = []  # 初始化按行存储数据列表,不接受结尾换行符
with open(txt_file_path) as fin:
    for line in fin:
        text_readline.append((line).replace('\n', ''))

my_user_key = text_readline[0]
my_api_token = text_readline[1]

client = Client(my_user_key, api_token=my_api_token)
client.send_message("测试内容……" + now, title="标题", sound="cosmic")

# send_message可用关键字包括title, priority, sound, callback, timestamp, url, url_title, device, retry

# ================运行时间计时================
run_time = time.time() - start_time
if run_time < 60:  # 两位小数的秒
    print("耗时:{:.2f}秒".format(run_time))
elif run_time < 3600:  # 分秒取整
    print("耗时:{:.0f}分{:.0f}秒".format(run_time // 60, run_time % 60))
else:  # 时分秒取整
    print("耗时:{:.0f}时{:.0f}分{:.0f}秒".format(run_time // 3600, run_time % 3600 // 60, run_time % 60))
Ejemplo n.º 55
0
class RaidStatusChecker(object):
    def __init__(self, config):
        init(config.get("settings", "pushover_api_token"))
        self.client = Client(config.get("settings", "pushover_user_key"))
        self.btrfs_mount_points = [path for key, path in config.items("btrfs_mount_points")]
        self.data_dir = config.get("settings", "data_directory")
        self.suppression_window = config.getint("settings", "suppression_window")
        self.btrfs_enabled = config.getboolean("settings", "btrfs_enabled")
        self.zfs_enabled = config.getboolean("settings", "zfs_enabled")

    @suppression_window
    def check_btrfs_stats(self):
        for mount_point in self.btrfs_mount_points:
            stats_filename = "%s/btrfs-stats_%s.p" % (self.data_dir, mount_point[1:].replace("/", "-"))

            device_stats = {}
            if os.path.exists(stats_filename):
                device_stats = pickle.load(open(stats_filename, "rb"))

            status = check_output(["sudo", "btrfs", "device", "stats", mount_point]).decode("utf-8").strip()
            new_errors = False
            regex = re.compile('\[/dev/(.*)\]\.(\S*)\s*(\d*)')

            for line in status.split('\n'):
                match = regex.match(line)
                if match is not None:
                    if match.group(1) not in device_stats:
                        device_stats[match.group(1)] = {}
                    previous_stats = device_stats[match.group(1)].get(match.group(2), 0)
                    if int(match.group(3)) > previous_stats:
                        device_stats[match.group(1)][match.group(2)] = int(match.group(3))
                        new_errors = True

            if not os.path.exists(self.data_dir):
                os.mkdir(self.data_dir)

            pickle.dump(device_stats, open(stats_filename, "wb"))

            if new_errors is not False:
                self.client.send_message(status, title="BTRFS Errors: %s" % mount_point)

    @suppression_window
    def check_btrfs_drives(self):
        status = check_output(["sudo", "btrfs", "fi", "show", "-d"]).decode("utf-8").strip()

        regex = re.compile('(missing|warning)')
        if regex.match(status) is not None:
            self.client.send_message(status, title="BTRFS Array Error")

    @suppression_window
    def check_zfs_drives(self):
        status = check_output(["sudo", "zpool", "status", "-x"])
        if status != "all pools are healthy":
            self.client.send_message(status, title="ZFS Array Error")

    def run(self):
        if self.zfs_enabled:
            self.check_zfs_drives()

        if self.btrfs_enabled:
            self.check_btrfs_stats()
            self.check_btrfs_drives()
Ejemplo n.º 56
0
def send_pushover_notification(message, title):
    client = Client(conf.PUSHOVER_USER, api_token=conf.PUSHOVER_API_TOKEN)
    return client.send_message(message, title=title, html=1)
class PokemonCatchWorker(object):
    BAG_FULL = 'bag_full'
    NO_POKEBALLS = 'no_pokeballs'
    
    def __init__(self, pokemon, bot):
        self.pokemon = pokemon
        self.api = bot.api
        self.bot = bot
        self.position = bot.position
        self.config = bot.config
        self.pokemon_list = bot.pokemon_list
        self.item_list = bot.item_list
        self.inventory = bot.inventory
        self.client = Client(self.config.pushover_user_key, api_token=self.config.pushover_api_token)

    def work(self):
        encounter_id = self.pokemon['encounter_id']
        spawnpoint_id = self.pokemon['spawnpoint_id']
        player_latitude = self.pokemon['latitude']
        player_longitude = self.pokemon['longitude']
        self.api.encounter(encounter_id=encounter_id, spawnpoint_id=spawnpoint_id,
                           player_latitude=player_latitude, player_longitude=player_longitude)
        response_dict = self.api.call()

        if response_dict and 'responses' in response_dict:
            if 'ENCOUNTER' in response_dict['responses']:
                if 'status' in response_dict['responses']['ENCOUNTER']:
                    if response_dict['responses']['ENCOUNTER']['status'] is 7:
                        logger.log('[x] Pokemon Bag is full!', 'red')
                        return PokemonCatchWorker.BAG_FULL

                    if response_dict['responses']['ENCOUNTER']['status'] is 1:
                        cp = 0
                        total_IV = 0
                        if 'wild_pokemon' in response_dict['responses']['ENCOUNTER']:
                            pokemon = response_dict['responses']['ENCOUNTER']['wild_pokemon']
                            catch_rate = response_dict['responses']['ENCOUNTER']['capture_probability']['capture_probability'] # 0 = pokeballs, 1 great balls, 3 ultra balls

                            if 'pokemon_data' in pokemon and 'cp' in pokemon['pokemon_data']:
                                cp = pokemon['pokemon_data']['cp']
                                iv_stats = ['individual_attack', 'individual_defense', 'individual_stamina']

                                for individual_stat in iv_stats:
                                    try:
                                        total_IV += pokemon['pokemon_data'][individual_stat]
                                    except:
                                        pokemon['pokemon_data'][individual_stat] = 0
                                        continue

                                pokemon_potential = round((total_IV / 45.0), 2)
                                pokemon_num = int(pokemon['pokemon_data'][
                                                  'pokemon_id']) - 1
                                pokemon_name = self.pokemon_list[
                                    int(pokemon_num)]['Name']
                                logger.log('[#] A Wild {} appeared! [CP {}] [Potential {}]'.format(
                                    pokemon_name, cp, pokemon_potential), 'yellow')

                                logger.log('[#] IV [Stamina/Attack/Defense] = [{}/{}/{}]'.format(
                                    pokemon['pokemon_data']['individual_stamina'],
                                    pokemon['pokemon_data']['individual_attack'],
                                    pokemon['pokemon_data']['individual_defense']
                                ))
                                pokemon['pokemon_data']['name'] = pokemon_name
                                # Simulate app
                                sleep(3)

                        balls_stock = self.bot.pokeball_inventory()
                        while(True):

                            pokeball = 1 # default:poke ball

                            if balls_stock[1] <= 0: # if poke ball are out of stock
                                if balls_stock[2] > 0: # and player has great balls in stock...
                                    pokeball = 2 # then use great balls
                                elif balls_stock[3] > 0: # or if great balls are out of stock too, and player has ultra balls...
                                    pokeball = 3 # then use ultra balls
                                else:
                                    pokeball = 0 # player doesn't have any of pokeballs, great balls or ultra balls

                            while(pokeball < 3):
                                if catch_rate[pokeball-1] < 0.35 and balls_stock[pokeball+1] > 0:
                                    # if current ball chance to catch is under 35%, and player has better ball - then use it
                                    pokeball = pokeball+1 # use better ball
                                else:
                                    break

                            # @TODO, use the best ball in stock to catch VIP (Very Important Pokemon: Configurable)

                            if pokeball is 0:
                                logger.log(
                                    '[x] Out of pokeballs, switching to farming mode...', 'red')
                                # Begin searching for pokestops.
                                self.config.mode = 'farm'
                                return PokemonCatchWorker.NO_POKEBALLS

                            balls_stock[pokeball] = balls_stock[pokeball] - 1
                            success_percentage = '{0:.2f}'.format(catch_rate[pokeball-1]*100)
                            logger.log('[x] Using {} (chance: {}%)... ({} left!)'.format(
                                self.item_list[str(pokeball)], 
                                success_percentage, 
                                balls_stock[pokeball]
                            ))

                            id_list1 = self.count_pokemon_inventory()
                            self.api.catch_pokemon(encounter_id=encounter_id,
                                                   pokeball=pokeball,
                                                   normalized_reticle_size=1.950,
                                                   spawn_point_guid=spawnpoint_id,
                                                   hit_pokemon=1,
                                                   spin_modifier=1,
                                                   NormalizedHitPosition=1)
                            response_dict = self.api.call()

                            if response_dict and \
                                'responses' in response_dict and \
                                'CATCH_POKEMON' in response_dict['responses'] and \
                                    'status' in response_dict['responses']['CATCH_POKEMON']:
                                status = response_dict['responses'][
                                    'CATCH_POKEMON']['status']
                                if status is 2:
                                    logger.log(
                                        '[-] Attempted to capture {}- failed.. trying again!'.format(pokemon_name), 'red')
                                    sleep(2)
                                    continue
                                if status is 3:
                                    logger.log(
                                        '[x] Oh no! {} vanished! :('.format(pokemon_name), 'red')
                                if status is 1:
                                    logger.log(
                                        '[x] Captured {}! [CP {}] [IV {}]'.format(
                                            pokemon_name,
                                            cp,
                                            pokemon_potential
                                        ), 'green'
                                    )

                                    id_list2 = self.count_pokemon_inventory()

                                    if self.config.evolve_captured:
                                        pokemon_to_transfer = list(Set(id_list2) - Set(id_list1))
                                        self.api.evolve_pokemon(pokemon_id=pokemon_to_transfer[0])
                                        response_dict = self.api.call()
                                        status = response_dict['responses']['EVOLVE_POKEMON']['result']
                                        if status == 1:
                                            logger.log(
                                                    '[#] {} has been evolved!'.format(pokemon_name), 'green')
                                        else:
                                            logger.log(
                                            '[x] Failed to evolve {}!'.format(pokemon_name))

                                    if self.should_release_pokemon(pokemon_name, cp, pokemon_potential, response_dict):
                                        # Transfering Pokemon
                                        pokemon_to_transfer = list(
                                            Set(id_list2) - Set(id_list1))
                                        if len(pokemon_to_transfer) == 0:
                                            raise RuntimeError(
                                                'Trying to transfer 0 pokemons!')
                                        self.transfer_pokemon(
                                            pokemon_to_transfer[0])
                                        logger.log(
                                            '[#] {} has been exchanged for candy!'.format(pokemon_name), 'green')

                                        message = '{} [CP {}] [IV {}], exchanged it for candy.'.format(
                                            pokemon_name,
                                            cp,
                                            pokemon_potential
                                        )

                                        self.client.send_message(message, title="Captured a Pokemon")
                                    else:
                                        logger.log(
                                        '[x] Captured {}! [CP {}]'.format(pokemon_name, cp), 'green')

                                        message = '{} [CP {}] [IV {}], kept it.'.format(
                                            pokemon_name,
                                            cp,
                                            pokemon_potential
                                        )

                                        self.client.send_message(message, title="Captured a Pokemon")
                            break
        time.sleep(5)

    def _transfer_low_cp_pokemon(self, value):
        self.api.get_inventory()
        response_dict = self.api.call()
        self._transfer_all_low_cp_pokemon(value, response_dict)

    def _transfer_all_low_cp_pokemon(self, value, response_dict):
        try:
            reduce(dict.__getitem__, [
                   "responses", "GET_INVENTORY", "inventory_delta", "inventory_items"], response_dict)
        except KeyError:
            pass
        else:
            for item in response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                try:
                    reduce(dict.__getitem__, [
                           "inventory_item_data", "pokemon"], item)
                except KeyError:
                    pass
                else:
                    pokemon = item['inventory_item_data']['pokemon']
                    self._execute_pokemon_transfer(value, pokemon)
                    time.sleep(1.2)

    def _execute_pokemon_transfer(self, value, pokemon):
        if 'cp' in pokemon and pokemon['cp'] < value:
            self.api.release_pokemon(pokemon_id=pokemon['id'])
            response_dict = self.api.call()

    def transfer_pokemon(self, pid):
        self.api.release_pokemon(pokemon_id=pid)
        response_dict = self.api.call()

    def count_pokemon_inventory(self):
        self.api.get_inventory()
        response_dict = self.api.call()
        id_list = []
        return self.counting_pokemon(response_dict, id_list)

    def counting_pokemon(self, response_dict, id_list):
        try:
            reduce(dict.__getitem__, [
                   "responses", "GET_INVENTORY", "inventory_delta", "inventory_items"], response_dict)
        except KeyError:
            pass
        else:
            for item in response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
                try:
                    reduce(dict.__getitem__, [
                           "inventory_item_data", "pokemon_data"], item)
                except KeyError:
                    pass
                else:
                    pokemon = item['inventory_item_data']['pokemon_data']
                    if pokemon.get('is_egg', False):
                        continue
                    id_list.append(pokemon['id'])

        return id_list

    def should_release_pokemon(self, pokemon_name, cp, iv, response_dict):
        if self._check_always_capture_exception_for(pokemon_name):
            return False
        else:
            release_config = self._get_release_config_for(pokemon_name)
            cp_iv_logic = release_config.get('cp_iv_logic')
            if not cp_iv_logic:
                cp_iv_logic = self._get_release_config_for('any').get('cp_iv_logic', 'and')

            release_results = {
                'cp':               False,
                'iv':               False,
            }

            if 'release_under_cp' in release_config:
                min_cp = release_config['release_under_cp']
                if cp < min_cp:
                    release_results['cp'] = True

            if 'release_under_iv' in release_config:
                min_iv = release_config['release_under_iv']
                if iv < min_iv:
                    release_results['iv'] = True

            if release_config.get('always_release'):
                return True

            logic_to_function = {
                'or': lambda x, y: x or y,
                'and': lambda x, y: x and y
            }

            #logger.log(
            #    "[x] Release config for {}: CP {} {} IV {}".format(
            #        pokemon_name,
            #        min_cp,
            #        cp_iv_logic,
            #        min_iv
            #    ), 'yellow'
            #)

            return logic_to_function[cp_iv_logic](*release_results.values())

    def _get_release_config_for(self, pokemon):
        release_config = self.config.release_config.get(pokemon)
        if not release_config:
            release_config = self.config.release_config['any']
        return release_config

    def _get_exceptions(self):
        exceptions = self.config.release_config.get('exceptions')
        if not exceptions:
            return None
        return exceptions

    def _get_always_capture_list(self):
        exceptions = self._get_exceptions()
        if not exceptions:
            return []
        always_capture_list = exceptions['always_capture']
        if not always_capture_list:
            return []
        return always_capture_list

    def _check_always_capture_exception_for(self, pokemon_name):
        always_capture_list = self._get_always_capture_list()
        if not always_capture_list:
            return False
        else:
            for pokemon in always_capture_list:
                if pokemon_name == str(pokemon):
                    return True
        return False
Ejemplo n.º 58
0
def send(title, message, options):
    if options['pushover']['enable']:
        client = Client(options['pushover']['user'], api_token=options['pushover']['apiToken'])
        client.send_message(message, title=title, priority=-1)
def monitorCasa():
    print("Iniciando....")
    logging.info('Starting')
    print("conectando pushbullet")

    po_client = Client(pb_key, api_token = pb_api_key)
    previo_no_tv='0'


    #resetear alarma
    globales['alarma'] = False
    globales['alarma_trip'] = False
    globales['alarma_enviada'] = False
    globales['auto_ac'] = False
    globales['activo'] = True
    actualizar_global('auto_ac',0, con2)
    actualizar_global('activo',1.0, con2)
    actualizar_global('auto_luces',1.0, con2)
    actualizar_global('alarma',0, con2)
    actualizar_global('chapa',0, con2)

    chapa_por_cerrar = False

    print("Probando sonos...")
    estado_sonos = tocar('iniciar.mp3')

    print("Apagando luces...")
    for key in luces:
        apagarGrupo(luces[key])
        estado_luces[key] = False
        print "Luces activas, apagadas " + key

    


    #limpiar comandos pendientes
    print("Conectando con bd de comandos...")
    concom = lite.connect('/Volumes/mmshared/bdatos/comandos.db')

    with concom:
        c = concom.cursor()
        c.execute('DELETE FROM pendientes') 
    concom.close()
    #iniciar conteos
    tiempo_comandos= time.time()
    tiempo_sonos = time.time()
    time_loop = time.time() 
    log_time = time.time()
    dweepy_time = time.time()
    dweepy_time_2 = time.time()
    felipe_phone_time = time.time()
    check_lights_time = time.time()
    tiempos_registro = {}
    estado_hue={}
    mom_registrar = {}
    tiempo_encendido={}
    for lugar in lugares:
        tiempos_registro[lugar] = 0
        mom_registrar[lugar] = 0
        movimiento_st[lugar] = 0.0
        estado_luces[lugar] = False
        tiempo_encendido[lugar] = 0

    tiempo_pressure = time.time()
    
    for key in tiempos_registro:
        tiempos_registro[key] = time.time()
    for key in mom_registrar:
        mom_registrar[key] = time.time()
    for key in tiempo_encendido:
        tiempo_encendido[key] = 0
    


    # xbees iniciar conección
    print("Activar xbee coordinator...")
    try:
        serialConnection = serial.Serial( SERIAL_PORT, 9600,timeout=0.15)
        xbee = ZigBee(serialConnection)
        print "Conexión xbee serial...OK"
    except:
        logging.warning('Error serial/xbee')
        print "Error serial/xbee"
    # luces cocina apagadas
    xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xbe\xf8\x62',command='D2',parameter='\x04')
    # zumbador apagado
    xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xbe\xf8\x62',command='D1',parameter='\x04')
    tstamp = time.time()

    anterior = time.time()
    #################### ciclo de monitoreo #########################
    print ("Iniciar ciclo principal...")
    contar_mysql=0
    while True:
        #tstamp del ciclo
        #print tstamp - time.time()

        tstamp = time.time()
        dt = datetime.datetime.fromtimestamp(tstamp, tz=tzone)
         # apagar si no se ha detectado movimiento en un rato
        for key in tiempo_movimiento:
            if((tstamp - tiempo_movimiento[key] ) >= delay_luces_l[key]):
                if(globales['activo'] and estado_luces[key] and globales['auto_luces']):
                    if(key=='cocina'):
                        xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xbe\xf8\x62',command='D2',parameter='\x04')
                        #estado_luces[key] = False
                        print("Apagar cocina.")
                    else:
                        if(ocupacion[key]==0):
                            apagarGrupo(luces[key])
                    estado_luces[key] = False
                    



        ##en inicio todos los movimientos son falsos
        for lugar in lugares:
            movimiento[lugar] = False

        ## leer xbee y procesar ############################

        response = xbee.wait_read_frame(timeout=0.15)
        #print(response)

        if('source_addr_long' in response.keys()):
            source = response['source_addr_long'].encode('hex')

            lugar = myxbees[source]
            
            if(lugar=='bano_escalera'):
                print "***** " + lugar
                print(response)

            #if(lugar=='cocina_entrada'):
            #    print(lugar)
            #    print(response)
            #    print('--------')

            st = datetime.datetime.fromtimestamp(tstamp, tz=tzone).strftime('%Y-%m-%d %H:%M:%S')
            if('rf_data' in response.keys()):
                ocurrencia = procesar_rf(response, st) ## datos de arduino
            if('samples' in response.keys()):
                ocurrencia = procesar_samples_unif(response, st) # datos de xbee sin arduino 
            if(lugar=='bano_escalera'):
                print "***** " + lugar
                print(ocurrencia)
                
        #######################################################   
            logging.info('Ocurrencia:'+str(ocurrencia))
            # niveles de luz y movimiento, puertas
          
            for item in ocurrencia:
                if(len(item)>6): ## evitar mesnajes de error de xbees
                    sensor_i = item[3]
                    lugar_i = item[2]
                    valor_i = item[6]
                    ## actualizar lecturas de luz
                    if(sensor_i=='ct'):
                        if(item[4]=='A'):
                            #print "Amperes " + str(valor_i)
                            globales['mA'] = str(int(1000*float(valor_i)))
                            actualizar_global('amperes', float(valor_i), con2)
                        if(item[4]=='kW'):
                            actualizar_global('kW', float(valor_i), con2)
                            globales['W'] = str(int(1000*float(valor_i)))
                    if(sensor_i=='dust_density'):
                        print("***************")
                        print(ocurrencia)
                    if(sensor_i == 'photo'):
                        try:
                            niveles_luz[lugar_i] = float(valor_i)
                            #poner nivel de cuarto a baño de cuarto
                            if(lugar_i=='cuarto'):
                                niveles_luz['bano_cuarto'] = float(valor_i) 
                        except:
                            print "Error float luz"
                    # actualizar movimiento
                    if(sensor_i == 'pir'):
                        movimiento['casa'] == True
                        mov = movimiento[lugar_i]
                        movimiento[lugar_i] = (valor_i=='1') or mov ## para más de un pir en un mismo lugar
                        if(lugar_i=='tv' and valor_i=='1'):
                            no_sensor = item[5]
                            movimiento_tv_st[item[5]] = 1.0
                            if(movimiento_tv_st['2'] > movimiento_tv_st['1']):
                                ocupacion['tv'] = 1
                            if(movimiento_tv_st['1'] > movimiento_tv_st['2']):
                                ocupacion['tv'] = 0
                            #if(movimiento_tv_st['2']==1.0 and movimiento_tv_st['1']>0.99):
                            #    ocupacion['tv'] = ocupacion['tv'] + 1
                            #if(movimiento_tv_st['1']==1.0 and movimiento_tv_st['2']>0.99):
                            #    ocupacion['tv'] = ocupacion['tv'] - 1
                        #print ocupacion
                        #print movimiento_tv_st
                    if(sensor_i== 'lev_snd'):  ## por el momento, el sonido está en el vector movimiento.
                        #print 'sonido_env: '+valor_i
                        if(lugar_i=='cuarto'):
                            if(float(valor_i) > 15):
                                movimiento[lugar_i] = True
                        if(lugar_i=='vestidor'):
                            try:
                                valor_snd = float(valor_i)
                                if(valor_snd > 155.0):
                                    if(not globales['ac_encendido']):
                                        globales['ac_encendido'] = True
                                        actualizar_global('ac', 1.0, con2)
                                else:
                                    if(globales['ac_encendido']):
                                        globales['ac_encendido'] = False
                                        actualizar_global('ac', 0.0, con2)
                                    #
                            except:
                                logging.info('Error sonido')
                            #print "Sonido"
                    ## reed switches
                    if(sensor_i=='puerta' and valor_i=='0'):
                        puertas[lugar_i] = 0
                        if(lugar_i=='puerta'):
                            movimiento['entrada'] = True  
                            globales['chapa'] = False

                        if(tstamp-tiempo_sonos > 15):
                            tiempo_sonos=time.time()
                            if(not  globales['alarma']):
                                estado_sonos = tocar("doorbell.mp3")
                            else:
                                tiempo_sonos=time.time() + 50
                                globales['alarma_trip'] = True
                                sonos.volume = 100
                                estado_sonos = tocar("bs_alarm.mp3") ## tocar cuando hay alarma
                                #sonos.volume = 40
                    if(sensor_i=='puerta' and valor_i=='1'):
                        if(puertas[lugar_i]==0 and lugar=='puerta'):
                            tiempo_cerrar_chapa = time.time()
                            chapa_por_cerrar = True
                        puertas[lugar_i] = 1
                        
                    ## temperaturas
                    if(sensor_i=='temperature'):
                        if(temperaturas[lugar_i] > 0):
                            #promediar temps porque algunas cajas tienen 2 sensores
                            try:
                                temperaturas[lugar_i] = (float(item[6]) + temperaturas[lugar_i])/2 
                            except:
                                temperaturas[lugar_i] = -99.99
                        else:
                            try:
                                temperaturas[lugar_i] = float(item[6])
                            except:
                                temperaturas[lugar_i] = -99.99
                    ## humedad
                    if(sensor_i=='humidity'):
                        try:
                            humedades[lugar_i] = float(valor_i)
                        except:
                            print "Error humedad"
                    ## checar gas
                    if(sensor_i =='gaslpg'):
                        gas[lugar_i] = valor_i
                        try:
                            if(float(valor_i) > 600):
                                globales['alarma_gas'] = True
                                lugar_gas = lugar_i
                                lectura = valor_i
                        except:
                            logging.error('Error float gas')



        ######### checar luces ########


        if(time.time()-check_lights_time > 15):
            #print "Check lights"
            try:
                check_lights_time = time.time()
                r_state = requests.get(ip_hue+'lights/', timeout=0.1)
                if(r_state.status_code == 200):
                    rs = r_state.json()
                    for key in rs:
                        estado_hue[rs[key]['name']] = rs[key]['state']['on']
                    #print estado_hue
                    logging.info('Estado luces: '+str(estado_hue))
            except:
                logging.error('Error getting light states')

        



        
        delta = time.time() - anterior
        #print delta
        for key in lugares:
            movimiento_st[key] = max(float(movimiento[key]),movimiento_st[key]*math.exp(-0.01*delta))  
        for key in movimiento_tv_st:
            movimiento_tv_st[key] = movimiento_tv_st[key]*math.exp(-0.01*delta)

        if(time.time() - dweepy_time > 10):
            dweepy_time = time.time()
            #print "registro dw 1"
            mov_send = {}
            for lugar in lugares:
                mov_send[lugar] = str(round(movimiento_st[lugar],2))
            #print mov_send
            logging.info('Estado movimiento:'+str(mov_send))
            try:
                #dweepy.dweet_for('well-groomed-move',mov_send)
                save_dweet('well-groomed-move',mov_send)

            except:
                print "error dweepy 1"
            
            gas_send = {}
            for key in gas:
                gas_send[key] = str(gas[key])
            hue_send = {}
            for key in estado_hue:
                hue_send[key] = str(int(estado_hue[key]))
            #try:
                #dweepy.dweet_for('cynical-powder',gas_send)
                #dweepy.dweet_for('fierce-cup',puertas)
                #dweepy.dweet_for('pleasant-fairies', hue_send)
            save_dweet('cynical-powder',gas_send)
            save_dweet('fierce-cup',puertas)
            save_dweet('pleasant-fairies',hue_send)
            #print 'pleasant-fairies'+str(hue_send)
            #except:
            #    print "error dweepy 2"
           
        anterior = time.time()
        if(time.time() - dweepy_time_2 > 23):
            #print "registro dw 2"
            dweepy_time_2 = time.time()
            temp_send = {}
            humid_send = {}
            for key in temperaturas:
                temp_send[key] = str(round(temperaturas[key], 2))
            for key in humedades:
                humid_send[key] = str(round(humedades[key], 2))
            try:
                #dweepy.dweet_for('zany-stomach',temp_send)
                save_dweet('verdant-credit', humid_send)
                save_dweet('zany-stomach',temp_send)
            except:
                print "Error dweepy zany 3"
            luz_send = {}
            for key in niveles_luz:
                luz_send[key] =str(niveles_luz[key])
            
            glob_send={}
            for key in globales:
                glob_send[key] = str(int(globales[key]))
            try:
                #dweepy.dweet_for('kindly-police',luz_send) 
                #dweepy.dweet_for('pretty-instrument',glob_send)
                save_dweet('kindly-police',luz_send) 
                save_dweet('pretty-instrument',glob_send)
                logging.info('Estado global:'+str(glob_send))
            except:
                print "error dweepy 4"


        ########## alarmas #########
        ## alertar por mensaje si alarma
        if(globales['alarma_trip'] and not(globales['alarma_enviada'])):
            encenderGrupo(luces['puerta'])
            encenderGrupo(luces['estudiof'])
            try:
                po_client.send_message("Alarma disparada", title="Alarma entrada")
                globales['alarma_enviada'] = True
            except: 
                print "error envio"
                globales['alarma_enviada'] = True
     
        if(globales['alarma_gas'] and not(globales['alarma_gas_enviada'])):
            po_client.send_message("Alarma de gas en "+lugar_gas+", lectura: " + lectura, title="Alarma gas")
            globales['alarma_gas_enviada'] = True
            try:
                sonos.volume = 80
                texto_voz('Alarma de gas en ' + lugar_gas)
                #time.sleep(8)
                #decir('Alarma de gas en ' + lugar_gas)
                #sonos.volume = 40
            except:
                print "Error decir alarma de gas"


        ############ temperatura #########
        # activar aire si temperatura en tv es alta y hay alguien presente
        if(globales['activo'] and temperaturas['tv'] >= 24.5 and (not globales['ac_encendido']) and globales['auto_ac']):
            if(movimiento_st['tv'] > 0.4):
                xbee.tx(dest_addr_long='\x00\x13\xa2\x00\x40\xbf\x96\x2c',dest_addr='\x40\xb3', data=b'1')
                globales['ac_encendido'] = True
                actualizar_global('ac',int(globales['ac_encendido']), con2)

        if(temperaturas['tv'] < 22 and globales['ac_encendido'] and globales['auto_ac']):
            globales['ac_encendido'] = False
            xbee.tx(dest_addr_long='\x00\x13\xa2\x00\x40\xbf\x96\x2c',dest_addr='\x40\xb3', data=b'1')
            actualizar_global('ac',int(globales['ac_encendido']), con2)

            
        ##### chapa cerrar por seguridad #####
        if(chapa_por_cerrar and time.time()-tiempo_cerrar_chapa > 60*3):
            chapa(True, xbee=xbee)
            chapa_por_cerrar = False
            globales['chapa'] = True
      
           
        # procesar comandos pendientes
        if(time.time() - tiempo_comandos > 1.0):
            tiempo_comandos = time.time()
            concom = lite.connect('/Volumes/mmshared/bdatos/comandos.db')
            actuales = {}
            with concom:
                c = concom.cursor()
                c.execute('SELECT * FROM pendientes')
                actuales = c.fetchall()
                #print actuales
                c.executemany('DELETE FROM pendientes WHERE comando=? AND params=?',actuales)
            concom.close()   

                #print actuales
            if(len(actuales)>0):
                for comando in actuales:
                    #print comando
                    logging.info('Comando: '+str(comando))
                    if(comando[0]=='aire_acondicionado'):
                        print "Aire acondicionado"
                        xbee.tx(dest_addr_long='\x00\x13\xa2\x00\x40\xbf\x96\x2c',dest_addr='\x40\xb3', data=b'1')
                        globales['ac_encendido'] = not globales['ac_encendido']
                        actualizar_global('ac',int(globales['ac_encendido']), con2)
                    if(comando[0]=='apagar_luces'):
                        apagarTodas(luces)
                        #print "Apagando luces"
                    if(comando[0]=='abrir_garage'):
                        print "Abriendo garage"
                        texto_voz('Alguien abrió la puerta del garash')
                        try:
                            #r = requests.post('http://192.168.100.19:8090/garage')
                            r = requests.post('http://beaglebone.local:8090/garage')
                        except:
                            print "Error: Garage no disponible"
                        movimiento['entrada'] = True
                    if(comando[0]=='activar_alarma'):
                        if(comando[1]=='1'):
                            globales['alarma'] = True
                            globales['alarma_enviada'] = False
                            globales['alarma_trip'] = False
                            estado_sonos = tocar("alarma_activada.mp3")
                            chapa(True, xbee = xbee)
                            for key in luces:
                                apagarGrupo(luces[key])
                            globales['activo'] = False
                            actualizar_global('alarma', 1.0, con2)
                            actualizar_global('activo', 0.0, con2)
                        if(comando[1]=='0'):
                            globales['alarma'] = False
                            estado_sonos = tocar("alarma_desactivada.mp3")
                            chapa(False, xbee=xbee)
                            globales['alarma_trip']= False
                            globales['alarma_enviada'] = False
                            globales['activo'] = True
                            globales['alarma_gas'] = False
                            globales['alarma_gas_enviada'] = False
                            actualizar_global('alarma', 0.0, con2)
                            actualizar_global('activo', 1.0, con2)
                    ##### wit.ai
                    if(comando[0]=='decir'):
                        print "^^^^^^^^ decir"+comando[1]
                        texto = comando[1]
                        try:
                            texto_voz(texto)
                        except:
                            print "Error sonos ---------------------------"
                    if(comando[0]=='get_temperature'):
                        temps = temperaturas['sala']
                        texto_voz('La temperatura en la sala es de '+str(round(temps))+' grados')
                    #####
                    if(comando[0]=='dormir'):
                        dormir['cuarto'] = not dormir['cuarto']
                        if(dormir['cuarto']):
                            print "vol"
                            sonos.volume = 30
                            print "decir"

                            texto_voz('Listo para dormir')
                            print "apagar"
                            apagarGrupo(luces['cuarto'])
                            print "cerrar chapa"
                            chapa(True, xbee = xbee)
                        else:
                            sonos.volume=40
                            texto_voz('Hora de despertar')
                            sonos.volume =40
                    if(comando[0]=='luces_cocina' and comando[1]=='1'):
                        #print "Prender cocina"
                        xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xbe\xf8\x62',command='D2',parameter='\x05')
                    if(comando[0]=='luces_cocina' and comando[1]=='0'):
                        #print "Apagar cocina"
                        xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xbe\xf8\x62',command='D2',parameter='\x04')
                    if(comando[0]=='puerta_zumbador'):
                        print "Zumbando"
                        texto_voz('Alguien está llegando.')
                        xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xbe\xf8\x62',command='D1',parameter='\x05')
                        tiempo_zumbador = time.time()
                        time.sleep(3)
                        xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xbe\xf8\x62',command='D1',parameter='\x04')
                        movimiento['entrada'] = True

                    if(comando[0]=='chapa' and comando[1]=='1'):
                        print "Cerrar chapa"
                        chapa(True, xbee = xbee)
                    if(comando[0]=='chapa' and comando[1]=='0'):
                        print "Abrir chapa"
                        chapa(False, xbee = xbee)

                    if(comando[0]=='regar' and comando[1]=='1'):
                        print "Regar" #'0013a20040caadda'
                        xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xca\xad\xda',command='D2',parameter='\x05')
                        globales['regadora'] = True
                        actualizar_global('regadora', int(globales['regadora']), con2)

                    if(comando[0]=='regar' and comando[1]=='0'):
                        print "no regar"
                        xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xca\xad\xda',command='D2',parameter='\x04')
                        globales['regadora'] = False
                        actualizar_global('regadora', int(globales['regadora']), con2)


                    if(comando[0]=='auto_luces'):
                        print("Autoluz toggle")
                        #globales['activo'] = not globales['activo']
                        globales['auto_luces'] = not globales['auto_luces']
                        actualizar_global('auto_luces', int(globales['auto_luces']), con2)
                    if(comando[0]=='auto_ac'):
                        #globales['activo'] = not globales['activo']
                        globales['auto_ac'] = not globales['auto_ac']
                        actualizar_global('auto_ac', int(globales['auto_ac']), con2)
                    if(comando[0]=='alarmas_reset'):
                        globales['alarma_enviada'] = False
                        globales['alarma_gas_enviada'] = False
                        globales['alarma_gas'] = False
                        globales['alarma_trip'] = False

                        
                        #try:
                        #   with con2:
                        #        cur2 = con2.cursor()
                        #        command1 = "UPDATE status SET valor ="+int(activo)+" WHERE lugar='global' AND medicion= 'activo' AND no_sensor=1"
                        #        command2 = "UPDATE status SET timestamp ="+str(st)+" WHERE lugar='global' AND medicion= 'activo' AND no_sensor=1"
                        #        cur2.execute(command1)
                        #        cur2.execute(command2)
                        #except:
                        #    print "Error activo escribir"
               
        
        # nivel de luz afuera
        now_1 = datetime.datetime.now().time()
        if(time_in_range(datetime.time(18, 0, 0),datetime.time(8, 0, 0), now_1)):
            niveles_luz['entrada'] = 600
        else:
            niveles_luz['entrada'] = 900   
        # encender luces donde haya movimiento, si están apagadas?
        for key in movimiento:
            if(movimiento[key]):
                tiempo_movimiento[key] = time.time()
                if(niveles_luz[key] < nivel_encendido[key]):
                    if(globales['activo'] and (not dormir[key])):       
                        if(time.time() - tiempo_encendido[key] > 10):
                            #print "Encender luces"
                            if(key=='cocina'):
                                print("Encender cocina, movimiento.")
                                xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xbe\xf8\x62',command='D2',parameter='\x05')
                            else:

                                encenderGrupo(luces[key])
                            tiempo_encendido[key] = time.time()
                            estado_luces[key] = True
                                
                            

        ## actividades programadas
        if((not globales['regadora']) and dt.hour==21 and dt.minute < 2):
            globales['regadora']=True
            xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xca\xad\xda',command='D2',parameter='\x05')
            actualizar_global('regadora', int(globales['regadora']), con2)
        if(globales['regadora'] and dt.hour==1):
            xbee.remote_at(dest_addr_long= '\x00\x13\xa2\x00@\xca\xad\xda',command='D2',parameter='\x04')
            globales['regadora'] = False
            actualizar_global('regadora', int(globales['regadora']), con2)

        if(dormir['cuarto'] and dt.hour==8):
            print 'Despertador'
            sonos.stop()
            sonos.volume = 40
            
            #time.sleep
            parte_dia='mañana'
            if(dt.hour>=12):
                parte_dia = 'tarde'
                if(dt.hour>=20):
                    parte_dia = 'noche'
            sonos.volume = 60
            if(dt.minute>0):
                texto_voz('Hora de despertar! Son las '+str(dt.hour)+' con '+str(dt.minute))
            else:
                texto_voz('Hora de despertar! Son las '+str(dt.hour)+' en punto')

            #decir('')
            dormir['cuarto'] = False


        ## pings
        #if(time.time() - felipe_phone_time > 10):
        #   pass
            #felipe_iphone = subprocess.call('ping -q -c1 -W 1 '+ '192.168.100.6' + ' > /dev/null', shell=True)
            #tere_iphone = subprocess.call('ping -q -c1 -W 1 '+ '192.168.100.7' + ' > /dev/null', shell=True)
            #felipe_phone_time = time.time()

            #if(felipe_iphone==0):
            #    globales['felipe'] = True
            #else:
            #    globales['felipe'] = False
            #if(tere_iphone==0):
            #    globales['tere'] = True
            #else:
            #    globales['tere'] = False


        ### registrar sensores
        try:
            if(time.time()-mom_registrar[lugar] > delay_registro[lugar]):
                mom_registrar[lugar] = time.time()
                #print ocurrencia
                if 'ocurrencia' in locals():
                    for item in ocurrencia:
                        #pass
                        #print(item)
                        #print item
                        update_ultimas(item, con2, str(st))
            if 'ocurrencia' in locals():
                for item in ocurrencia:
                    if item[3] == 'pressure':
                       # print "Pressure"
                        if(time.time()-tiempo_pressure > delay_pressure):
                            update_ultimas(item, con2, str(st))
                            tiempo_pressure=time.time()

        except:
            print("error registro ultimas")



        nuevo_tiempo = time.time() - tstamp
        tiempos.append(nuevo_tiempo)
        ant = tiempos.popleft()
        #time_loop = time.time()
        
        if((time.time()-log_time) > 20):
            print time.time()-log_time
            log_time = time.time()
            actualizar_global('heartbeat', round(sum(tiempos)/len(tiempos),2), con2)
            print '\033[91m'+'Media: '+str(round(sum(tiempos)/len(tiempos),2))+'  Max: '+str(round(max(tiempos),2))+'\033[0m'
        
            #print "Luz, ", niveles_luz
            #print "Temperatura, ", temperaturas
            #print "Humedad", humedades
            #decir('La temperatura es '+str(round(temperaturas['sala']))+' grados')
            print "Movimiento, ", movimiento
            #print "Mov st ", movimiento_st
            print "Globales ", globales
            print " "
            print " "
            if(int(globales['mA']) > 20000):
                texto_voz('Están usando más de '+ str(math.floor(float(globales['mA'])/1000)) + ' amperios.')
            latencia = round(sum(tiempos)/len(tiempos),2)
            if(latencia > 2):
                texto_voz('Latencia de '+str(round(sum(tiempos)/len(tiempos),2))+' segundos' )
        #print estado_sonos
        #print time.time() - estado_sonos['tiempo_inicio'], estado_sonos['alertDuration']
        if((time.time() - estado_sonos['tiempo_inicio']) > estado_sonos['alertDuration']):
            try:
                print "Continuar sonos"
                estado_sonos['alertDuration'] = 10000000
                #continuar_sonos(estado_sonos)

            except:
                'Error continuar sonos ****'