Ejemplo n.º 1
0
def _read_am2302(pin, para):
    #http://www.home-automation-community.com/temperature-and-humidity-from-am2302-dht22-sensor-displayed-as-chart/
    with Timeout(seconds=2.5):
        humidity, temperature = Adafruit_DHT.read(Adafruit_DHT.AM2302, pin)
        if para == 'temperature':
            v = float(temperature)
            if v > 150.:
                print '_read_am2302: temperature is too high %s' % v
                raise BaseException('temperature is too high %s' % v)
            if v < -55.:
                print '_read_am2302: temperature is too low %s' % v
                raise BaseException('temperature is too low %s' % v)
            return v
        elif para == 'humidity':
            v = float(humidity)
            if v > 100.:
                print 'humidity is too high %s' % v
                raise BaseException('humidity is too high %s' % v)
            if v < 0.:
                print 'humidity is too low %s' % v
                raise BaseException('humidity is too low %s' % v)
            return v
        else:
            print '! _read_am2302: para should be either temperatue or humidity'
            raise BaseException('para should be either temperatue or humidity')
Ejemplo n.º 2
0
def get_time_error():
    """
    gets time error in seconds
    """
    try:
        with Timeout(seconds=16):
            import dateutil.parser
            import pytz
            import ssl
            t1 = time.time()
            #resp = urllib2.urlopen(r'https://script.google.com/macros/s/AKfycbyd5AcbAnWi2Yn0xhFRbyzS4qMq1VucMVgVvhul5XqS9HkAyJY/exec', timeout=15).read().strip()
            resp = urllib2.urlopen(urllib2.Request('https://script.google.com/macros/s/AKfycbyd5AcbAnWi2Yn0xhFRbyzS4qMq1VucMVgVvhul5XqS9HkAyJY/exec'), context=ssl._create_unverified_context()).read()
            jresp = json_util.loads(resp)
            if not (jresp['timezone'].lower()=="utc"):
                print ">> timecheck: !!!Time error might not be UTC"
                raise BaseException('')
            t2 = time.time()
            time_needed = (t2 - t1)
            correction = time_needed/2.
            dt_internet = dateutil.parser.parse(jresp['fulldate']).astimezone(pytz.utc)
            seconds = (datetime.datetime.utcnow().replace(tzinfo=pytz.utc) - dt_internet).total_seconds() - correction
            return seconds
    except:
        print ">> timecheck: could not get time_error"
        return None
Ejemplo n.º 3
0
def create_tunnel(slave_port, tunnel_para):
    with Timeout(seconds=30):
        website.processing.execute(
            'sudo chmod 700 /home/pi/rpislave/tunnelonly')
        revssh_line = 'sudo ssh -o TCPKeepAlive=no -o ExitOnForwardFailure=yes -o StrictHostKeyChecking=no -o ServerAliveInterval=30 -o ServerAliveCountMax=2 -i /home/pi/rpislave/tunnelonly -R \*:%s:localhost:%s -N ubuntu@%s' % (
            tunnel_para['server_port'], slave_port, tunnel_para['server_ip'])
        print ">> status: creating tunnel: %s" % revssh_line
        website.processing.execute(revssh_line, daemon=True)
Ejemplo n.º 4
0
def restart_networking():
    try:
        with Timeout(seconds=30):
            print ">> status: not connected to internet, will attempt to restart network"
            print '>> status: sudo /etc/init.d/networking stop'
            website.processing.execute('sudo /etc/init.d/networking stop')
            print '>> status: sudo /etc/init.d/networking start'
            website.processing.execute('sudo /etc/init.d/networking start')
            #execute("sudo sed -i '1s/^/nameserver 8.8.8.8\n/' /etc/resolv.conf")
            time.sleep(3)
    except:
        pass
Ejemplo n.º 5
0
def _read_ds18b20(id):
    with Timeout(seconds=1.1):
        base_dir = '/sys/bus/w1/devices'
        device_folder = base_dir + '/' + id
        reading_file = device_folder + '/' + 'w1_slave'
        f = open(reading_file, 'r')
        text = f.read(
        )  #text = 'd5 01 55 00 7f ff 0c 10 11 : crc=11 YES\nd5 01 55 00 7f ff 0c 10 11 t=29312\n'
        if not ("YES" in text):
            raise BaseException('YES is not in text')
        f.close()
        raw = re.compile(r'(.+)t=(?P<raw>[-+]?\d+)(.+)',
                         flags=re.DOTALL).match(text).groupdict()['raw']
        v = float(raw) / 1000.
        if v == -62.0 or v == 85.0:
            raise BaseException(
                'ds18b20 temperature value -62 or 85 which is an error code of the sensor %s'
                % v)
        if v < -55. or v > 125.:
            raise BaseException('ds18b20 temperature value out of range')
        return v  #this number is in celsuis, could be positive or negative
Ejemplo n.º 6
0
def _read_hcsr04(pin_trig, pin_echo):
    """
    this is a sensor to measure distances
    """

    with Timeout(seconds=2.0):  #not sure about the length of this time

        GPIO.setmode(GPIO.BCM)

        #pin_trig = 23
        #pin_echo = 24

        GPIO.setup(pin_trig, GPIO.OUT)
        GPIO.setup(pin_echo, GPIO.IN)

        #sending the triger signal
        GPIO.output(pin_trig, False)
        sleep(0.5)  #wait for sensor to settle
        GPIO.output(pin_trig, True)
        sleep(0.00001)
        GPIO.output(pin_trig, False)

        #reading the echo signal
        while GPIO.input(pin_echo) == 0:
            pass
        pulse_start = time()
        while GPIO.input(pin_echo) == 1:
            pass
        pulse_end = time()
        pulse_duration = pulse_end - pulse_start

        #measuring distance
        distance = pulse_duration * 17150
        distance = round(distance, 2)
        distance = distance - 0.5
        if distance > 2 - 0.5 and distance < 400 - 0.5:
            return distance
        else:
            raise BaseException('distance is out of acceptable range %s' %
                                distance)
Ejemplo n.º 7
0
def get_status():
    def gitcmd(cmd):
        r = website.processing.execute(cmd).strip()
        #"/bin/sh: 1: cd: can't cd to /home/pi/rpislave_conf\n"
        #'fatal: Not a git repository (or any of the parent directories): .git\n'
        if ("cd to " in r) or ("Not a git" in r):
            return '-'
        else:
            return r

    d = {}

    try:
        with Timeout(seconds=30):
            resp = urllib2.urlopen('http://api.ipify.org?format=json').read()
            d['ip_wan'] = json.loads(resp)['ip']
    except:
        d['ip_wan'] = "-"
        pass

    #CPU
    try:
        with Timeout(seconds=10):
            resp = website.processing.execute("cat /proc/cpuinfo")
            d['serial'] = [x for x in resp.split("\n")
                           if "Serial" in x][0].split()[-1]
    except:
        d['serial'] = "-"
        pass

    try:
        with Timeout(seconds=30):
            resp = website.processing.execute("cat /proc/cpuinfo")
            d['revision'] = [x for x in resp.split("\n")
                             if "Revision" in x][0].split()[-1]
    except:
        d['revision'] = "-"
        pass

    #GIT
    try:
        with Timeout(seconds=30):
            d['git_rpislave'] = gitcmd(
                "cd /home/pi/rpislave&&git rev-parse HEAD")
            d['gitbranch_rpislave'] = gitcmd(
                "cd /home/pi/rpislave&&git rev-parse --abbrev-ref HEAD")
    except:
        d['git_rpislave'] = '-'
        d['gitbranch_rpislave'] = '-'

    #IP
    try:
        with Timeout(seconds=30):
            resp = website.processing.execute("ifconfig")
            d['ip_lan'] = "192.168.{0[p3]}.{0[p4]}".format(
                re.compile(
                    r'(.+)inet addr:192\.168\.(?P<p3>\d+)\.(?P<p4>\d+)(.+)',
                    flags=re.DOTALL).match(resp).groupdict())
    except:
        d['ip_lan'] = "-"

    try:
        with Timeout(seconds=30):
            resp = website.processing.execute("ifconfig")
            d['ip_vlan'] = "10.0.{0[p3]}.{0[p4]}".format(
                re.compile(
                    r'(.+)inet addr:10\.0\.(?P<p3>\d+)\.(?P<p4>\d+)(.+)',
                    flags=re.DOTALL).match(resp).groupdict())
    except:
        d['ip_vlan'] = "-"

    return d