def check_timers(): flag = "NO" deviceip="notset" cur_time = strftime("%H:%M") datimers = timer.query.all() dastatus = check_status("192.168.1.101") testlist = [] #maxtemp = 23 for timer_entry in datimers: deviceip=devices.query.filter_by(id=timer_entry.name_id).first().ip maxtemp=float(devices.query.filter_by(id=timer_entry.name_id).first().temp) if maxtemp == 0.0: maxtemp=99 if timer_entry.start_time < cur_time and timer_entry.end_time > cur_time and temperature.read_temp() < maxtemp: if check_status(deviceip) =="OFF": turn_on(deviceip, timer_entry.name_id) #teststatus = "OFF" testv = datetime.strptime(cur_time, '%H:%M') - datetime.strptime(timer_entry.end_time, '%H:%M') if testv > timedelta(minutes=1) and testv < timedelta(minutes=5) or temperature.read_temp() > maxtemp: flag = "YES " + str(testv) + " " + (deviceip) if check_status(deviceip) == "ON": turn_off(deviceip, timer_entry.name_id) if testv > timedelta(minutes=1) and timer_entry.timer_type == 0: delete_timer(timer_entry.id) #time.strptime(stamp, '%I:%M') teststatus = check_status(deviceip) testlist.append([timer_entry.name_id,timer_entry.start_time,timer_entry.end_time,teststatus,testv,maxtemp]) return render_template('test.html', time=cur_time, status=dastatus, flag=flag, testv=testv, testc=timedelta(minutes=1), timers=testlist)
def raise_temperature(target_temperature): while read_temp() < target_temperature: switch_on_boiler() logging.debug( "Boiler On. Waiting {} secs to rise to {}. Current temp {}". format(MONITOR_BOILER_SWITCHOFF_DELAY, target_temperature, read_temp())) sleep(MONITOR_BOILER_SWITCHOFF_DELAY) switch_off_boiler() logging.debug("Target temperature {} reached. Now {}C".format( target_temperature, read_temp()))
def monitorizar_hilo(threadName): if a: threadName.exit() while True: global temperatura global timeString global now global puerta global state global datos temperatura = temperature.read_temp() state = GPIO.input(PIN_REED) # La fecha/hora en formato timestamp timestamp = int(time.time()) now = datetime.datetime.now() timeString = now.strftime("%Y-%m-%d %H:%M") if state == False: puerta = str("puerta abierta") else: puerta = str("puerta cerrada") datos = { "fecha": timeString, "Usuario": "Frutgan", "placa": "Placa_Diego", "temperatura": temperatura, "Puerta": puerta } print("informacion de la placa: " + str(datos)) time.sleep(10)
def read_temps(self): """ Read the temperature from each sensor """ try: import temperature dataset = self.readings date = datetime.datetime.now() # Get the actual temperature reading for sensor in self.sensors: the_temp = temperature.read_temp(sensor) dataset.append({ 'line_name': sensor, 'x': date, 'y': the_temp, 'key': self.private_key }) if sensor == '/sys/bus/w1/devices/28-0000077b5cfd/w1_slave': self.do_redis(sensor, the_temp) # Update the readings self.readings = dataset except Exception as e: # `import temp` has probably failed, load test temperatures # This should only execute when not on a Pi. print('Reverting to test mode:', e) self.test_read_temps()
def relay(number, state): now = round(read_temp(), 2) ############# ### Relay ### ############# if state == "1": # LED if number == "3": if kitchen.get_state() == 1: kitchen.turn_on() if living_room.get_state() == 1: living_room.turn_on() if bathroom.get_state() == 1: bathroom.turn_on() if hall.get_state() == 1: hall.turn_on() # DIMMER if number == "1": controller_h.turn_on() temperature_set[0] = 1 relay_o.set_state(11, 1) relay_o.set_state(12, 1) relay_o.set_state(eval(number), 1) if state == "0": if number == "1": controller_h.turn_off() relay_o.set_state(eval(number), 0) color_now = [ kitchen.get_color(), hall.get_color(), living_room.get_color(), bathroom.get_color() ] state_now = [ kitchen.get_state(), hall.get_state(), living_room.get_state(), bathroom.get_state() ] relay_now = [] for i in range(1, 9): relay_now.append(relay_o.read_state(i)) temperature_set = [None] * 4 temperature_set[0] = controller_h.get_state() temperature_set[1] = controller_c.get_state() temperature_set[2] = pid_h.getPoint() temperature_set[3] = pid_c.getPoint() fan_date = [fan_c.state, fan_c.pwm] return render_template('control.html', color=color_now, state=state_now, relay=relay_now, temperature=temperature_set, now_temp=now, fan=fan_date)
def run(self): while(True): print("Monitoring thread says: ") reed.getStateReed() global temp temp =temperature.read_temp() print(temp) time.sleep(5)
def add_record(): while True: try: ins = table.insert().values(time=datetime.datetime.now(),temperature=temperature.read_temp()) conn = engine.connect() conn.execute(ins) conn.close() time.sleep(0.5) except: pass
def raise_temperature_for(target_temperature, target_minutes=0): raise_temperature(target_temperature) logging.debug("Holding at {} for {} minutes".format( target_temperature, target_minutes)) start = datetime.now() while (datetime.now() - start).seconds < target_minutes * 60: logging.debug("Waiting 30 seconds before re-reading temperature") sleep(30) logging.debug("Current temperature {}C".format(read_temp())) raise_temperature(target_temperature) logging.debug("Held at {} for {} seconds ".format( target_temperature, (datetime.now() - start).seconds))
def index(): #state_bed1 = urllib2.urlopen('http://192.168.1.101/cgi-bin/relay.cgi?state').read() datimers = timer.query.all() dadevices = devices.query.all() device_status_list = [] cur_temp = str(round(temperature.read_temp(),1)) for check_devices in dadevices: state_bed1 = check_status(check_devices.ip) state_bed1 = state_bed1.strip() if state_bed1 == "ON": button_status="mdl-color--green-300" else: button_status="mdl-color--red-300" device_status_list.append([check_devices.id, check_devices.name, button_status, check_devices.ip, check_devices.temp]) return render_template('index.html', title='Home', device_list = device_status_list, timer = datimers, cur_temp = cur_temp, state_bed1=state_bed1)
def led(room, action): now = round(read_temp(), 2) ################## ### LED ON/OFF ### ################## if action == 'on': eval(room).turn_on() elif action == 'off': eval(room).turn_off() color_now = [ kitchen.get_color(), hall.get_color(), living_room.get_color(), bathroom.get_color() ] state_now = [ kitchen.get_state(), hall.get_state(), living_room.get_state(), bathroom.get_state() ] relay_now = [] for i in range(1, 9): relay_now.append(relay_o.read_state(i)) temperature_set = [None] * 4 temperature_set[0] = controller_h.get_state() temperature_set[1] = controller_c.get_state() temperature_set[2] = pid_h.getPoint() temperature_set[3] = pid_c.getPoint() fan_date = [fan_c.state, fan_c.pwm] return render_template('control.html', color=color_now, state=state_now, relay=relay_now, temperature=temperature_set, now_temp=now, fan=fan_date)
import boto3 import temperature as temp access_key = "" access_secret = "" region = "" queue_url = "" def post_message(client, message_body, url): response = client.send_message(QueueUrl=url, MessageBody=message_body) client = boto3.client('sqs', aws_access_key_id=access_key, aws_secret_access_key=access_secret, region_name=region) temperature = temp.read_temp() message = "temp_" + str(temperature) print(message) post_message(client, message, queue_url)
def check_temp(): cur_temp = str(round(temperature.read_temp(),1)) return jsonify(temp=cur_temp)
datefmt='%m/%d/%Y %I:%M:%S') from actions import message, wait_until_temperature_has_fallen_to, switch_off_boiler, create_pump MAX_TEMPERATURE = 20 MIN_TEMPERATURE = 19.8 CYCLE_MINUTES = 10 with manage(create_pump()) as pump: message("Cooling initiated : target temp {}C".format(MAX_TEMPERATURE)) try: while (True): switch_off_boiler() if (read_temp() > MAX_TEMPERATURE): message('Cooling. temp {} : target {}'.format( read_temp(), MIN_TEMPERATURE)) wait_until_temperature_has_fallen_to(MIN_TEMPERATURE, pump=pump) message( "Target Temperature ( {}C ) reached. Current temperature {}" .format(MIN_TEMPERATURE, read_temp())) logging.debug('Waiting {} mins : temp {} C : max {}'.format( CYCLE_MINUTES, read_temp(), MAX_TEMPERATURE)) sleep(CYCLE_MINUTES * 60) except Exception as e: message("Error received. Exiting {}".format(e))
from machine import Pin from neopixel import NeoPixel import time import temperature NEOPIXEL_COUNT = 8 pin = Pin(4, Pin.OUT) np = NeoPixel(pin, NEOPIXEL_COUNT) RED = (16, 16, 0) BLUE = (0, 0, 16) OFF = (0, 0, 0) WHITE = (16, 16, 16) def set_panel(temp): color = RED if temp > 0 else BLUE for i in range(NEOPIXEL_COUNT): if temp > -1 and temp < 1: np[i] = WHITE else: np[i] = color if abs(temp) >= i + 1 else OFF np.write() while True: temp = temperature.read_temp() set_panel(temp) time.sleep(5)
from temperature import read_temp, initialise_temperature_probe import time initialise_temperature_probe() while True: print(read_temp()) time.sleep(1)
def tick(t): mqtt.c.check_msg() temp = temperature.read_temp() mqtt.send(temp)
def getStatesButtons(): stateButton1 = GPIO.input(PIN_BUTTON1) if stateButton1 == False: print('Button 1 Pressed') api_url = "http://api.carriots.com/streams" device = "[email protected]" api_key = "2cfb12bf7c883ef81a59a324a4cae6687b816427d259641f1d7100e4907c03ee" content_type = "application/json" mydata = { 'tipo': 'temp', 'identificador': 'abcdef', 'fecha': int(time.time()), 'valor': temperature.read_temp() } params = { "protocol": "v2", "device": device, "at": timestamp, "data": mydata } binary_data = json.dumps(params).encode('ascii') header = { "User-Agent": "raspberrycarriots", "Content-Type": content_type, "carriots.apikey": api_key } req = urllib.request.Request(api_url, binary_data, header) f = urllib.request.urlopen(req) print(f.read().decode('utf-8')) time.sleep(5) else: print('Button 1 Not Pressed') stateButton2 = GPIO.input(PIN_BUTTON2) if stateButton2 == False: print('Button 2 Pressed') api_url = "http://api.carriots.com/streams/" device = "[email protected]" api_key = "2cfb12bf7c883ef81a59a324a4cae6687b816427d259641f1d7100e4907c03ee" content_type = "application/json" content_type = "application/json" api_url = "http://api.carriots.com/streams/" api_key = "2cfb12bf7c883ef81a59a324a4cae6687b816427d259641f1d7100e4907c03ee" content_type = "application/json" content_type = "application/json" headers = { 'User-Agent': 'Raspberry-Carriots', 'Carriots.apikey': api_key, } req = urllib.request.Request(api_url, headers=headers) data = json.loads(urllib.request.urlopen(req).read().decode('utf-8')) print(data["result"][0]["id_developer"]) print(json.dumps(data, indent=4, sort_keys=True)) api_url = api_url + str(data["result"][0]["id_developer"]) + "/" print(api_url) params = {"protocol": "v2"} binary_data = json.dumps(params).encode('ascii') header = {"carriots.apikey": api_key} req = urllib.request.Request(api_url, binary_data, header) req.get_method = lambda: "DELETE" f = urllib.request.urlopen(req) print(f.read().decode('utf-8')) time.sleep(5) else: print("nopressed 2")
def current_temp(): return str(read_temp())
SQLQuery = 'SELECT website FROM Cards where Codes="%s"' % MainClass.card Mysql = mybase.Mysql() Mysql.configuration() WebSite = Mysql.query_select(SQLQuery) try: print(WebSite) ##webbrowser.open(WebSite[0]['website']) except KeyError: pass return None if __name__ == "__main__": MainClass = general() project = Run(2) start = time.clock() finish = start + TimeRuning while ((finish - start) > 0): project.rfid() project.click() start = time.clock() start = time.clock() finish = start + TimeRuning while ((finish - start) > 0): print(temperature.read_temp()) # Print temperature time.sleep(1) start = time.clock()
import logging logging.basicConfig(level=logging.DEBUG) from temperature import read_temp, initialise_temperature_probe from actions import message, raise_temperature_for, action initialise_temperature_probe() action("Confirm Start") message("Boiling for 1 minute") exit(0) raise_temperature_for(target_temperature=95, target_minutes=1) message("Reached {}".format(read_temp()))
def panel(): now = round(read_temp(), 2) ################################## ### Methods - LED + TEMP + FAN ### ################################## if request.method == 'POST' and 'kitchen' in request.form: color = request.form['kitchen'] kitchen.change_color_string(color) if request.method == 'POST' and 'hall' in request.form: color = request.form['hall'] hall.change_color_string(color) if request.method == 'POST' and 'living_room' in request.form: color = request.form['living_room'] living_room.change_color_string(color) if request.method == 'POST' and 'bathroom' in request.form: color = request.form['bathroom'] bathroom.change_color_string(color) if request.method == 'POST' and 'heating' in request.form: if controller_h.state == 1: temperature = request.form['heating'] pid_h.setPoint(float(temperature)) if request.method == 'POST' and 'cooling' in request.form: if controller_c.state == 1: temperature = request.form['cooling'] pid_c.setPoint(float(temperature)) if request.method == 'POST' and 'fan' in request.form: fan_c.pwm = request.form['fan'] relay_o.set_pwm("enb", fan_c.pwm) fan_c.state = 1 relay_o.set_state(13, 1) relay_o.set_state(14, 0) color_now = [ kitchen.get_color(), hall.get_color(), living_room.get_color(), bathroom.get_color() ] state_now = [ kitchen.get_state(), hall.get_state(), living_room.get_state(), bathroom.get_state() ] relay_now = [] for i in range(1, 9): relay_now.append(relay_o.read_state(i)) temperature_set = [None] * 4 temperature_set[0] = controller_h.get_state() temperature_set[1] = controller_c.get_state() temperature_set[2] = pid_h.getPoint() temperature_set[3] = pid_c.getPoint() fan_date = [fan_c.state, fan_c.pwm] return render_template('control.html', color=color_now, state=state_now, relay=relay_now, temperature=temperature_set, now_temp=now, fan=fan_date)
def temperature(HC, state): now = round(read_temp(), 2) ############################## ### Heating/Cooling ON/OFF ### ############################## if HC == "heating": if state == "1": controller_c.turn_off() controller_h.turn_on() relay_o.set_state(11, 1) relay_o.set_state(12, 1) relay_o.set_state(1, 1) if state == "0": relay_o.set_state(1, 0) controller_h.turn_off() if HC == "cooling": if state == "1": controller_h.turn_off() controller_c.turn_on() relay_o.set_state(1, 0) relay_o.set_state(2, 1) relay_o.set_state(11, 1) relay_o.set_state(12, 0) if state == "0": controller_c.turn_off() relay_o.set_state(11, 1) relay_o.set_state(12, 1) if HC == "fan": if state == "1": fan_c.set_state(1) relay_o.set_pwm("enb", fan_c.pwm) relay_o.set_state(13, 1) relay_o.set_state(14, 0) if state == "0": fan_c.set_state(0) relay_o.set_state(13, 1) relay_o.set_state(14, 1) fan_date = [fan_c.state, fan_c.pwm] color_now = [ kitchen.get_color(), hall.get_color(), living_room.get_color(), bathroom.get_color() ] state_now = [ kitchen.get_state(), hall.get_state(), living_room.get_state(), bathroom.get_state() ] temperature_set = [None] * 4 temperature_set[0] = controller_h.get_state() temperature_set[1] = controller_c.get_state() temperature_set[2] = pid_h.getPoint() temperature_set[3] = pid_c.getPoint() relay_now = [] for i in range(1, 9): relay_now.append(relay_o.read_state(i)) return render_template('control.html', color=color_now, state=state_now, relay=relay_now, temperature=temperature_set, now_temp=now, fan=fan_date)
curtime9 = curtime.strftime("%H:%M:%S") db.motion(curtime9) print("\tMotion detected, turning lights on\n") l.startMotion() break while (1): #outer while for authorization x = s.moisture() #moisture if (x == 0): #no moisture start led l.stopSoil() elif (x == 1): l.startSoil() currtemp = temp.read_temp() if (flag == 0): if currtemp > 25: print("\n\tCurrent temp : {}").format(currtemp) print("\tTurning AC on to 25\n") flag = 1 db.temperature(currtemp) elif currtemp < 25: print("\n\tCurrent temp: {}").format(currtemp) print("\tTurning heater on to 25\n") flag = 1 ctime = datetime.datetime.now() sotime, sotime1, sctime, sctime1 = db.motor()
def run(self): while (True): reed.getStateReed() print(temperature.read_temp()) time.sleep(5)
def read_and_post(stream): # read temperature from our stub module temp = temperature.read_temp() # post data to plotly stream.write({'x': datetime.datetime.now(), 'y': temp})
def index(): return render_template("index.html", temp=read_temp())
mycursor = mydb.cursor() def writeTemp(tempData, timeStr): sql = "INSERT INTO temperature (temperature,datetime) VALUES (%s,%s)" val = (tempData, timeStr) mycursor.execute(sql, val) mydb.commit() while True: now = time.localtime() timeStr = str(now[0]) + '-' + str(now[1]).zfill(2) + '-' + str( now[2]).zfill(2) + ' ' + str(now[3]).zfill(2) + ':' + str( now[4]).zfill(2) + ':' + str(now[5]).zfill(2) datestamp = str(now[0]) + '-' + str(now[1]).zfill(2) + '-' + str( now[2]).zfill(2) curTemp = temp.read_temp()[0] #import pdb; pdb.set_trace() writeTemp(curTemp, timeStr) try: """ with open(os.path.join("tempdata", datestamp + '.dat'),'a') as data: datum = (str(curTemp[0]) + ',' + str(curTemp[1]) + ',' + timestr + '\n') data.write(datum) print(datum[:-1]) """ except: print('Database write error') time.sleep(60)
import humidity as h import my_mysql as msql import time delta = 20.0 temp_probe_id = ["28-0000045d724a", "28-0000045d7be4"] sensor_id_name = {temp_probe_id[0]: "na zewnÄ…trz", temp_probe_id[1]: "w domu"} #while 1: for step in range(int(60.0 / delta)): start_time = time.time() time_to_db = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time)) # print(time_to_db) for i in temp_probe_id: temp = t.read_temp(i) query = """INSERT INTO temperature (Date_and_Time, Sensor_Id, VALUE) VALUES ('{}', '{}', {});""".format( time_to_db, i, temp) msql.write_to_db(query) temp_pressure, pressure = p.read_pressure_sensor() query = """INSERT INTO pressure (Date_and_Time, Sensor_Id, pressure, temperature) VALUES ('{}', '{}', {}, {});""".format( time_to_db, "BMP085", pressure, temp_pressure) msql.write_to_db(query) temp_humidity, humidity = h.read_humidity_sensor() query = """INSERT INTO humidity (Date_and_Time, Sensor_Id, humidity, temperature) VALUES ('{}', '{}', {}, {});""".format( time_to_db, "DHT11", humidity, temp_humidity) msql.write_to_db(query) d = time.time() - start_time