Beispiel #1
0
    def __init__(self, api_key, channel_name):

        from pushetta import Pushetta

        self._api_key = api_key
        self._channel_name = channel_name
        self.pushetta = Pushetta(self._api_key)
Beispiel #2
0
class PushettaNotificationService(BaseNotificationService):
    """Implement the notification service for Pushetta."""
    def __init__(self, api_key, channel_name, send_test_msg):
        """Initialize the service."""
        from pushetta import Pushetta
        self._api_key = api_key
        self._channel_name = channel_name
        self.is_valid = True
        self.pushetta = Pushetta(api_key)

        if send_test_msg:
            self.send_message("Home Assistant started")

    def send_message(self, message="", **kwargs):
        """Send a message to a user."""
        from pushetta import exceptions
        title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)

        try:
            self.pushetta.pushMessage(self._channel_name,
                                      "{} {}".format(title, message))
        except exceptions.TokenValidationError:
            _LOGGER.error("Please check your access token")
            self.is_valid = False
        except exceptions.ChannelNotFoundError:
            _LOGGER.error("Channel '%s' not found", self._channel_name)
            self.is_valid = False
Beispiel #3
0
class PushettaNotificationService(BaseNotificationService):
    """Implement the notification service for Pushetta."""

    def __init__(self, api_key, channel_name, send_test_msg):
        """Initialize the service."""
        from pushetta import Pushetta
        self._api_key = api_key
        self._channel_name = channel_name
        self.is_valid = True
        self.pushetta = Pushetta(api_key)

        if send_test_msg:
            self.send_message("Home Assistant started")

    def send_message(self, message="", **kwargs):
        """Send a message to a user."""
        from pushetta import exceptions
        title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)

        try:
            self.pushetta.pushMessage(self._channel_name,
                                      "{} {}".format(title, message))
        except exceptions.TokenValidationError:
            _LOGGER.error("Please check your access token")
            self.is_valid = False
        except exceptions.ChannelNotFoundError:
            _LOGGER.error("Channel '%s' not found", self._channel_name)
            self.is_valid = False
Beispiel #4
0
    def __init__(self, api_key, channel_name, send_test_msg):
        """Initialize the service."""
        from pushetta import Pushetta
        self._api_key = api_key
        self._channel_name = channel_name
        self.is_valid = True
        self.pushetta = Pushetta(api_key)

        if send_test_msg:
            self.send_message("Home Assistant started")
def sendNotification(token, channel, message):
       API_KEY=token
       #req = urllib2.Request('http://api.pushetta.com/api/pushes/{0)/')
       CHANNEL_NAME=channel
       p=Pushetta(API_KEY)
       p.pushMessage(CHANNEL_NAME,"Somone is there in ur house")
       print  "how r "
      # req.add_header('Content-Type', 'application/json')
       #req.add_header('Authorization', 'Token {0}'.format(token))
       u
Beispiel #6
0
class PushettaNotificationService(BaseNotificationService):
    """Implement the notification service for Pushetta."""
    def __init__(self, api_key, channel_name):
        """Initialize the service."""
        from pushetta import Pushetta
        self._api_key = api_key
        self._channel_name = channel_name
        self.pushetta = Pushetta(self._api_key)

    def send_message(self, message="", **kwargs):
        """Send a message to a user."""
        title = kwargs.get(ATTR_TITLE)
        self.pushetta.pushMessage(self._channel_name,
                                  "{} {}".format(title, message))
class PushettaNotificationService(BaseNotificationService):
    """Implement the notification service for Pushetta."""

    def __init__(self, api_key, channel_name):
        """Initialize the service."""
        from pushetta import Pushetta
        self._api_key = api_key
        self._channel_name = channel_name
        self.pushetta = Pushetta(self._api_key)

    def send_message(self, message="", **kwargs):
        """Send a message to a user."""
        title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
        self.pushetta.pushMessage(self._channel_name,
                                  "{} {}".format(title, message))
    def __init__(self, api_key, channel_name):

        from pushetta import Pushetta

        self._api_key = api_key
        self._channel_name = channel_name
        self.pushetta = Pushetta(self._api_key)
Beispiel #9
0
def send_notification(working_dir, msg):
    if len(msg) == 0:
        return

    f_name = working_dir + "/SettingFiles/pushetta"
    if not os.path.isfile(f_name):  # if such a file doesnt exist
        print("Are you sure you dont want to use pushetta? It is pretty neat.")
        return

    with open(f_name, "r") as myfile:
        raw_input = myfile.read().split('\n')
        API_KEY = raw_input[0]
        CHANNEL_NAME = raw_input[1]

    p = Pushetta(API_KEY)
    p.pushMessage(CHANNEL_NAME, msg)
Beispiel #10
0
    def __init__(self, **kwargs):
        """
        Send a push message to an android phone via Pushetta API
        :param message: Message to send
        :param api_key: The Pushetta service secret token
        :param channel_name: Pushetta channel name
        """
        super(Push_message, self).__init__(**kwargs)

        self.message = kwargs.get('message', None)
        self.api_key = kwargs.get('api_key', None)
        self.channel_name = kwargs.get('channel_name', None)

        # check if parameters have been provided
        if self._is_parameters_ok():
            p = Pushetta(self.api_key)
            p.pushMessage(self.channel_name, self.message)
def get_service(hass, config):
    """Get the Pushetta notification service."""
    from pushetta import Pushetta, exceptions

    try:
        pushetta = Pushetta(config[CONF_API_KEY])
        pushetta.pushMessage(config[CONF_CHANNEL_NAME],
                             "Home Assistant started")
    except exceptions.TokenValidationError:
        _LOGGER.error("Please check your access token")
        return None
    except exceptions.ChannelNotFoundError:
        _LOGGER.error("Channel '%s' not found", config[CONF_CHANNEL_NAME])
        return None

    return PushettaNotificationService(config[CONF_API_KEY],
                                       config[CONF_CHANNEL_NAME])
Beispiel #12
0
    def __init__(self, api_key, channel_name, send_test_msg):
        """Initialize the service."""
        from pushetta import Pushetta
        self._api_key = api_key
        self._channel_name = channel_name
        self.is_valid = True
        self.pushetta = Pushetta(api_key)

        if send_test_msg:
            self.send_message("Home Assistant started")
Beispiel #13
0
def get_service(hass, config):
    """Get the Pushetta notification service."""
    from pushetta import Pushetta, exceptions

    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_API_KEY, 'channel_name']}, _LOGGER):
        return None

    try:
        pushetta = Pushetta(config[CONF_API_KEY])
        pushetta.pushMessage(config['channel_name'], "Home Assistant started")
    except exceptions.TokenValidationError:
        _LOGGER.error("Please check your access token")
        return None
    except exceptions.ChannelNotFoundError:
        _LOGGER.error("Channel '%s' not found", config['channel_name'])
        return None

    return PushettaNotificationService(config[CONF_API_KEY],
                                       config['channel_name'])
Beispiel #14
0
def get_service(hass, config):
    """Get the Pushetta notification service."""
    from pushetta import Pushetta, exceptions

    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_API_KEY, 'channel_name']},
                           _LOGGER):
        return None

    try:
        pushetta = Pushetta(config[CONF_API_KEY])
        pushetta.pushMessage(config['channel_name'], "Home Assistant started")
    except exceptions.TokenValidationError:
        _LOGGER.error("Please check your access token")
        return None
    except exceptions.ChannelNotFoundError:
        _LOGGER.error("Channel '%s' not found", config['channel_name'])
        return None

    return PushettaNotificationService(config[CONF_API_KEY],
                                       config['channel_name'])
Beispiel #15
0
    def __init__(self,
                 message=None,
                 api_key=None,
                 channel_name=None,
                 **kwargs):
        """
        Send a push message to an android phone via Pushetta API
        :param message: Message to send
        :param api_key: The Pushetta service secret token
        :param channel_name: Pushetta channel name
        :return:
        """
        super(Push_message, self).__init__(**kwargs)
        if message is None:
            raise NotImplementedError("Pushetta neuron needs message to send")

        if api_key is None:
            raise NotImplementedError("Pushetta neuron needs api_key")
        if channel_name is None:
            raise NotImplementedError("Pushetta neuron needs channel_name")

        p = Pushetta(api_key)
        p.pushMessage(channel_name, message)
def main():
 try:
  sensor = 4

  GPIO.setmode(GPIO.BCM)
  GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)

  previous_state = False
  current_state = False
  cam = picamera.PiCamera()

  API_KEY="e224478433d166114af5e762433790fb5f5921a5"
  CHANNEL_NAME="CzechBery"
  p=Pushetta(API_KEY)
  print "...Camera trap is ready... "

  while True:
      time.sleep(0.1)
      previous_state = current_state
      current_state = GPIO.input(sensor)
      if current_state != previous_state:
          new_state = "HIGH" if current_state else "LOW"
          print("GPIO pin %s is %s" % (sensor, new_state))
          if current_state:
              fileName = get_file_name()
              cam.start_preview()
              p.pushMessage(CHANNEL_NAME, "Motion Detected... Look at mail!")
              time.sleep(2)
              cam.capture(fileName)
              time.sleep(1)
              SendMail(fileName)#zde volam na metodu SendMail a pridavam ji atribut filname coz je nazev souboru ktery se ma poslat mailem
          else:
              cam.stop_preview()
 except KeyboardInterrupt:
     print " System is terminated"
 except Exception:
     print "Nastal Error"
Beispiel #17
0
 def __init__(self,filepath,bomurl,fileradix,port,errfile,lowT,highT):
     self.filename=filepath+fileradix+'.html'
     self.bomurl=bomurl
     self.datalogfile=filepath+fileradix
     self.fileradix=fileradix
     self.filepath=filepath
     self.port=port
     self.errfile=errfile
     self.errfilen=open(errfile,'a',0) # error file in unbuffered
     self.TCPlistener=TCPlistener(port,self.errfilen)
     self.TCPlistener.gotnewdata=False
     self.sensidtable={}
     self.lastUpdate=time()-60 
     self.alertTempLow=lowT
     self.alertTempHigh=highT
     self.sentAlertHigh=False
     self.sentAlertLow=False
     self.inflog('climateHTMLfile class initiated')
     if(API_KEY):
         self.p=Pushetta(API_KEY)
         self.p.pushMessage(CHANNEL_NAME,"Service started")            
     else:
         self.p=False
Beispiel #18
0
def main():
    global start_value
    global data_max

    # Initialize sensor with external library class.
    sensor = mpu9250()

    # Key taken from account.
    API_KEY = "fb2dc4530995b2fe3d3f823a0fa35a5e8d635716"

    # Name of channel.
    CHANNEL_NAME = "JuicySeniorDesign"

    # Create pushetta object.
    p = Pushetta(API_KEY)

    print('entering main loop...')
    sys.stdout.flush()
    while True:

        # Get sensor data.
        data = sensor.accel[2]

        # Look at new max value.
        if data > data_max:
            print('New Maximum... {}'.format(data_max))
            data_max = data

        # Thresholding for alarm detection. Adjust magnitude for each axis.
        if (data_max >= (start_value + Z_THRESHOLD)):
            print('Sending out alert... {} {} {}'.format(
                data_max, start_value, Z_THRESHOLD))
            sys.stdout.flush()
            alert(p, CHANNEL_NAME, sensor)
            print('Done... {} {} {}'.format(data_max, start_value,
                                            Z_THRESHOLD))
            sys.stdout.flush()
Beispiel #19
0
# -*- coding:utf8 -*-
import MySQLdb as mdb
from datetime import datetime,timedelta
import time as ttim
import smtplib
from socket import *
import subprocess
import sys
reload(sys)
from pushetta import Pushetta
sys.setdefaultencoding('utf8')
API_KEY = "58fee02c2e20ed7511b179af994fc34850f84656"
CHANNEL_NAME = "attendance1"
p = Pushetta(API_KEY)
ab=0



def send_email(user, pwd, recipient, subject, body):


    gmail_user = user
    gmail_pwd = pwd
    FROM = user
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
Beispiel #20
0
class climatehtmlfileTCP:
    def __init__(self,filepath,bomurl,fileradix,port,errfile,lowT,highT):
        self.filename=filepath+fileradix+'.html'
        self.bomurl=bomurl
        self.datalogfile=filepath+fileradix
        self.fileradix=fileradix
        self.filepath=filepath
        self.port=port
        self.errfile=errfile
        self.errfilen=open(errfile,'a',0) # error file in unbuffered
        self.TCPlistener=TCPlistener(port,self.errfilen)
        self.TCPlistener.gotnewdata=False
        self.sensidtable={}
        self.lastUpdate=time()-60 
        self.alertTempLow=lowT
        self.alertTempHigh=highT
        self.sentAlertHigh=False
        self.sentAlertLow=False
        self.inflog('climateHTMLfile class initiated')
        if(API_KEY):
            self.p=Pushetta(API_KEY)
            self.p.pushMessage(CHANNEL_NAME,"Service started")            
        else:
            self.p=False

    def inflog(self,txt):
        txt=strftime('%d-%m-%Y %H:%M:%S')+': '+txt+'\n'
        self.errfilen.write(txt)
        self.errfilen.flush()
            
    def waterPartialPressure(self,temperature,humidity):
        "Calculates watersaturatiopressure(temperature,humidity) temperautre (C), h (%)"
        # formula for water saturation vapor pressure from
        # http://www.vaisala.com/Vaisala%20Documents/Application%20notes/Humidity_Conversion_Formulas_B210973EN-F.pdf
        Tc = 647.096 
        Pc = 22064000
        C1 = -7.85951783
        C2 = 1.84408259
        C3 = -11.7866497
        C4 = 22.6807411
        C5 = -15.9618719
        C6 = 1.80122502
        t=1-(temperature+273.15)/Tc
        pw=humidity/100*Pc*math.exp(Tc/(temperature+273.15)*(C1*t+C2*math.pow(t,1.5)+C3*math.pow(t,3)+C4*math.pow(t,3.5)+C5*math.pow(t,4)+C6*math.pow(t,7.5)))
        #print pw
        return pw

    def getBomData(self):
        "get BOM observations"
        try:
            response=requests.get(self.bomurl)
            self.bomdata=json.loads(response.content)
            self.ot=float(self.bomdata["observations"]["data"][0]["air_temp"])
            self.oh=float(self.bomdata["observations"]["data"][0]["rel_hum"])
            self.bomdatatime=self.bomdata["observations"]["data"][0]["local_date_time"]
            bomd=self.bomdata["observations"]["data"][0]["local_date_time_full"]
            self.bomdatatimefull=strptime(bomd,"%Y%m%d%H%M%S")
            self.op=self.waterPartialPressure(self.ot,self.oh)
            self.hasbomdata=True
        except:
            self.hasbomdata=False
            self.ot=NaN
            self.op=NaN
            self.oh=NaN
            self.bomdatatime=localtime()
            self.bomdatatimefull=localtime()
            self.inflog("failed to load bom data")
				   

    def getSensorData(self):    
        #data comes from TCP reader - here we just update the vapour pressure based on existing data
        if self.TCPlistener.ih<0:
             self.hasSensorData=False
             self.inflog(asctime()+'Sensor error: '+str(self.TCPlistener.sensorID)+'returned '+str(self.TCPlistener.ih)+'\n')
        else:
            self.addSensorData(self.TCPlistener.it,self.TCPlistener.ih,self.TCPlistener.sensorID,self.TCPlistener.itimestamp, self.TCPlistener.battery)
            self.hasSensorData=True
            
    def addSensorData(self,t,h,sensid,timest,b):
        ip=self.waterPartialPressure(t,h)
        self.sensidtable[sensid]={'T': t,'H': h, 'P': ip, 'Time': timest,'B': b}
        self.adddatatologfile(sensid)
        
    def addlinetotable(self,text):
        self.filen.write("<tr>"+text+"</tr>")

    def begintable(self):
        self.filen.write('<table border CLASS="climatetable">')
                    
    def closetable(self):
        self.filen.write("</table>")
        
    def adddatatologfile(self,sensid):
        it=self.sensidtable[sensid]['T']
        ih=self.sensidtable[sensid]['H']
        ip=self.sensidtable[sensid]['P']
        ib=self.sensidtable[sensid]['B']
        timest=self.sensidtable[sensid]['Time']
        datafilen=open(self.datalogfile+str(sensid)+'.csv','a') 
        datafilen.write(str.format('{0:.3f}',mktime(timest))+',')
        datafilen.write(strftime('%d-%m-%Y %H:%M:%S',timest)+",")
        datafilen.write(str.format("{0:.1f}",it)+",")
        datafilen.write(str.format("{0:.0f}",ih)+",")
        datafilen.write(str.format("{0:.0f}",ip)+",")
        datafilen.write(str.format("{0:.0f}",ib)+"\n")
        datafilen.flush() # force writing buffer
        datafilen.close()
        #self.inflog('added data to file - sensor '+str(sensid))

        
    def writeBOMcsv(self):
        if(self.hasbomdata):
            datafilen=open(self.datalogfile+'BOM.csv','a+')
            #check if last line exist and if timestamp is identical to current time stamp
            try:
                lastBomTime=datafilen.readlines()[-1].split(',')[0] 
            except:
                lastBomTime=''
                
            if(str.format('{0:.3f}',mktime(self.bomdatatimefull))!=lastBomTime):
                datafilen.write(str.format('{0:.3f}',mktime(self.bomdatatimefull))+',')
                datafilen.write(strftime('%d-%m-%Y %H:%M:%S',self.bomdatatimefull)+",")
                datafilen.write(str.format("{0:.1f}",self.ot)+",")
                datafilen.write(str.format("{0:.0f}",self.oh)+",")
                datafilen.write(str.format("{0:.0f}",self.op)+"\n")
            datafilen.close()

    def ftpcopy(self, name):
        # copies file name to  remote webserver over ftp - without path information
        if(ftpserver): # only if ftpserver is defined
            lf=open(name, 'r') 
            try:
                f=FTP(ftpserver) # defined in config file
                f.login(ftplogin,ftppwd)
                rname=name.split('/')[-1] # remove path
                f.storbinary('STOR ' +rname ,lf)
                f.quit()
            except:
                self.inflog("failed to uplod to ftp")
            
            lf.close()
        
        
    def plotdataday(self,nameext,days=1):        
	#plot data for last days day only, save with nameext.png extension
        data={}
        cols=['r', 'b' ,'g', 'y','c','k']
        #plt.style.use('ggplot')
        plt.rc('lines', linewidth=3)
        f, (ax1, ax2,ax3)= plt.subplots(3,sharex=True,sharey=False)
        f.set_size_inches(5,10)
        # plot BOM data first
        ax1.set_prop_cycle('color',cols)
        ax2.set_prop_cycle('color',cols)
        ax3.set_prop_cycle('color',cols)
        icol=0
        data=np.genfromtxt(self.datalogfile+'BOM.csv',skip_header=0,delimiter=',')
        if(data.ndim>1):
            data=data[~np.isnan(data[:,0])] # remove lines with nan for date
            if data[:,0].size>1: # only plot if more than one data point
                lcol=cols[icol]
                ndates=data[:,0]
                ldates=dateconv(ndates[ndates[:]>=ndates[-1]-24*3600*days])
                ldata=data[ndates[:]>=ndates[-1]-24*3600*days]
                if(ldata[:,0].size>1):
                    ax1.plot_date(ldates,ldata[:,2],ls='solid',marker="",color=lcol,label='outside')
                    ax2.plot_date(ldates,ldata[:,3],ls='solid',marker="",color=lcol,label='outside')
                    ax3.plot_date(ldates,ldata[:,4],ls='solid',marker="",color=lcol,label='outside')

        ax1.set_title('Temperature')
        ax1.set_ylabel('Temp')
        ax2.set_title('Rel humidity')
        ax2.set_ylabel('%')
        ax3.set_title('Vap pressure')
        ax3.set_ylabel('Pa')

        # now add all sensor data
        for sid in self.sensidtable:
            data=np.genfromtxt(self.datalogfile+str(sid)+'.csv',skip_header=0,delimiter=',')
            if data.ndim>1:
                data=data[~np.isnan(data[:,0])] # remove lines with nan for date
                if(data[:,0].size>1):
                    icol=icol+1
                    if icol>=len(cols): icol=1
                    lcol=cols[icol]                
                    ndates=data[:,0]
                    ldates=dateconv(ndates[ndates[:]>=ndates[-1]-24*3600*days])
                    #                ndates=ndates[~np.isnan(data).any(axis=1)] # removs raws with nans
                    if len(set(ldates))>1: #only plot if more than one unique timestamp in srlected timeframe
                        ldata=data[ndates[:]>=ndates[-1]-24*3600*days]
                        if(ldata[:,0].size>1):
                            ax1.plot_date(ldates,ldata[:,2],ls='solid',marker="",color=lcol,label=str(sid))
                            ax2.plot_date(ldates,ldata[:,3],ls='solid',marker="",color=lcol,label=str(sid))
                            ax3.plot_date(ldates,ldata[:,4],ls='solid',marker="",color=lcol,label=str(sid))

        f.autofmt_xdate()        
        if days>1:
            xfmt = md.DateFormatter('%Y-%m-%d %H:%M')
        else:
            xfmt = md.DateFormatter('%H:%M')        
        ax3.xaxis.set_major_formatter(xfmt)
        ax1.grid()
        ax2.grid()
        ax3.grid()
        ax1.xaxis_date()
        ax2.xaxis_date()
        ax3.xaxis_date()
        f.subplots_adjust(top=0.85)
        plt.legend(bbox_to_anchor=(0., 0.95, 1., .102),  bbox_transform=plt.gcf().transFigure, loc=3, ncol=3, mode="expand", borderaxespad=0.)
        plt.savefig(self.datalogfile+nameext+'.png',dpi=100)
        self.ftpcopy(self.datalogfile+nameext+'.png')
        f.clf()
        plt.close()
        gc.collect()
        
    def sendAlerts(self):
        if(self.p and self.hasbomdata): #if pushetta service has been enabled, send alerts
            if (self.ot<self.alertTempLow) and not(self.sentAlertLow):
                try:
                    self.p.pushMessage(CHANNEL_NAME,"Temperature alert (" +str(self.ot)+")")
                    self.sentAlertLow=True
                except:
                    self.inflog("puschetta notification failed")
                    
            if (self.ot>self.alertTempHigh) and not(self.sentAlertHigh):
                try:
                    self.p.pushMessage(CHANNEL_NAME,"Temperature alert (" +str(self.ot)+")")
                    self.sentAlertHigh=True
                except:
                    self.inflog("puschetta notification failed")
                                        
    # reset flags            
            if (self.ot>self.alertTempLow+1) and (self.sentAlertLow):
                self.sentAlertLow=False
            if (self.ot<self.alertTempHigh-1) and (self.sentAlertHigh):
                self.sentAlertHigh=False


    def update(self):
        " update webpage, based on it (inside temp), ih (inside rel humidity), ot (outside temp), oh (outside hum)"
       # try:
        self.getSensorData()
        if time()>self.lastUpdate+60: # do not update files more often than once per minute            
            self.TCPlistener.gotnewdata=False
            self.lastUpdate=time()
            self.getBomData()
                
            self.writeBOMcsv()
            self.sendAlerts()

            if self.hasSensorData:
                # first write to NOW file
                datafilen=open(self.datalogfile+'NOW.txt','w')
                datafilen.write('Canterburry: ')
                datafilen.write(str.format(": {0:.1f} C",self.ot)+", ")
                datafilen.write(str.format("{0:.0f} %",self.oh)+", ")
                datafilen.write(str.format("{0:.0f} Pa",self.op)+" (")
                datafilen.write(strftime('%d-%m %H:%M',self.bomdatatimefull)+")\n")

                for sid in self.sensidtable:
                    it=self.sensidtable[sid]['T']
                    ih=self.sensidtable[sid]['H']
                    ip=self.sensidtable[sid]['P']
                    ib=self.sensidtable[sid]['B']
                    its=self.sensidtable[sid]['Time']
                    datafilen.write(str(sid))
                    datafilen.write(str.format(": {0:.1f} C",it)+", ")
                    datafilen.write(str.format("{0:.0f} %",ih)+", ")
                    datafilen.write(str.format("{0:.0f} Pa",ip)+" (")
                    datafilen.write(strftime('%d-%m %H:%M',its)+")\n")
                datafilen.close()
                self.ftpcopy(self.datalogfile+'NOW.txt')
                
                self.filen=open(self.filename,'w')
                self.datafilen=open(self.datalogfile,'a')
                self.filen.write('<html><head><link rel="stylesheet" type="text/css" href="climatetable.css"><meta http-equiv="refresh" content="30"></head><body>\n')
                self.begintable()
                self.addlinetotable("<td> Sensor</td><td>Temperature </td><td>Relative humidity</td><td>Water Vapour Pressure</td><td>time</td><td>Battery level</td>")
                self.addlinetotable("<td>Outside:</td><td>"+str.format("{0:.1f}",self.ot)+"&deg;C</td><td>"+str.format("{0:.1f}",self.oh)+" %</td><td>"+
                                    str.format("{0:.1f}",self.op)+" Pa</td><td>"+strftime('%d-%m-%Y %H:%M:%S',self.bomdatatimefull)+"</td><td></td>")
                for sid in self.sensidtable:
                    it=self.sensidtable[sid]['T']
                    ih=self.sensidtable[sid]['H']
                    ip=self.sensidtable[sid]['P']
                    ib=self.sensidtable[sid]['B']
                    its=self.sensidtable[sid]['Time']
                    if ib<3400:
                        self.addlinetotable("<td>"+str(sid)+":</td><td>"+str.format("{0:.1f}",it)+"&deg;C</td><td>"+str.format("{0:.1f}",ih)+" %</td><td>"+
                                        str.format("{0:.1f}",ip)+" Pa</td><td>"+strftime('%d-%m-%Y %H:%M:%S',its)+'</td><td CLASS="bad">'+str(ib)+"</td>")
                    else:
                        self.addlinetotable("<td>"+str(sid)+":</td><td>"+str.format("{0:.1f}",it)+"&deg;C</td><td>"+str.format("{0:.1f}",ih)+" %</td><td>"+
                                        str.format("{0:.1f}",ip)+" Pa</td><td>"+strftime('%d-%m-%Y %H:%M:%S',its)+'</td><td CLASS="good">'+str(ib)+"</td>")
                    #self.adddatatologfile(sid) #having this here writes one line on csv file each time 
                                               # any sensor sends data, ending up with as many repeat lines as there are sensors

                self.closetable()
                self.filen.write("<p><img src="+self.fileradix+"day.png></p>")
                self.filen.write("<p><img src="+self.fileradix+".png></p>")


                self.filen.write("</body></html>")
                self.filen.close()
                self.ftpcopy(self.filename)
                self.plotdataday('',30)
                self.plotdataday('day',1)
Beispiel #21
0
def push(x):
    # 	API_KEY="YOU API KEY"
    # 	CHANNEL_NAME="YOUR CHANNEL NAME"
    p = Pushetta(API_KEY)
    p.pushMessage(CHANNEL_NAME, x)
 def __init__(self, api_key, channel_name):
     """Initialize the service."""
     from pushetta import Pushetta
     self._api_key = api_key
     self._channel_name = channel_name
     self.pushetta = Pushetta(self._api_key)
Beispiel #23
0
def push(x):
    # API_KEY="YOU API KEY"
    # CHANNEL_NAME="YOUR CHANNEL NAME"
    ps = Pushetta(config.API_KEY)
    ps.pushMessage(config.CHANNEL_NAME, x)
Beispiel #24
0
###########################################
# CONFIGURATION
WIDTH = 640
HEIGHT = 480
FRAMERATE = 24
HTTP_PORT = 8082
WS_PORT = 8084
COLOR = u'#444'
BGCOLOR = u'#333'
JSMPEG_MAGIC = b'jsmp'
JSMPEG_HEADER = Struct('>4sHH')

config = configparser.ConfigParser()
PUSHETTA_KEY = "e591b03544179db61e747dddccceac0fa3714d26"
CHANNEL_NAME = "SensorRPI"
alarm = Pushetta(PUSHETTA_KEY)
pir = MotionSensor(4)
###########################################


class StreamingHttpHandler(BaseHTTPRequestHandler):
    def do_HEAD(self):
        self.do_GET()

    def do_GET(self):
        config.read('config.ini')
        ACTIVE = config.get('main','active')
        STREAMING = config.get('main', 'streaming')
        SAVE = config.get('main', 'save')
        ACTIVE_CHECK = ''
        SAVE_CHECK=''
Beispiel #25
0
#!/usr/bin/env python
from pushetta import Pushetta

API_KEY = "your_key"
CHANNEL_NAME = "HomeKeeper"
p = Pushetta(API_KEY)
p.pushMessage(CHANNEL_NAME, "Hello World From MotionEye")
Beispiel #26
0
# Kütüphaneleri import ettik
from pushetta import Pushetta
from bs4 import BeautifulSoup
import requests
from os import getcwd

# Pushetta için ApiKey'imizi buraya yazıyoruz
API_KEY = "API-KEY-HERE"
kanal = "Anime Bildirim"
# bildirim göndermek için Pushetta nesnesi oluşturduk
bildirim = Pushetta(API_KEY)
# Örnek kullanım
# bildirim.pushMessage("KanalAdı", "Bildirim")

# dizimob anasayfası kaynak kodunu çektik
r = requests.get('https://www.dizimob1.com/')
# BeautifulSoup ile kaynak kodu, html.parser modunda inceleyeceğiz
source = BeautifulSoup(r.content, "html.parser")
# A değişkeni bize class'ında listfilm bulunan tüm div leri çekti,
# sitede bu div ler dizi ve animelerin listelendiği divlerdir.
# yani tüm dizi ve animeleri çektik.
A = source.findAll("div", attrs={"class", "listfilm"})

# hata almamak için çektiklerimizi kaynak koda atıyoruz
content = ""
for element in A:
    content += str(element)
# Çektiklerimiz üstünden devam edelim
source = BeautifulSoup(content, "html.parser")

# animeler.txt okuma modunda dosyasını açtık
Beispiel #27
0
from pushetta import Pushetta

API_KEY = "019c881997e32c0fe1919ea546e851c4ad453508"
CHANNEL_NAME = "MyArduino9678"
p = Pushetta(API_KEY)
p.pushMessage(CHANNEL_NAME, "Hello World")
Beispiel #28
0
 def __init__(self, api_key, channel_name):
     """Initialize the service."""
     from pushetta import Pushetta
     self._api_key = api_key
     self._channel_name = channel_name
     self.pushetta = Pushetta(self._api_key)
Beispiel #29
0
def main():

    parser = OptionParser(usage=__doc__)  #, version=__version__)
    parser.set_defaults(gui=True)
    parser.add_option("--ini",
                      action="store",
                      dest="inifile",
                      default="config/config.ini",
                      help="specify pyocto ini file (default: config.ini)")
    parser.add_option("-n",
                      "--notify",
                      action="store_true",
                      dest="push",
                      default=False,
                      help="send push notification when script terminates")
    parser.add_option("--setup",
                      action="store_true",
                      dest="setup",
                      default=False,
                      help="setup a vivado project")
    parser.add_option("--clear",
                      action="store_true",
                      dest="clear",
                      default=False,
                      help="clear a yocto build project")
    parser.add_option("--build",
                      action="store_true",
                      dest="build",
                      default=False,
                      help="build the yocto project")
    parser.add_option("--update",
                      action="store",
                      dest="update",
                      help="update the git repos.")

    # Parse command-line
    global options
    if len(sys.argv) < 2:
        if os.path.exists("pyocto.cmd"):
            argv = list(
                flatten([
                    a for a in (l.split('#')[0].split()
                                for l in open("pyocto.cmd")) if len(a)
                ]))
        else:
            argv = ["--help"]
    else:
        argv = sys.argv[1:]
    cmdline = ' '.join(argv)
    (options, args) = parser.parse_args(argv)

    inifile = options.inifile

    # Parse options form the configuration file
    v_pyocto = pyocto(inifile, options)

    #execute using the selected options
    if options.setup:
        print "-.- clone the yocto repos."
        v_pyocto.pyocto_git_clone("yocto")
        #if (os.path.exists("./poky")):
        #    print "-W- poky exists. Consider using the update switch - skip the clone"
        #else:
        #    g.clone(v_pyocto.yocto.repo_yocto)
        #    # git.Git().clone(v_pyocto.yocto.repo_yocto)

        os.chdir('poky')
        print "-.- path is now: " + os.getcwd()
        v_pyocto.pyocto_git_clone("meta-xilinx")
        v_pyocto.pyocto_git_clone("meta-xilinx-tools")
        # v_pyocto.pyocto_git_clone("meta-xilinx-petalinux")
        v_pyocto.pyocto_git_clone("meta-zynqberry")

        print "-I- Setup is DONE ----"

        notification = "PYOCTO (setup) is over"

    if options.clear:
        print "clear"
        notification = "PYOCTO (clear) is not supported"

        print "---- DONE ----"
        exit()

    if options.build:
        print "build"
        notification = "PYOCTO (build) is not supported"
        exit()

    if options.update:
        print "update"
        notification = "PYOCTO (update) is not supported"
        exit()

    if options.push and importpushetta:

        print "-.- Send notification"

        API_KEY = v_pyocto.notification.api_key
        CHANNEL_NAME = v_pyocto.notification.channel_name

        p = Pushetta(API_KEY)
        p.pushMessage(CHANNEL_NAME, notification)

    print "-.- done"
Beispiel #30
0
    start_value = sensor.accel[2]
    
    
if __name__ == "__main__":

    # Initialize sensor with external library class.
    sensor = mpu9250()
    
    # Key taken from account.
    API_KEY = "fb2dc4530995b2fe3d3f823a0fa35a5e8d635716"
    
    # Name of channel.
    CHANNEL_NAME = "JuicySeniorDesign"
    
    # Create pushetta object.
    p = Pushetta(API_KEY)

    data_max = 0
    
    while True:
        
        # Get sensor data.
        data = sensor.accel[2]

        # Look at new max value.
        if data > data_max:
            data_max = data
            
        # Thresholding for alarm detection. Adjust magnitude for each axis.           
        if (data_max >= (start_value + Z_THRESHOLD)):
            alert(p, CHANNEL_NAME, sensor)
from pushetta import Pushetta

API_KEY = "dad789bb30df8263eb2ea9322201372d54f6c6c6"
CHANNEL_NAME = "Testcamcalt"
p = Pushetta(API_KEY)
p.pushMessage(CHANNEL_NAME, "Alert - Motion Detected")
Beispiel #32
0
# Save the file (locally) from post request in django views
destination = open('my_file.extension', 'wb+')
for chunk in request.FILES['file_key'].chunks():
    destination.write(chunk)
destination.close()

# ---------------------------------------------------------------------------- #

from django.core.files import File  # This is to save the raw file in models
my_file = open('file.extension', 'rb')
my_new_record = ModelName(field1='',
                          file_field=File(my_file),
                          field2=request.data['key'])
# File class helps to store file in django db
my_new_record.save()  # Save the new record in database
my_file.close()

# ---------------------------------------------------------------------------- #

# Send notifications on android mobile using third party app Pushetta
# pip install pushetta
from pushetta import Pushetta

api_key = ""
channel_name = ""
p = Pushetta(api_key)
msg = 'Hey there, Android! I am Python here.'
p.pushMessage(channel_name, msg)
# ---------------------------------------------------------------------------- #
Beispiel #33
0
# load the Google Coral object detection model
print("[INFO] loading Coral model...")
model = DetectionEngine(args["model"])

# initialize the video stream and allow the camera sensor to warmup
print("[INFO] starting video stream...")
# vs = VideoStream(src=0).start()
vs = VideoStream(usePiCamera=True).start()
time.sleep(2.0)

# initializing base variables
sec = -1
prevLabel = []
API_KEY = "31549955596bf4c90732ef6c878372b2a3eca83c"
CHANNEL_NAME = "RaspiSecurityCamera"
p = Pushetta(API_KEY)

# loop over the frames from the video stream
while True:
    # grab the frame from the threaded video stream and resize it
    # to have a maximum width of 500 pixels
    frame = vs.read()
    frame = imutils.resize(frame, width=1000)
    orig = frame.copy()

    # prepare the frame for object detection by converting (1) it
    # from BGR to RGB channel ordering and then (2) from a NumPy
    # array to PIL image format
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame = Image.fromarray(frame)