def send_mqtt_data(self): ''' Collects all sensors, and sends MQTT packets for each ''' try: self.sensor.measure() except OSError as tmpex: print(("Unable to read DHT22 sensor: {}".format(tmpex))) data = { 'ipaddr': network.WLAN(network.STA_IF).ifconfig()[0], 'freemem': esp.freemem(), #'voltage': machine.ADC(1).read(), 'timestamp': time.time(), 'time': mytz.mktime() } sensor = { 'temp': "{0:0.2f}".format(self.sensor.temperature()), 'humidity': "{0:0.2f}".format(self.sensor.humidity()) } self.mqttcli.pub(b"segclock/system", json.dumps(data)) self.mqttcli.pub(b"segclock/sensor", json.dumps(sensor)) return
def get_esp_stats(self): import esp return { 'flash_id': esp.flash_id(), 'flash_size': esp.flash_size(), 'free_mem': esp.freemem() }
def printl(self, outstring): rtc = RTC() timeNow = rtc.datetime() __currHour = timeNow[4] __currMinute = timeNow[5] self.__getip__() if self.__logto == 0: outbuffer = '[' outbuffer += '\'' + str(__currHour) + ':' + str( __currMinute) + '\', ' outbuffer += '\'' + self.__deviceid + '\', ' outbuffer += '\'' + self.__ip + '\', ' outbuffer += '\'' + str(self.__rssi) + '\', ' outbuffer += '\'' + str(esp.freemem()) + '\', ' outbuffer += '\'' + outstring + '\', ' outbuffer += ']\n' f = uio.open("tank.log", "a", encoding="utf-8") f.write(outbuffer) f.close() else: # api.add_resource(LogEvents, # '/logEvent/<string:sensorId>/<string:sensorIp>/<string:rssi>/<string:freemem>/<string:logtext>') url = self.__resthost + "/logEvent/{0}/{1}/{2}/{3}/{4}" url = url.replace('{0}', self.__deviceid) url = url.replace('{1}', self.__ip) url = url.replace('{2}', str(self.__rssi)) url = url.replace('{3}', str(esp.freemem())) url = url.replace('{4}', outstring.replace(' ', '_')) print(url) try: response = urequests.get(url) response.close() except: print('Fail www connect...')
def sysinfo(): ''' Returns dict of some system info ''' calib_add_mV = 308 mV = machine.ADC(1).read() + calib_add_mV voltage = "{0:0.2f}".format(mV / 1000.0) sysinfo = { 'ipaddr': network.WLAN(network.STA_IF).ifconfig()[0], 'freemem': esp.freemem(), 'voltage': voltage, } return sysinfo
# This file is executed on every boot (including wake-boot from deepsleep) # import sys import esp #esp.osdebug(None) import uos, machine # uos.dupterm(None, 1) # disable REPL on UART(0) import gc # import webrepl # webrepl.start() gc.collect() sys.path.append('/main') reasons = { 0: "Power On Reset", 1: "Watchdog Timer Reset", 4: "Soft Reset", 5: "Deepsleep Reset", 6: "Hard Reset" } # print ("Machine id: " + hex(machine.unique_id()) ) print("") print(uos.uname().machine) print("Running verson: " + uos.uname().version) print("Reason for reset: " + reasons.get(machine.reset_cause())) print("Flash size: " + str(esp.flash_size())) print("Free memory: " + str(esp.freemem())) import app
password=settings["mqttapikey"], port=1883) while True: print("connecting to wifi") if sta.isconnected(): print("connected!") c.connect() print("mqtt connected!") break time.sleep(1) time.sleep(5) counter = 0 while True: blink() #print("BME1", bme1.values) #print("BME2", bme2.values) rv1 = bme1.values rv2 = bme2.values t1 = ctof(float(rv1[0][:-1])) t2 = ctof(float(rv2[0][:-1])) h1 = float(rv1[2][:-1]) h2 = float(rv2[2][:-1]) payload = bytes( "field1={:.1f}&field2={:.1f}&field3={:.1f}&field4={:.1f}&field5={:d}&field6={:d}\n" .format(t1, t2, h1, h2, get_rssi(), esp.freemem()), 'utf-8') c.publish(credentials, payload) counter += 1 time.sleep(MEASR_DELAY)
return None def ctof(t): return t * (9 / 5) + 32 f = open("settings.json") raw_settings = "".join(f.readlines()) f.close() settings = json.loads(raw_settings) sta = network.WLAN(network.STA_IF) sta.active(True) sta.connect(settings["network"], settings["password"]) c = MQTTClient(settings["name"], settings["broker"]) while True: if sta.isconnected(): c.connect() break time.sleep(1) counter = 0 while True: d.measure() blink() c.publish(settings["topic"], "Blinked! Free mem: {}, Count: {}, Temp: {}, RH: {}, RSSI: {}".format(esp.freemem(), counter, ctof(d.temperature()), d.humidity(), get_rssi())) counter += 1 time.sleep(MEASR_DELAY)
if scan_state == 'on': tim.init(period=scan_rate, callback=Scan_callback) if scan_state == 'off': tim.deinit() ## print('Inicio de medicion') #print(ATTR_txt) #c.publish(attributes, ATTR_txt) print("Suscribirse a TOPIC") c.subscribe(attributes) print(attributes) pin_EN.on() print("memoria libre ANTES: " + str(esp.freemem())) print("Abrir socket") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(1) while True: utime.sleep_ms(1) global APS conn, addr = s.accept() print("memoria libre: " + str(esp.freemem())) form_data = [[0, 0], [0, 0], [0, 0]] print('Got a connection from %s' % str(addr)) request = conn.recv(1024) request = str(request) request = request.split()
def routine(self): msg = self.read() if msg is not None: msg = msg.decode("utf-8") items = msg.split(" ") cmd = items[0] if cmd == "Question": self.write(cmd + " Answer") print("Q A") else: self.write(str(self.address) + "; time: %d; freemem: %d" % (time.ticks_ms(), esp.freemem()))
def status(remote=False, evt=0): import net from esp import freemem from machine import freq as cpufreq import gc s_evts = ['auto', 'BOOTUP', 'REQUEST', 'RESPONSE', 'reconnect'] m_reset = [ 'POWERON', 'WATCHDOG', 'CRASH?', 'BADCRASH?', 'DEEPSLEEP', 'DEEPSLEEP_RESET', 'HARD_RESET' ] m_cust = ['reconnect'] # -1 try: # but wha if u hav both up.. if (not type(evt) == int) or (evt <= 0 or evt >= len(s_evts)): evt = 4 except: print("WTF") ifc = net.sta.ifconfig() mem = str(freemem()) cpufreq = str(cpufreq() / (10**6)) + 'Mhz' mac = net.sta.config('mac') stats = { 'host': cfg.hostname, 'up': uptime(), 'cpufreq': cpufreq, 'mem': mem, 'mem_alloc': gc.mem_alloc(), 'mem_free': gc.mem_free(), 'gc': gc.isenabled(), 'ip': ifc[0], 'mac': net.prmac(mac), 'dns': ifc[3], 'gw': ifc[2], 'phy': net.phymode(), 'essid': net.sta.config('essid'), 'rssi': net.sta.status('rssi'), 'event': s_evts[evt], } if evt == 1: from machine import reset_cause cause = reset_cause() if cause in m_reset: stats['RESET_CAUSE'] = '%d(%s)' % (cause, m_reset[cause]) else: stats['RESET_CAUSE'] = cause del reset_cause if remote: # in [1,2]: if remote == 2: print(stats) try: from mqtt import pub pub('/sys/%s' % cfg.hostname, stats) # wow. except Exception as e: print('stats/mqtt: %s' % e) finally: del pub else: return (stats)
#print(ATTR_txt) #c.publish(attributes, ATTR_txt) print("Suscribirse a TOPIC") c.subscribe(attributes) print(attributes) pin_EN.on() print("Abrir socket") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(1) while True: print(esp.freemem()) utime.sleep_ms(1) global APS conn, addr = s.accept() print("memoria libre") print(esp.freemem()) form_data = [[0, 0], [0, 0], [0, 0]] print('Got a connection from %s' % str(addr)) request = conn.recv(1024) request = str(request) request = request.split() print(request) request = request[1].split("?") print(request[0]) if request[0] == '/': print("HOME")