def get_temprature(what=None): if what == "header": return " Temp." elif what == "unit": return "degreeC" elif what == "text": C = (raw_temperature() - 32) / 1.8 return "{:5.2f}".format(C) else: C = (raw_temperature() - 32) / 1.8
def handleInterrupt(tim): global addr print(esp32.raw_temperature()) print(esp32.hall_sensor()) s = usocket.socket() s.connect(addr) addr = usocket.getaddrinfo('www.thingspeak.com',80)[0][-1] #s = usocket.socket() imfor = "field1="+str(esp32.raw_temperature())+"&field2="+str(esp32.hall_sensor()) s.send(b'GET https://api.thingspeak.com/update?api_key=YO282TSJI25DUDBU&{} HTTP/1.0\r\n\r\n'.format(imfor)) s.close()
def setup(temps, sm): i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21)) lcd = I2cLcd(i2c, 39, 2, 16) lcd.clear() r = RotaryIRQ(18, 19, 0, 10, False) menu = ep_lcd_menu.menu_rot_enc(menu_config_file="menu.json", display_type="1602", display=lcd, rotary=r, button_pin=5) menu.display_funcs = { "print_T_Oven": lambda: "{:.2f} C".format(temps("T_Oven")), "print_T_TankU": lambda: "{:.2f} C".format(temps("T_TankU")), "print_T_TankL": lambda: "{:.2f} C".format(temps("T_TankL")), "print_state": lambda: "{}".format(sm.state), "print_cpu_temp": lambda: "{:.2f} C".format((esp32.raw_temperature() - 32) * 5 / 9), "print_ram": lambda: "{:.1f}/{:.1f}kB".format(gc.mem_free() / 1024, (gc.mem_alloc( ) + gc.mem_free()) / 1024), } menu.load() menu.render() return menu
def sample_sensors(t): # update metrics metric_alloc.set(gc.mem_alloc()) metric_beat.inc(1) metric_cpu.set(machine.freq()) metric_free.set(gc.mem_free()) # sample sensors bme_reading = bme.read_compensated_data() esp_reading = esp32.raw_temperature() stemma_reading = ss.moisture_read() location = config['metric_location'] metric_humidity.labels(location, 'bme280').set(bme_reading[2]) metric_moisture.labels(location, 'stemma').set(stemma_reading) metric_temp.labels(location, 'esp32').set(temp_ftoc(esp_reading)) metric_temp.labels(location, 'bme280').set(bme_reading[0]) metric_temp.labels(location, 'stemma').set(ss.get_temp()) # scale & buffer last reading sl.push(scale(bme_reading[0], 16, 24)) # update display display_moisture = stemma_reading display_temp = bme_reading[0] oled.fill(0x0) sl.draw(oled, 0, 16) oled.text('{:04.2f}'.format(display_temp), 0, 0) oled.text('{:04.2f}'.format(display_moisture), 64, 0) oled.show()
def mqtt_publish(t): client.publish("test/{}/alive".format(mqtt_client_settings["client_id"]), str(alive)) client.publish("test/{}/hall".format(mqtt_client_settings["client_id"]), str(esp32.hall_sensor())) client.publish("test/{}/temp".format(mqtt_client_settings["client_id"]), str((esp32.raw_temperature() - 32) / 1.8))
def draw_temp(oled, x, y): # todo add icon? temp_str = "" #temp_str += "TEMP:" temp_str += "{0:3d}".format(esp32.raw_temperature()) temp_str += "F" draw_text(oled, temp_str, x, y)
def timerEvent(): #print("Timer Event") global _cmd if _cmd > 0: values = bytearray([_cmd]) uart.write(values) _cmd = 0 return if len(websocketList) > 0: dict = {} ret = _readuart(0x89, dict) ret = _readuart(0x8b, dict) ret = _readuart(0x8a, dict) dict['internal'] = round((esp32.raw_temperature() - 32) * 5 / 9, 1) # Read ESP32 internal temp try: dict['time'] = rtc.datetime() # Record current time except: dict['time'] = "0" dictfirst = dict["first"] dictsecond = dict["second"] if dictfirst["mode"] == "Diode": if dictfirst["realvalue"] > 3.1: dictsecond["value"] = "open" else: dictsecond["value"] = "shrt" for i, webSocket in enumerate(websocketList): webSocket.SendText("" + json.dumps(dict))
def thingspeak(): int_temp = esp32.raw_temperature() hall_val = esp32.hall_sensor() print() print("Internal Temperature: " + str(int_temp) + " Degrees Fahrenheit") print("Hall: " + str(hall_val)) #send temperature info s = socket.socket() address = socket.getaddrinfo("thingspeak.com", 80)[0][-1] s.connect(address) s.send( b"GET https://api.thingspeak.com/update?api_key=0P5Y117MOWZABDHV&field1=" + str(int_temp) + " HTTP/1.0\r\n\r\n") s.close() time.sleep(18) #send hall info s = socket.socket() address = socket.getaddrinfo("thingspeak.com", 80)[0][-1] s.connect(address) s.send( "GET https://api.thingspeak.com/update?api_key=0P5Y117MOWZABDHV&field2=" + str(hall_val) + " HTTP/1.0\r\n\r\n") s.close()
def raw_temp(): import esp32 raw = str(esp32.raw_temperature()) rtemp = ("CPU Temp: " + raw + "F") # print(rtemp) rrr = rtemp return rrr
def get_data_ESP32(): # Get Temperature of the ESP itself and convert to Celsius temp_core = (esp32.raw_temperature() - 32) / 1.8 print('Temperature in Core in Celsius') print(temp_core) return temp_core
def read_cpu_temp(): tc = 0 try: tf = esp32.raw_temperature() tc = (tf - 32.0) / 1.8 except: tc = 0 return tc
def read(self): self.current_count += 1 if self.current_count >= self.sleep_count: self.current_count = 0 self.triggered = False f = esp32.raw_temperature() c = (f - 32) / 1.8 return c
def button_pressed(): iotine.publish([{ "name": "CORE_TEMP_ESP", "value": esp32.raw_temperature() }, { "name": "CORE_HALL", "value": esp32.hall_sensor() }], on_pub)
def info(): # Get and display Info # SCREEN 2 ip = "Wifi Off" mfreq = str(machine.freq()) raw = str(esp32.raw_temperature()) gfx.text_long("Info", "", ip, "CPU temp = " + raw + "F", "", mfreq, "", "") gc.collect()
def cpu_temp() -> float: "read internal ESP32 CPU temperature in Celsius" try: tf = esp32.raw_temperature() tc = (tf - 32.0) / 1.8 except OSError: tc = -1 # print("T = {0:4d} deg F or {1:5.1f} deg C".format(tf,tc)) return tc
def _httpHandlerTempGet(httpClient, httpResponse): temp = (esp32.raw_temperature() - 32) * 5.0 / 9.0 httpResponse.WriteResponseOk(headers=({ 'Cache-Control': 'no-cache' }), contentType='text/html', contentCharset='UTF-8', content="Temperatur = {}".format(temp))
def _httpHandlerSensors(httpClient, httpResponse): data = 'Hall: {0:.1f} <br> CPU: {1:.1f}°C'.format( esp32.hall_sensor(), esp32.raw_temperature()) # es funktionieren keine \n im string. httpResponse.WriteResponseOk(headers=({ 'Cache-Control': 'no-cache' }), contentType='text/event-stream', contentCharset='UTF-8', content='data: {0}\n\n'.format(data))
def pub_sys(): global f_pub_sys if (time.time() - f_pub_sys) > 300: sys = {} sys["freeMem"] = gc.mem_free() sys["uptime"] = time.time() sys["temp"] = "{:.1f}".format((esp32.raw_temperature() - 32) * 5 / 9) sys["rssi"] = station.status('rssi') pub(b'/sys', ujson.dumps(sys), True) f_pub_sys = time.time()
def hardDispTime(timer): t = esp32.raw_temperature() h = esp32.hall_sensor() print("temperature (°F): " + str(t)) print("hall sensor: " + str(h)) base_url = 'https://api.thingspeak.com/update' API_key = '?api_key=R1N8YAFNXLY6MMWM' fieldanddata = "&field1=" + str(t) + "&field2=" + str(h) url = base_url + API_key + fieldanddata http_get(url)
def raw_temperature(self): import esp32 value = 0 while True: new_value = esp32.raw_temperature() if new_value != value: print(new_value) value = new_value time.sleep(0.1)
def send_sensor_values_mqtt(): # send cpu temperature mqtt.publish('cpu_temp', str(esp32.raw_temperature())) # send hall_sensor mqtt.publish('hall_sensor', str(esp32.hall_sensor())) #send bme280 values mqtt.publish('temperature', str(bme.temperature_float)) mqtt.publish('humidity', str(bme.humidity_float)) mqtt.publish('pressure', str(bme.pressure_float)) #analog tmp sensor mqtt.publish('analog_tmp', str(tmp_sensor.read())) mqtt.publish('ip_address', str(wifi.get_ip()))
def getdata(counter, flag): if (counter < 30) & (flag == 1): temp = esp32.raw_temperature() hall = esp32.hall_sensor() print('Hall:'+str(hall), 'Temperature:'+str(temp)) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockaddr = socket.getaddrinfo('api.thingspeak.com', 80)[0][-1] sock.connect(sockaddr) sock.sendall("GET https://api.thingspeak.com/update?api_key=4XEMEDRHEKUNEHHQ&field1="+str(temp)+"&field2="+str(hall)+"HTTP/1.0\r\n\r\n") sock.recv(1024) sock.close() elif(counter == 30): flag = 0
def btn_callback(p): if (display.menu_page == 0): display.write('Temp: ' + bme.temperature, 'Humidity: ' + bme.humidity, 'Pressure: ' + bme.pressure) display.next_page() elif (display.menu_page == 1): display.write('Internal', 'IP:' + wifi.get_ip(), 'Hall:' + str(esp32.hall_sensor()), 'CPU:' + str(esp32.raw_temperature())) display.next_page() elif (display.menu_page == 2): display.write('last page') display.wrap()
def fullSend(counter): temperature = str(esp32.raw_temperature()) hall_sensor = str(esp32.hall_sensor()) print("Temperature is " + temperature) print("Hall is " + hall_sensor) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) address = socket.getaddrinfo('api.thingspeak.com', 80)[0][-1] s.connect(address) s.send( "GET http://api.thingspeak.com/update?api_key=3VDFM8XC3RT41CEJ&field1=" + temperature + "&field2=" + hall_sensor + "HTTP/1.0\r\n\r\n") counter += 1 print(s.recv(1024)) s.close()
def display_info(self): gc.collect() output = dict( freq=int(machine.freq() / 1_000_000), flash=esp.flash_size(), hall=esp32.hall_sensor(), temp=int((esp32.raw_temperature() - 32) / 1.8), mac=self.network.mac, ip=self.network.ip, ram=gc.mem_free(), ) output = ["%s: %s" % (key, val) for key, val in output.items()] self.screen.display_lines(output)
def measure(): HALL = esp32.hall_sensor() TEMP = esp32.raw_temperature() print("Temp: " + str(TEMP)) print("Hall: " + str(HALL)) api_key = 'F1Z7M4ES4TCB1UFO' host = 'api.thingspeak.com' path = 'update?api_key=' + api_key + '&field1=' + str(TEMP) + '&field2=' + str(HALL) try: addr = socket.getaddrinfo(host, 80)[0][-1] s = socket.socket() s.connect(addr) s.send(bytes('GET /' + path + ' HTTP/1.0\r\n\r\n', 'utf8')) s.close() sleep(0.1) except Exception as e: # Here it catches any error. print(e)
def main(): # setup sensors bus = machine.I2C(scl=machine.Pin(16), sda=machine.Pin(13)) bme = BME280(i2c=bus) # setup storage card = machine.SDCard() os.mount(card, '/card') # setup networking config = load_config('/card', 'config.yml') eth = start_network(config) # setup Prometheus metrics registry = CollectorRegistry(namespace='prometheus_express') metric_c = Counter('system_heartbeat', 'system heartbeat counter', labels=['location'], registry=registry) metric_g = Gauge('sensor_temperature', 'temperature data from the sensors', labels=['location', 'sensor'], registry=registry) router = Router() router.register('GET', '/metrics', registry.handler) server = False # wait for incoming connection while True: while not server: time.sleep(1) server = bind(eth, config) location = config['metric_location'] metric_c.labels(location).inc(1) metric_g.labels(location, 'esp32').set(temp_ftoc(esp32.raw_temperature())) metric_g.labels(location, 'bme280').set(bme.read_compensated_data()[0]) try: server.accept(router) except OSError as err: print('Error accepting request: {}'.format(err)) except ValueError as err: print('Error parsing request: {}'.format(err))
async def sys_monitor(): row1 = "4. System monitor" row1_colour = 'black' row2 = "Uptime: %s" % (time() - net.startup_time) row2_colour = 'blue' row3 = "Mem free: %s" % gc.mem_free() row3_colour = 'blue' row4 = "Mem allocated: %s" % gc.mem_alloc() row4_colour = 'blue' row5 = "Flash size: %s " % esp.flash_size() row5_colour = 'blue' row6 = "MCU Temp: %sC" % ("{:.1f}".format(((float(esp32.raw_temperature())-32.0) * 5/9))) row6_colour = 'blue' row7 = "Hall sensor %s" % esp32.hall_sensor() row7_colour = 'blue' rows = row1, row2, row3, row4, row5, row6, row7 row_colours = row1_colour, row2_colour, row3_colour, row4_colour, row5_colour, row6_colour, row7_colour return rows, row_colours
def send_data(timer): html = """ POST /update HTTP/1.1 Host: api.thingspeak.com Connection: close X-THINGSPEAKAPIKEY: 3ODNWZEY2LM86CTX Content-Type: application/x-www-form-urlencoded Content-Length: %d %s """ temp = esp32.raw_temperature() hall = esp32.hall_sensor() print('Temperature: '+str(temp)+', Hall: '+str(hall)) s = socket.socket() s.connect(addr) s = ssl.wrap_socket(s) data = 'field1=%.2f&field2=%.2f' % (temp, hall) http = html & (len(data), data) s.write(http.encode()) s.close()
async def data_pass(): global d2, d3, d4, d5, d6,d7, auto, t while True: t=ticks_us() d2= int(len(CPM)/2) d3 = d2*0.0057 time = ticks_diff(ticks_ms(),timer)/1000 avg = event/time std = (event**0.5)/time d4 = str(avg)+ " +/- " +str(std) d5 = delta_t d6 = usonic.distance_cm() d7 = (esp32.raw_temperature()-32)*5/9 if config["local"] == "true": try: mqtt_local.publish(b"time",str(time)) mqtt_local.publish(b"total-counts",str(event)) mqtt_local.publish(b"cpm",str(d2)) mqtt_local.publish(b"usv",str(d3)) mqtt_local.publish(b"counting-rate",d4) mqtt_local.publish(b"delta-t",str(d5)) mqtt_local.publish(b"distance",str(d6)) mqtt_local.publish(b"temperature",str(d7)) mqtt_local.publish(b"freq",str(int(freq()/1000000))) except: print("local publish failed") if d2 < 400: await uasyncio.sleep_ms(200) elif d2 < 700: auto = 160000000 await uasyncio.sleep_ms(500) elif d2 < 1500: auto = 240000000 await uasyncio.sleep_ms(800) elif d2 < 2500: await uasyncio.sleep_ms(1000) else: await uasyncio.sleep_ms(2000)