Ejemplo n.º 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
Ejemplo n.º 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)
Ejemplo n.º 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)
Ejemplo n.º 4
0
Archivo: test.py Proyecto: 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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
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
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
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")
Ejemplo n.º 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
Ejemplo n.º 12
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
Ejemplo n.º 13
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)
Ejemplo n.º 14
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)
Ejemplo n.º 15
0
				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)
			check_GPIO = 1
Ejemplo n.º 16
0
"""

# 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
"""
Ejemplo n.º 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
"""