예제 #1
0
def gather_telemetry(bar: BMP085, accel: mpu6050):
    """
    Gather data from the satellite's systems
    :return: string of telemetry data
    """
    accel_data = accel.get_accel_data()
    gyro_data = accel.get_gyro_data()
    temp = bar.read_temperature()
    pressure = bar.read_pressure()
    alt = bar.read_altitude()
    accel_x = accel_data["x"]
    accel_y = accel_data["y"]
    accel_z = accel_data["z"]
    gyro_x = gyro_data["x"]
    gyro_y = gyro_data["y"]
    gyro_z = gyro_data["z"]
    payload_signal = GPIO.input(payload_in_pin)
    t = datetime.datetime.now().timestamp()
    data = "{},{},{},{},{},{},{},{},{},{},{}".format(t, temp, pressure, alt,
                                                     accel_x, accel_y, accel_z,
                                                     gyro_x, gyro_y, gyro_z,
                                                     payload_signal)
    data += "\n"

    return data
예제 #2
0
 def run(self):
     try:
         sensor = BMP085.BMP085(busnum=1, mode=BMP085.BMP085_ULTRAHIGHRES)
     except OSError as e:
         print(e)
         solved = False
         while not solved:
             self.error.emit()
             try:
                 sensor = BMP085.BMP085(busnum=1,
                                        mode=BMP085.BMP085_ULTRAHIGHRES)
                 solved = True
             except OSError as f:
                 print(f)
             time.sleep(0.1)
     while True:
         try:
             self.new_data.emit(
                 [sensor.read_pressure(),
                  sensor.read_temperature()])
         except OSError as e:
             print(e)
             solved = False
             while not solved:
                 self.error.emit()
                 try:
                     sensor = BMP085.BMP085(busnum=1,
                                            mode=BMP085.BMP085_ULTRAHIGHRES)
                     solved = True
                 except OSError as f:
                     print(f)
                 time.sleep(0.1)
예제 #3
0
 def Server_Update(self):
     self.humidity, self.temperature = Adafruit_DHT.read_retry(
         Adafruit_DHT.DHT22, self.temperature_humidity_sensor_pin)
     GPIO.setmode(GPIO.BCM)
     GPIO.setup(self.rain_sensor_pin, GPIO.IN)
     self.rain = GPIO.input(self.rain_sensor_pin)
     sensor = BMP085.BMP085()
     sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
     self.pressure = sensor.read_pressure()
    def getEnvironmentalConditions(self):

        pm = [None, None, None, None]
        pressure = None
        humidity = None
        temperature = None
        dew_point = None

        try:
            aqi_sensor = pmsA003(AQI_SENS_DEV_ADDRESS)
            pm = aqi_sensor.read_data()
        except:
            print('pms7003 sensor error')
        try:
            bus = smbus.SMBus(1)
            try:
                bus.read_byte(0x77)
                baro_sensor = BMP085.BMP085()
                baro_sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
                pressure = baro_sensor.read_pressure() / 100
            except:
                print('BMP sensor error')
        except:
            print('BMP085 wrong bus')

        try:
            humidity, temperature = Adafruit_DHT.read_retry(
                Adafruit_DHT.AM2302, 4)
        except:
            print('DHT sensor error')

        if humidity is not None and temperature is not None and pressure is not None and pm[
                1] is not None and pm[2] is not None and pm[3] is not None:
            if humidity >= 0.0 and humidity <= 100.0 and temperature > -40.0 and temperature < 80.0:
                temperature = temperature - 1.0  #account for sensor and rpi self heating by approx 1C TODO: this needs to be improved by reduction for detector work
                dew_point = self.calculateDewPoint(humidity, temperature)
                return [
                    pressure, humidity, temperature, dew_point, pm[1], pm[2],
                    pm[3], '0', self.lat, self.lon, self.alt
                ]
            else:
                return [
                    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '0', self.lat, self.lon,
                    self.alt
                ]
        else:
            return [
                0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '0', self.lat, self.lon,
                self.alt
            ]
예제 #5
0
    def __init__(self, altitude, sensor_id):
        logging.info(MODULE_NAME + ": constructor start")
        self.altitude = altitude
        # intialize the sensor in read mode standard
        self.sensor = BMP085.BMP085()

        # You can also optionally change the BMP085 mode to one of BMP085_ULTRALOWPOWER,
        # BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES.  See the BMP085
        # datasheet for more details on the meanings of each mode (accuracy and power
        # consumption are primarily the differences).  The default mode is STANDARD.
        sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)

        self.sensor_id = sensor_id
        logging.info(MODULE_NAME + ": constructor exit")
예제 #6
0
    def _init_station(self):
        """
        Attempts to initialize this AirStation object.

        This method is used to initialize the various fields and sensors of an AirStation object.
        If the object cannot be initialized then this method returns False, otherwise it returns
        True.

        :return: True if the AirStation could be initialized. False otherwise.
        """
        self._id = utils.get_mac('eth0')
        self._bmp = BMP085.BMP085()
        self._gpsp = utils.GpsPoller()
        self._gpsp.start()  # start polling the GPS sensor
        self._gps = gps.gps("localhost", "2947")
        self._gps.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)

        # Wait a few seconds to ensure a GPS fix
        time.sleep(10)
        (self._lon, self._lat) = self.get_location()
 
        # Open a connection with the PMS3003 sensor
        self._pm = serial.Serial(port="/dev/ttyO1", baudrate=9600, rtscts=True, dsrdtr=True)
        self._pm.close()
        self._pm.open()
        
        return True
예제 #7
0
    def read_pressure(self):
        sensor = BMP085.BMP085()

        pressure = sensor.read_pressure()
        pressure = float(pressure) / 100

        return pressure
예제 #8
0
    def __init__(self):
        self.hoehe = 166  # Hoehe Seyring
        self.lastTemp = -99.0
        self.actTemp = -99.0
        self.minTemp = 99.9
        self.maxTemp = -99.9
        self.lastPress = 0.0
        self.actPress = 0.0
        self.minPress = 2000
        self.maxPress = 0.0
        self.rrdFile = "/home/robert/jrWetterstation/db/jrWetter.rrd"

        self.myLogger = getLogger('jrWetterstationLogger')
        self.myLogger.debug('KY053 constructor started')

        retrytime = 1  # sec
        while True:
            try:
                # Sensor wird initialisiert
                self.myLogger.debug('BMP085 initialisieren')
                self.BMPSensor = BMP085.BMP085()
                self.myLogger.debug('KY-053 sensor successful created')
                break
            except IOError:
                self.myLogger.debug(
                    'KY-053 sensor not detected. Check wiring. Try again in: ' + str(retrytime) + ' seconds')
                print("KY-053 Sensor nicht erkannt!")
                print("Ueberpruefen Sie die Verbindungen")
                print("Naechste Versuch in: " + str(retrytime) + " Sekunden")
                sleep(retrytime)
                retrytime *= 3

        self.myLogger.debug('KY053 constructor ended')
예제 #9
0
def get_bmp180_data():
    try:
        # i2c on channel 77 (pin 2 data,pin 3 clock)
        # "sudo i2cdetect -y 1" - to check channel
        bmp = BMP085.BMP085()
        status = "Ok"
        temp = bmp.read_temperature()
        pressure = bmp.read_pressure()
        altitude = bmp.read_altitude()
    except Exception as er:
        status = str(er)
        temp = 0
        pressure = 0
        altitude = 0
    return {
        'status': status,
        'temperature': {
            'value': "%.2f" % temp,
            'unit': 'C'
        },
        'pressure': {
            'value': "%.2f" % (pressure / 100.0),
            'unit': 'hPa'
        },
        'altidude': {
            'value': "%.2f" % altitude,
            'unit': 'm'
        }
    }
예제 #10
0
def main():
    seconds = 0
    loop = 0
    interval = 1
    pressure_sensor = BMP085.BMP085()
    running = True
    print "%d \t %d" % (seconds, loop)
    time.sleep(1)
    seconds += 1
    if seconds == 20:
        loop1()
        time.sleep(20)
    if seconds == 20:
        loop1()
        time.sleep(20)
    if seconds == 20:
        loop1()
        time.sleep(20)
    if loop == 3:
        loop2()
        print "start"
    if seconds == 20:
        loop1()
        time.sleep(20)
    if seconds == 20:
        loop1()
        time.sleep(20)
    if seconds == 20:
        loop1()
        time.sleep(20)
    print "end"
예제 #11
0
def main():
    """Sensor program, running in infinite loop"""
    sensor = BMP085.BMP085()
    com = communicateWithServer()
    com.getUserPsw()
    date = str(datetime.datetime.now().date()) + ".txt"
    open(date, 'w+').close()

    while True:
        payload = {}
        payload['temp'] = sensor.read_temperature()
        payload['pressure'] = sensor.read_pressure()
        payload['altitude'] = sensor.read_altitude()
        payload['sealevel_pressure'] = sensor.read_sealevel_pressure()
        payload["username"] = com.deviceName
        payload["password"] = com.devicePsw
        payload["time"] = str(datetime.datetime.now())
        print payload

        try:
            com.putReadingToServer(payload)

        except Exception as error:
            print "The call putReadingToServer failed with an exception.", str(
                error)
            if str(datetime.datetime.now().date()) + ".txt" != date:
                open(str(datetime.datetime.now().date()) + ".txt", 'a').close()
            out_file = open(date, "a")
            out_file.write(str(payload))
            out_file.close()

        time.sleep(com.REFRESH_RATE)
예제 #12
0
def measure():
    sensor = BMP085.BMP085()
    return {
        'temperature': sensor.read_temperature(),
        'pressure': sensor.read_pressure(),
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
예제 #13
0
파일: BMP180.py 프로젝트: InRong/Glance
        def __init__(self, main_app_log):
                if main_app_log is None:

                        self.log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')

                        self.logFile = 'logs/BMP180.log'

                        self.my_handler = RotatingFileHandler(self.logFile, mode='a', maxBytes=5*1024*1024, backupCount=1, encoding=None, delay=0)
                        self.my_handler.setFormatter(self.log_formatter)
                        self.my_handler.setLevel(logging.INFO)

                        self.app_log = logging.getLogger('root')
                        self.app_log.setLevel(logging.INFO)

                        self.app_log.addHandler(self.my_handler)

                else:
                        self.app_log = main_app_log

                self._sensor = BMP085.BMP085()
                self._temperature = ""
                self._pressure = ""
                self._altitude = ""

                self._db = DB.DB()
                self._db.load_settings()

                self.start_mos()
                self.process_loop()
예제 #14
0
 def getTemperature(self):
     if self._sensorType == const._sens_dht22 and self._sensor_function_temp == "1":
         humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, self._sensor_pin)
         return temperature
     elif self._sensorType == const._sens_bmp085 and self._sensor_function_temp == "1":
         self.bmp = BMP085.BMP085()
         return self.bmp.read_temperature()
예제 #15
0
파일: quiz1.py 프로젝트: imprld01/IoT-Lab11
def readAlt():
    # Altitude
    #==================================================================
    sensor = BMP085.BMP085()
    alti = sensor.read_altitude()

    return alti
예제 #16
0
파일: sensors.py 프로젝트: nottix/iotly
    def fetchBmp085(self, name):
        # Default constructor will pick a default I2C bus.
        #
        # For the Raspberry Pi this means you should hook up to the only exposed I2C bus
        # from the main GPIO header and the library will figure out the bus number based
        # on the Pi's revision.
        #
        # For the Beaglebone Black the library will assume bus 1 by default, which is
        # exposed with SCL = P9_19 and SDA = P9_20.
        sensor = BMP085.BMP085()

        temperature = '{0:0.2f}'.format(sensor.read_temperature())
        pressure = '{0:0.2f}'.format(sensor.read_pressure())
        altitude = '{0:0.2f}'.format(sensor.read_altitude())
        sealevelPressure = '{0:0.2f}'.format(sensor.read_sealevel_pressure())

        log.info('BMP: Temp = {0:0.2f} *C'.format(sensor.read_temperature()))
        log.info('BMP: Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()))
        log.info('BMP: Altitude = {0:0.2f} m'.format(sensor.read_altitude()))
        log.info('BMP: Sealevel Pressure = {0:0.2f} Pa'.format(
            sensor.read_sealevel_pressure()))

        data = {}
        data['temperature'] = temperature
        data['pressure'] = pressure
        data['altitude'] = altitude
        data['sealevel_pressure'] = sealevelPressure

        self.client.publish(
            self.config['domain'] + "/" + self.config['name'] + "/sensors/" +
            name, json.dumps(data), 0, True)
예제 #17
0
def report(arg):
    prepared_data = {
        'description': 'windows dummy endpoint',
        'temperature': '15C',
        'operations': ['report']
    }

    if sys.platform.startswith("linux"):
        import Adafruit_BMP.BMP085 as BMP085
        import Adafruit_DHT
        sensor_a = BMP085.BMP085()
        sensor_b = Adafruit_DHT.DHT22
        pin = 17
        humidity, temperature = Adafruit_DHT.read_retry(sensor_b, pin)
        prepared_data = {
            'description': 'Raspberry Pi, west-side balcony',
            'operations': ['report'],
            'temp_worse': str(round(sensor_a.read_temperature(), 1)) + ' degrees centigrade',
            'pressure': str(round(sensor_a.read_pressure() / 100, 0)) + ' hPa',
            'altitude': str(round(sensor_a.read_altitude(), 0)) + ' m',
            'sealevel_pressure': str(round(sensor_a.read_sealevel_pressure(250) / 100, 0)) + ' hPa',
            'temp': str(round(temperature, 1)) + ' degrees centigrade',
            'humidity': str(round(humidity, 1)) + ' %',
        }

    jsond_data = json.dumps(prepared_data)

    return jsond_data
예제 #18
0
def get_sensors():
    sensor = BMP085.BMP085()
    sens_temp = sensor.read_temperature()
    sens_hum = 80
    sens_press = sensor.read_pressure()
    json_data = {'senstype': 'temperature', 'current': sens_temp}
    return jsonify({'sensors': json_data})
예제 #19
0
def bmp180():

    # Default constructor will pick a default I2C bus.
    #
    # For the Raspberry Pi this means you should hook up to the only exposed I2C bus
    # from the main GPIO header and the library will figure out the bus number based
    # on the Pi's revision.
    #
    # For the Beaglebone Black the library will assume bus 1 by default, which is
    # exposed with SCL = P9_19 and SDA = P9_20.
    sensor = BMP085.BMP085()

    # Optionally you can override the bus number:
    #sensor = BMP085.BMP085(busnum=2)

    # You can also optionally change the BMP085 mode to one of BMP085_ULTRALOWPOWER, 
    # BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES.  See the BMP085
    # datasheet for more details on the meanings of each mode (accuracy and power
    # consumption are primarily the differences).  The default mode is STANDARD.
    #sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)

    print ('Temp = {0:0.2f} *C'.format(sensor.read_temperature()))
    print ('Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()))
    print ('Altitude = {0:0.2f} m'.format(sensor.read_altitude()))
    print ('Sealevel Pressure = {0:0.2f} Pa'.format(sensor.read_sealevel_pressure()))
예제 #20
0
    def __init__(self):
        try:
            self.inst = BMP085.BMP085()

        except Exception as e:
            logging.error(f"BMP180 Init Exception({e})"e))
            self.inst = None
    def get_bmp180(self, event):
        sensor = BMP085.BMP085()

        pressure = float(sensor.read_pressure()/100.0)
        syslog.syslog(syslog.LOG_DEBUG, "extrasensors: found pressure value of %s mbar" % pressure)
        # NOTE: stores as mbar
        event.packet['pressure'] = float(pressure)
예제 #22
0
def main():

    switch = light.read_switch()
    title = "DHT temperature and humdidity readings"
    paragraph = [
        "getting ambient temperature and humidity readings from the DHT22"
    ]

    dh, dt1 = dht.read_retry(dht.DHT22, 4)
    dt = (dt1 * 1.8) + 32
    sensor = BMP085.BMP085()
    btemp1 = sensor.read_temperature()
    btemp = (btemp1 * 1.8) + 32
    bpressure = sensor.read_pressure()
    balt = sensor.read_altitude()
    slp = sensor.read_sealevel_pressure()

    return render_template('index.html',
                           switch=switch,
                           btemp=btemp,
                           bpressure=bpressure,
                           balt=balt,
                           slp=slp,
                           dh=dh,
                           dt=dt)
def getTemperature():
	temperature = BMP085.BMP085().read_temperature()
	
	if temperature is not None:
		return temperature
	else:
		print 'Failed to get temperature reading.'
		sys.exit(1)
예제 #24
0
 def __init__(self):
     try:
         self.sensor = BMP085.BMP085()
     except:
         print("BMP180 Connection is Broken..")
         sys.exit(0)
     else:
         print("BMP180 Sensor start")
예제 #25
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev, testing=testing, name=__name__)

        if not testing:
            from Adafruit_BMP import BMP085

            self.i2c_bus = input_dev.i2c_bus
            self.bmp = BMP085.BMP085(busnum=self.i2c_bus)
예제 #26
0
def pressao():
    try:
        sensor = BMP085.BMP085()
        temperatura = sensor.read_temperature()
        pressao = sensor.read_pressure() / 100.0
        return temperatura, pressao
    except:
        return -10, -10
예제 #27
0
 def __init__(self, interval, altitude, dataqueue, logger):
     self.interval = interval
     self.altitude = altitude
     self.dataqueue = dataqueue
     self.logger = logger
     self.logger.info("Connecting to Bosch BMP085/180 sensor on I2C bus...")
     self.sensor = BMP.BMP085(mode = BMP.BMP085_ULTRAHIGHRES)
     self.logger.info("BMP085/180 connected!")
예제 #28
0
def getBaro():
    try:
        sensor = BMP085.BMP085()
        p = int(sensor.read_pressure()/100)
        reply = "Baro : {}".format(p)
    except:
        reply = "Error in getBaro"
    return reply
예제 #29
0
def getRoomTemp():
    try:
        sensor = BMP085.BMP085()
        t = int(sensor.read_temperature())
        reply = "RoomTemp : {}".format(t)
    except:
        reply = "Error in getRoomTemp"
    return reply
예제 #30
0
    def __init__(self,
                 io_client_conf="/etc/wxchip.cfg",
                 io_client_type="mqtt"):
        # VARIABLES
        self.io_client = None
        self.io_client_conf = io_client_conf
        self.io_client_type = io_client_type
        self.io_key = None
        self.io_user = None
        self.io_update_rate = SLEEPTIME
        self.data = [["wxchip-BMP180-temp", -1], ["wxchip-BMP180-baro", -1],
                     ["wxchip-lux", -1], ["wxchip-windspeed", -1],
                     ["wxchip-AM2315-temp", -1],
                     ["wxchip-AM2315-humidity", -1]]
        self.dead = False
        self.last_pres_avg = 0
        self.pres_trending = "flat"

        # READ OUR CONFIG
        config = ConfigParser.ConfigParser()
        config.read(self.io_client_conf)
        self.io_key = config.get("aio", "key", None)
        self.io_user = config.get("aio", "username", None)
        # OVER-WRITE THE IO CLIENT TYPE WITH THE STUFF FROM THE CONFIG
        self.io_client_type = config.get("aio", "type", self.io_client_type)
        # GET THE UPDATE RATE FROM THE CONFIG
        self.io_update_rate = config.get("aio", "update_rate",
                                         self.io_update_rate)

        # GET THE BUS NUMBERS FOR THE DEVICES
        self.bmp180_bus = config.get("devices", "bmp180_bus", 1)
        self.ads1015_bus = config.get("devices", "ads1015_bus", 1)
        self.am2315_bus = config.get("devices", "am2315_bus", 1)

        if self.io_key == None:
            text = "No AIO Key found in %s" % self.io_client_conf
            raise ValueError(text)

        if self.io_user == None and self.io_client_type == "mqtt":
            text = "No AIO User found in %s" % self.io_client_conf
            raise ValueError(text)

        # NO ERROR CHECKING FOR THE TYPE AND UPDATE RATE AS THEY HAVE DEFAULTS

        # CREATE OUR IO_CLIENT
        if self.io_client_type == "mqtt":
            self.io_client = Adafruit_IO.MQTTClient(self.io_user, self.io_key)
            logging.debug('Setting up AIO callbacks')
            self.io_client.on_connect = io_connected
            self.io_client.on_disconnect = io_disconnected
        elif self.io_client_type == "rest":
            self.io_client = Adafruit_IO.Client(self.io_key)

        # CREATE OUR DEVICE OBJECTS
        logging.debug('Setting up objects')
        self.bmp180 = BMP085.BMP085(busnum=self.bmp180_bus)
        self.ads1015 = Adafruit_ADS1x15.ADS1015(busnum=self.ads1015_bus)