def sense(): import machine, onewire, ds18x20 import network import boot import ubinascii from umqtt.simple import MQTTClient import time # connect to the network and set network varialbe (just in case) # boot.connect() # sta_if = network.WLAN(network.STA_IF) #pull from the temperature.py script from temperature import TemperatureSensor t = TemperatureSensor(21) t.read_temp() # use t.read_temp(False) to return Celsius # connect to devans laptop IP c = MQTTClient("ESP32_dev", '192.168.121.156') c.connect() try: while True: c.publish('sensor-data', str(t.read_temp())) time.sleep(3) except KeyboardInterrupt: print('interrupted!') c.disconnect()
class SensorFrame(Frame): def __init__(self, master, category='', location='', value=0): Frame.__init__(self, master) # 마스터는 부모 윈도우 # 다중상속을 대비해 super로 상속하지 않는다. self.master = master self.master.title('sensor : ' + category) self.pack(fill=BOTH, expand=True) #부모윈도우에 맞게 조정 self.scale = Scale(self, from_=0, to=100, orient=VERTICAL) self.scale.pack(ipadx=10, ipady=0, side=LEFT) #크기조정 불가 self.lb1Value = Label(self) self.lb1Value.pack(side=LEFT, fill=X, padx=10, expand=True) # 높이고정 x축 늘림가능 self.sensor = TemperatureSensor(value, on_change=lambda v: self.on_change(v)) self.sensor.start() self.set_value(self.sensor.measure()) ## 사용하는 측에서 ## 딴데서 쓸려고 분리했다. ## 스크롤 할때 위치조정하기위해 생겨난 메서드 def set_value(self, value): self.lb1Value.config(text='온도 : ' + str(value)) # print(value, 50-value) self.scale.set(50 - value) ## 딴데서 쓸려고 분리했다. def on_change(self, value): self.set_value(value)
def __init__(self, client_id, server='192.168.1.215', pin=2, fahrenheit=True, topic=None, **kwargs): """ Instantiates a TemperatureSensor and MQTTClient; connects to the MQTT broker. Arguments `server` and `client_id` are required. :param client_id: Unique MQTT client ID :type client_id: str :param server: MQTT broker domain name / IP :type server: str :param pin: 1-Wire bus pin :type pin: int :param fahrenheit: Whether or not to publish temperature in Fahrenheit :type fahrenheit: bool :param topic: Topic to publish temperature on :type topic: str :param kwargs: Arguments for MQTTClient constructor """ self.sensor = TemperatureSensor(pin) self.client = MQTTClient(client_id, server, **kwargs) if not topic: self.topic = 'devices/%s/temperature/degrees' % \ self.client.client_id else: self.topic = topic self.fahrenheit = bool(fahrenheit) self.client.connect()
def sense(): import machine, onewire, ds18x20 import network import boot import ubinascii from umqtt.simple import MQTTClient import time pin = 21 # connect to the network and set network varialbe (just in case) # boot.connect() # sta_if = network.WLAN(network.STA_IF) #pull from the temperature.py script print("setting up sensor") from temperature import TemperatureSensor t = TemperatureSensor(pin, 'DS18B20-1') num_sens = len(t.ds.scan()) print('Found ' + str(num_sens) + ' Sensors. reading....') for k in range(0, num_sens): print('Temp of sensor ' + str(k) + ': ') temp = t.read_temp( addr_num=k) # use t.read_temp(False) to return Celsius print(temp) # connect to devans laptop IP print("connecting.... ") c = MQTTClient("ESP32_dev", "192.168.121.117", port=1883, keepalive=60) c.connect() print("Done it should be connected") c.publish('sensor-setup', str(num_sens)) try: while True: for k in range(0, num_sens): print("Data To Published, Temperature is " + str(t.read_temp(addr_num=k)) + ' F' + ' From Sensor ' + str(k)) c.publish( 'sensor-data', str(t.name) + '-' + str(k) + ' Temp: ' + str(t.read_temp(addr_num=k)) + ' F') print("Done!") time.sleep(1) except KeyboardInterrupt: print('interrupted!') c.disconnect()
async def main(): """Main brewery task. This task manely creates the different tasks for the brewery to operate and monitors the state of those tasks. """ network_config = Config('network_config.json') config = Config('config.json') mqtt_server = MQTTClient(config['mqtt']['server_ip'], config['project_name'], ssid=network_config['ssid'], wifi_pw=network_config['__password']) sensor_name = 'environment temperature' mqtt_server.add_device(sensor_name, 'temperature', '°C') reduce_environment_temperature = ReduceCallbacks(sensor_name, callback=mqtt_server.publish) environment_temperature_sensor = TemperatureSensor(sensor_name, hardware_config=config['hardware'], callback=reduce_environment_temperature) reduce_environment_temperature.set_nr_of_measurements(10 / environment_temperature_sensor.interval) sensor_name = 'kettle temperature' mqtt_server.add_device(sensor_name, 'temperature', '°C') reduce_kettle_temperature = ReduceCallbacks(sensor_name, callback=mqtt_server.publish) kettle_temperature_sensor = TemperatureSensor(sensor_name, hardware_config=config['hardware'], callback=reduce_kettle_temperature) reduce_kettle_temperature.set_nr_of_measurements(10 / kettle_temperature_sensor.interval) actuator_name = 'kettle switch' mqtt_server.add_device(actuator_name, 'outlet') recipe = get_recipe(callback=mqtt_server.publish) mqtt_server.add_device('target temperature', 'temperature', '°C', recipe.set_target_temperature) # TODO: this is related to get_recipe... mqtt_server.add_device('recipe', 'actions', None) mqtt_server.add_device('recipe_ack_action', 'action', None, recipe.ack_action) mqtt_server.add_device('recipe_stage', 'action', None, recipe.set_stage) kettle_control = KettleControl(kettle_temperature_sensor, PowerSwitch(actuator_name, int(config['hardware']['kettle switch']), callback=mqtt_server.publish), recipe) asyncio.create_task(mqtt_server.run()) asyncio.create_task(environment_temperature_sensor.run()) asyncio.create_task(kettle_temperature_sensor.run()) asyncio.create_task(kettle_control.run()) uptime = 0 while True: await asyncio.sleep(10) uptime += 10 uptime_str = f'{uptime//3600}:{(uptime//60)%60:02}:{uptime%60:02}' mqtt_server.publish(uptime=uptime_str)
class TemperatureClient: """ Represents an MQTT client which publishes temperature data on an interval """ def __init__(self, client_id, server, pin, fahrenheit=True, topic=None, **kwargs): """ Instantiates a TemperatureSensor and MQTTClient; connects to the MQTT broker. Arguments `server` and `client_id` are required. :param client_id: Unique MQTT client ID :type client_id: str :param server: MQTT broker domain name / IP :type server: str :param pin: 1-Wire bus pin :type pin: int :param fahrenheit: Whether or not to publish temperature in Fahrenheit :type fahrenheit: bool :param topic: Topic to publish temperature on :type topic: str :param kwargs: Arguments for MQTTClient constructor """ self.sensor = TemperatureSensor(pin) self.client = MQTTClient(client_id, server, **kwargs) if not topic: self.topic = 'devices/%s/temperature/degrees' % \ self.client.client_id else: self.topic = topic self.fahrenheit = bool(fahrenheit) self.client.connect() def publishTemperature(self): """ Reads the current temperature and publishes a JSON payload on the configured topic, e.g., `{"unit": "F", "degrees": 72.5}` """ t = self.sensor.read_temp(self.fahrenheit) payload = dict(degrees=t) if self.fahrenheit: payload['unit'] = 'F' else: payload['unit'] = 'C' self.client.publish(self.topic, json.dumps(payload)) def start(self, interval=60): """ Begins to publish temperature data on an interval (in seconds). This function will not exit! Consider using deep sleep instead. :param interval: How often to publish temperature data (60s default) :type interval: int """ while True: self.publishTemperature()
def __init__(self, master, category='', location='', value=0): Frame.__init__(self, master) # 마스터는 부모 윈도우 # 다중상속을 대비해 super로 상속하지 않는다. self.master = master self.master.title('sensor : ' + category) self.pack(fill=BOTH, expand=True) #부모윈도우에 맞게 조정 self.scale = Scale(self, from_=0, to=100, orient=VERTICAL) self.scale.pack(ipadx=10, ipady=0, side=LEFT) #크기조정 불가 self.lb1Value = Label(self) self.lb1Value.pack(side=LEFT, fill=X, padx=10, expand=True) # 높이고정 x축 늘림가능 self.sensor = TemperatureSensor(value, on_change=lambda v: self.on_change(v)) self.sensor.start() self.set_value(self.sensor.measure())
from flask import Flask app = Flask(__name__) from flask import render_template from temperature import TemperatureSensor sensor = TemperatureSensor() @app.route('/temperature/') def hello(): temp_c = sensor.read_temp_c() message_froid = 'il fait froid' message_chaud = 'il fait chaud' message_neutre = 'il fait neutre' message = '' if temp_c < 20: message = message_froid elif temp_c > 30: message = message_chaud else: message = message_neutre return render_template('index.html', message=message, temp_c=temp_c)
from led import Led from led2 import Led2 from temperature import TemperatureSensor from flask import Flask app = Flask(__name__) from flask import render_template degcel = TemperatureSensor() led2 = Led2() @app.route('/on/') def hello(): return render_template('on.html') @app.route('/led/<on_off>') def led(on_off): if on_off == 'on' or on_off == 'off': led1.status = on_off led1.led_status() elif on_off == 'blink': led1.blink() return render_template('on.html') @app.route('/temp/<Celsius>') def tempC(Celsius): Celsius = degcel.degreeCelsius() led2.led2_Celsius(Celsius)
from light import LightSensor from movement import MovementSensor from morse import convertStrToMorse import RPi.GPIO as GPIO from threading import Thread app = Flask(__name__) socketio = SocketIO(app) #Utilisation d'une norme de nommage pour les broches GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) redLed = Led(18) greenLed = Led(24) buzzer = Buzzer(22) tempSensor = TemperatureSensor('28-01131a4f0da1') lightSensor = LightSensor(27) @app.route('/') def home(): temp = tempSensor.read_temp() return render_template('home.html', temp=temp) @app.route('/temp') def temp(): temp = tempSensor.read_temp() return str(temp) @app.route('/light') def light():
ampy -p /dev/ttyUSB0 put ./temperature.py ampy -p /dev/ttyUSB0 put ./09-temperature-oled.py main.py # reset device """ import machine import ssd1306 import time from temperature import TemperatureSensor ONE_WIRE_PIN = 32 I2C_SCL_PIN = 22 I2C_SDA_PIN = 21 ts = TemperatureSensor(ONE_WIRE_PIN) i2c = machine.I2C(-1, machine.Pin(I2C_SCL_PIN), machine.Pin(I2C_SDA_PIN)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) # test_whole display oled.fill(1) oled.show() time.sleep_ms(300) # reset display oled.fill(0) oled.show() while True:
from movement import MovementSensor from morse import convertStrToMorse import RPi.GPIO as GPIO from threading import Thread app = Flask(__name__) socketio = SocketIO(app) #Utilisation d'une norme de nommage pour les broches GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) redLed = Led(16) blueLed = Led(12) buzzer = Buzzer(14) tempSensor = TemperatureSensor('28-01131a3de1fd') lightSensor = LightSensor(27) @app.route('/') def home(): temp = tempSensor.read_temp() return render_template('home.html', temp=temp) @app.route('/temp') def temp(): temp = tempSensor.read_temp() return str(temp)
from flask import Flask app = Flask(__name__) from flask import render_template from temperature import TemperatureSensor michel = TemperatureSensor() @app.route('/temperature/') def hello(): temps_c = michel.read_temp_c() message_froid = 'il fait froid' message_chaud = 'il fait chauuuuuuud' message_neutre = 'mouais ' message = '' if temps_c < 20: message = message_froid elif temps_c > 30: message = message_chaud else: message = message_neutre return render_template('index.html', message=message, temps_c=temps_c)
for t in threads: if t.isAlive(): t.stop() '''for t in threads: if t.isAlive(): t.join()''' print("Finished.") sys.exit(0) signal.signal(signal.SIGINT, signal_handler) queue_ = Queue(100) obs = Observer(queue_) temp_sensor = TemperatureSensor("temp", queue_, sleeptime, pin=0) flame_sensor = FlameSensor("flame", queue_, sleeptime, pin=27) #rotary_sensor = RotarySensor(thread_id="rotary", queue_, sleeptime) buzzer = ActorBuzzer(15) def tempAlarm(*args, **kwargs): print("HIGH TEMPERATURE: %s" % str(kwargs["value"])) buzzer.buzz() obs.addSensor("temp", temperature_threshold, operator.ge, tempAlarm) def flameAlarm(*args, **kwargs):
from light import LightSensor from movement import MovementSensor from morse import convertStrToMorse import RPi.GPIO as GPIO from threading import Thread app = Flask(__name__) socketio = SocketIO(app) #Utilisation d'une norme de nommage pour les broches GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) redLed = Led(18) blueLed = Led(24) buzzer = Buzzer(22) tempSensor = TemperatureSensor('28-01192fa66041') lightSensor = LightSensor(27) @app.route('/') def home(): temp = tempSensor.read_temp() return render_template('home.html', temp=temp) @app.route('/temp') def temp(): temp = tempSensor.read_temp() return str(temp) @app.route('/light') def light():
import ubinascii import time import machine from blink import Blink from temperature import TemperatureSensor from temperature_client import TemperatureClient client_id = ubinascii.hexlify(machine.unique_id()) sensor = TemperatureSensor(5) led = Blink(16) tc = TemperatureClient(client_id, '93.80.147.216', 5, topic='esp/temp') while True: tc.publishTemperature() print(str(time.localtime()) + ' | temp: ' + str(sensor.read_temp())) led.blink(2, 0.2) time.sleep(60)
from flask import Flask from temperature import TemperatureSensor from motion import Motion import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) temperature = TemperatureSensor(14) motion = Motion(17) motion.run() app = Flask(__name__) @app.route("/metrics") def metrics(): temperature_data = "" result = temperature.read() if result.is_valid(): temperature_data = f"""pihome_temperature {result.temperature} pihome_humidity {result.humidity}""" return f"""{temperature_data} pihome_movement {motion.read()}""", 200, { 'Content-Type': 'text/plain; charset=utf-8' } if __name__ == "__main__":
from umqtt.robust import MQTTClient