Data Late Code Analysis

You guys have been great helping out on here, so I thought I’d drop some code that someone else could use. This analysis will run through every device in an account that has a tag “Watch” set to value “True” It will check the time stamp of the last data entry and if it’s over 2 hours old, it’ll send an email alert indicating that device is not online.

from tago import Account
from tago import Analysis
from tago import Services
import tago

from datetime import datetime,timezone
from dateutil import parser

def getDate(devID):
  my_device = tago.Device(devID)
  device_info=my_device.info()
  name=device_info['result']['name']
  ds_result = my_device.find({ 'variable': 'datestamp', 'qty': 1 })
  lastdate=ds_result['result'][0]['time']
  nowtime = datetime.now(timezone.utc).replace(microsecond=0)
  lasttime=parser.parse(lastdate).replace(microsecond=0)
  difftime=(nowtime-lasttime).total_seconds()/3600
  return(name,difftime)


def myAnalysis(context, scope):
  # reads the value of account_token from the environment variable
  account_token = 'MY_ACCOUNT_TOKEN'
  my_account = Account(account_token)

  my_filter = {
'tags': [{
  'key': 'watch', 'value': 'True',
}],
  }
  # Searching all devices with tag we want
  devices = my_account.devices.list(1, ['id', 'tags'], my_filter, 10000)

  if devices['status'] is True:
    for d in devices['result']:
      device_token_list = my_account.devices.tokenList(d['id'])
      tokeninfo=device_token_list['result'][0]
      devtoken=tokeninfo['token']
      mydevicename,mydeviceage=getDate(devtoken)
      context.log(mydevicename,mydeviceage)
      email = Services(context.token).email
      to = 'mydevicedown@mydomain.com'
      subject = 'Delayed Data '+mydevicename
      message = 'Looks like mydevice '+mydevicename+' is down. \n Data is '+str(int(mydeviceage))+' hours old.'
      email_origin = 'mydevicedown@mydomain.com'
      # Printing response
      if mydeviceage >2.0:
        response=email.send(to, subject, message, email_origin, None, None, None)
        context.log(response)
     else:
       context.log(devices['message']) # Error (if status is False)

# The analysis token in only necessary to run the analysis outside TagoIO
Analysis('MY-ANALYSIS-TOKEN-HERE').init(myAnalysis)
4 Likes