Example #1
0
def getFrame():
    raw_data = {
        "linux_time": (time.time()),
        "a_x": round(motion.accelerometer().x, roundOff),
        "a_y": round(motion.accelerometer().y, roundOff)
    }
    frame.append(raw_data)
def getFrame():
    raw_data = { "time" : (time.time()),
                 "flight_mode": 0,
                 "squib_deployed": 0,
    "a_x": round(motion.accelerometer().x, roundOff), 
    "a_y": round(motion.accelerometer().y, roundOff),
    "a_z": round(motion.accelerometer().z, roundOff),    
    "temp": round(weather.temperature(), roundOff),                        
    "pressure": round(weather.pressure(), roundOff),                           
    "s1": round(ina219A.getShuntVoltage_mV(), roundOff),                
    "volt_b1": round(ina219A.getBusVoltage_V(), roundOff),                  
    "current_1": round(ina219A.getCurrent_mA(), roundOff),                     
    "s2": round(ina219B.getShuntVoltage_mV(), roundOff),                
    "volt_b2": round(ina219B.getBusVoltage_V(), roundOff),                   
    "current_2": round(ina219B.getCurrent_mA(), roundOff),
                 "gps_lat" : 12,
                 "gps_lon" : 13,
                 "gps_alt" : 14,
                 "gps_spd" : 15,
    #"gps_lat": round(gpsd.fix.latitude, roundOff),                          
    #"gps_lon": round(gpsd.fix.longitude, roundOff),                         
    #"gps_alt": round(gpsd.fix.altitude, roundOff),                          
    #"gps_spd": round(gpsd.fix.speed, roundOff),
                 "mag_x": round(motion.magnetometer().x, roundOff),
                 "mag_y": round(motion.magnetometer().y, roundOff),
                 "mag_z": round(motion.magnetometer().z, roundOff)
                 }                              
    frame.append(raw_data)
Example #3
0
    def update(self):
        """Get the latest data from Enviro pHAT."""
        from envirophat import analog, leds, light, motion, weather

        # Light sensor reading: 16-bit integer
        self.light = light.light()
        if self.use_leds:
            # pylint: disable=no-value-for-parameter
            leds.on()
        # the three color values scaled agains the overall light, 0-255
        self.light_red, self.light_green, self.light_blue = light.rgb()
        if self.use_leds:
            # pylint: disable=no-value-for-parameter
            leds.off()

        # accelerometer readings in G
        self.accelerometer_x, self.accelerometer_y, self.accelerometer_z = \
            motion.accelerometer()

        # raw magnetometer reading
        self.magnetometer_x, self.magnetometer_y, self.magnetometer_z = \
            motion.magnetometer()

        # temperature resolution of BMP280 sensor: 0.01°C
        self.temperature = round(weather.temperature(), 2)

        # pressure resolution of BMP280 sensor: 0.16 Pa, rounding to 0.1 Pa
        # with conversion to 100 Pa = 1 hPa
        self.pressure = round(weather.pressure() / 100.0, 3)

        # Voltage sensor, reading between 0-3.3V
        self.voltage_0, self.voltage_1, self.voltage_2, self.voltage_3 = \
            analog.read_all()
Example #4
0
def sbc_rpi0_envirophat():
    update = {}

    update["phatlightrgb"] = light.rgb()
    update["phatlight"] = light.light()
    update["phattemperature"] = round(weather.temperature(), 1)
    update["phatpressure"] = round(weather.pressure(unit='hPa'), 1)
    update["phataltitude"] = round(weather.altitude(qnh=1020), 1)
    update["phatanalog"] = analog.read_all()
    update["phatmagnetometer"] = str(motion.magnetometer())
    update["phataccelerometer"] = str(motion.accelerometer())
    update["phatheading"] = round(motion.heading(), 1)
    update["soiltemp"] = round(
        therm200_convert_analog(update["phatanalog"][2]), 1)
    update["soilmoist"] = round(vh400_convert_analog(update["phatanalog"][1]),
                                1)
    update["relhum"] = round(vghumid_convert_analog(update["phatanalog"][0]),
                             1)

    (result, mid) = mqttc.publish(hass_autogen_topic + "/" + cid + "/state",
                                  json.dumps(update),
                                  qos=1,
                                  retain=True)

    return update
def disp_stats():
    write("--- Enviro pHAT Monitoring ---")
    rgb = light.rgb()
    analog_values = analog.read_all()
    mag_values = motion.magnetometer()
    acc_values = [round(x, 2) for x in motion.accelerometer()]
    # DHT Type 11, Pin 17 (Line 41 Github)
    humidity, temp2 = Adafruit_DHT.read_retry(11, 17)
    currentDT = datetime.datetime.now()

    output = """
Time: {tm}; Temp: {t}c; Plant Temp: {t2}c; Humd: {hd}%; Pressure: {p}Pa; Light: {c}, RGB: {r}, {g}, {b}; Soil: {a0}%
""".format(tm=currentDT.strftime("%Y-%m-%d %H:%M:%S"),
           t=abs(weather.temperature() * 9 / 5.0 + 32),
           t2=abs((temp2 * 9 / 5.0 + 32)),
           hd=round(humidity, 0),
           p=round(weather.pressure(), 0),
           c=light.light(),
           r=rgb[0],
           g=rgb[1],
           b=rgb[2],
           h=motion.heading(),
           a0=round((analog_values[0] * 100) / 434, 2) * 100,
           a1=analog_values[1],
           a2=analog_values[2],
           a3=analog_values[3],
           mx=mag_values[0],
           my=mag_values[1],
           mz=mag_values[2],
           ax=acc_values[0],
           ay=acc_values[1],
           az=acc_values[2])
    #output = output.replace("\n","\n\033[K")
    write(output)
Example #6
0
    def update(self):
        """Get the latest data from Enviro pHAT."""
        from envirophat import analog, leds, light, motion, weather

        # Light sensor reading: 16-bit integer
        self.light = light.light()
        if self.use_leds:
            # pylint: disable=no-value-for-parameter
            leds.on()
        # the three color values scaled agains the overall light, 0-255
        self.light_red, self.light_green, self.light_blue = light.rgb()
        if self.use_leds:
            # pylint: disable=no-value-for-parameter
            leds.off()

        # accelerometer readings in G
        self.accelerometer_x, self.accelerometer_y, self.accelerometer_z = \
            motion.accelerometer()

        # raw magnetometer reading
        self.magnetometer_x, self.magnetometer_y, self.magnetometer_z = \
            motion.magnetometer()

        # temperature resolution of BMP280 sensor: 0.01°C
        self.temperature = round(weather.temperature(), 2)

        # pressure resolution of BMP280 sensor: 0.16 Pa, rounding to 0.1 Pa
        # with conversion to 100 Pa = 1 hPa
        self.pressure = round(weather.pressure() / 100.0, 3)

        # Voltage sensor, reading between 0-3.3V
        self.voltage_0, self.voltage_1, self.voltage_2, self.voltage_3 = \
            analog.read_all()
Example #7
0
    def run(self):
        print '[CarMonitor::EnviroPoller] Starting...'

        try:
            while not self.stopRequest.isSet():
                temperature = weather.temperature()
                pressure = weather.pressure()
                accelerometer = motion.accelerometer()
                magnetometer = motion.magnetometer()
                heading = motion.heading()

                self.enviroData = {
                    'temperature': temperature,
                    'pressure': pressure,
                    'accelerometer': {
                        'x': accelerometer.x,
                        'y': accelerometer.y,
                        'z': accelerometer.z
                    },
                    'magnetometer': {
                        'x': magnetometer.x,
                        'y': magnetometer.y,
                        'z': magnetometer.z
                    },
                    'heading': heading
                }

                time.sleep(.5)

        except StopIteration:
            pass
def track(init_heading, i, motor, prev):
    acc = motion.accelerometer()
    heading = (motion.heading() + i) % 360

    # handle tilt
    tilt = math.floor(90 * acc[0])
    if tilt > 90:
        tilt = 90
    elif tilt < -90:
        tilt = -90

    if prev[0] is None or abs(tilt - prev[0]) > 3:
        motor.tilt(tilt)
    else:
        tilt = prev[0]

    # handle pan
    heading = heading - init_heading
    if heading < -90:
        heading = -90
    elif heading > 90:
        heading = 90

    if prev[1] is None or abs(heading - prev[1]) > .5:
        motor.pan(heading)
    else:
        heading = prev[1]

    return (tilt, heading)
 def update_sensor_data(self):
     """Pretend to read the device's sensor data.
     If the fan is on, assume the temperature decreased one degree,
     otherwise assume that it increased one degree.
     """
     #self.proximity = self.sensor.proximity
     #self.ambient_lux = self.sensor.ambient_lux
     self.accel_x, self.accel_y, self.accel_z = motion.accelerometer()
Example #10
0
def getFrame():
    raw_data = { "linux_time" : (time.time()),
    "a_x": round(motion.accelerometer().x, roundOff), 
    "a_y": round(motion.accelerometer().y, roundOff),
    "a_z": round(motion.accelerometer().z, roundOff),    
    "t": round(weather.temperature(), roundOff),                        
    "p": round(weather.pressure(), roundOff),                           
    "s1": round(ina219A.getShuntVoltage_mV(), roundOff),                
    "b1": round(ina219A.getBusVoltage_V(), roundOff),                  
    "c1": round(ina219A.getCurrent_mA(), roundOff),                     
    "s2": round(ina219B.getShuntVoltage_mV(), roundOff),                
    "b2": round(ina219B.getBusVoltage_V(), roundOff),                   
    "c2": round(ina219B.getCurrent_mA(), roundOff),                     
    "lat": round(gpsd.fix.latitude, roundOff),                          
    "lon": round(gpsd.fix.longitude, roundOff),                         
    "alt": round(gpsd.fix.altitude, roundOff),                          
    "sp": round(gpsd.fix.speed, roundOff)}                              

    frame.append(raw_data)
Example #11
0
def writedata():
    with open(folder + 'meta.csv', 'a') as meta:
        writer = csv.writer(meta)
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        altitude = round(weather.altitude() + 90, 2)
        temperature = round(weather.temperature(), 2)
        heading = motion.heading()
        accx = round(motion.accelerometer()[0], 2)
        accy = round(motion.accelerometer()[1], 2)
        accz = round(motion.accelerometer()[2], 2)
        red = light.rgb()[0]
        green = light.rgb()[1]
        blue = light.rgb()[2]
        newrow = [
            "{:04}".format(index), timestamp, altitude, temperature, red,
            green, blue, heading, accx, accy, accz
        ]
        print newrow
        writer.writerow(newrow)
def motion_detector(threshold=0.1):
    # adapted from https://github.com/pimoroni/enviro-phat/blob/master/examples/motion_detect.py
    from envirophat import motion
    from collections import deque
    readings = deque(maxlen=4)
    last_z = 0
    while True:
        readings.append(motion.accelerometer().z)
        z = sum(readings) / len(readings)
        yield last_z > 0 and abs(z - last_z) > threshold
        last_z = z
Example #13
0
def get_sensor_data():
    data = {}
    data['analog'] = analog.read_all()
    data['accelerometer'] = tuple(motion.accelerometer())
    data['heading'] = motion.heading()
    data['leds'] = leds.is_on()
    data['light'] = light.light()
    data['rgb'] = light.rgb()
    data['pressure'] = weather.pressure()
    data['temperature'] = weather.temperature()
    return data
Example #14
0
def publish_sensor_data(hostname, root):
	messages = []
	for i, data in enumerate(analog.read_all()):
		messages.append(('%s/analog/%d' % (root, i), str(data), 0, True))
	messages.append((root+'/light/light', str(light.light()), 0, True))
	messages.append((root+'/light/rgb', str(light.rgb()), 0, True))
	messages.append((root+'/motion/accelerometer', str(motion.accelerometer()), 0, True))
	messages.append((root+'/motion/heading', str(motion.heading()), 0, True))
	messages.append((root+'/weather/pressure', str(weather.pressure()), 0, True))
	messages.append((root+'/weather/temperature', str(weather.temperature()), 0, True))
	publish.multiple(messages), hostname=hostname)
Example #15
0
def main():
    if DEVICE_ID == None:
        print("M_TSUNAMI_DEVICE_ID is not set.")
        return
    if TOKEN == None:
        print("M_TSUNAMI_TOKEN is not set.")
        return
    print("Press Ctrl+C to exit.")

    data = [[],[],[]]
    last_d = [-1,-1,-1]
    started = -1
    started_at = None

    try:
        while True:
            v = motion.accelerometer()
            data[0].append(v.x)
            data[1].append(v.y)
            data[2].append(v.z)
            shaked = False
            for i in range(3):
                data[i] = data[i][-DATA_MAX:]
                if len(data[i]) < DETECT_NUM: continue
                d = sum(data[i][-DETECT_NUM:]) / DETECT_NUM
                if last_d[i] > 0 and abs(d - last_d[i]) > DETECT_THRESH:
                    shaked = True
                last_d[i] = d
            if shaked:
                started = DETECT_NOOP
                if started_at == None:
                    started_at = time.time()
                    print("detected the quake!")
                    leds.on()
            time.sleep(DETECT_INTERVAL)
            started -= 1
            if started == 0:
                elapsed = time.time() - started_at
                sp,ss = strength(data,int(elapsed / DETECT_INTERVAL))
                msg = "An earthquake detected! %.2f P:%.2f S:%.2f" % (elapsed,sp,ss)
                print(msg)
                started_at = None
                leds.off()
                if elapsed > RAILS_THRESH:
                    q = {'quake[elapsed]': elapsed, 'quake[p]': sp, 'quake[s]': ss, 'quake[device_id]': DEVICE_ID, 'token': TOKEN}
                    r = requests.post(RAILS_WEBHOOK, data = q)
                    print(r)
                if SLACK_WEBHOOK and elapsed > SLACK_THRESH:
                    requests.post(SLACK_WEBHOOK, data = json.dumps({
                      'text': msg ,
                    }))
    except KeyboardInterrupt:
        leds.off()
Example #16
0
def run_measurements(client):
    """Measures accelerometer activity continously and stores an aggregated sum once per minute"""

    print_sample_time = 60  # How often data will be published to InfluxDB [seconds]
    last_print_time = datetime.datetime.now()
    limit = 350  # Minimum distance between two subsequent measurements to be counted as activity. [G]
    last_sample_x = 0
    last_sample_y = 0
    last_sample_z = 0
    activity_x = 0
    activity_y = 0
    activity_z = 0

    leds.on()  # Turn on LEDs to indicate measurement
    try:
        while True:
            x, y, z = motion.accelerometer()
            if x > limit:
                activity_x += x
            if y > limit:
                activity_y += y
            if z > limit:
                activity_z += z

            # Probably unnecessary


#            x_dist = x - last_sample_x
#            y_dist = y - last_sample_y
#            z_dist = z - last_sample_z
#
#            if x_dist > limit:
#                activity_x += x_dist
#            if y_dist > limit:
#                activity_y += y_dist
#            if z_dist > limit:
#                activity_z += z_dist

            time_dist = datetime.datetime.now() - last_print_time

            if time_dist.total_seconds() >= print_sample_time:
                last_print_time = datetime.datetime.now()
                activity_tot = activity_x + activity_y + activity_z
                temp = weather.temperature()
                publish_data(client, activity_tot, temp)
                activity_x = 0
                activity_y = 0
                activity_z = 0

    except KeyboardInterrupt:
        leds.off()  # Shut off LEDs
        out.close()  # Close log
        client.close()  # Close influx connection
Example #17
0
 def __getAcceleration(self):
     """ 
   Read acceleration in UNITS??? for (x,y,z) axis.
   
   Returns
   -------
   touple
      Acceleration touple (x,y,z) in UNITS???
   """
     try:
         value = motion.accelerometer()
     except:
         DinoLog.logMsg("ERROR - Envirophat fail to read acceleration.")
         value = (None, None, None)
     return value
Example #18
0
def getSensorData():
    sensors = {}
    t = datetime.datetime.now()
    sensors["timestamp"] = str(t.strftime('%Y%m%d %H:%M'))
    sensors["device_name"] = "YOUR DEVICE NAME"
    sensors["city"] = 'YOUR CITY'
    sensors["lng"] = 'YOUR LONGITUDE'
    sensors["lat"] = 'YOUR LATITUDE'

    sensors["lux"] = light.light()
    leds.on()
    sensors["rgb"] = str(light.rgb())[1:-1].replace(' ', '')
    leds.off()
    sensors["accel"] = str(motion.accelerometer())[1:-1].replace(' ', '')
    sensors["heading"] = motion.heading()
    sensors["temperature"] = weather.temperature()
    sensors["pressure"] = weather.pressure()

    return sensors
Example #19
0
def idle_work():
    global last_hf_time, last_lf_time
    now = time.time()
    if hf_enabled and (now - last_hf_time > hf_interval):
        mag = motion.magnetometer()
        accel = motion.accelerometer()
        h = motion.heading()
        print "X%0.10f,%0.10f,%0.10f,%d,%d,%0d,%0.2f".format(
            accel.x, accel.y, accel.z, mag.x, mag.y, mag.z, h)
        last_hf_time = now
    if lf_enabled and (now - last_lf_time > lf_interval):
        t = round(weather.temperature(), 2)
        p = round(weather.pressure(), 2)
        c = light.light()
        r = rgb[0]
        g = rgb[1]
        b = rgb[2]
        print "Y%0.2f,%0.2f,%d,%d,%d,,%d".format(t, p, c, r, g, b)
        last_lf_time = now
Example #20
0
def main():
    print("Press Ctrl+C to exit.")

    data = [[],[],[]]
    last_d = [-1,-1,-1]
    started = -1
    started_at = None

    try:
        while True:
            v = motion.accelerometer()
            data[0].append(v.x)
            data[1].append(v.y)
            data[2].append(v.z)
            shaked = False
            for i in range(3):
                data[i] = data[i][-DATA_MAX:]
                if len(data[i]) < DETECT_NUM: continue
                d = sum(data[i][-DETECT_NUM:]) / DETECT_NUM
                if last_d[i] > 0 and abs(d - last_d[i]) > DETECT_THRESH:
                    shaked = True
                last_d[i] = d
            if shaked:
                started = DETECT_NOOP
                if started_at == None:
                    started_at = time.time()
                    print("detected the quake!")
                    leds.on()
            time.sleep(DETECT_INTERVAL)
            started -= 1
            if started == 0:
                elapsed = time.time() - started_at
                sp,ss = strength(data,int(elapsed / DETECT_INTERVAL))
                msg = "An earthquake detected! %.2f P:%.2f S:%.2f" % (elapsed,sp,ss)
                print(msg)
                started_at = None
                leds.off()
                if SLACK_WEBHOOK and elapsed > SLACK_THRESH:
                    requests.post(SLACK_WEBHOOK, data = json.dumps({
                      'text': msg ,
                    }))
    except KeyboardInterrupt:
        leds.off()
Example #21
0
    def train(self, training_type):
        if os.path.isfile("training_data_" + training_type + ".npy"):
            old_data = numpy.load("training_data_" + training_type + ".npy")
            training_data_temp = old_data.tolist()
        else:
            training_data_temp = []
        try:
            last_accel = numpy.array([float(0),float(0),float(0)])
            while True:
                time.sleep(self.delay)
                x,y,z = motion.accelerometer()
                current_accel = numpy.array([x,y,z])
                jerk = self.calculate_jerk(current_accel, last_accel, self.delay) 
                training_data_temp.append(jerk)
#                absolute_value = numpy.linalg.norm(acceleration)
                print("|{}|".format(jerk))
        except KeyboardInterrupt:
            training_data = numpy.array(training_data_temp)
            numpy.save("training_data_" + training_type, training_data)
Example #22
0
def process_accel_req(message):
   global accel_sub
   global accel_sub_rate
   global accel_sub_ticks

   if message_list[3] == 'CMD=READ':
      # Get the values 
      s_x, s_y, s_z = motion.accelerometer()
 
      # format the message
      message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ACCEL,X=%.2f,Y=%.2f,Z=%.2f,SENSOR_REP_END" % (s_x,s_y,s_z)

   elif message_list[3] == 'CMD=SUB_START':
      rate_message_list = message_list[4].split('=')
      if rate_message_list[0] == 'RATE':
         rate = int(rate_message_list[1])
         if rate < 250:
            accel_sub_rate = 250 
         else:
            accel_sub_rate = rate
      accel_sub_ticks = 0
      accel_sub = True

      # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=ACCEL,CMD=SUB_START,RATE=1000,SENSOR_REQ_END
      # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ACCEL,STATUS=OK|BUSY,SENSOR_REP_END
      message =  "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ACCEL,STATUS=OK,SENSOR_REP_END"

   elif message_list[3] == 'CMD=SUB_STOP':
 
      accel_sub = False
      accel_sub_rate = 0
      accel_sub_ticks = 0

      # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=ACCEL,CMD=SUB_STOP,SENSOR_REQ_END
      # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ACCEL,STATUS=OK,SENSOR_REP_END
      message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ACCEL,STATUS=OK,SENSOR_REP_END"

   else:
      # unknown Command
      message = "SENSOR_REP," + message_list[1] + ",SUB_DEV=ACCEL,ERROR=UNKNOWN_CMD,SENSOR_REP_END"
   #  Send reply back to client
   return message
Example #23
0
def _get_data():
    light_values = {
        'sensor_type': 'TCS3472',
        'level': light.light(),
        **dict(zip(["red", "green", "blue"], light.rgb()))
    }
    weather_values = {
        'sensor_type': 'BMP280',
        'altitude': weather.altitude(),  # meters
        'pressure': round(weather.pressure("Pa"), 2),  # pascals
        'temperature': round(weather.temperature(), 2)  # celcius
    }
    motion_values = {
        'sensor_type':
        'LSM303D',
        **dict(
            zip(["acceleration_x", "acceleration_y", "acceleration_z"], [
                    round(x, 2) for x in motion.accelerometer()
                ])),  # x, y and z acceleration as a vector in Gs.
        'heading':
        motion.heading(),
        **dict(
            zip(["magnetic_field_x", "magnetic_field_y", "magnetic_field_z"],
                motion.magnetometer()))  # raw x, y and z magnetic readings as a vector.
    }
    analog_values = {
        'sensor_type': 'ADS1015',
        **{"channel_%i" % k: v
           for k, v in enumerate(analog.read_all())}
    }
    data = {
        'created_at': datetime.utcnow().isoformat() + 'Z',
        'light': light_values,
        'weather': weather_values,
        'motion': motion_values,
        'analog': analog_values
    }
    return data
Example #24
0
def readdata():
    leds.on()

    rgb = light.rgb()
    analog_values = analog.read_all()
    mag_values = motion.magnetometer()
    acc_values = [round(x, 2) for x in motion.accelerometer()]
    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime(
        '%Y-%m-%d %H:%M:%S')

    data = {}
    data['altitude'] = weather.altitude()
    data['temperature'] = weather.temperature()
    data['pressure'] = weather.pressure(unit=unit)
    data['lux'] = light.light()
    data['red'] = rgb[0]
    data['green'] = rgb[1]
    data['blue'] = rgb[2]
    data['heading'] = motion.heading()
    data['timestamp'] = timestamp

    leds.off()
    return data
Example #25
0
#!/usr/bin/env python

import time

from envirophat import motion, leds


print("""This example will detect motion using the accelerometer.

Press Ctrl+C to exit.

""")

threshold = 0.2
readings = []
last_z = 0

try:
    while True:
        readings.append(motion.accelerometer().z)
        readings = readings[-4:]
        z = sum(readings) / len(readings)
        if last_z > 0 and abs(z-last_z) > threshold:
            print("Motion Detected!!!")
            leds.on()
        last_z = z
        time.sleep(0.01)
        leds.off()
except KeyboardInterrupt:
    pass
Example #26
0
unit = 'hPa'  # Pressure unit, can be either hPa (hectopascals) or Pa (pascals)


def write(line):
    sys.stdout.write(line)
    sys.stdout.flush()


write("--- DJRFF pHAT Monitoring ---")

try:
    while True:
        rgb = light.rgb()
        mag_values = motion.magnetometer()
        acc_values = [round(x, 2) for x in motion.accelerometer()]

        output = """
Temp: {t:.2f}c
Pressure: {p:.2f}{unit}
Altitude: {a:.2f}m
Light: {c}
RGB: {r}, {g}, {b}
Heading: {h}
Magnetometer: {mx} {my} {mz}
Accelerometer: {ax}g {ay}g {az}g
""".format(
            unit=unit,
            a=weather.altitude(
            ),  # Supply your local qnh for more accurate readings
            t=weather.temperature(),
Example #27
0
 def acceleration(self):
     return motion.accelerometer()
Example #28
0
last_d = [-1,-1,-1]
started = -1
started_at = None

## TODO: 揺れ終わり後、フーリエ変換を使って、震度を求める
# 気象庁
# https://www.data.jma.go.jp/svd/eqev/data/kyoshin/kaisetsu/calc_sindo.htm
# FFT
# https://momonoki2017.blogspot.com/2018/03/pythonfft-1-fft.html
def stlength(data):
    fx = np.abs(np.fft.fft(data[0]))[len(data[0])/2+1:]
    return 1.0

try:
    while True:
        v = motion.accelerometer()
        data[0].append(v.x)
        data[1].append(v.y)
        data[2].append(v.z)
        shaked = False
        for i in range(3):
            data[i] = data[i][-DATA_MAX:]
            if len(data[i]) < DETECT_NUM: continue
            d = sum(data[i][-DETECT_NUM:]) / DETECT_NUM
            if last_d[i] > 0 and abs(d - last_d[i]) > DETECT_THRESH:
                shaked = True
            last_d[i] = d
        if shaked:
            started = DETECT_NOOP
            if started_at == None:
                started_at = time.time()
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

DEBUG = os.getenv('DEBUG', None)
MONGO_DB_URL = os.getenv('MONGO_DB')

parser = argparse.ArgumentParser()
parser.add_argument('--location',
                    default='Unkown',
                    help='Location to descibe where the Pi is')
args = parser.parse_args()

leds.on()
rgb = str(light.rgb())[1:-1].replace(' ', '')
leds.off()
acc = str(motion.accelerometer())[1:-1].replace(' ', '')

data = {
    'location': args.location,
    'time': datetime.utcnow().isoformat(),
    'light': light.light(),
    'rgb': rgb,
    'motion': acc,
    'heading': motion.heading(),
    'temp': weather.temperature(),
    'pressure': weather.pressure(),
}

# json_data = json.dumps(data)
# print(json_data)
Example #30
0
# FSYS - Alexander St.
# This Flight System has the following purpose:

# Supplying pressure, accelaration and heading data from Enviro pHAT to a file

from envirophat import motion, weather
from datetime import datetime

t = open('FlightRecord', 'a')

while True:
    t.write("\n " + str(datetime.now().time()))
    t.write("\n " + str(weather.pressure()))
    t.write("\n " + str(weather.altitude()))
    t.write("\n " + str(motion.accelerometer()))
    t.write("\n " + str(motion.heading()))
    t.write("\n ")
    t.close()
Example #31
0
from envirophat import light, motion, weather, leds

# define credentials in secret.py file
# ADAFRUIT_IO_KEY = ""
from secret import *

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USER, ADAFRUIT_IO_KEY)

print('Start uploading to Adafruit IO')

try:
    while True:
        now = datetime.utcnow()
        lux = light.light()
        leds.on()
        r,g,b = light.rgb()
        leds.off()
        acc = motion.accelerometer()
        heading = motion.heading()
        temp = weather.temperature()
        press = weather.pressure(unit='hPa')
        aio.send('env1-lux', lux)
        aio.send('env1-temp', temp)
        aio.send('env1-press', press)
        print("Posted to Adafruit IO: {:.2f}, {:.2f}, {:.2f}".format(lux, temp, press))
        time.sleep(60)#yyyy-MM-dd HH:mm:ss
except KeyboardInterrupt:
    leds.off()
    print('Stopped uploading to Adafruit IO')
Example #32
0
from envirophat import light, weather, motion, analog


def write(line):
    sys.stdout.write(line)
    sys.stdout.flush()

write("--- Enviro pHAT Monitoring ---")

try:
    while True:
        rgb = light.rgb()
        analog_values = analog.read_all()
        mag_values = motion.magnetometer()
        acc_values = [round(x,2) for x in motion.accelerometer()]

        output = """
Temp: {t}c
Pressure: {p}Pa
Light: {c}
RGB: {r}, {g}, {b} 
Heading: {h}
Magnetometer: {mx} {my} {mz}
Accelerometer: {ax}g {ay}g {az}g
Analog: 0: {a0}, 1: {a1}, 2: {a2}, 3: {a3}

""".format(
        t = round(weather.temperature(),2),
        p = round(weather.pressure(),2),
        c = light.light(),
Example #33
0
    exit("This script requires the envirophat module\nInstall with: sudo pip install envirophat")

import blinkt

offset = 0
direction = 0
t = []
t_start = 0

total_time = 1000

def millis():
    return int(round(time.time() * 1000))

while True:
    x, y, z = motion.accelerometer()
    print(y)

    if y < -1.9 and not direction == -1:
        direction = -1
        t.append(millis() - t_start)
        t_start = millis()
        t = t[-5:]

    if y > 1.9 and not direction == 1:
        direction = 1
        t.append(millis() - t_start)
        t_start = millis()
        t = t[-5:] 

    if len(t) > 0:
Example #34
0
def get_accelerometer_instant():
    return motion.accelerometer()
Example #35
0
mqtt_client = mqtt.Client("DRYOT")
mqtt_client.connect(mqtt_broker_addr)

try:
    while True:
        start_time = time.time()
        #
        # First, collect samples from the accelerometer
        #  This works well for my dryer, but you might need to change this
        #  if yours is smoother. I have tried it all the way up to 100 samples
        #  per second with no real performance issues. But samples pretty much
        #  work for my dryer. 
        #
        motion_detected = 0
        for x in range (0,samples_per_sec):
           accel_z = motion.accelerometer().z
           # print ('Z = ', accel_z)
           readings.append(accel_z)
           readings = readings[-4:]
           z = sum(readings) / len(readings)
           if last_z > 0 and abs(z-last_z) > sensor_threshold:
               motion_detected = 1
           last_z = z
           # Make sure this delay matches the number of samples per second
           time.sleep(loop_delay)

        #
        # Get light and temperature data
        # 
        light_level = light.light()
        temp = weather.temperature()
Example #36
0
#!/usr/bin/env python

from envirophat import light, motion, weather, analog, leds
import time

while True:
    print("LEDs on...")
    leds.on()
    time.sleep(1)
    print("LEDs off...")
    leds.off()
    print("Light...")
    print(light.rgb())
    print("Motion...")
    print(motion.heading())
    print(motion.magnetometer())
    print(motion.accelerometer())
    print("Weather...")
    print(weather.temperature())
    print(weather.pressure())
    print("Analog...")
    print(analog.values())
    time.sleep(1)
Example #37
0
import time
from colorsys import hsv_to_rgb
import math

offset = 0
direction = 0
t = []
t_start = 0

total_time = 1000

def millis():
    return int(round(time.time() * 1000))

while True:
    x, y, z = motion.accelerometer()
    print(y)

    if y < -1.9 and not direction == -1:
        direction = -1
        t.append(millis() - t_start)
        t_start = millis()
        t = t[-5:]

    if y > 1.9 and not direction == 1:
        direction = 1
        t.append(millis() - t_start)
        t_start = millis()
        t = t[-5:] 

    if len(t) > 0: