def soil_reading():
    #read moisture level through capacitive touch pad
    ss = Seesaw(i2c_bus, addr=0x36)
    touch = ss.moisture_read()
    time.sleep(1)
    touch2 = ss.moisture_read()
    difference = touch - touch2

    #check sensor for daily errors
    if (difference > 3 or difference < -3):
        print("moisture warning", difference)

    

    #read temperature from  the temperature from the temperature sensor
    temp = ss.get_temp()
    time.sleep(1)
    temp2 = ss.get_temp()
    temp_difference = temp - temp2

    #check sensor for daily errors
    if (temp_difference > 3 or temp_difference < -3):
        print("tempurature warning", temp_difference)
    
    print("temp: ",temp, " moisture: ",touch)
    time.sleep(1)
Example #2
0
class SoilSensor:
    # initialize needed values for communication
    def __init__(self):
        self.i2c_bus = busio.I2C(SCL, SDA)
        # Need to put the address into the sensor constructor for each
        self.ss = Seesaw(self.i2c_bus, addr=0x36)

    # get the soil moisture from the sensor
    def get_moisture(self):
        #i2c_bus = busio.I2C(SCL, SDA)
        # Need to put the address into the sensor constructor for each
        #ss = Seesaw(i2c_bus, addr=0x36)
        # read moisture level through capacitive touch pad
        moisture = self.ss.moisture_read()
        print("Soil Moisture Reading:", moisture)
        return moisture

    # get the soil temperature from the sensor
    def get_temperature(self):
        #i2c_bus = busio.I2C(SCL, SDA)
        # Need to put the address into the sensor constructor for each
        #ss = Seesaw(i2c_bus, addr=0x36)
        # read temperature from the temperature sensor
        temp = self.ss.get_temp()
        print("Soil Temperatured Reading:", temp)
        return temp
Example #3
0
class InputModule(AbstractInput):
    """ A sensor support class that measures soil moisture using adafruit's i2c soil sensor """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev, testing=testing, name=__name__)

        self.sensor = None

        if not testing:
            self.initialize_input()

    def initialize_input(self):
        from adafruit_seesaw.seesaw import Seesaw
        from adafruit_extended_bus import ExtendedI2C

        try:
            self.sensor = Seesaw(
                ExtendedI2C(self.input_dev.i2c_bus),
                addr=int(str(self.input_dev.i2c_location), 16))
        except:
            self.logger.exception("Setting up sensor")

    def get_measurement(self):
        if not self.sensor:
            self.logger.error("Input not set up")
            return

        self.return_dict = copy.deepcopy(measurements_dict)

        if self.is_enabled(0):
            self.value_set(0, self.sensor.moisture_read())

        if self.is_enabled(1):
            self.value_set(1, self.sensor.get_temp())

        return self.return_dict
Example #4
0
def reading():
    # Soil Moisture Sensor Readings
    i2c_bus = busio.I2C(SCL, SDA)
    ss = Seesaw(i2c_bus, addr=0x36)
    # read moisture level through capacitive touch pad
    touch = ss.moisture_read()
    return touch
def soil(name): #Thread 4
    i2c_bus = busio.I2C(board.SCL, board.SDA)
    ss = Seesaw(i2c_bus, addr=0x36)
    countStemma = 0
    while True:
        # read moisture level through capacitive touch pad
        touch = ss.moisture_read()
        if touch is not None:
            satPercent = 200*(touch-200)/1800
            try:
                logging.info("Thread %s: Logging soil info into MariaDB",name)
                cur.execute("INSERT INTO soil_moisture (moisture,taken_at) VALUES (?,?)", (satPercent,datetime.datetime.now()))
                conn.commit()
            except mariadb.Error as e:
                print(f"Error: {e}")
                dataStorageFail("Soil Moisture Sensor")
        else:
            print("Stemma Data could not be collected")
            countStemma += 1
            #Didn't collect value
        if satPercent >= 60:
            #drip off
            GPIO.output(12,False)
        elif satPercent <= 40:
            #drip on
            GPIO.output(12,True)
            dataPasser.action[0] += 1
        else:
            continue
            #no change drip
        if countStemma >= 5:
            noData("Stemma Soil Moisture Sensor")
        time.sleep(30)
 def get_moisture(self):
     i2c_bus = busio.I2C(SCL, SDA)
     # Need to put the address into the sensor constructor for each
     ss = Seesaw(i2c_bus, addr=0x36)
     # read moisture level through capacitive touch pad
     moisture = ss.moisture_read()
     print("Soil Moisture Reading:", moisture)
     return moisture
Example #7
0
def get_soil():
    try:
        i2c_bus = busio.I2C(SCL, SDA)
        ss = Seesaw(i2c_bus, addr=0x36)
        # read moisture level through capacitive touch pad
        touch = ss.moisture_read()
        # read temperature from the temperature sensor
        temp = ss.get_temp()
        print("Soil moisture: {0}".format(touch))
        return touch
    except Exception as e:
        return 0
Example #8
0
class SeesawSoilSensor(drivers.Sensor):

    i2c_address = 54  # 0x36
    moisture_metric = 'soil-moisture'
    t9e_metric = 'soil-temp'

    def setup(self):
        i2c_bus = busio.I2C(SCL, SDA)
        self.ss = Seesaw(i2c_bus, addr=int(self.i2c_address))

    def read(self):
        # read moisture level through capacitive touch pad
        moisture = self.ss.moisture_read()
        metrics.create_metric_log(self.moisture_metric, moisture)

        # read temperature from the temperature sensor
        t9e = self.ss.get_temp()
        metrics.create_metric_log(self.t9e_metric, t9e)
Example #9
0
class InputModule(AbstractInput):
    """A sensor support class that measures soil moisture using adafruit's i2c soil sensor."""
    def __init__(self, input_dev, testing=False):
        super().__init__(input_dev, testing=testing, name=__name__)

        self.sensor = None

        if not testing:
            self.try_initialize()

    def initialize(self):
        from adafruit_seesaw.seesaw import Seesaw
        from adafruit_extended_bus import ExtendedI2C

        try:
            self.sensor = Seesaw(ExtendedI2C(self.input_dev.i2c_bus),
                                 addr=int(str(self.input_dev.i2c_location),
                                          16))
        except:
            self.logger.exception("Setting up sensor")

    def get_measurement(self):
        if not self.sensor:
            self.logger.error(
                "Error 101: Device not set up. See https://kizniche.github.io/Mycodo/Error-Codes#error-101 for more info."
            )
            return

        self.return_dict = copy.deepcopy(measurements_dict)

        if self.is_enabled(0):
            self.value_set(0, self.sensor.moisture_read())

        if self.is_enabled(1):
            self.value_set(1, self.sensor.get_temp())

        return self.return_dict
Example #10
0
ss = Seesaw(i2c_bus, addr=0x36)

# Create an instance of the Azure IoT Central device
device = IoTCentralDevice(socket, esp, secrets["id_scope"],
                          secrets["device_id"], secrets["key"])

# Connect to Azure IoT Central
device.connect()

# Hide the splash screen and show the telemetry values
gfx.show_text()

while True:
    try:
        # read moisture level
        moisture_level = ss.moisture_read()
        # read temperature
        temperature = ss.get_temp()
        # display soil sensor values on pyportal
        gfx.display_moisture(moisture_level)
        gfx.display_temp(temperature)

        print('Sending data to Azure')
        gfx.display_azure_status('Sending data...')

        # send the temperature and moisture level to Azure
        message = {"Temperature": temperature, "MoistureLevel": moisture_level}
        device.send_telemetry(json.dumps(message))
        device.loop()

        gfx.display_azure_status('Data sent!')
Example #11
0
# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

# Create a device shadow handler, use this to update and delete shadow document
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
    args.thingName, True)

# Delete current shadow JSON doc
deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

# Read data from moisture sensor and update shadow
while True:

    # read moisture level through capacitive touch pad
    moistureLevel = ss.moisture_read()

    # read temperature from the temperature sensor
    temp = ss.get_temp()

    #Timestamp
    dateTimeObj = datetime.now()

    # Display moisture and temp readings
    print("Moisture Level: {}".format(moistureLevel))
    print("Temperature: {}".format(temp))

    # Create message payload
    payload = {
        "state": {
            "reported": {
class RaspberryPi(IotDevice):
    """ Class to interface with Raspberry Pi for
        an Automated Irrigation System. This Raspberry Pi
        setup actuates a solenoid valve that is collecting
        a variety of sensor data (Moisture, Flow,
        Humidity, Temperature).

    Args:
        gpio_relay: Integer. Indicates GPIO pin on Raspberry Pi
            for relay to actuate solenoid valve or an LED for testing.
        gpio_flow: Integer. Indicates GPIO pin on Raspberry Pi for flow sensor.
        ip_address: Optional. A string. Indicates IP Address of Raspberry Pi.
            By default None. If provided, then use PiGPIOFactory package
            for remote GPIO control.
        use_dht_11: Optional. A boolean. When set to True a DHT11 will be used
            instead of the DHT22.  By default False.
        moisture: Optional. A String. "I2C" or "SIM" (for simulated device).
            By default "I2C".

    Attributes:
        dht_sensor: DHT22 sensor to measure humidity and temperature. connected
            to pin 18 for now.
        moisture_sensor: connected to pin 3 and pin 2 for now
    """
    def __init__(self,
                 gpio_relay,
                 gpio_flow,
                 ip_address=None,
                 humid_temp="DHT22",
                 moisture="I2C"):
        IotDevice.__init__(self)

        if gpio_relay == "SIM":
            self.gpio_relay = None
        else:
            if ip_address is not None:
                self.gpio_relay = LED(gpio_relay,
                                      PiGPIOFactory(host=ip_address))
            else:
                self.gpio_relay = LED(gpio_relay)

        # For now we want to leave the DHT sensor (measures temperature and humidity)
        # connected to pin 18.
        if humid_temp == "BME280":
            i2c = board.I2C()
            self.ht_sensor = Bme280(i2c)
            self.ht_sensor.set_sea_level_pressure(1022.2)
        elif humid_temp == "DHT11":
            self.ht_sensor = adafruit_dht.DHT11(board.D18)
        elif humid_temp == "DHT22":
            self.ht_sensor = adafruit_dht.DHT22(board.D18)
        else:
            self.ht_sensor = None

        # For now we want to leave SCL to pin 3 and SDA to pin 2 for i2c interface.
        # meaning moisture sensor will need to be connected to these pins
        if moisture == "SIM":
            self.moisture_sensor = None
        else:
            self.moisture_sensor = Seesaw(busio.I2C(board.D3, board.D2),
                                          addr=0x36)

        if gpio_flow == "SIM":
            self.gpio_flow = None
        else:
            self.gpio_flow = FrequencySignal(gpio_flow)

    def get_humidity_and_temperature(self):
        """ Function to retrieve humidity and temperature data and then update model. """
        temperature_f, humidity = None, None

        while humidity is None and temperature_f is None:
            try:
                temperature_c = self.ht_sensor.temperature
                temperature_f = temperature_c * (9 / 5) + 32
                humidity = self.ht_sensor.humidity
            except RuntimeError as err:
                # DHT's are hard to read, keep going
                sleep(2.0)
                continue
            except Exception as e:
                print(
                    'Encountered error while trying to retrieve humidity and temeperature data: {0}'
                    .format(e))
                return (None, None)

        # update model
        self.set_humidity_and_temperature(humidity, temperature_f)
        return super().get_humidity_and_temperature()

    def get_moisture(self):
        """ Function to retrieve moisture data and then update model """
        try:
            moist_val = self.moisture_sensor.moisture_read()
            moist_val -= 300
            moist_val *= 0.014
            if moist_val < 0:
                moist_val = 0
            if moist_val > 10:
                moist_val = 10
            # upate model
            self.set_moisture(moist_val)
        except Exception as e:
            print(
                'Encountered error while trying to retrieve moisture data: {0}'
                .format(e))
        return super().get_moisture()

    def get_flow(self):
        """ Funtion to retrieve flow data and then update model """

        try:
            # For our device you get 3.1Hz for each Liter/minute of water
            rate = 3.1  # Adjust this based on testing your device.
            self.set_flow(self.gpio_flow.measure_frequency() / rate)
        except Exception as e:
            print('Encountered error while trying to retrieve flow data: {0}'.
                  format(e))
        return super().get_flow()

    def turn_valve_on(self):
        """ Function to turn relay/LED on. """

        try:
            self.gpio_relay.on()
        except Exception as e:
            print(
                'Encountered error while trying to turn relay on: {0}'.format(
                    e))
        # update model
        super().turn_valve_on()

    def turn_valve_off(self):
        """ Function to turn relay/LED off. """

        try:
            self.gpio_relay.off()
        except Exception as e:
            print(
                'Encountered error while trying to turn relay off: {0}'.format(
                    e))
        # update model
        super().turn_valve_off()
Example #13
0
class GardenShelf():

    def __init__(self, config, i2c):
        self._name = config.get('Name', '')
        self._dht = adafruit_dht.DHT22(int(config.get('DhtPin', 0)))
        self._light_pin = int(config.get('LightPin', 0))
        self._water_pin = int(config.get('WaterPin', 0))
        if config.getboolean('UseSS'):
            self._useSS = True
            self._soil_sensor = Seesaw(i2c, addr=int(config.get('SSAddr', 0x0), 16))
            self._soil_min = int(config.get('SSMin', 0))
            self._soil_max = int(config.get('SSMax', 0))
        else:
            self._useSS = False
        self._light_on = False
        self._water_on = False
        self._turn_light_on = int(config.get('LightOn', 0))
        self._turn_light_off = int(config.get('LightOff', 0))
        self._water_on_pct = int(config.get('MoistureOnPct',25))
        self._water_off_pct = int(config.get('MoistureOffPct', 75))
        self._water_on_time = datetime.strptime(config.get('WaterOnTime', '00:00'), '%H:%M').time()
        self._water_off_time = datetime.strptime(config.get('WaterOffTime', '00:00'), '%H:%M').time()
        self._prefix = config.get('Prefix', '')

        GPIO.setup(self._light_pin, GPIO.OUT, initial=GPIO.HIGH)
        GPIO.setup(self._water_pin, GPIO.OUT, initial=GPIO.HIGH)

        self.temperature = 0.0
        self.humidity = 0.0
        self.soil_temp = 0.0
        self.moisture = 0
        self.prev_temperature = 0.0
        self.prev_humidity = 0.0
        self.prev_moisture = 0.0
        self.prev_soil_temp = 0
        self.water = 0
        self.light = 0


    def _set_grow_light(self, status):
        """
        flips the light status
        """
        # control the device (always set, regardless of logging or not)
        if (status):
            GPIO.output(self._light_pin, GPIO.LOW) 
        else:
            GPIO.output(self._light_pin, GPIO.HIGH) 

        # log the info but guard with flag so we don't go overboard
        if (status and not self._light_on):
            logging.info("Turning grow light on")
            self._light_on = True
        elif (not status and self._light_on):
            logging.info("Turning grow light off")
            self._light_on = False


    def _set_water_pump(self, status):
        """
        flips the water pump
        """
        # control the device (always set, regardless of logging or not)
        if (status):
            GPIO.output(self._water_pin, GPIO.LOW) 
        else:
            GPIO.output(self._water_pin, GPIO.HIGH) 

        # log the info but guard with flag so we don't go overboard
        if (status and not self._water_on):
            logging.info("Turning water pump on")
            self._water_on = True
        elif (not status and self._water_on):
            logging.info("Turning water pump off")
            self._water_on = False


    def scale_moisture(self, current):
        return utils.scale_to_percent(current, self._soil_min, self._soil_max)


    def major_loop(self, now):
        # TODO: read the water flow sensor
        # TODO: should probably indicate if there was a sensor read error

        try:
            self.temperature = self._dht.temperature
            self.humidity = self._dht.humidity
        except:
            logging.error("Unable to read temp/humidity sensor")
            self.temperature = self.prev_temperature
            self.humidity = self.prev_humidity

        try:
            if self._useSS:
                self.moisture = self._soil_sensor.moisture_read()
                self.soil_temp = self._soil_sensor.get_temp()
            else:
                self.moisture = 0
                self.soil_temp = 0
        except:
            logging.error("Unable to read soil moisture sensor")
            self.mosisture = self.prev_moisture
            self.soil_temp = self.prev_soil_temp

        # control the grow light
        if (now.hour >= self._turn_light_on) and (now.hour < self._turn_light_off):
            self._set_grow_light(True)
            self.light = 1
        else:
            self._set_grow_light(False)
            self.light = 0

        # control the water pump
        # NOTE: We would like to maybe do this based on the moisture reading, but that
        # seems to be a bit inconsistent. For now, we will use a simple daily timer
        if (now.time() >= self._water_on_time) and (now.time() < self._water_off_time):
            self._set_water_pump(True)
            self.water = 1
        else:
            self._set_water_pump(False)
            self.water = 0

        # if self._scale_moisture(self.mosisture) < self._water_on_pct:
        #     self._set_water_pump(True)
        #     self.water = 1
        # elif self._scale_moisture(touch) > self._water_off_pct:
        #     self._set_water_pump(False)
        #     self.water = 0
        # else:
        #     self.water = 1 if self._water_on else 0

        # store values for next loop
        self.prev_temperature = self.temperature
        self.prev_humidity = self.humidity
        self.prev_moisture = self.moisture
        self.prev_soil_temp = self.soil_temp


    def get_state(self):
        """
        returns the current state of the shelf (and sensors)
        based on the last main loop
        """
        state = {
            self._prefix + 'temp': self.temperature,
            self._prefix + 'humidity': self.humidity,
            self._prefix + 'soiltemp': self.soil_temp,
            self._prefix + 'moisture': self.moisture,
            self._prefix + 'water': self.water,
            self._prefix + 'light': self.light
        }

        return state
Example #14
0
    def soil_moisture(self):
        soil_sensor = busio.I2C(board.SCL, board.SDA)

        seesaw = Seesaw(soil_sensor, addr=0x36)

        return seesaw.moisture_read()
Example #15
0
    print('Subscribed with {}'.format(str(subscribe_result['qos'])))

    refresh_interval = 10
    time_fetch_interval = 12 * 60  # Approx. minutes to refetch sunrise/sunset

    while True:
        # Initialize Astral time
        city = LocationInfo(args.city, args.region, args.timezone, args.lat,
                            args.long)
        s = sun(observer=city.observer, tzinfo=args.timezone)
        sunrise = s['sunrise']
        sunset = s['sunset']
        tz = sunrise.tzinfo
        for i in range(time_fetch_interval):
            temperature = soil.get_temp()
            capacitance = soil.moisture_read()
            print('Temp: ' + str(temperature) + ' Capacitance: ' +
                  str(capacitance))

            print('Publishing to topic garden/sensorData...')
            mqtt_connection.publish(topic='garden/sensorData',
                                    payload=json.dumps({
                                        'temperature':
                                        temperature,
                                        'capacitance':
                                        capacitance
                                    }),
                                    qos=mqtt.QoS.AT_LEAST_ONCE)

            if sunrise < datetime.now(tz=tz) < sunset:
                set_lightStatus(True)
Example #16
0
                       user=db_user,
                       password=user_password,
                       host='localhost')
cur = con.cursor()

i2c_bus = busio.I2C(SCL, SDA)

ss = Seesaw(i2c_bus, addr=0x36)

# read moisture level several times and take average to limit measure error
measurements = 0
max_moisture = 0
min_moisture = 2000

for i in range(15):
    moisture_measurement = ss.moisture_read()
    measurements = measurements + moisture_measurement

    if moisture_measurement > max_moisture:
        max_moisture = moisture_measurement

    if moisture_measurement < min_moisture:
        min_moisture = moisture_measurement

avg_moisture = round((measurements / 15))

# read temperature from the temperature sensor
temp = round(ss.get_temp(), 1)

# Operate pump
#if avg_moisture < 1200:
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe
io.on_message = message

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
plant_feed = "plant"

START = 0

while True:
    # read moisture level through capacitive touch pad
    touch = seesaw.moisture_read()

    # read temperature from the temperature sensor
    temp = seesaw.get_temp()

    if touch < MIN:
        if not LOW:
            io.publish(plant_feed, touch)
            print("published")
        LOW = True

    elif touch >= MIN and time.time() - START > 10:
        io.publish(plant_feed, touch)
        print("published to Adafruit IO")
        START = time.time()
        LOW = False
Example #18
0
import board
from adafruit_seesaw.seesaw import Seesaw
from busio import I2C

# Create library object using our Bus I2C port
i2c = I2C(board.SCL, board.SDA)
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, address=0x76, debug=False)
ss1 = Seesaw(i2c, addr=0x36)
ss2 = Seesaw(i2c, addr=0x37)
ss3 = Seesaw(i2c, addr=0x38)

# change this to match the location's pressure (hPa) at sea level
bme680.sea_level_pressure = 1014

while True:
    print("\nTemperature: %0.1f C" % bme680.temperature)
    print("Gas: %d ohm" % bme680.gas)
    print("Humidity: %0.1f %%" % bme680.humidity)
    print("Pressure: %0.3f hPa" % bme680.pressure)
    print("Altitude = %0.2f meters" % bme680.altitude)
    touch = ss1.moisture_read()
    temp = ss1.get_temp()
    print("1:   temp: " + str(temp) + "  moisture: " + str(touch))
    touch = ss2.moisture_read()
    temp = ss2.get_temp()
    print("2:   temp: " + str(temp) + "  moisture: " + str(touch))
    touch = ss3.moisture_read()
    temp = ss3.get_temp()
    print("3:   temp: " + str(temp) + "  moisture: " + str(touch))
    time.sleep(1)
def NeoPixelPattern():
    pixel.fill(BLUE)
    time.sleep(SHORTBLINK)
    pixel.fill(NAVY)
    time.sleep(LONGBLINK)
    pixel.fill(BLUE)
    time.sleep(SHORTBLINK)


while True:
    # When not connected via BLERadio
    ble.start_advertising(advertisement)
    while not ble.connected:
        Stemp = ss.get_temp(
        )  # read soil temperature from the temperature sensor
        Smoist = ss.moisture_read(
        )  # read soil moisture level through capacitive touch pad

        # share data via serial
        print(("temp: " + str(Stemp) + "  moisture: " + str(Smoist)))
        time.sleep(1)
    ble.stop_advertising()

    # When connected via BLERadio
    while ble.connected:
        Stemp = ss.get_temp(
        )  # read soil temperature from the temperature sensor
        Smoist = ss.moisture_read(
        )  # read soil moisture level through capacitive touch pad

        # share data via serial, and BLERadio (UART & Plotter)
        x = Stemp
Example #20
0
MOIST_HIGH = 60
LIGHT_TIME_LOW = 4
LIGHT_TIME_HIGH = 8
LUX_HIGH = 20000
LUX_LOW = 400

temp_list = []
moist_list = []
lux_list = []
light_time = 0
night_time = 0
while True:

    print("received data in ", int(time.time() - initTime), "seconds")
    initTime = time.time()
    moisture = ss.moisture_read(
    )  # read moisture level through capacitive touch pad
    temp = ss.get_temp()  # read temperature from the temperature sensor
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    lux = lightsensor.lux

    moisture = (100 * moisture / 1023)

    print("temp = ", temp)
    print("humidity = ", humidity)
    print("light = ", lux)
    print("moisture = ", moisture)

    temp_list.append(temp)
    moist_list.append(moisture)
    lux_list.append(lux)
Example #21
0
import time

from board import SCL, SDA
import busio

from adafruit_seesaw.seesaw import Seesaw

i2c_bus = busio.I2C(SCL, SDA)

ss = Seesaw(i2c_bus, addr=0x36)

while True:
    # read moisture level through capacitive touch pad
    touch = ss.moisture_read()

    # read temperature from the temperature sensor
    temp = ss.get_temp()

    print("temp: " + str(temp) + "  moisture: " + str(touch))
    time.sleep(1)
Example #22
0
def getFullStatus():

    # read all pumps
    GPIO.setmode(GPIO.BCM)
    pumpStatus = {}
    for pump in Pump.objects.all():
        zonePin = ZONE_PINS[pump.zoneNumberOnHAT - 1]
        GPIO.setup(zonePin, GPIO.OUT)
        pumpStatus[pump.id] = GPIO.input(zonePin)

    # read all sensors
    sensorReadings = {}
    for sensor in SoilSensor.objects.all():
        currentMoisture = "N/A"

        try:
            soilSensor = Seesaw(i2c_bus, addr=int(sensor.i2cAddr,
                                                  16))  # convert "0x36" to int
            currentMoisture = soilSensor.moisture_read()
        except ValueError:
            currentMoisture = "** error **"

        sensorReadings[sensor.id] = currentMoisture

    # tie it all together in a plant-focused dict
    data = {}

    for plant in Plant.objects.all():
        pump = plant.pump
        sensor = plant.sensor

        latestLogs = WateringLog.objects.all() \
         .filter(plant_id = plant.id) \
         .values("logDateTime", "durationSeconds") \
         .order_by("-logDateTime")[:1]

        row = {
            "id": plant.id,
            "name": str(plant),
            "imageUrl": "",
            "waterSeconds": 10,
            "moisture": "",
            "pump": "",
            "zone": "",
            "isRunning": False,
            "latestLog": None,
            "lastWatered": None,
            "nextWater": None
        }

        if (pump is not None):
            row["pump"] = str(pump)
            row["zone"] = pump.zoneNumberOnHAT
            row["isRunning"] = pumpStatus[pump.id]

        if (sensor is not None):
            row["moisture"] = sensorReadings[sensor.id]

        if (plant.image):
            row["imageUrl"] = plant.image.url

        if (len(latestLogs) > 0):
            latestLog = latestLogs[0]
            row["latestLog"] = latestLog
            row["lastWatered"] = latestLog["logDateTime"]
            row["nextWater"] = latestLog["logDateTime"] + timedelta(
                days=plant.waterFrequencyDays)

        data[plant.id] = row

    GPIO.cleanup()

    return data
Example #23
0
import time, requests
from board import SCL, SDA
import busio
from adafruit_seesaw.seesaw import Seesaw 
ss = Seesaw(busio.I2C(SCL, SDA), addr=0x36)

heroku = "" #Enter your heroku app URL here
while True:
    requests.post(heroku, data={"temp": ss.get_temp(), "moisture": ss.moisture_read()})
    time.sleep(1)
Example #24
0
aws_iot.on_publish = publish
aws_iot.on_message = message

print('Attempting to connect to %s' % client.broker)
aws_iot.connect()

# Time in seconds since power on
initial = time.monotonic()

while True:
    try:
        gfx.show_aws_status('Listening for msgs...')
        now = time.monotonic()
        if now - initial > (SENSOR_DELAY * 60):
            # read moisture level
            moisture = ss.moisture_read()
            print("Moisture Level: ", moisture)
            # read temperature
            temperature = ss.get_temp()
            # Display Soil Sensor values on pyportal
            temperature = gfx.show_temp(temperature)
            gfx.show_water_level(moisture)
            print('Sending data to AWS IoT...')
            gfx.show_aws_status('Publishing data...')
            # Create a json-formatted device payload
            payload = {
                "state": {
                    "reported": {
                        "moisture": str(moisture),
                        "temp": str(temperature)
                    }
Example #25
0

def cf(ctemp):
    if f: return int((ctemp * 9 / 5) + 32)
    else: return float("{:.1f}".format(ctemp))


def pformat(raw):
    if p: return int(((raw - mmin) * 100) / (mmax - mmin))
    else: return float("{:.2f}".format((raw - mmin) / (mmax - mmin)))


print("Loading averages!")
for i in range(n):
    atemp.append(ss.get_temp())
    awet.append(ss.moisture_read())
    time.sleep(.1)

while True:
    now = dt.utcnow()

    atemp.append(ss.get_temp())
    tmean = s.mean(atemp)
    tsd = s.stdev(atemp, xbar=tmean)
    #print(tsd,' | ',cf(tmean),' | ',atemp)
    atemp.pop(0)
    btemp.append(cf(tmean))
    if len(btemp) > 3: btemp.pop(0)
    #print(btemp)
    if len(btemp) > 1 and len(btemp) == len(set(btemp)): temp = btemp[1]
    else: temp = s.mode(btemp)
Example #26
0
#This is the tutorial testing for the soil sensor
#Just wired all my sensors and tested them individually
#Tomorrow I wire them all on the same board if I can and run it on a cron command
# to start dumping data into a database with SQLite-
#I will have photos posted on how I wired each sensor up to the bread board
import time

from board import SCL, SDA
import busio
from adafruit_seesaw.seesaw import Seesaw

i2c_bus =busio.I2C(SCL, SDA)
ss = Seesaw(i2c_bus, addr=0x36)

while True:

    #read moisture level through capacitive touch pad
    
    touch = ss.moisture_read()

    #read temperature from  the temperature from the temperature sensor
    temp = ss.get_temp()

    print("temp: " + str(temp) + " moisture: " + str(touch))
    time.sleep(1)
Example #27
0
#!/usr/bin/env python3

from board import SCL, SDA
import busio

from adafruit_seesaw.seesaw import Seesaw

i2c_bus = busio.I2C(SCL, SDA)

ss = Seesaw(i2c_bus, addr=0x36)
print(ss.moisture_read())
print(ss.get_temp())