Beispiel #1
0
 def on_motion(self, z, z_delta):
     print("Motion detected: [last_z:{}] [z:{}] [z_delta:{}]".format(
         self.last_z, z, z_delta))
     leds.on()
     self.play(self.song())
     print("Done playing")
     leds.off()
Beispiel #2
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()
Beispiel #3
0
def main(args=None):
    args = parse_arguments()

    leds.off()
    print('Envirophat MQTT starting up')

    try:
        client = mqtt.Client(client_id=args.mqtt_clientid)
        client.connect(host=args.mqtt_host, port=args.mqtt_port)
    except Exception as e:
        print("Failed to start MQTT client, abort: {0}".format(str(e)))
        return 1

    client.loop_start()

    while (True):
        data = gather_env_data(args)
        # print(f"lux = {data['lux']}")
        # print(f"temp = {data['temperature']}")
        # print(f"pres = {data['pressure']}")
        for key in data.keys():
            try:
                client.publish(f"{args.mqtt_topic}/{key}", f"{data[key]}")
            except Exception as e:
                print("Unable to publish topic, aborting. {0}".format(str(e)))
                return 1
Beispiel #4
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()
    def on_message(self, unused_client, unused_userdata, message):
        """Callback when the device receives a message on a subscription."""
        payload = message.payload
        print('Received message \'{}\' on topic \'{}\' with Qos {}'.format(
            payload, message.topic, str(message.qos)))
        # The device will receive its latest config when it subscribes to the
        # config topic. If there is no configuration for the device, the device
        # will receive a config with an empty payload.
        if not payload:
            print("No payload")
            return
        # The config is passed in the payload of the message. In this example,
        # the server sends a serialized JSON string.
        try:
            data = json.loads(payload.decode('utf-8'))
        except Exception as e:
            print("Exception caught: " + str(e))
        if data['led_on'] != self.led_on:
            # If changing the state of the led, print a message and
            # update the internal state.
            self.led_on = data['led_on']
            if self.led_on:
                print('Led turned on.')
                leds.on()

            else:
                print('Led turned off.')
                leds.off()
Beispiel #6
0
def on_message(client, userdata, message):
    logging.debug(message.topic + " : " + message.payload.decode('UTF-8'))
    if message.topic == hass_autogen_topic + "/switch/" + cid + "/leds/command":
        if mqtt_bool(message.payload):
            leds.on()
        elif not mqtt_bool(message.payload):
            leds.off()
        else:
            logging.warning("Message recieved but no match " +
                            mqtt_bool(message.payload))
    elif message.topic == hass_autogen_topic + "/switch/" + cid + "/phatrelay/command":
        if mqtt_bool(message.payload):
            automationhat.relay.one.on()
        elif not mqtt_bool(message.payload):
            automationhat.relay.one.off()
    elif message.topic == hass_autogen_topic + "/switch/" + cid + "/phatoutput0/command":
        if mqtt_bool(message.payload):
            automationhat.output.one.on()
        elif not mqtt_bool(message.payload):
            automationhat.output.one.off()
    elif message.topic == hass_autogen_topic + "/switch/" + cid + "/phatoutput1/command":
        if mqtt_bool(message.payload):
            automationhat.output.two.on()
        elif not mqtt_bool(message.payload):
            automationhat.output.two.off()
    elif message.topic == hass_autogen_topic + "/switch/" + cid + "/phatoutput2/command":
        if mqtt_bool(message.payload):
            automationhat.output.three.on()
        elif not mqtt_bool(message.payload):
            automationhat.output.three.off()
    else:
        logging.warning("Message recieved but no match")
def iothub_client_sample_run():
    id = 0  

    iot.initialise(callback)

    while True:
        try:
            leds.on()

            openWeather.getWeather()
            humidity = 50

            ## normalise light to something of 100%
            lightLevel = light.light();
            if lightLevel > 1024:
                lightLevel = 1024            
            lightLevel = lightLevel * 100 / 1024

            id += 1

            msg_txt_formatted = msg_txt % (sensorLocation, humidity, round(weather.pressure()/100,2),  round(weather.temperature(),2), lightLevel, id)
            
            iot.publish(msg_txt_formatted, id)

            leds.off()
            time.sleep(4)

        except IoTHubError as e:
            print("Unexpected error %s from IoTHub" % e)
            print_last_message_time(iot.iotHubClient)
            time.sleep(4)
        
        except KeyboardInterrupt:
            print("IoTHubClient sample stopped")
            return
Beispiel #8
0
def get_leds():
    """leds."""
    global leds
    state = request.args["state"]
    if state == "on":
        leds.on()
    else:
        leds.off()
    return jsonify({"success": True})
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))
    if msg.topic == ch and msg.payload == "query-temp":
        leds.on()
        temp = weather.temperature()
        res = {"temp": temp}
        client.publish(ch, json.dumps(res))
        sleep(0.3)
        leds.off()
Beispiel #10
0
def send(data):
    global counter
    global connect_type
    leds.on()
    counter = counter + 1
    if connect_type == "WS":
        sendWS(data)
    else:
        sendREST(data)
    leds.off()
def color_sensing(accurate = True):
    if(accurate):
        leds.on()
        time.sleep(0.5)
    color = light.rgb()
    time.sleep(0.5)
    if(accurate):
        leds.off()

    return color
Beispiel #12
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()
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
Beispiel #14
0
def process_led_req(message):

   led_message_list = message.split(',')
   if led_message_list[3] == 'CMD=LED_ON':
      leds.on()
      message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=LED,LED=ON,SENSOR_REP_END"
   else:
      leds.off()
      message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=LED,LED=OFF,SENSOR_REP_END"

   #  Send reply back to client
   return message
Beispiel #15
0
def perform_update():
    """Update weather data and write entries to file(s).
    """
    global currtime
    currtime = datetime.now().strftime('%H:%M:%S')
    lux = light.light()
    leds.on()
    get_condition()
    get_temps()
    write_file()
    # write_json()
    # send_message()
    out.flush()
    leds.off()
Beispiel #16
0
def perform_update():
    """Update weather data and write entries to file(s).
    """
    global currtime
    currtime = datetime.now().strftime('%H:%M:%S')
    lux = light.light()
    leds.on()
    get_condition()
    get_temps()
    write_file()
    # write_json()
    send_message()
    out.flush()
    leds.off()
Beispiel #17
0
def main():
    logger.info("Starting")
    try:
        while True:
            leds.on()
            logger.debug("Getting data...")
            data = _get_data()
            write(json.dumps(data) + '\n')
            #sys.stdout.write(json.dumps(data) + '\n')
            leds.off()
            logger.debug("Waiting %s seconds" % SLEEP_SECONDS)
            time.sleep(SLEEP_SECONDS)
    except KeyboardInterrupt:
        logger.warning("KeyboardInterrupt")
        pass
    logger.info("Finished.")
Beispiel #18
0
    def __new__(cls):
        """
      Create a singleton instance of the DinoEnvirophat class. 
      """
        if (DinoEnvirophat.__instance is None):
            DinoEnvirophat.__instance = object.__new__(cls)
            DinoEnvirophat.__data = [None] * ENV_HAT_SIZE

            # Turns LEDs on the board off so that they do not
            # interfere with the experiment.
            try:
                leds.off()
            except:
                DinoLog.logMsg(
                    "ERROR - Envirophat fail to turn off on-board led.")
        return DinoEnvirophat.__instance
Beispiel #19
0
    def measure(self):
        leds.on()

        self.openWeather.getWeather()
        self.id += 1
        humidity = 50

        ## normalise light to something of 100%
        lightLevel = light.light();
        if lightLevel > 1024:
            lightLevel = 1024            
        lightLevel = lightLevel * 100 / 1024        

        json = self.msg_txt % (self.sensorLocation, humidity, round(weather.pressure()/100,2),  round(weather.temperature(),2), lightLevel, self.id)
        
        leds.off()
        return json
Beispiel #20
0
def main():
    leds.on()

    cputemp = get_cpu_temperature()
    envtemp = weather.temperature()
    caltemp = envtemp - ((cputemp - envtemp) / 1.3)

    envdate = datetime.datetime.utcnow().strftime('%c')

    json = {
        "hostname": socket.gethostname(),
        "envdate": envdate,
        "light": light.light(),
        "temp": round((caltemp * 1.8 + 32), 2),
        "pressure": round(weather.pressure(), 2)
    }

    leds.off()
    print(json)
Beispiel #21
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
Beispiel #22
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()
def iothub_client_sample_run():
    global id

    iotHubClient = iothub_client_init()

    while True:
        try:

            leds.on()

            ## normalise light to something of 100%
            lightLevel = light.light()
            if lightLevel > 1024:
                lightLevel = 1024
            lightLevel = lightLevel * 100 / 1024

            id += 1

            msg_txt_formatted = msg_txt % (round(
                weather.pressure() / 100,
                2), lightLevel, round(weather.temperature(), 2), id)

            message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))

            iotHubClient.send_event_async(message, send_confirmation_callback,
                                          id)

            leds.off()
            time.sleep(1)

        except IoTHubError as e:
            print("Unexpected error %s from IoTHub" % e)
            print_last_message_time(iotHubClient)
            time.sleep(10)

        except KeyboardInterrupt:
            print("IoTHubClient sample stopped")
            return
Beispiel #24
0
def main():
    try:
        while True:
            logger.debug('Performing all updates.')
            perform_update()

            schedule.run_pending()

            time.sleep(300)

    except APICallError:
        logger.error('Problem calling OWM API.', exc_info=True)
        print("Error calling OWM API.")
        bot.sendMessage(user_id, "Tempi Script has crashed.")
        requests.post(slack_webhook,
                      json={'text': ':bug: Uhoh, something has gone wrong.'})
        time.sleep(300)
        main()
        pass

    except socket.error as serr:
        logger.error('Socket Error from OWM API.', exc_info=True)
        if serr.errno == 104:
            print("Error retrieving data from OWM Socket.")
            time.sleep(300)
            pass
        else:
            raise serr

    except KeyboardInterrupt:
        logger.info('User terminated application.')
        leds.off()
        out.close()
        # json_file.close()

    except:
        logger.error('Something has broken.', exc_info=True)
Beispiel #25
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
Beispiel #26
0
def publish():
    id = 0

    while True:
        try:
            leds.on()

            openWeather.getWeather()

            humidity = 50

            ## normalise light to something of 100%
            lightLevel = light.light()
            if lightLevel > 1024:
                lightLevel = 1024
            lightLevel = lightLevel * 100 / 1024

            id += 1

            msg_txt_formatted = msg_txt % (
                sensorLocation, humidity, round(weather.pressure() / 100, 2),
                round(weather.temperature(), 2), lightLevel, id)

            client.publish(hubTopicPublish, msg_txt_formatted)

            leds.off()

            time.sleep(4)

        except KeyboardInterrupt:
            print("IoTHubClient sample stopped")
            return

        except:
            print("Unexpected error")
            time.sleep(4)
Beispiel #27
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
Beispiel #28
0
def flash_leds(message):
    for count in range(4):
        leds.on()
        sleep(0.5)
        leds.off()
        sleep(0.5)
Beispiel #29
0
def blink(times):
    for i in range(times):
        leds.on()
        time.sleep(0.05)
        leds.off()
        time.sleep(0.05)
Beispiel #30
0
def strobe():
    time.sleep(0.1)
    leds.on()
    time.sleep(0.1)
    leds.off()
Beispiel #31
0
def leds_off():
    leds.off()
    return redirect('/')
Beispiel #32
0
 def ledOff(self):
     self.ledStatus = False
     leds.off()