示例#1
0
文件: terrain.py 项目: rgbkrk/ds18b20
def before_all():
    # mock sensors
    DS18B20.BASE_DIRECTORY = world.MOCKED_SENSORS_DIR

    sensors = []
    sensor_ids = DS18B20.get_available_sensors()
    for sensor_id in sensor_ids:
        sensors.append(DS18B20(sensor_id, load_kernel_modules=False))
    world.sensors = sensors
示例#2
0
def main():
    sensor = DS18B20()

    while True:
        time = datetime.datetime.strftime(datetime.datetime.now(),
                                          '%Y-%m-%d %H:%M:%S')
        temperatures = sensor.get_temperatures(
            [DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN])

        print time
        print("Degrees Celsius: %f" % temperatures[0])
        print("Kelvin: %f" % temperatures[2])
        print("Degrees Fahrenheit: %f" % temperatures[1])
        print("Adding row please wait...")

        x = 0
        try:
            for values in wks.col_values(1):  ## loop count row
                x = x + 1
            rowToAdd = [
                time, temperatures[0], temperatures[2], temperatures[1]
            ]  ## your data want to send
            wks.resize(x)
            wks.append_row(rowToAdd)
            print("Add row done !!!")
            print("==================================")
            sleep(5)
        except:
            print("Exit.")
            print("Bye...")
            break
示例#3
0
class DS18B20:

    def __init__(self, address):
        logging.info('Initialising DS18B20 sensor with address {}'.format(address))
        self._address = address
        self._sensor = Sensor(sensor_id=address)

    def get_temperature(self, mqtt_details):
        """
        Return measured temperature from the sensor.

        :param dict mqtt_details: Relevant details for publishing to the MQTT broker
        :return:
        """
        logging.debug('Measuring temperature')
        temperature = self._sensor.get_temperature()
        logging.info('Broadcasting temperature: {}'.format(temperature))

        temperature_signal = signal('temperature')
        temperature_signal.send(
            self,
            temperature=temperature,
            address=self._address,
            mqtt_topic=mqtt_details['topic']
        )
示例#4
0
def getTemperatureStats(temperaturesensors):
    try:
        for temperaturesensor in temperaturesensors:
            if temperaturesensor['type'] == "temperature":
                avg = 0
                summation = 0
                rowCount = 0
                temperature = 0
                temperaturesensor['temperature'] = float("%.2f" % (
                    DS18B20(str(temperaturesensor['address'])).get_temperature(
                        DS18B20.DEGREES_F) +
                    temperaturesensor['temperaturecorrection']))
            if temperaturesensor['pin']:
                ps = subprocess.Popen(
                    ('gpio', '-g', 'read', str(temperaturesensor['pin'])),
                    stdout=subprocess.PIPE,
                    bufsize=1,
                    universal_newlines=True)
                output = str(ps.communicate())
                output = output.translate(None, "\n',N('on\e) ")
            if output == "1":
                temperaturesensor['pinstatus'] = "Off"
            if output == "0":
                temperaturesensor['pinstatus'] = "On"
        return temperaturesensors

    except:
        print "Error getting sensor status."
示例#5
0
 def checkTemp(self):
     if (config.TEMP_ENABLED):
         sensor = DS18B20()
         temperatures = sensor.get_temperatures(
             [DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN])
         if (temperatures[1] >= config.TEMP_MAX_F) or (temperatures[0] >=
                                                       TEMP_MAX_C):
             self.n.sendAlert(3)
示例#6
0
文件: setup.py 项目: adavidson32/EOTG
def sensor_setup(all_settings):
    ds = DS18B20()
    if all_settings['mpu6050_settings']['i2c_addr'] == 68:
        mpu_addr = 0x68
    mpu = mpu6050(mpu_addr)
    pump = relays(all_settings['pump_settings'])
    heater = relays(all_settings['heater_settings'])
    return ds, mpu, pump, heater
示例#7
0
def read_w1_bus():
    print("read_w1")
    sensor_ids = []
    sensors_temp = DS18B20.get_all_sensors()
    for sensor in sensors_temp:
        sensor_ids.append(sensor.get_id())

    return sensor_ids
示例#8
0
文件: example.py 项目: MWold/ds18b20
def main():
    sensor = DS18B20()
    while True:
        temperatures = sensor.get_temperatures([DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN])
        print("Kelvin: %f" % temperatures[2])
        print("Degrees Celsius: %f" % temperatures[0])
        print("Degrees Fahrenheit: %f" % temperatures[1])
        print("=====================================")
        sleep(1)
示例#9
0
    def __init__(self, period, sample_q=None):
        self.period = period
        self.sample_q = sample_q or queue.Queue()

        self._sensor = DS18B20()
        self._thread = None
        self._stop_event = threading.Event()
        self._sampling_time = 0           # how long it takes to read sensor
        self._timeout = self.period  - self._sampling_time
示例#10
0
def before_all():
    # mock sensors
    DS18B20.BASE_DIRECTORY = world.MOCKED_SENSORS_DIR

    sensors = []
    sensor_ids = DS18B20.get_available_sensors()
    for sensor_id in sensor_ids:
        sensors.append(DS18B20(sensor_id, load_kernel_modules=False))
    world.sensors = sensors
示例#11
0
    def __init__(self,  histories={}, minimum_period = 60, sample_q=None):
        self.minimum_period = minimum_period

        self.latest = Sample("No data")
        self.histories = histories

        self._sensor = DS18B20()
        self.stopping_ev = threading.Event()
        self._sampling_time = 0
        self.sample_q = sample_q or queue.Queue()
示例#12
0
def getTemp(temp):
    if (config.TEMP_ENABLED):
        sensor = DS18B20()
        temperatures = sensor.get_temperatures(
            [DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN])
        if (temp == 0): return str(temperatures[1])
        if (temp == 1): return str(temperatures[0])

        return temperatures

    return 'No Sensor'
示例#13
0
def main():
    sensor = DS18B20()

    print("=====================================")

    temperatures = sensor.get_temperatures(
        [DS18B20.DEGREES_C, DS18B20.DEGREES_F, DS18B20.KELVIN])

    print("Kelvin: %f" % temperatures[2])
    print("Temp C : %f" % temperatures[0])
    print("Degrees Fahrenheit: %f" % temperatures[1])
    print("=====================================")
示例#14
0
    def __init__(self, scheduler, model, temp_period, pic_period, readings):
        self.task = scheduler
        self.spabModel = model
        self.temp_p = temp_period
        self.pic_p = pic_period
        self.readings = readings
        self.temp_sensor = DS18B20()
        #self.camera = PiCamera()
        #self.camera.resolution = (320, 240)
        #self.camera.start_preview()

        i2c = busio.I2C(board.SCL, board.SDA)
        self.ads = ADS.ADS1115(i2c)
        self.chan = AnalogIn(self.ads, ADS.P0)
def get_temp_data_f():
    '''Get temperature data in Fahrenheit''' 
    os.system('modprobe w1-gpio')
    os.system('modprobe w1-therm')
    
    sensors = []
    temps = []

    sensor = DS18B20()
    for sensor_id in DS18B20.get_available_sensors():
        sensors.append(DS18B20(sensor_id))
    
    for sensor in sensors:
        temps.append(sensor.get_temperature(DS18B20.DEGREES_F))
    return temps
示例#16
0
 def __init__(self,type=sensorType.FAKE,pin=None):
     # types are 
     self.temp = 80
     self.reads = 0
     self.change = .1        
     self.pin = pin        # need to add some error/bound checking here!!!
     
     if type == sensorType.DS18B20:
         self.sensor = DS18B20()            
     elif type == sensorType.DHT11:
         self.sensor = DHTXX(type=sensorType.DHT11,pin=self.pin)
     elif type == sensorType.DHT22:
         self.sensor = DHTXX(type=sensorType.DHT22,pin=self.pin)
     else:
         self.sensor = None
示例#17
0
def main(tank_id):
    logging.basicConfig(filename='main.log', format="%(asctime)s %(levelname)s: %(message)s",level=logging.DEBUG)   
    ds_object = DS18B20()

    while True:
        #Read sensors
        sensor1 = read_sensor1(ds_object)
        sensor2 = read_sensor2(ds_object)

        #Transmit to google app engine
        try:
                transmit(tank_id, sensor1, sensor2)
        except: 
                logging.debug('Could not transmit!')

        #Sleepy weepy!
        time.sleep(60)
示例#18
0
def main():
    esp.osdebug(None)
    config = load_config()
    broadcaster = Broadcaster(100)
    one_wire = onewire.OneWire(machine.Pin(22, machine.Pin.PULL_UP))
    temp_sensor = DS18B20(one_wire)

    sensor_ids = temp_sensor.scan()
    if not sensor_ids:
        machine.reset()
        return
    sensor_id = sensor_ids[0]

    try:
        temperature = temp_sensor.convert_read_temp(sensor_id)
        broadcaster.broadcast(temperature)
    except Exception:
        broadcaster.broadcast(Broadcaster.ERROR_TEMPERATURE)

    measure("end")
    machine.reset()
示例#19
0
def getTemperatureStats(temperaturesensors, tempCSVpath, tempCSV):
    try:
        for temperaturesensor in temperaturesensors:
            if temperaturesensor['type'] == "temperature":
                avg = 0
                summation = 0
                rowCount = 0
                temperature = 0
                temperaturesensor['temperature'] = float("%.2f" % (
                    DS18B20(str(temperaturesensor['address'])).get_temperature(
                        DS18B20.DEGREES_F) +
                    temperaturesensor['temperaturecorrection']))
                with open(tempCSVpath + tempCSV, 'r') as csvfile:
                    csvreader = csv.reader(csvfile)
                    next(csvreader)
                    for row in csvreader:
                        summation = float(row[int(
                            temperaturesensor['csvid'])]) + summation
                        rowCount += 1
                    csvfile.close()
                    avg = summation / rowCount
                    temperaturesensor['temperatureaverage'] = str("%.2f" % avg)
                    if temperaturesensor['pin']:
                        ps = subprocess.Popen(
                            ('gpio', '-g', 'read', str(
                                temperaturesensor['pin'])),
                            stdout=subprocess.PIPE,
                            bufsize=1,
                            universal_newlines=True)
                        output = str(ps.communicate())
                        output = output.translate(None, "\n',N('on\e) ")
                    if output == "1":
                        temperaturesensor['pinstatus'] = "Off"
                    if output == "0":
                        temperaturesensor['pinstatus'] = "On"
        return temperaturesensors

    except:
        print "Error getting sensor status."
示例#20
0
def ds18b20_init():
    # initialise temperature sensors
    sensorArray = DS18B20()
示例#21
0
def create_temp_sensors():
    sensors = [SpiTempSensor(0, 0)]
    for s in DS18B20.get_available_sensors():
        sensors.append(DS18B20(s))
    return sensors
示例#22
0
from ds18b20 import DS18B20
import gspread
from oauth2client.service_account import ServiceAccountCredentials

# use creds to create a client to interact with the Google Drive API
scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]
creds = ServiceAccountCredentials.from_json_keyfile_name(
    'client_secret.json', scope)
client = gspread.authorize(creds)
# DS18B20
probes = DS18B20()
probe_count = probes.device_count()

# Constants
global_offset = 2  # 2 Degree change, then we push changes.
"""
So the old temperature is 18C and the new temperature is 21C, offset is 2, this would return true, and so should now post into the Google Sheet.
"""


def rangeCheck(old_number, offset, new_number):  # Thanks @Eladkay, for this
    return not new_number <= (old_number + offset) and new_number > (
        old_number - offset)


"""
Get the last temperatures posting, compare to the current temperatures. If they exceed offsets, send an update to the google sheet
"""
        reader = csv.reader(config_file)
        config = {rows[0]: rows[1] for rows in reader}
        logger.debug(config)
        atlas_ph_id = None
        atlas_ec_id = None
        try:
            atlas_ph_id = config["atlas_ph_id"]
            atlas_ec_id = config["atlas_ec_id"]
            logger.debug("Atlas pH ID is: {}, Atlas EC ID is: {}".format(
                atlas_ph_id, atlas_ec_id))
        except:
            logger.error("Unable to parse config file")

    atlas_ph_1 = AtlasPh(atlas_ph_id)
    atlas_ec_1 = AtlasEc(atlas_ec_id)
    ds18b20_1 = DS18B20()
    grove_o2_1 = GroveO2()

    while True:
        mhz16_1.poll()
        mhz16_1.transmitToMemcache(shared)

        am2315_1.poll()
        am2315_1.transmitToMemcache(shared)

        atlas_ph_1.poll()
        atlas_ph_1.transmitToMemcache(shared)

        atlas_ec_1.poll()
        atlas_ec_1.transmitToMemcache(shared)
示例#24
0
redisPrefix = "flaskheat"
#get Generlasettings
generalSettings = redis_connector.redisCmdHgetAll(redisPrefix + ':general')

#Set Relay pin
relayPin = int(generalSettings['relayGpio'])

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(relayPin, GPIO.OUT)

days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
relay = int(generalSettings['relay'])

sensor = DS18B20()
temperature = round(sensor.get_temperature(), 3)
print("The temperature is %s celsius" % temperature)

#Save temp on redis

redis_connector.redisCmdHset(redisPrefix + ':general', 'lastTemp', temperature)

delta = float(generalSettings['delta'])
#set historical temp if enabled

if generalSettings['enableHistoricalData'] == 'true':
    timestamp = int(time.time())
    print(
        timestamp,
        datetime.datetime.fromtimestamp(timestamp).strftime(
示例#25
0
in_btn_left = 13
in_btn_right = 20
in_btn_up = 26
in_btn_down = 16

GPIO.setup(in_btn_red, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(in_btn_green, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(in_btn_blue, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(in_btn_left, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(in_btn_right, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(in_btn_up, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(in_btn_down, GPIO.IN, GPIO.PUD_DOWN)

# initialise temperature sensors
sensorArray = DS18B20()
count = sensorArray.device_count()

# Create display instance on default I2C address (0x70) and bus number.
display = BicolorMatrix8x8.BicolorMatrix8x8()
display.begin()

# Clear the display buffer.
display.clear()
tSleep = 1
tSleep_main = 5
print 'CTRL-C to stop'

# Sourire
image_smile = Image.new('RGB', (8, 8))
draw_smile = ImageDraw.Draw(image_smile)
示例#26
0
文件: pop.py 项目: puka89/HackTuesX30
from ds18b20 import DS18B20

read = DS18B20.get_all_sensors()

for sensor in read:
    print(sensor.get_id())
示例#27
0
 def __init__(self, address):
     logging.info('Initialising DS18B20 sensor with address {}'.format(address))
     self._address = address
     self._sensor = Sensor(sensor_id=address)
示例#28
0
    def run(self):  #Create this function to run
        #bring in global variables
        global weightTop
        global weightMid
        global weightBot
        global dryMatter
        global initialSampleWeight
        global targetWeight
        
        dryMatterPercent = dryMatter/initialSampleWeight
        initialMoisturePercent = 1-dryMatterPercent
        
        #ui2.show()
        
        count = 0  #In this case creating a counter
        while True:   #While counter is less than 100 (edited to While True, from count < 100)
            #time.sleep(.5)  #Wait half a second
            #print("Increasing") #Print this for debugging
            count += 1  #increment count
            ui2.updateLED(count)  #Update the LED by calling this method of the ControlWindow Class
            x = DS18B20()
            counter=x.device_count()              #count number of temperature sensors
            i = 0
            templist = []                       #create list to save temp data
            while i < counter:
                temp_temp = x.tempC(i)          #read temp data of first sensor
                templist.append(temp_temp)
                i += 1
            top_temp_f = (templist[0] * 9.0 / 5.0 + 32.0) * 0.98945
            bot_temp_f = (templist[1] * 9.0 / 5.0 + 32.0) * 0.96945
            ui2.updateTopTemp(top_temp_f)  #updates temperature sensor display
            ui2.updateBotTemp(bot_temp_f)
            
            vRatioTop = wd.main0()  #calls main0 of other script, to import voltage ratio reading
            #print(vRatioTop)
            weightTop = -5.10209e5*vRatioTop-zeroTop  #calculates weight based on calibration
 
            
            vRatioMid = wd.main1()  #calls main1 of other script, to import voltage ratio reading
            #print(vRatioMid)
            weightMid = -5.002223e5*vRatioMid-zeroMid  #calculates weight based on calibration
            
            
            vRatioBot = wd.main2()  #calls main0 of other script, to import voltage ratio reading
            #print(vRatioBot)
            weightBot = -4.9078e5*vRatioBot-zeroBot  #calculates weight based on calibration

            ui2.updateTopWeight(weightTop)  #updates weight display box
            ui2.updateMiddleWeight(weightMid)  #updates weight display box
            ui2.updateBottomWeight(weightBot)  #updates weight display box
            
            moistureTop = -100*(((dryMatter*initialWeightTop)/(weightTop*initialSampleWeight))-1)    #DO MOISTURE CALC HERE
            moistureMid = -100*(((dryMatter*initialWeightMid)/(weightMid*initialSampleWeight))-1)     #DO MOISTURE CALC HERE
            moistureBot = -100*(((dryMatter*initialWeightBot)/(weightBot*initialSampleWeight))-1)        #DO MOISTURE CALC HERE
            ui2.updateTopMoistureDisplay(moistureTop) #updates moisture display box
            ui2.updateMiddleMoistureDisplay(moistureMid)  #updates moisture display box
            ui2.updateBottomMoistureDisplay(moistureBot)  #updates moisture display box

#            print(EStopTemp)
            ui2.show()
            app.processEvents()
            
            
            #print(started)
            if started == True:
                GPIO.output(6, GPIO.HIGH)

            #else:
                #GPIO.output(6, GPIO.LOW)
                #if moistureTop < 8:
                #    shutoff()
            
                if moistureTop < targetPercent or moistureMid < targetPercent or moistureBot < targetPercent:
                    shutoff()
            
                      
            #Test of controlling power relay based on temperature
            if top_temp_f > EStopTemp or bot_temp_f > EStopTemp:
                shutoff()
示例#29
0
from ds18b20 import DS18B20
import time

print(DS18B20.get_available_sensors())

sensor = DS18B20()
while True:
    temperature_in_celsius = sensor.get_temperature()
    print(temperature_in_celsius)
    time.sleep(2)
示例#30
0
            os.path.abspath(os.path.join(os.getcwd(), os.pardir)) +
            "/config/temperaturesensors.json") as json_temperaturesensors:
        temperaturesensors = json.load(json_temperaturesensors)
except:
    print "Temperature Sensor config file not found."

#Log temperatures to CSV.
while True:
    try:
        data = []
        currentDT = datetime.datetime.now()
        data.append(currentDT.strftime("%m-%d-%Y %I:%M:%S %p"))
        for temperaturesensor in temperaturesensors:
            data.append(
                str("%.1f" % (
                    DS18B20(str(temperaturesensor['address'])).get_temperature(
                        DS18B20.DEGREES_F) +
                    temperaturesensor['temperaturecorrection'])))
        file = open(
            os.path.abspath(
                os.path.join(os.getcwd(), os.pardir) + "/static/temp.txt"),
            "a")
        write = str((data[0], data[1], data[2])) + "\n"
        write = write.translate(None, "(')")
        file.write(write)
        file.close()
        print data
        time.sleep(30)
    except KeyboardInterrupt:
        quit()
    except:
        print "Error logging temperatures."
示例#31
0
deviceNames = ['Ruche01', 'Ruche02', 'Ruche03', 'Ruche04', 'Ruche05']
temperatureDeviceNames = ['Matrice01', 'Matice02', 'Matrice03', 'Matrice04', 'Matrice05']
#Matrice = la valeur moyenne de la température entre les 2 cadres

connecting_time = time.time() + 10

if time.time() < connecting_time:  #try connecting to AWS for 10 seconds
    myMQTTClient.connect()
    myMQTTClient.publish(topic, "connected", 0)
    print("MQTT Client connection success!")
else:
    print("Error: Check your AWS details in the program")

#create external temperature sensor variable
exTemperatureSensor = DS18B20()

#create internal temperature sensor variable
inTemperatureSensor = 0 #PUT THE REAL FUNCTION HERE !!

#Event Handler Callback Functions

def BridgeAttached(e):
    attached = e.device
    print("Bridge %i Attached!" % (attached.getSerialNum()))

def BridgeDetached(e):
    detached = e.device
    print("Bridge %i Detached!" % (detached.getSerialNum()))

def BridgeError(e):
示例#32
0
mqttc.will_set("system/connectionstatus/raspberrypi2",
               payload="OFF",
               qos=2,
               retain=True)

# Connect to the MQTT server
if debug:
    print("Connecting to MQTT server...")
connect(mqttc)
time.sleep(1)

mqttc.loop_start()

time.sleep(1)

# test temperature sensors
x = DS18B20()
count = x.device_count()

while True:
    i = 0
    while i < count:
        print(x.tempC(i))
        #post data to mqtt broker
        publish_message(msg=x.tempC(i)[0],
                        mqtt_path='raspberrypi2/temp/' + x.tempC(i)[1],
                        mqtt_qos=2,
                        mqtt_retain=True)
        i += 1
    time.sleep(60)
示例#33
0
            outlet_num = int(payload[6]) if (len(payload) == 7) else 'all'
            relays.off(outlet_num)
    print('O1: {}, O2: {}, O3: {}, O4: {}'.format(
        relays.receive_info_states()))


#--------------------------------MAIN CODE-------------------------------

client = MQTTClient(ADAFRUIT_IO['USERNAME'], ADAFRUIT_IO['KEY'])
client.on_connect = connected
client.on_disconnect = disconnected
client.on_message = message
client.connect()

relays = four_relays(outlet_pins, outlet_names, outlet_types)
ds = DS18B20('f', 2)
num_ds = ds.device_count()
print('Number of DS18B20 sensors detected: {}'.format(num_ds))

last = 0
print('Publishing a new message every 10 seconds (press Ctrl-C to quit)...')
while True:
    #sensor_values = (ds.temp(), bmp.pressure(), bmp.altitude('ft'), bh.light('lux'), pir.motion(t_last_motion))
    client.loop()
    if (time.time() - last) >= sample_rate:
        room_temp = ds.temp()
        print('Publishing {0:.2f}F to RoomTemp feed.'.format(room_temp))
        client.publish(PUB_FEED, room_temp)
        last = time.time()

#------------------------------------------------------------------------
示例#34
0
import ConfigParser
import paho.mqtt.client as mqtt
from ds18b20 import DS18B20

delay = 30.0

dir = os.path.dirname(os.path.realpath(__file__))
config = ConfigParser.SafeConfigParser()
config.read(dir + '/application.cfg')
mqtt_broker = config.get('mqtt', 'broker')

sensor_locations = {}
sensors = {}
for id, location in config.items('sensors'):
    sensor_locations[id] = location
    sensors[id] = DS18B20(id)

mqtt_client = mqtt.Client()
mqtt_client.connect(mqtt_broker)
mqtt_client.loop_start()

while True:
    for id in sensor_locations.keys():
        location = sensor_locations[id]
        topic = "sensor/temperature/" + location
        temperature = sensors[id].read_fahrenheit()
        msg = json.dumps({
            'location': location,
            'datetime': str(datetime.now()),
            'type': 'temperature',
            'value': temperature