# -*- coding: utf-8 -*- import os import datetime import json import yaml import pycurl from pprint import pprint import Adafruit_BMP.BMP085 as BMP ## cURL python client(pycurl) sample if __name__ == '__main__': cur_dir = os.path.abspath(os.path.dirname(__file__)) os.chdir(cur_dir) sensor = BMP.BMP085() ## you can access BMP180 sensor temp = sensor.read_temperature() print('Temp = {0:0.2f} *C'.format(sensor.read_temperature())) print('Temp = {0:0.2f} *C'.format(sensor.read_raw_temp())) 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())) with open('m2x.yml', 'r') as f: conf = yaml.load(f) api_key = conf['api_key'] url = conf['base_url'] + '/' + conf['stream'][0] + '/value' timestamp = datetime.datetime.now().isoformat() data = {'value': temp} ## required 'value', 'timestamp' keys
windspeed_count += 1 def rainEventHandler(pin): print "handling rain event" global rain_count rain_count += 1 # Main Loop if __name__ == '__main__': # Logger open CSV fp = open('test.csv', 'a') csv = csv.writer(fp, delimiter=',') bmp180Sensor = BMP085.BMP085(busnum=BMP_i2c_busnum) # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) GPIO.setup(mywindspeed, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(myraingauge, GPIO.IN, pull_up_down=GPIO.PUD_UP) # tell the GPIO library to look out for an # event on pin x and deal with it by calling # the buttonEventHandler function GPIO.add_event_detect(mywindspeed, GPIO.FALLING) GPIO.add_event_callback(mywindspeed, windEventHandler)
raw = str(ser.readline(), 'utf-8') line = raw.replace("\r\n", "") app.logger.info("Received: {}".format(line)) data = ast.literal_eval(line) except Exception as e: app.logger.error( 'UNABLE TO GET DATA FROM THE DEVICE SENSOR: {} {}'.format( datetime.now(), e)) data = {'STATUS': 'UNABLE TO GET DATA FROM THE DEVICE SENSOR'} return data values_sensor = BMP085.BMP085() humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 23) if humidity is not None and temperature is not None: reading = TempLog('temperature_sensor1', datetime.now(), 'livingroom', 'AM2302', temperature) reading.save_to_db() readingH = HumidityLog('humidity_sensor1', datetime.now(), 'livingroom', 'AM2302', humidity) readingH.save_to_db() else: print("sensor error") if values_sensor is not None: temp_reading = TempLog('temperature_sensor3', datetime.now(), 'livingroom', 'BMP180', values_sensor.read_temperature())
import gps import time from datetime import datetime import os.path import csv from math import sqrt, pow from Adafruit_BMP import BMP085 import Adafruit_LSM303 as LSM303 # Constants debug = 1 override_log = 1 # Sensor initialization accelSensor = LSM303.LSM303() tempSensor = BMP085.BMP085() # Open a new file to store our info in filename = "LOG00.csv" if not override_log: filename_l = list(filename) for n in range(0, 100): filename_l[3] = str(0 + n / 10) filename_l[4] = str(0 + n % 10) s = "".join(filename_l) if not os.path.exists(s): break filename = "".join(filename_l) logfile = open(filename, "w") if debug: print "Log file created! Log name: ", filename
GPIO.FALLING, callback=calculo_intervalo, bouncetime=20) init_GPIO() # Inicializo pin GPIO init_interrupt() # Inicializo Interrupción # ------------------------------------------------------------------- # CONFIGURACION DE LOS SENSORES #DHT22 -> Temperatura y Humedad relativa #BMP180 -> Presión y Altitud # Configuracion del tipo de sensores sensorDHT22 = Adafruit_DHT.DHT22 sensorBMP180 = BMP085.BMP085() # Configuracion del pin GPIO al cual esta conectado el sensor DHT22 (GPIO 4) pin = 4 #------------------------------------------------------------------- # OBTENCION DE PARÁMETROS # Obtiene la humedad y la temperatura desde el sensor DHT22 # Obtiene la presión y la altitud desde el sensor BMP180 while True: humedad, temperatura = Adafruit_DHT.read_retry(sensorDHT22, pin) altitud = sensorBMP180.read_altitude() presion = sensorBMP180.read_pressure() print 'temp =' + str(temperatura) # Calcular la velocidad del viento [KM/H]
def login_open_sheet(oauth_key_file, spreadsheet): """Connect to Google Docs spreadsheet and return the first worksheet.""" try: credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scopes=['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']) gc = gspread.authorize(credentials) worksheet = gc.open(spreadsheet).sheet1 return worksheet except Exception as ex: print('Unable to login and get spreadsheet. Check OAuth credentials, spreadsheet name, and') print('make sure spreadsheet is shared to the client_email address in the OAuth .json file!') print('Google sheet login failed with error:', ex) sys.exit(1) bmp = BMP085.BMP085() print('Logging sensor measurements to {0} every {1} seconds.'.format(GDOCS_SPREADSHEET_NAME, FREQUENCY_SECONDS)) print('Press Ctrl-C to quit.') worksheet = None while True: # Login if necessary. if worksheet is None: worksheet = login_open_sheet(GDOCS_OAUTH_JSON, GDOCS_SPREADSHEET_NAME) # Attempt to get sensor reading. dat = datetime.datetime.now() temp = bmp.read_temperature() pressure = bmp.read_pressure() altitude = bmp.read_altitude()
import Adafruit_BMP.BMP085 as BMP085 from gpiozero import InputDevice import datetime import csv import time baro_sensor = BMP085.BMP085() rain_sensor = InputDevice(pin=4, pull_up=True) rain_since_last_time = False def logg_data_now(): print("Logging " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) with open("weather_data.csv", 'a') as csv_file: global rain_since_last_time writer = csv.writer(csv_file) rain = 1 if rain_since_last_time else 0 pressure = 0 for i in range(5): pressure += baro_sensor.read_pressure() pressure = pressure / 5 data = [ rain, baro_sensor.read_temperature(), pressure, datetime.datetime.now().strftime("%Y-%m-%d %H:%M") ] writer.writerow(data) rain_since_last_time = False
print("\n\n\n") # Only setup pygame if this is the MASTER if 'yes' == MASTER: import pygame pygame.init() # Only setup for making web requests if this is the MASTER if 'yes' == MASTER: import requests # For the BMP180 sensor, use the Adafruit library import Adafruit_BMP.BMP085 as BMP085 # Imports the BMP library # Create a BMP085 object to poll the BMP180 for indoor temperature data BMP180 = BMP085.BMP085() # Constants WEB_BIND_ADDRESS = '0.0.0.0' WEB_BIND_PORT = 80 if 'yes' == MASTER: # Directory where the web server files will be served from SERVER_DIR = './www/' # Globals done = False temp = None web_server = None if 'yes' == MASTER: my_screen = None
import mysql.connector from mysql.connector import Error import Adafruit_DHT import Adafruit_BMP.BMP085 as BMP085 from datetime import datetime db_host = 'arfo8ynm6olw6vpn.cbetxkdyhwsb.us-east-1.rds.amazonaws.com' db_database = 's0c8nimyeq16ttuu' db_user = '******' db_password = '******' sensor_bmp = BMP085.BMP085() sensor_dht = Adafruit_DHT.DHT22 h, t = Adafruit_DHT.read_retry(sensor_dht, 26) temp = (sensor_bmp.read_temperature() + t)/2 pressure = sensor_bmp.read_pressure() time = datetime.now(tz=None) print('Temp = {0:0.1f}*C Humidity = {1:0.1f}% Pressure = {2:0.2f} Pa'.format(temp,h,pressure)) print(time) try: connection = mysql.connector.connect(host= db_host, database= db_database, user= db_user, password= db_password) cursor = connection.cursor()
def get_temps(): #this function gets temp values from the bmp bmp = BMP.BMP085() tempc = bmp.read_temperature() tempc = round(tempc, 1) tempf = round(tempc * 9 / 5 + 32, 1) return tempc, tempf
def get_pressure(): #this function gets pressure bmp = BMP.BMP085() pres = bmp.read_pressure() presin = round(pres / 3386.39, 2) #(inHg) return presin
apache_indexfile = "/var/www/html/index.html" # binnen- en buitentemperatuur meter import time from w1thermsensor import W1ThermSensor sensor_binnentemp = W1ThermSensor() binnen_temp = 0 binnen_temp_oud = -30 buiten_temp = 0 buiten_temp_oud = -30 # luchtdruk meten import Adafruit_BMP.BMP085 as BMP085 sensor_luchtdruk = BMP085.BMP085() luchtdruk = 0 luchtdruk_oud = 950 # luchtvochtigheid en buitentemperatuur import Adafruit_DHT DHT_PIN = 17 buiten_temp = 0 buiten_temp_oud = -30 luchtvochtigheid = 0 luchtvochtigheid_oud = 0 # windsnelheid km_per_uur = 0 km_per_uur_oud = 0
def UpdateTemps(): global EngineTemp global AmbientTemp global lcdline1 global lcdline2 global lcdline3 global tmp global oldktemp global strip tmp = None i2cLock.acquire() try: tmp = BMP085.BMP085() AmbientTemp = tmp.read_temperature() logTemplineDB("ambient", AmbientTemp) except: tmp = None logging.error("UpdateTemps() Ambient Temp Read Error: ", exc_info=True) finally: i2cLock.release() try: EngineTemp = thermocouple.get() if ( EngineTemp < 200 ): # check to remove unrealistic measurement...which happen frequently due to engine noise. ktempq.append(EngineTemp) qavg = sum(ktempq) / ktempq.__len__() if (abs(EngineTemp - qavg) < 10): logTemplineDB("engine", EngineTemp) #lcdline1 = "E:%4.1fC A:%4.1fC" % (EngineTemp, AmbientTemp) except KeyboardInterrupt: raise except MAX6675Error as e: #EngineTemp = "Error: "+ e.value EngineTemp = -10 logging.error("UpdateTemps() Excepted getting enginetemp: ", exc_info=True) if (ninedof != None): i2cLock.acquire() try: roll = ninedof.roll #lcdline3 = "Roll: %4.1f " % (ninedof.roll) roll = roll + 90 charposition = round(abs(roll / 12)) s = " " if (charposition < 15): lcdline3 = s[:charposition] + 'O' + s[charposition:] except: logging.error("UpdateTemps() ninedof sensor couldn't be read", exc_info=True) finally: i2cLock.release() if (strip != None): colour = IntegertoRGB(EngineTemp - 80) strip.setPixelColorRGB(0, int(colour[0] * 255), int(colour[1] * 255), int(colour[2] * 255)) colour = IntegertoRGB(AmbientTemp - 25) strip.setPixelColorRGB(1, int(colour[0] * 255), int(colour[1] * 255), int(colour[2] * 255)) strip.show()
def execute(self): fContinous = 1 fSingle = 1 fPrint = 1 try: while fContinous: ## Set up devices if self.use_dc1700: dc1700 = dc.dc1700(self.counter_address) if self.use_bmp180: bmp180 = bmp085.BMP085() ## Prepare hd = '# Date | Time | Temperature [C] | Humidity [%]| | Pressure [Bar] | Particles > 0.5 um [m^-3] | Particles > 2.5 um [m^-3] | ISO | Class\n' ## Read measurements date = time.strftime("%Y-%m-%d", time.localtime()) clock = time.strftime("%H:%M:%S", time.localtime()) hum = temp = pres = cnt05 = cnt25 = -1 if self.use_dht22: hum, temp = dht22.read_retry(22, self.hum_meter_pin) if self.use_bmp180: pres = bmp180.read_pressure() if self.use_dc1700: cnt05, cnt25 = dc1700.read_particle_counts() # takes 60s of integration time ## Determine cleanroom class from particle count per cubic inch if (cnt05/0.0002831685 < 35200): iso = 6 clas = 1000 elif (cnt05/0.0002831685 < 352000): iso = 7 clas = 10000 elif (cnt05/0.0002831685 < 3520000): iso = 8 clas = 100000 else: iso = 9 clas = 1000000 line = [date, clock, temp, hum, pres, cnt05, cnt25, iso, clas] ## Print feedback if fPrint: print '{:s} {:s} {:3.1f} {:3.1f} {:d} {:.0f} {:.0f} {:d} {:d}'.format(*line) ## One file per day file_name = time.strftime("%Y_%m_%d", time.localtime()) ## Create log folder if it dpes not already exist if not (os.path.isdir(self.dat_path)): os.makedirs(self.dat_path) ## Create file if it does not already exists if not (os.path.isfile(self.dat_path + '/' + file_name + '.txt')): file = open(self.dat_path + '/' + file_name + '.txt', 'w') file.write(hd) file.close() ## Append file file = open(self.dat_path + '/' + file_name + '.txt', 'a') file.write('{:s} {:s} {:3.1f} {:3.1f} {:d} {:.0f} {:.0f} {:d} {:d}\n'.format(*line)) file.close() if fSingle: fContinous = 0 else: time.sleep(self.wait) ## Break if keyboard interrupt except KeyboardInterrupt: print "Keyboard interrupt." #self.logging.error("Keyboard interrupt.")
phant_url = 'gimp-phant.azurewebsites.net' phant_public_key = 'kgkWV69Nqnupn6W9Xbo6' pressure_samples = [] pressure_sampling_lock = threading.Lock() queue = queue.Queue() uart = gpio.uarts.uart1 uart.open() # We have a quarter-second timeout because if we start reading in # the middle of a serial message or if a byte is dropped for any # reason, we'll throw away the partial message and try again ser = serial.Serial(port="/dev/ttyO1", baudrate=9600, timeout=0.25) pressure_sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES) headers = { "Phant-Private-Key": str(args.key), 'Content-Type': 'application/x-www-form-urlencoded' } def sendData(): while True: body = queue.get() success = False while not success: try: phantServer = http.client.HTTPConnection(phant_url, timeout=10)
def __init__(self): if Temperature.__instance is None: Temperature.__instance = BMP085.BMP085()
bus.write_i2c_block_data(a2d_address, 0x01, [197, 131]) sleep(.01) a0 = bus.read_i2c_block_data(a2d_address, 0x00, 2) bus.write_i2c_block_data(a2d_address, 0x01, [213, 131]) sleep(.01) a1 = bus.read_i2c_block_data(a2d_address, 0x00, 2) bus.write_i2c_block_data(a2d_address, 0x01, [229, 131]) sleep(.01) a2 = bus.read_i2c_block_data(a2d_address, 0x00, 2) bus.write_i2c_block_data(a2d_address, 0x01, [245, 131]) sleep(.01) a3 = bus.read_i2c_block_data(a2d_address, 0x00, 2) import Adafruit_BMP.BMP085 as BMP085 bmp085 = BMP085.BMP085() temperature = bmp085.read_temperature() pressure = bmp085.read_pressure() altitude = bmp085.read_altitude() sealevel_pressure = bmp085.read_sealevel_pressure() out = [ time(), 256 * a0[0] + a0[1], 256 * a1[0] + a1[1], 256 * a2[0] + a2[1], 256 * a3[0] + a3[1], temperature, pressure, altitude, sealevel_pressure ] # echo "a0, a1, a2, a3" > out.csv f = open('out.csv', 'a') f.write(str(out)[1:-1] + "\n") f.close()
for i in frange(1.0, 0.0, -0.1): led.value = i time.sleep(speed) # Try to set-up Scroll pHAT, set flag if not available try: import scrollphat scrollphat.set_brightness(5) scrollphat_connected = True except: scrollphat_connected = False try: import Adafruit_BMP.BMP085 as BMP085 BMP = BMP085.BMP085() bmp_sensor_okay = True except: print("BMP sensor not working") bmp_sensor_okay = False # Try to connect to network and get IP. If not connected, set flag try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("gmail.com", 80)) ip = s.getsockname()[0] s.close() network_connected = True except: ip = "Not connected"
import board import busio i2c = busio.I2C(board.SCL, board.SDA) import time import adafruit_tsl2561 sensor0 = adafruit_tsl2561.TSL2561(i2c) import adafruit_si7021 sensor1 = adafruit_si7021.SI7021(i2c) import Adafruit_BMP.BMP085 as BMP085 sensor2 = BMP085.BMP085() while True: print('Lux: {}'.format(sensor0.lux)) print('Broadband: {}'.format(sensor0.broadband)) print('Infrared: {}'.format(sensor0.infrared)) print('Luminosity: {}'.format(sensor0.luminosity)) #print('Temperature: {} degrees C'.format(sensor1.temperature)) print('Humidity: {}%'.format(sensor1.relative_humidity)) print('Temp = {0:0.2f} *C'.format(sensor2.read_temperature())) print('Pressure = {0:0.2f} Pa'.format(sensor2.read_pressure())) #print ('Altitude = {0:0.2f} m'.format(sensor2.read_altitude())) #print ('Sealevel Pressure = {0:0.2f} Pa'.format(sensor2.read_sealevel_pressure())) GPIO.setwarnings(False)
def get_measurement(self): """ Gets the measurement in units by reading the BMP180/085 """ time.sleep(2) bmp = BMP085.BMP085(busnum=self.I2C_bus_number) return bmp.read_temperature(), bmp.read_pressure(), bmp.read_altitude()
req3.add_header('x-aio-key', aiokey) response3 = urllib2.urlopen(req3) try: device = sh1106(serial, rotate=0) #device = ssd1306(serial, rotate=0) hasOLED = True except: hasOLED = False font1 = make_font("code2000.ttf", 12) sensor = SHT31(address=0x44) sensorBMP = BMP085.BMP085() #print 'Temp = {0:0.3f} deg C'.format(degrees) #print 'Humidity = {0:0.2f} %'.format(humidity) if ccs.available(): temp = ccs.calculateTemperature() if not ccs.readData(): print "Initial CO2: ", ccs.geteCO2(), "ppm, TVOC: ", ccs.getTVOC( ), " temp: ", temp degrees = 0 humidity = 0 co2 = 0 tvoc = 0 while (True):
import time import sys import urllib2 import Adafruit_DHT import Adafruit_BMP.BMP085 as BMP085 sys.path.append('./Adafruit_ADS1x15') import SDL_Pi_Weather_80422 as SDL_Pi_Weather_80422 from tentacle_pi.AM2315 import AM2315 am = AM2315(0x5c, "/dev/i2c-1") import SI1145.SI1145 as SI1145 # PRINT TO FILE #sys.stdout = open('temperature.php', 'w') # BMP180 sensorbmp = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES) # AM2315 temperature, humidity, crc_check = am.sense() Fahrenheit = 9.0 / 5.0 * temperature + 32 # SI1145 # not working? # sensorsi = SI1145.SI1145() # CONVERSIONS ETC inttemperature = sensorbmp.read_temperature() #internal temperature pressure = sensorbmp.read_pressure() #station pressure mb = sensorbmp.read_sealevel_pressure() * 0.01 #sea level pressure mb inhg = sensorbmp.read_sealevel_pressure( ) * 0.000295299830714 #altimeter setting inHg ft = sensorbmp.read_altitude() * 3.280839895 #pressure altitude ft density = ft + (120 * (temperature - 3.16233)) #density altitude ft dewpointC = temperature - (
# print(bmp_address) # print(led_display_address) darksky_secret_key = config["darksky"]["secret-key"] darksky_lat = config["darksky"]["lat"] darksky_lng = config["darksky"]["lng"] # print(darksky_lat, darksky_lng) owm_secret_key = config["owm"]["secret-key"] owm_lat = config["owm"]["lat"] owm_lon = config["owm"]["lon"] nest_client_id = config['timetemp_nest']['client_id'] nest_client_secret = config['timetemp_nest']['client_secret'] nest_access_token_cache_file = 'nest.json' # Create sensor instance with default I2C bus bmp = BMP085.BMP085(mode=BMP085.BMP085_HIGHRES, address=bmp_address) # Initialize a LED display segment = SevenSegment(address=led_display_address) segment.begin() print(segment) if LOGGING: # Read in Phant config file json_keys_file2 = 'phant-config.json' p2 = Phant(jsonPath=json_keys_file2) print('Logging sensor measurements taken every {2} seconds \ to "{0}" every {1} seconds.'.format(p2.title, FREQUENCY_SECONDS, MEASUREMENT_INTERVAL)) # print(p2)
def __init__(self): self.sensor = BMP085.BMP085()
# Can enable debug output by uncommenting: #import logging #logging.basicConfig(level=logging.DEBUG) import Adafruit_BMP.BMP085 as BMP085 # 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()))
def read_pressure_sensor(): sensor = BMP085.BMP085() return int(sensor.read_temperature() * 10), sensor.read_pressure()
os.system('modprobe w1-gpio') # Turns on the GPIO module os.system('modprobe w1-therm') # Turns on the Temperature module # Finds the correct device file that holds the temperature data base_dir = "/sys/bus/w1/devices/" device_folder = glob.glob(base_dir + "28*")[0] device_file = device_folder + "/w1_slave" print(f"base_dir: {base_dir}") print(f"device_folder: {device_folder}") print(f"device_file: {device_file}") ## 2. Initialize DHT11 Humidity sensor on GPIO24 dhtDevice = adafruit_dht.DHT11(board.D24) ## 3. Initialize BBMP180 sensor bmp180_sensor = BMP085.BMP085() ### Sensor read functions def read_temp_raw(device_file): with open(device_file, 'r') as f: return f.readlines() def read_temp_ds18b20(device_file, wait_interval=0.1): """Convert the value of the sensor into temp""" lines = read_temp_raw(device_file) # While the first line does not contain 'YES', wait for 0.2s # and then read the device file again while lines[0].strip()[-3:] != 'YES': time.sleep(wait_interval)
# Create logger and set options logging.getLogger().setLevel(logging.INFO) logging.info("Starting logging") # Create the data server and assigning the request handler logging.info("Starting socket server") try: i2c = busio.I2C(board.SCL, board.SDA) htu21dsensor = HTU21D(i2c) except: logging.info("No htu21dsensor detected, or a fault happened.", exc_info=True) htu21dsensor = None try: bmp085sensor = BMP085.BMP085() except: logging.info("No bmp085 detected, or a fault happened.", exc_info=True) bmp085sensor = None try: tmp102sensor = TMP102('C', 0x48, 1) except: logging.info("No tmp102 detected, or a fault happened.", exc_info=True) tmp102sensor = None if (htu21dsensor == None and bmp085sensor == None and tmp102sensor == None): logging.info("No sensors detected. Quitting.") quit()
conn.send('{0}\n'.format(data["humi"])) elif msg == "LUMI": conn.send('{0}\n'.format(sensor3.lux())) elif msg == "PING": conn.send('{0}\n'.format("PONG")) elif msg == "ALLD": data = sensor2.pollsensordata() dicti = {} dicti['temperature'] = data["temp"] dicti['humidity'] = data["humi"] dicti['pressure'] = sensor.read_pressure() dicti['luminosity'] = sensor3.lux() conn.send(json.dumps(dicti, ensure_ascii=False) + "\n") else: print "received message in conflict with our protocol" except Exception as e: print e.message print "closed connection to:", addr if __name__ == '__main__': sensor = BMP085.BMP085() sensor2 = HDC1008(0x40) sensor3 = TSL2561() soc = socket.socket() soc.bind(("", 1337)) soc.listen(5) # max 5 waiting connections while True: conn, addr = soc.accept() thread.start_new_thread(handler, ())
def __init__(self): import Adafruit_BMP.BMP085 as BMP self.sensor = BMP.BMP085()