예제 #1
0
def setupNMA(keyFile):
    """Return and instance of PyNMA with the NMA api key loaded"""
    p = PyNMA()

    nmaKey = open(keyFile, 'r').readline().strip()
    p.addkey(nmaKey)

    return p
예제 #2
0
def sendAlert(key, usage, date):
    if not has_pynma:
        raise ImportError("No module named PyNMA ")
    global p
    pkey = None

    p = PyNMA()
    p.addkey(key)

    message = "You have used %sGB bandwidth in %s" % (usage,date)
    res = p.push("Comcast Bandwidth Check", 'Daily Update', message, 'http://misfoc.us', batch_mode=False)
예제 #3
0
def sendAlert(key, usage, date):
    if not has_pynma:
        raise ImportError("No module named PyNMA ")
    global p
    pkey = None

    p = PyNMA()
    p.addkey(key)

    message = "You have used %sGB bandwidth in %s" % (usage, date)
    res = p.push("Comcast Bandwidth Check", 'Daily Update', message, 'http://misfoc.us', batch_mode=False)
예제 #4
0
 def __call__(
     self,
     apikeys = [],
     app = u"EventGhost",
     event = u"{eg.event.string}",
     description = u"{eg.event.payload}",
     url = "",
     priority = 0,
     batch_mode = False,
     resType = 1,
     subst = True,
     prnt = False
     ):
     text = self.text
     app = eg.ParseString(app) if app else "EventGhost"
     event = eg.ParseString(event) if event else text.empty
     description = eg.ParseString(description) if description else text.empty
     url = eg.ParseString(url)
     if url:
         if url.lower()[:7] != r"http://" and url.lower()[:8] != r"https://":
             url = r"http://" + url
     nmaResult = {}
     prowlResult = {}
     nmaRes = {}
     prowlRes = {}
     apis = self.plugin.apikeys
     nmaList, prowlList = self.plugin.GetApiKeyLsts(apikeys, apis)
     if nmaList:
         try:
             devel = self.plugin.devel if self.plugin.devel else None
             mess = PyNMA(nmaList, devel)
             nmaRes = mess.push(
                 app,
                 event,
                 description,
                 url,
                 None,
                 priority,
                 batch_mode
             )
         except Exception, e:
             i = e.args[0]
             s = e.args[1].decode(eg.systemEncoding)
             eg.PrintError(text.errMess3 + "\n" + text.errMess4 % (s,str(i)))
예제 #5
0
    def parse_results(self, response):
      nma = PyNMA(self.crawler.settings.get('NMA_APIKEY'))

      r = redis.StrictRedis(host='localhost')
      forrige_studiepoeng = r.get('forrige_studiepoeng')
      hxs = Selector(response)
      studiepoeng = hxs.xpath('/html/body/table/tr[3]/td[2]/table/tr[last()]/td[3]/text()').extract()[0]
      studiepoeng = float(str(studiepoeng).replace(",", "."))
      #self.log("Antall studiepoeng: %s" % studiepoeng)
      if forrige_studiepoeng is None:
        r.set('forrige_studiepoeng', studiepoeng)
        self.log('Redis key did not exist, setting it now!')
      else:
        if studiepoeng > float(forrige_studiepoeng):
          nma.push('Karakterer', 'Eksamensresultater', 'Antall studiepoeng har gått opp!')
          r.set('forrige_studiepoeng', studiepoeng)
          self.log('Studiepoeng er høyere enn forrie gang!')
        else:
          self.log('Studiepoeng: %s, forrige Studiepoeng: %s' % (studiepoeng, forrige_studiepoeng))
예제 #6
0
파일: sabnma.py 프로젝트: dryes-old/sabnma
def main(argv, apikey):
    p = PyNMA()
    p.addkey(apikey)

    message = argv[3] + ' [' + argv[5] + ']'
   
    status = ''
    if argv[7] == '0':
    	status = 'Complete'
    elif argv[7] == '1':
    	status = 'Failed Verification'
    elif argv[7] == '2':
    	status = 'Failed Unpack'
    elif argv[7] == '3':
       	status = 'Failed Unpack + Verification'
    else:
    	status = 'Failed'

    res = p.push('SABnzbd+', message, status, priority=0)
    pprint(res)
예제 #7
0
def sendAlert(key, usage, date):
    if not has_pynma and not has_notifo:
        raise ImportError("No notification modules loaded")
    
    global p
    pkey = None

    message = "You have used %sGB bandwidth in %s" % (usage,date)

    if has_pynma:
        p = PyNMA()
        p.addkey(key)

        res = p.push("Comcast Bandwidth Check", 'Daily Update', message, 'http://misfoc.us', batch_mode=False)
    
    if has_notifo:
        if notifo_username == '' or notifo_secret == '':
            raise SystemExit("No API username/secret specified for Notifo notifications.")
        
        res = notifo.send_notification(notifo_username, notifo_secret, notifo_username, message, "Comcast Bandwidth Check", "Daily Update")
예제 #8
0
 def __call__(self,
              apikeys=[],
              app=u"EventGhost",
              event=u"{eg.event.string}",
              description=u"{eg.event.payload}",
              url="",
              priority=0,
              batch_mode=False,
              resType=1,
              subst=True,
              prnt=False):
     text = self.text
     app = eg.ParseString(app) if app else "EventGhost"
     event = eg.ParseString(event) if event else text.empty
     description = eg.ParseString(
         description) if description else text.empty
     url = eg.ParseString(url)
     if url:
         if url.lower()[:7] != r"http://" and url.lower(
         )[:8] != r"https://":
             url = r"http://" + url
     nmaResult = {}
     prowlResult = {}
     nmaRes = {}
     prowlRes = {}
     apis = self.plugin.apikeys
     nmaList, prowlList = self.plugin.GetApiKeyLsts(apikeys, apis)
     if nmaList:
         try:
             devel = self.plugin.devel if self.plugin.devel else None
             mess = PyNMA(nmaList, devel)
             nmaRes = mess.push(app, event, description, url, None,
                                priority, batch_mode)
         except Exception, e:
             i = e.args[0]
             s = e.args[1].decode(eg.systemEncoding)
             eg.PrintError(text.errMess3 + "\n" + text.errMess4 %
                           (s, str(i)))
예제 #9
0
def main(keys):
    global p
    pkey = None
    
    p = PyNMA()
    if os.path.isfile("mydeveloperkey"):
        dkey = open("mydeveloperkey",'r').readline().strip()
        p.developerkey(dkey)

    p.addkey(keys)
    res = p.push("test app", 'test event', 'test msg', 'http://example.com', batch_mode=False)
    pprint(res)
예제 #10
0
    def parse_results(self, response):
        nma = PyNMA(self.crawler.settings.get('NMA_APIKEY'))

        r = redis.StrictRedis(host='localhost')
        forrige_studiepoeng = r.get('forrige_studiepoeng')
        hxs = Selector(response)
        studiepoeng = hxs.xpath(
            '/html/body/table/tr[3]/td[2]/table/tr[last()]/td[3]/text()'
        ).extract()[0]
        studiepoeng = float(str(studiepoeng).replace(",", "."))
        #self.log("Antall studiepoeng: %s" % studiepoeng)
        if forrige_studiepoeng is None:
            r.set('forrige_studiepoeng', studiepoeng)
            self.log('Redis key did not exist, setting it now!')
        else:
            if studiepoeng > float(forrige_studiepoeng):
                nma.push('Karakterer', 'Eksamensresultater',
                         'Antall studiepoeng har gått opp!')
                r.set('forrige_studiepoeng', studiepoeng)
                self.log('Studiepoeng er høyere enn forrie gang!')
            else:
                self.log('Studiepoeng: %s, forrige Studiepoeng: %s' %
                         (studiepoeng, forrige_studiepoeng))
예제 #11
0
def plugin(srv, item):
    ''' expects (apikey, appname, eventname) in addrs'''

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
                      item.service, item.target)
    if not HAVE_NMA:
        srv.logging.warn("PyNMA is not installed")
        return False

    try:
        apikey, appname, event = item.addrs
    except:
        srv.logging.warn("NMA incorrect # of target params passed")
        return False

    text = item.message
    priority = item.get('priority', 0)

    try:
        p = PyNMA()
        p.addkey(apikey)

        res = p.push(application=appname,
                     event=event,
                     description=text,
                     url="",
                     contenttype=None,
                     priority=priority,
                     batch_mode=False)

        srv.logging.debug("NMA returns %s" % (res))
        # {'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx': {'message': '', u'code': u'200', 'type': u'success', u'remaining': u'798', u'resettimer': u'46'}}

        # FIXME: test for code 200
    except Exception, e:
        srv.logging.warn("NMA failed: %s" % (str(e)))
        return False
예제 #12
0
파일: nma.py 프로젝트: 19317362/mqttwarn
def plugin(srv, item):
    ''' expects (apikey, appname, eventname) in addrs'''

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)
    if not HAVE_NMA:
        srv.logging.warn("PyNMA is not installed")
        return False

    try:
        apikey, appname, event = item.addrs
    except:
        srv.logging.warn("NMA incorrect # of target params passed")
        return False

    text = item.message
    priority = item.get('priority', 0)

    try:
        p = PyNMA()
        p.addkey(apikey)

        res = p.push(application=appname,
            event=event,
            description=text,
            url="",
            contenttype=None,
            priority=priority,
            batch_mode=False)

        srv.logging.debug("NMA returns %s" % (res))
        # {'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx': {'message': '', u'code': u'200', 'type': u'success', u'remaining': u'798', u'resettimer': u'46'}}

        # FIXME: test for code 200
    except Exception, e:
        srv.logging.warn("NMA failed: %s" % (str(e)))
        return False
예제 #13
0
파일: test.py 프로젝트: zoni/pynma
def main(keys):
    global p
    pkey = None
    
    p = PyNMA()
    if os.path.isfile("mydeveloperkey"):
        dkey = open("mydeveloperkey",'r').readline().strip()
        p.developerkey(dkey)

    p.addkey(keys)
    res = p.push("test app", 'test event', 'test msg <a href="http://www.google.com/">google</a>', 'http://example.com', batch_mode=False, html=True)
    pprint(res)
예제 #14
0
파일: checkpage.py 프로젝트: Zokol/WebDog
def notify(keys, app, event, msg, url):
	global p
	pkey = None
	
	p = PyNMA()
	if os.path.isfile("mydeveloperkey"):
		dkey = open("mydeveloperkey",'r').readline().strip()
		p.developerkey(dkey)

	p.addkey(keys)
	res = p.push(app, event, msg, url, batch_mode=False)
	pprint(res)
예제 #15
0
def reportSensor( sensorId ):

        myconfig = ConfigParser.ConfigParser()
        myconfig.read("/home/pi/Surveillance/uploader-no-ip.cfg")

        #Domoticz account credentials
        username = myconfig.get('domoticz', 'user')
        password = myconfig.get('domoticz', 'password')

	output = ''
	p = urllib2.HTTPPasswordMgrWithDefaultRealm()

        process = Popen(["/home/pi/Surveillance/extractLast433.sh", str(sensorId)], stdout=PIPE)
        (output, err) = process.communicate()
        exit_code = process.wait()
        output = output[:-1]
	csv_data = output.split(",")
	if len(output)>0:
		csv_data = output.split(",")
                humStat = 0

	        if (sensorId==2):
			if (float(csv_data[3]) < 40):	humStat = 2
			elif(float(csv_data[3]) > 70):	humStat = 3
	                url = "http://caquiroga.no-ip.biz:8081/json.htm?type=command&param=udevice&idx=8&nvalue=0&svalue=" +  str(csv_data[2]) + ";" + str(csv_data[3]) + ";" + str(humStat) + ";"
	        elif sensorId==1:
                        if (float(csv_data[3]) < 40):      humStat = 2
                        elif(float(csv_data[3]) > 70):     humStat = 3
	                url = "http://caquiroga.no-ip.biz:8081/json.htm?type=command&param=udevice&idx=9&nvalue=0&svalue=" +  str(csv_data[2]) + ";" + str(csv_data[3]) + ";" + str(humStat) + ";"
	        elif sensorId==10:
        	        nma = PyNMA()
			temp = shelve.open("/home/pi/Surveillance/tmp/raintemp")
			nma.addkey(temp['nmakey'])
			print temp['nmakey']
        	        url = "http://caquiroga.no-ip.biz:8081/json.htm?type=command&param=udevice&idx=11&nvalue=0&svalue=0;" + str(csv_data[2]) + ";"
			if (float(csv_data[2]) > temp['rain']+2): nma.push("Maceda", 'Plou molt a Maceda', '', '', batch_mode=False)
			elif (float(csv_data[2]) > temp['rain']): nma.push("Maceda", 'Plou a Maceda', '', '', batch_mode=False)
			temp['rain'] = float(csv_data[2])		
			temp.close()
	        print url
	        p.add_password(None, url, username, password)
	        handler = urllib2.HTTPBasicAuthHandler(p)
	        opener = urllib2.build_opener(handler)
	        urllib2.install_opener(opener)
	        page = urllib2.urlopen(url).read()
	return
예제 #16
0
def main(keys):
    global p
    pkey = None
    
    p = PyNMA()
    if os.path.isfile("mydeveloperkey"):
        dkey = open("mydeveloperkey",'r').readline().strip()
        p.developerkey(dkey)

    p.addkey(keys)
    res = p.push(options.app_name, options.evn_title, options.evn_desc, options.evn_url, options.evn_pri, batch_mode=False)

    if options.debug:
        pprint(res)
예제 #17
0
Hooks
"""

# Hook command
w.hook_command("nma", "Activate NotifyMyAndroid notifications",
        "on | off",
        """    on : Activate notifications
    off : Deactivate notifications\n
        """,
        "on || off",
        "nma_cmd_cb", "");
# Hook privmsg/hilights
w.hook_print("", "irc_privmsg", "", 1, "priv_msg_cb", "")

from pynma import PyNMA
p = PyNMA()
p.addkey(w.config_get_plugin("apikey"))


"""
Helpers
"""

def _debug(text):
    if w.config_string_to_boolean(w.config_get_plugin("debug")):
        w.prnt("", text)


"""
Functions
"""
예제 #18
0
import time
from copy import copy
from pynma import PyNMA
from urllib import request
from sys import stdout

# API-nyckel for Notify My Android
p = PyNMA('3a1ff5b87baff90fc5ac7c73e37c3f7d07a4a48e1035b4f2')


# Main function
def main():
    old = []
    url_g = "http://www.webhallen.com/se-sv/datorkomponenter/fyndvaror/grafikkort/mest_salda/alla/"
    klass_g = [3, 4, 5]
    namn_g = "Grafikkort"

    url_c = "http://www.webhallen.com/se-sv/datorkomponenter/fyndvaror/chassi/mest_salda/alla/"
    klass_c = [3, 4, 5]
    namn_c = "Chassi"

    url_m = 'http://www.webhallen.com/se-sv/datorkomponenter/fyndvaror/minnen/dimm/mest_salda/alla/'
    klass_m = [3, 4, 5]
    namn_m = 'Minne'
    opt_m = 'DDR3'

    sleep_time = 60
    while True:
        start = time.time()
        check_url(url_g, klass_g, namn_g, old)
        check_url(url_c, klass_c, namn_c, old)
예제 #19
0
"""

# Hook command
w.hook_command("nma", "Activate NotifyMyAndroid notifications",
        "on | off | test",
        """    on : Activate notifications
    off : Deactivate notifications
    test : Test a notification\n
        """,
        "on || off || test",
        "nma_cmd_cb", "");
# Hook privmsg/hilights
w.hook_print("", "irc_privmsg", "", 1, "priv_msg_cb", "")

from pynma import PyNMA
p = PyNMA()

"""
Helpers
"""

def _debug(text):
    if w.config_string_to_boolean(w.config_get_plugin("debug")):
        w.prnt("", "[nma] - %s" % text)

def nma_get_instance():
    global p
    for k in p._apikey:
        p.delkey(k)
    key = w.config_get_plugin("apikey")
    if key:
예제 #20
0
def main(keys):
	print ("In main(), loop")
	# Read settings
 	do_read_settings()

	print ("Settings ok")

	# Setup logging
	logger = logging.getLogger('washpower')
	hdlr = logging.FileHandler('/var/tmp/washpower.log')
	formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
	hdlr.setFormatter(formatter)
	logger.addHandler(hdlr) 
	logger.setLevel(logging.INFO)
	logger.info('Start log')
	
	print ("Log started")
	
	# Variables
	runs = 0
	running = 0
	notrunning = 0
	washerrunning = 0
	
	# Eternal loop
	while(1):
		# Get data from Emoncms
		# TODO Find a better way to get data (locally)
		# Get value from Emoncms
		#response = urllib2.urlopen('http://192.168.1.6/emoncms/feed/value.json?id=23&apikey=1b3bdd0f474738012cb85b79f1b7e104')
		response = urllib2.urlopen('http://192.168.1.6/emoncms/feed/value.json?id=23&apikey='+emonapi)
		
		html = response.read()
		power = ''.join(e for e in html if e.isalnum())
		ipower=int(power)
		
		#print ("Current power: " + str(ipower))
		# For debug, store values constantly
		# Theese values can be used to analyze the current consumption
		# 
		#logger.info(power)
		#logtext = "running: " + str(running) + "---notrunning: " + str(notrunning)
		#logger.info(logtext)
		
		# For debug, read "power" from a local file
		#f = open('test', 'r')
		#power = int(f.read())
		#print str(power)
		#ipower=int(power)
		
		# Power is (much) higher than idle current? (Which in this case is 11).
		# But we use a higher value, sometimes the washer is using a little more 
		# power when idle. 
		if ipower > 50:
			running+=1
			notrunning=0
			#print "running:"+str(running)
			print ("Current power: " + power + " (above limit)")
			
			if (running >= 3 and washerrunning == 0):
				# The power is high for three runs in a row
				logger.info("Washer is running")
				print "Washer is running"
				
				# Send NMA
				global p
				pkey = None
				p = PyNMA()
				if os.path.isfile("mydeveloperkey"):
					dkey = open("mydeveloperkey",'r').readline().strip()
					p.developerkey(dkey)
				p.addkey(keys)
				res = p.push("Emoncms alarm", 'Washer', 'Washer is running', '', batch_mode=False)
				pprint(res)
				washerrunning = 1
		else: 
			#print "Washer idle"
			if (washerrunning == 1):
				# Washer has been running but power is below limit
				notrunning+=1
				if (notrunning >=6):
					# Power has been below limit for three runs
					# so the washer is done
					washerrunning = 0
					# Reset running counter
					running = 0
					logger.info("Washer is done")
					print "Washer is done"
					# Send NMA
					#global p
					pkey = None
					p = PyNMA()
					if os.path.isfile("mydeveloperkey"):
						dkey = open("mydeveloperkey",'r').readline().strip()
						p.developerkey(dkey)
					p.addkey(keys)
					res = p.push("Emoncms alarm", 'Washer', 'Washer is done', '', batch_mode=False)
					pprint(res)

		# Wait 2 minutes
		time.sleep(120)
예제 #21
0
 def __call__(
     self,
     apikeys = [],
     app = u"EventGhost",
     event = u"{eg.event.string}",
     description = u"{eg.event.payload}",
     url = "",
     priority = 0,
     batch_mode = False,
     resType = 1,
     subst = True
     ):
     text = self.text
     app = eg.ParseString(app) if app else "EventGhost"
     event = eg.ParseString(event) if event else text.empty
     description = eg.ParseString(description) if description else text.empty 
     url = eg.ParseString(url)
     if url:
         if url.lower()[:7] != r"http://" and url.lower()[:8] != r"https://":
             url = r"http://" + url
     apiList = []
     for api in apikeys:
         apis = self.plugin.apikeys
         keys = [i[0] for i in apis]
         if api in keys:
             ix = keys.index(api)
             apiList.append([i[1] for i in apis][ix])
         else:
             eg.PrintError(text.errMess1 % api)
     if apiList:
         try:
             devel = self.plugin.devel if self.plugin.devel else None
             mess = PyNMA(apiList, devel)
             res = mess.push(
                 app,
                 event,
                 description,
                 url,
                 priority,
                 batch_mode
             )
         except Exception, e:
             i = e.args[0]
             s = e.args[1].decode(eg.systemEncoding)
             eg.PrintError(text.errMess3 + "\n" + text.errMess4 % (s,str(i)))
             res = None
         if res is not None:
             if batch_mode:
                 key = list(res.iterkeys())[0]
                 aps = []
                 for r in key.split(','):
                     ix = [itm[1] for itm in apis].index(r)
                     aps.append([i[0] for i in apis][ix])
                 ap = ",".join(aps) if subst else key
                 r = res[key][u'code'] if resType else res[key]
                 return {ap: r}   
             else:
                 result = {}
                 for r in res.iterkeys():
                     if subst:
                         ix = [itm[1] for itm in apis].index(r)
                         ap = [i[0] for i in apis][ix]
                     else:
                         ap = r
                     result[ap] = res[r][u'code'] if resType else res[r]
                 return result                   
예제 #22
0
        "plugins.var.python.nma.apikey \"you_nma_api_token\" to fix that.")
"""
Hooks
"""

# Hook command
w.hook_command(
    "nma", "Activate NotifyMyAndroid notifications", "on | off",
    """    on : Activate notifications
    off : Deactivate notifications\n
        """, "on || off", "nma_cmd_cb", "")
# Hook privmsg/hilights
w.hook_print("", "irc_privmsg", "", 1, "priv_msg_cb", "")

from pynma import PyNMA
p = PyNMA()
p.addkey(w.config_get_plugin("apikey"))
"""
Helpers
"""


def _debug(text):
    if w.config_string_to_boolean(w.config_get_plugin("debug")):
        w.prnt("", text)


"""
Functions
"""
예제 #23
0
def main(keys):
    print("In main(), loop")
    # Read settings
    do_read_settings()

    print("Settings ok")

    # Setup logging
    logger = logging.getLogger('washpower')
    hdlr = logging.FileHandler('/var/tmp/washpower.log')
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    logger.info('Start log')

    print("Log started")

    # Variables
    runs = 0
    running = 0
    notrunning = 0
    washerrunning = 0

    # Eternal loop
    while (1):
        # Get data from Emoncms
        # TODO Find a better way to get data (locally)
        # Get value from Emoncms
        #response = urllib2.urlopen('http://192.168.1.6/emoncms/feed/value.json?id=23&apikey=1b3bdd0f474738012cb85b79f1b7e104')
        response = urllib2.urlopen(
            'http://192.168.1.6/emoncms/feed/value.json?id=23&apikey=' +
            emonapi)

        html = response.read()
        power = ''.join(e for e in html if e.isalnum())
        ipower = int(power)

        #print ("Current power: " + str(ipower))
        # For debug, store values constantly
        # Theese values can be used to analyze the current consumption
        #
        #logger.info(power)
        #logtext = "running: " + str(running) + "---notrunning: " + str(notrunning)
        #logger.info(logtext)

        # For debug, read "power" from a local file
        #f = open('test', 'r')
        #power = int(f.read())
        #print str(power)
        #ipower=int(power)

        # Power is (much) higher than idle current? (Which in this case is 11).
        # But we use a higher value, sometimes the washer is using a little more
        # power when idle.
        if ipower > 50:
            running += 1
            notrunning = 0
            #print "running:"+str(running)
            print("Current power: " + power + " (above limit)")

            if (running >= 3 and washerrunning == 0):
                # The power is high for three runs in a row
                logger.info("Washer is running")
                print "Washer is running"

                # Send NMA
                global p
                pkey = None
                p = PyNMA()
                if os.path.isfile("mydeveloperkey"):
                    dkey = open("mydeveloperkey", 'r').readline().strip()
                    p.developerkey(dkey)
                p.addkey(keys)
                res = p.push("Emoncms alarm",
                             'Washer',
                             'Washer is running',
                             '',
                             batch_mode=False)
                pprint(res)
                washerrunning = 1
        else:
            #print "Washer idle"
            if (washerrunning == 1):
                # Washer has been running but power is below limit
                notrunning += 1
                if (notrunning >= 6):
                    # Power has been below limit for three runs
                    # so the washer is done
                    washerrunning = 0
                    # Reset running counter
                    running = 0
                    logger.info("Washer is done")
                    print "Washer is done"
                    # Send NMA
                    #global p
                    pkey = None
                    p = PyNMA()
                    if os.path.isfile("mydeveloperkey"):
                        dkey = open("mydeveloperkey", 'r').readline().strip()
                        p.developerkey(dkey)
                    p.addkey(keys)
                    res = p.push("Emoncms alarm",
                                 'Washer',
                                 'Washer is done',
                                 '',
                                 batch_mode=False)
                    pprint(res)

        # Wait 2 minutes
        time.sleep(120)
예제 #24
0
파일: sec53.py 프로젝트: cammck/sec53
			if PIR[3] == "PIR":
				cur.execute("INSERT INTO EventLog(EventDesc, EventInfo) VALUES('WARNING: Motion detected during Start-up', '{0} - GPIO {1}')".format(PIR[0], GPIO_value))
			con.commit()
		print "Setting initial value for {0} - {1}".format(PIR[0], GPIO_value)
		PIR[4] = GPIO_value

#GPIO.setup(GPIO_HALL_PIR, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

print "Waiting for PIR to settle ..."

# Loop until PIR output is 0 (no motion)
while GPIO.input(GPIO_STUDY_PIR)==1:
	Current_State  = 0
print "  Ready"

p = PyNMA()
p.addkey("769dd5e70415a3e4610298ac28176229c2fa33f068eedbb7")




try:
	while True:
		cur.execute("SELECT KeyPair FROM Control WHERE KeyVal = 'Monitor' limit 1")
		CONTROL_MONITOR = cur.fetchone()[0]
		if CONTROL_MONITOR == "ON":
			print "Switching GPIO checking on!"
			cur.execute("INSERT INTO EventLog(EventDesc, EventInfo) VALUES('Switching GPIO checking ON!', 'CONTROL_MONITOR has changed in main loop.')")
			con.commit()
			# Send NMA push notification
			res = p.push("Sec53", 'GPIO switch', 'Switching GPOI checking on!', 'http://mckerral.ddns.net/Sec53/events.php', batch_mode=False)