예제 #1
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")
예제 #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()
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
예제 #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()
예제 #6
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()
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()
예제 #8
0
def get_leds():
    """leds."""
    global leds
    state = request.args["state"]
    if state == "on":
        leds.on()
    else:
        leds.off()
    return jsonify({"success": True})
예제 #9
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()
예제 #10
0
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
예제 #11
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
예제 #12
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
예제 #13
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()
예제 #14
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()
예제 #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()
예제 #16
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.")
예제 #17
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
예제 #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
예제 #19
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)
예제 #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()
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
예제 #22
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)
예제 #23
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
예제 #24
0
def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    if (body == 'off'):
        leds.off()
    else:
        leds.on()
예제 #25
0
def blink(times):
    for i in range(times):
        leds.on()
        time.sleep(0.05)
        leds.off()
        time.sleep(0.05)
예제 #26
0
def leds_on():
    leds.on()
    return redirect('/')
               tls_version=ssl.PROTOCOL_TLSv1_2,
               ciphers=None)
# Set this to ignore hostname only. TLS is still valid with this setting.
client.tls_insecure_set(True)
client.connect(broker_address, port=port)
client.subscribe(topic)
client.loop_start()

while Connected != True:  #Wait for connection
    print("Connecting...")
    time.sleep(1)

try:
    while True:
        lux = light.light()
        leds.on()  # shows a reading has been taken
        rgb = str(light.rgb())[1:-1].replace(' ', '')
        leds.off()
        acc = str(motion.accelerometer())[1:-1].replace(' ', '')
        heading = motion.heading()
        temp = weather.temperature()
        press = weather.pressure()
        values = {
            "temp": temp,
            "pressure": press,
            "heading": heading,
            "accelerometer": acc,
            "light_level": lux,
            "light_colour": rgb
        }
예제 #28
0
 def ledOn(self):
     self.ledStatus = True
     leds.on()
예제 #29
0
def strobe():
    time.sleep(0.1)
    leds.on()
    time.sleep(0.1)
    leds.off()
예제 #30
0
def flash_leds(message):
    for count in range(4):
        leds.on()
        sleep(0.5)
        leds.off()
        sleep(0.5)
예제 #31
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
예제 #32
0
def setLedOn():
    leds.on()