示例#1
0
 def analog_read(self, mode="analog"):
     try:
         if mode is 'analog':
             data = grovepi.analogRead(self.pin)
             if data > 1023:
                 return None
             return data
         elif mode == 'dht':
             temp, hum = grovepi.dht(self.pin, 0)
             return temp, hum
         elif mode == 'ultrasonic':
             distance = grovepi.ultrasonicRead(self.pin)
             return distance
     except IOError:
         return None
示例#2
0
import time
from datetime import datetime
from grovepi import grovepi

while True:
    # define pin number for sensors here
    dht = 4
    light_sensor = 1
    sound_sensor = 0
    moist_sensor = 2

    temp = grovepi.dht(dht, 0)[0]
    humidity = grovepi.dht(dht, 0)[1]
    lightlvl = grovepi.analogRead(light_sensor)
    soundlvl = grovepi.analogRead(sound_sensor)
    moistlvl = grovepi.analogRead(moist_sensor)

    # timestamp is UTC, and UTC time shall be used across
    myData = {
        "d": {
            'temp': temp,
            'humidity': humidity,
            'lightlvl': lightlvl,
            'soundlvl': soundlvl,
            'moistlvl': moistlvl
        },
        "ts": datetime.utcnow().isoformat() + "Z"
    }
    print(myData)
    time.sleep(1)
# Set the time between sensor reads
SECONDS_BETWEEN_READS = 1
# ---------------------------------


def isFloat(string):
    try:
        float(string)
        return True
    except ValueError:
        return False


while True:
    try:
        airSensorVal = grovepi.analogRead(AIR_SENSOR_PIN)

        if isFloat(airSensorVal):
            if airSensorVal > 700:
                print "High pollution"
            elif airSensorVal > 300:
                print "Low pollution"
            else:
                print "Air fresh"

            print "Air Quality = ", airSensorVal

    except IOError:
        print "Error"

    time.sleep(SECONDS_BETWEEN_READS)
        grovepi.digitalWrite(led, 0)


# create a gateway service instance
# the parameters are: app name, deviot address, mq server address, deviot account
app = Gateway("grovepi_test", "www.ciscodeviot.com",
              "mqtt.ciscodeviot.com:1883", "")

# register input sensors
# the parameters are: sensor kind, sensor id, sensor display name
app.register("light", "grovelight", "GroveLight")

# register output sensors
# the parameters are: sensor kind, sensor id, sensor display name, action call back function
app.register_action("led", "groveled", "GroveLed", trigger_grove_led)

# run service
app.run()

while True:
    try:
        # get sensor value
        sensor_value = grovepi.analogRead(light_sensor)

        # update the sensor value, the parameters are: sensor id, new sensor value
        app.set_value("grovelight", sensor_value)
        time.sleep(.5)

    except IOError:
        print("Error")
示例#5
0
def main():
    conditions = get_conditions()
    astronomy = get_astronomy()
    if ('current_observation' not in conditions) or ('moon_phase'
                                                     not in astronomy):
        print "Error! Wunderground API call failed, check your STATE and CITY and make sure your Wunderground API key is valid!"
        if 'error' in conditions['response']:
            print "Error Type: " + conditions['response']['error']['type']
            print "Error Description: " + conditions['response']['error'][
                'description']
        exit()
    else:
        streamer = Streamer(bucket_name=BUCKET_NAME,
                            bucket_key=BUCKET_KEY,
                            access_key=ACCESS_KEY)
        streamer.log(
            ":house: Location",
            conditions['current_observation']['display_location']['full'])
    while True:
        # -------------- GrovePi Zero --------------
        # Read the sensors
        try:
            [temp_c, hum] = grovepi.dht(DHT_SENSOR_PIN, DHT_SENSOR_TYPE)
            airSensorVal = grovepi.analogRead(AIR_SENSOR_PIN)

            if isFloat(temp_c):
                if (METRIC_UNITS):
                    streamer.log(
                        ":sunny: " + SENSOR_LOCATION_NAME + " Temperature(C)",
                        temp_c)
                else:
                    temp_f = temp_c * 9.0 / 5.0 + 32.0
                    temp_f = float("{0:.2f}".format(temp_f))
                    streamer.log(
                        ":sunny: " + SENSOR_LOCATION_NAME + " Temperature(F)",
                        temp_f)
            if ((isFloat(hum)) and (hum >= 0)):
                streamer.log(
                    ":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)",
                    hum)

            if isFloat(airSensorVal):
                if airSensorVal > 700:
                    streamer.log(SENSOR_LOCATION_NAME + " Air Quality",
                                 ":fog: :bangbang:")
                elif airSensorVal > 300:
                    streamer.log(SENSOR_LOCATION_NAME + " Air Quality",
                                 ":foggy: :exclamation:")
                else:
                    streamer.log(SENSOR_LOCATION_NAME + " Air Quality",
                                 ":rainbow:")
                streamer.log(SENSOR_LOCATION_NAME + " Air Quality Sensor",
                             airSensorVal)
        except IOError:
            print("Error")

        # -------------- Wunderground --------------
        conditions = get_conditions()
        astronomy = get_astronomy()
        if ('current_observation' not in conditions) or ('moon_phase'
                                                         not in astronomy):
            print "Error! Wunderground API call failed. Skipping a reading then continuing ..."
        else:
            humidity_pct = conditions['current_observation'][
                'relative_humidity']
            humidity = humidity_pct.replace("%", "")

            # Stream valid conditions to Initial State
            streamer.log(":cloud: " + CITY + " Weather Conditions",
                         weather_status_icon(conditions, astronomy))
            streamer.log(":crescent_moon: Moon Phase",
                         moon_icon(astronomy['moon_phase']['phaseofMoon']))
            streamer.log(":dash: " + CITY + " Wind Direction",
                         wind_dir_icon(conditions, astronomy))
            if (METRIC_UNITS):
                if isFloat(conditions['current_observation']['temp_c']):
                    streamer.log(CITY + " Temperature(C)",
                                 conditions['current_observation']['temp_c'])
                if isFloat(conditions['current_observation']['dewpoint_c']):
                    streamer.log(
                        CITY + " Dewpoint(C)",
                        conditions['current_observation']['dewpoint_c'])
                if isFloat(conditions['current_observation']['wind_kph']):
                    streamer.log(":dash: " + CITY + " Wind Speed(KPH)",
                                 conditions['current_observation']['wind_kph'])
                if isFloat(conditions['current_observation']['wind_gust_kph']):
                    streamer.log(
                        ":dash: " + CITY + " Wind Gust(KPH)",
                        conditions['current_observation']['wind_gust_kph'])
                if isFloat(conditions['current_observation']['pressure_mb']):
                    streamer.log(
                        CITY + " Pressure(mb)",
                        conditions['current_observation']['pressure_mb'])
                if isFloat(conditions['current_observation']
                           ['precip_1hr_metric']):
                    streamer.log(
                        ":umbrella: " + CITY + " Precip 1 Hour(mm)",
                        conditions['current_observation']['precip_1hr_metric'])
                if isFloat(conditions['current_observation']
                           ['precip_today_metric']):
                    streamer.log(
                        ":umbrella: " + CITY + " Precip Today(mm)",
                        conditions['current_observation']
                        ['precip_today_metric'])
            else:
                if isFloat(conditions['current_observation']['temp_f']):
                    streamer.log(CITY + " Temperature(F)",
                                 conditions['current_observation']['temp_f'])
                if isFloat(conditions['current_observation']['dewpoint_f']):
                    streamer.log(
                        CITY + " Dewpoint(F)",
                        conditions['current_observation']['dewpoint_f'])
                if isFloat(conditions['current_observation']['wind_mph']):
                    streamer.log(":dash: " + CITY + " Wind Speed(MPH)",
                                 conditions['current_observation']['wind_mph'])
                if isFloat(conditions['current_observation']['wind_gust_mph']):
                    streamer.log(
                        ":dash: " + CITY + " Wind Gust(MPH)",
                        conditions['current_observation']['wind_gust_mph'])
                if isFloat(conditions['current_observation']['pressure_in']):
                    streamer.log(
                        CITY + " Pressure(IN)",
                        conditions['current_observation']['pressure_in'])
                if isFloat(conditions['current_observation']['precip_1hr_in']):
                    streamer.log(
                        ":umbrella: " + CITY + " Precip 1 Hour(IN)",
                        conditions['current_observation']['precip_1hr_in'])
                if isFloat(
                        conditions['current_observation']['precip_today_in']):
                    streamer.log(
                        ":umbrella: " + CITY + " Precip Today(IN)",
                        conditions['current_observation']['precip_today_in'])
            if isFloat(conditions['current_observation']['solarradiation']):
                streamer.log(
                    ":sunny: " + CITY + " Solar Radiation (watt/m^2)",
                    conditions['current_observation']['solarradiation'])
            if isFloat(humidity):
                streamer.log(":droplet: " + CITY + " Humidity(%)", humidity)
            if isFloat(conditions['current_observation']['UV']):
                streamer.log(":sunny: " + CITY + " UV Index:",
                             conditions['current_observation']['UV'])
            streamer.flush()
        time.sleep(60 * MINUTES_BETWEEN_READS)
示例#6
0
 def read(self):
     return grovepi.analogRead(self.pin)
示例#7
0
import time
from datetime import datetime
from grovepi import grovepi

while True:
	# define pin number for sensors here
	dht = 4
	light_sensor = 1
	sound_sensor = 0
	moist_sensor = 2

	temp = grovepi.dht(dht,0)[0]
	humidity = grovepi.dht(dht,0)[1]
	lightlvl = grovepi.analogRead(light_sensor)
	soundlvl = grovepi.analogRead(sound_sensor)
	moistlvl = grovepi.analogRead(moist_sensor)


	# timestamp is UTC, and UTC time shall be used across
	myData={"d": {'temp':temp, 'humidity':humidity, 'lightlvl':lightlvl, 'soundlvl':soundlvl, 'moistlvl':moistlvl}, "ts": datetime.utcnow().isoformat()+"Z"}
	print(myData)
	time.sleep(1)


# def myCommandCallback(cmd):
#   print("Command received: %s" % cmd.data)
#   if cmd.command == "TurnOn":
#     grovepi.digitalWrite(2,1)
#     print("LED is now turned ON")
#   elif cmd.command == "TurnOff":
#     grovepi.digitalWrite(2,0)
    else:
        grovepi.digitalWrite(led, 0)


# create a gateway service instance
# the parameters are: app name, deviot address, mq server address, deviot account
app = Gateway("grovepi_test", "www.ciscodeviot.com", "mqtt.ciscodeviot.com:1883", "")

# register input sensors
# the parameters are: sensor kind, sensor id, sensor display name
app.register("light", "grovelight", "GroveLight")

# register output sensors
# the parameters are: sensor kind, sensor id, sensor display name, action call back function
app.register_action("led", "groveled", "GroveLed", trigger_grove_led)

# run service
app.run()
    
while True:
    try:
        # get sensor value
        sensor_value = grovepi.analogRead(light_sensor)

        # update the sensor value, the parameters are: sensor id, new sensor value
        app.set_value("grovelight", sensor_value)
        time.sleep(.5)

    except IOError:
        print ("Error")
示例#9
0
initialized = False
data_available = False
time.sleep(1)


while True:

        #init
        if not initialized:
                setRGB(0, 50, 0)
                setText("Getting data..")
                initialized = True

    #Try to read the sensor measurements
    try:
            light_intensity = grovepi.analogRead(light_sensor)
        [temp, hum] = grovepi.dht(dht_sensor_port, dht_sensor_type)
                sound_level = grovepi.analogRead(sound_sensor)
        wind_dir_raw = grovepi.analogRead(rotary_sensor)
                switch = grovepi.digitalRead(button)
                distance = grovepi.ultrasonicRead(ultrasonic_ranger)

        if wind_dir_raw == 0:
            wind_direction = 0
        else:
            wind_direction = wind_dir_raw * (360 / 1024.0)

                wind_direction = float("{0:.1f}".format(wind_direction))

                #Save locally
                sensor_values[0] = light_intensity