def store_scan(self, scan): # Check if we already did a scan too recently. now = time.time() if (now - self.last_scan_time) < MIN_STORE_TIME: # Nothing to do. return self.last_scan_time = now # Seek to end of file self.data_file.seek(0,2) def store_info(info): # Store binary info. self.data_file.write(info) self.data_file.write(b"\n") store_info(b'machine-' + hex_str(machine.unique_id())) store_info(b'time-%d' % (now, )) if self.reset: store_info(b'reset-%d' % (machine.reset_cause())) self.reset = False for s in scan: bssid = s[1] strength = s[3] store_info(b'ap-%s-%d' % (hex_str(bssid), strength)) store_info(b'eom') # Make sure data are written. self.data_file.flush()
def main(): import utime, array # ESP stuff from machine import Pin, Signal import tphg, pm25 # Version 905 sensors - comment this line for stub.py #import stub # when no sensors are attached. import iot # IOT networking start_time = utime.ticks_ms() # let's track runtime (for measuring current usage) aq = {} id = machine.unique_id() chipId='{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}'.format(id[0], id[1], id[2], id[3], id[4], id[5]) # make each sensor its own group #aq.update(analog.measure()) #aq.update(dht11.measure()) #aq.update(enviro.measure()) #aq.update(ppd42.measure()) #aq.update(tph.measure()) aq.update(tphg.measure()) #aq.update(stub.measure()) # when you only want the MCU and no sensors. # for reasons I can't explain, UART takes time to setup - so do this last? WTF. aq.update(pm25.measure()) iot.init_ap(False) iot.init_sta(True) # Now let's post all iot.io_post(chipId,aq) #iot.io_post({"runtime": ((utime.ticks_ms() - start_time)/1000)}) print("Runtime is:", (utime.ticks_ms() - start_time)/1000) sleep.init(sleep_interval) # see you later!
def mqtt_subscribe(self): client_id = b'tom_' + ubinascii.hexlify(machine.unique_id()) self.mqtt = MQTTClient(client_id, self.config['host'], port=int(self.config['port'])) self.mqtt.set_callback(self.mqtt_callback) self.mqtt.connect() self.mqtt.subscribe(self.config['topic'])
def get_machine_stats(self): import machine import ubinascii id = "0x{}".format(ubinascii.hexlify(machine.unique_id()).decode().upper()) return { 'freq': machine.freq(), 'unique_id': id }
def default_remote_id(): """generate remote id based on machine.unique_id()""" import uhashlib from ustruct import unpack # we compute a hash of board's unique_id, since a boards manufactured # closely together probably share prefix or suffix, and I don't know # which one. we want to avoid accidental remote_id clashes unique_hash = uhashlib.sha256(machine.unique_id()).digest() # and a 4 byte prefix of a sha256 hash is more than enough uint32 = unpack("I", unique_hash[:4])[0] # let's mask it to 26 bits uint26 = uint32 & (2**26 - 1) return uint26
import micropython import network import esp esp.osdebug(None) import gc gc.collect() running = True ssid = 'J_C' password = '******' mqtt_server = 'jcerasmus.ddns.net' #EXAMPLE IP ADDRESS #mqtt_server = '192.168.1.144' mac_string = ubinascii.hexlify(network.WLAN().config('mac'), ':').decode() client_id = ubinascii.hexlify(machine.unique_id()) topic_sub = b'/down/' + mac_string topic_pub = b'/up/' + mac_string print("My MAC is: " + mac_string) last_message = 0 message_interval = 1 station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while station.isconnected() == False: print("We are waiting for WIFI connection")
def generate_key(): id_str = ubinascii.hexlify(machine.unique_id()).decode('utf-8') id_str = id_str * 5 id_str = id_str[:32] return id_str
def get_unique_id(): id = machine.unique_id() id = ("000000" + hex((id[3] << 16) | (id[4] << 8) | id[5])[2:])[-6:] return id
audio.recorder_deinit() def play_wave(freq): global P8 P8 = MPythonPin(8, PinMode.PWM) P8.write_analog(512, freq) def stop_wave(): global P8 P8.pwm.deinit() # MAC id machine_id = ubinascii.hexlify(machine.unique_id()).decode().upper() # a,b按键中断处理函数:蜂鸣器响 def btn_A_irq(_): if button_a.value() == 0: music.pitch(1000) else: music.stop() def btn_B_irq(_): if button_b.value() == 0: music.pitch(1000) else: music.stop()
def uid(): from machine import unique_id from ubinascii import hexlify return hexlify(unique_id()).decode("utf-8").upper()
''' import machine import os from network import WLAN mch = os.uname().machine if not 'LaunchPad' in mch and not'WiPy' in mch: raise Exception('Board not supported!') wifi = WLAN() print(machine) machine.idle() print(machine.freq() == (80000000,)) print(machine.unique_id() == wifi.mac()) machine.main('main.py') rand_nums = [] for i in range(0, 100): rand = machine.rng() if rand not in rand_nums: rand_nums.append(rand) else: print('RNG number repeated') break for i in range(0, 10): machine.idle()
def assemble(self, sensor_period): name = machine.unique_id() assert len(name) == 6 task_num = len(self._tasks) # we have a start-character, '#' start_char = 1 # after that start character, we follow up with the of the # total message. It's the length in one byte, followd by the # XOR of that length. The reason for this verified storage is # that we need a reliable way of syncing after the start-char # to the expected number of bytes message_length = 2 # Then comes the unique ID of the device, 6 bytes name_length = len(name) # After that, the task count and descriptor. The descriptor specifies # the attached sensors/tasks, that all have a specific byte-size. # Each sensor is described as a nibble, with the first in the lowest # nibble of the first byte, second upper nibble, etc. task_count = 1 descriptor_length = task_num // 2 + task_num % 2 # it follows the payload, the size is the accumulated size of # all tasks' storage needs payload_size = sum(buffer_size for _, _, _, buffer_size, _ in self._tasks) # the final checksum is just all bytes so far summed up as uint8_t checksum_size = 1 buffer_size = start_char + message_length + name_length + \ task_count + descriptor_length + \ payload_size + checksum_size name_start = start_char + message_length descriptor_byte_count_offset = start_char + \ message_length + name_length descriptor_start = descriptor_byte_count_offset + task_count payload_start = descriptor_start + descriptor_length if payload_start % 4: padding = 4 - (payload_start % 4) payload_start += padding buffer_size += padding self.buffer = bytearray(buffer_size) self.buffer[0] = ord(b'#') self.buffer[1] = buffer_size self.buffer[2] = 0xff ^ buffer_size self.buffer[name_start:name_start + name_length] = name self.buffer[descriptor_byte_count_offset] = task_num descriptor = memoryview( self.buffer)[descriptor_start:descriptor_start + descriptor_length] newjoy.init(sensor_period, self.buffer) osc_payload_start = task_byte_offset = payload_start for i, (bus, address, task, task_size, busno) in enumerate(self._tasks): self._osc_spec.append(( osc_payload_start, self.TASK_SPEC[task], )) self._osc_descriptor[busno] += self.TASK_ID[task] offset = i // 2 current = descriptor[offset] current |= task << (4 * (i % 2)) descriptor[offset] = current newjoy.add_task(bus, address, task, task_byte_offset) task_byte_offset += task_size osc_payload_start += task_size osc_descriptor = "" for busno, devices in sorted(self._osc_descriptor.items()): if devices: osc_descriptor += "{}{}".format(busno, devices) self._osc_descriptor = osc_descriptor
""" import machine import ubinascii import time import dht from machine import Pin from umqtt.simple import MQTTClient d = dht.DHT11(Pin(2)) config = { 'broker': 'io.adafruit.com', 'user': '******', 'key': '你的AIO KEY', 'id': 'room/' + ubinascii.hexlify(machine.unique_id()).decode(), 'topic_temp': b'poushen/feeds/temperature', 'topic_humi': b'poushen/feeds/humidity' } def publish(topic, data): client = MQTTClient(client_id=config['id'], server=config['broker'], user=config['user'], password=config['key']) client.connect() client.publish(topic, data.encode()) time.sleep(1) client.disconnect()
import machine import ubinascii MY_ID = str(ubinascii.hexlify(machine.unique_id()), 'utf-8') AP_PIN = 35 # ground this pin to activate AP mode on reset CFG_NAME = '_config' # store wifi ssid/pswd and tWeb ip:port TS_NAME = '_timestamp' # timestamp for ntp DATA_FILE = '_data' # measuring storage DATA_LENGTH = 64 # number of records to store CONNECT_WAIT = 10 # wait seconds to connect LVL_PIN = 34 # 220k/220k to power/ground and middle node to check power level LVL_LOWPWR = 1880 # low power level ~= 3.15V LVL_SUNPIN = 33 # Solar battery level pin (33) or None LED_PIN = 5 I2CSCL_PIN = 22 I2CSDA_PIN = 21 I2C_FREQ = 10000 DEEP_SLEEP = 900 # seconds FAKE_SLEEP = 0 # 1 -- no really go to deep sleep (for debug only) NTP_SYNC_PERIOD = DEEP_SLEEP*6 # ntp sync interval POSITIONING = 'YES' # NO -- no positioning # positioning with mg995 servo TZ = 1 # timezone difference with UTC in hours, could be float. NOT SUMMER TIME! AZ_PIN = 25 ALT_PIN = 27
from machine import unique_id from utime import sleep, ticks_ms, ticks_diff def tdiff(): new_semantics = ticks_diff(2, 1) == 1 def func(old, new): nonlocal new_semantics if new_semantics: return ticks_diff(new, old) return ticks_diff(old, new) return func ticksdiff = tdiff() SERVER = "192.168.0.23" CLIENT_ID = ubinascii.hexlify(unique_id()) TOPIC = b"led" QOS = 1 t = 0 maxt = 0 mint = 5000 def sub_cb(topic, msg): global t, maxt, mint dt = ticksdiff(t, ticks_ms()) print('echo received in {} ms'.format(dt)) print((topic, msg)) maxt = max(maxt, dt) mint = min(mint, dt)
client.connect() time.sleep(10) uart = UART(1, 9600, pins=("G28","G22"), timeout_chars=2000) i2c = I2C(0, I2C.MASTER, baudrate=100000) sensor = sht31.SHT31(i2c, addr=0x44) rtc = machine.RTC() rtc.ntp_sync("tw.pool.ntp.org", 3600) sd = SD() os.mount(sd, '/sd') # check the content os.listdir('/sd') # try some standard file operations deviceid = binascii.hexlify(machine.unique_id()) p_out = Pin('P3', mode=Pin.OUT) p_out1 = Pin('P22', mode=Pin.OUT) def axis(): i2c.writeto_mem(29, 0x2A, bytes([0x00])) i2c.writeto_mem(29, 0x2A, bytes([0x01])) i2c.writeto_mem(29, 0x0E, bytes([0x00])) data = i2c.readfrom_mem(29, 0x00, 7) xAccl = (data[1] * 256 + data[2]) / 16 if xAccl > 2047 : xAccl -= 4096 yAccl = (data[3] * 256 + data[4]) / 16 if yAccl > 2047 : yAccl -= 4096
#---End Wifi Config--- from machine import Pin led = Pin(2, Pin.OUT, value=1) #---MQTT Sending--- from time import sleep_ms from ubinascii import hexlify from machine import unique_id #import socket from umqtt import MQTTClient SERVER = "192.168.0.101" CLIENT_ID = hexlify(unique_id()) TOPIC1 = b"/sensor1/tem" TOPIC2 = b"/sensor1/hum" TOPIC3 = b"/sensor1/led" def envioMQTT(server=SERVER, topic="/foo", dato=None): try: c = MQTTClient(CLIENT_ID, server) c.connect() c.publish(topic, dato) sleep_ms(200) c.disconnect() #led.value(1) except Exception as e: pass #led.value(0)
from umqtt.simple import MQTTClient import machine import utime import ubinascii import p9813 from machine import Pin from config import SERVER, COMMAND_TOPIC, STATE_TOPIC, AVAILABILITY_TOPIC LED = machine.Pin(2, machine.Pin.OUT, value=1) CLIENT = None CLIENT_ID = ubinascii.hexlify(machine.unique_id()) pin_clk = Pin(5, Pin.OUT) pin_data = Pin(4, Pin.OUT) num_leds = 1 chain = p9813.P9813(pin_clk, pin_data, num_leds) def new_msg(topic, msg): print("Received {}".format(msg)) if msg == b"on": LED.value(0) chain[0] = (0, 0, 0) chain.write() CLIENT.publish(STATE_TOPIC, "on") elif msg == b"off":
# $Id: MySense.py,v 2.8 2018/05/04 14:55:41 teus Exp teus $ # __version__ = "0." + "$Revision: 2.8 $"[11:-2] __license__ = 'GPLV4' from time import sleep, time from time import localtime, timezone from machine import Pin # user button/led from machine import unique_id import binascii import pycom import struct from micropython import const PyCom = 'PyCom' # identity PyCom SN myID = binascii.hexlify(unique_id()).decode('utf-8') # Turn off hearbeat LED pycom.heartbeat(False) try: from Config import Network except: pass if not Network: raise OSError("No network config found") if Network == 'TTN': PyCom = 'LoPy' try: from Config import dev_eui, app_eui, app_key from lora import LORA lora = None except:
def main(): # Enable automatic garbage collector gc.enable() if machine.reset_cause() == machine.DEEPSLEEP_RESET: print('wake from deep sleep') hard_reset = False else: hard_reset = True print('wake from hard reset') chipid = hexlify(machine.unique_id()) # Read from file the whole configuration config.read_config() # Get WiFi defaults and connect ssid = config.get_config('ssid') pwd = config.get_config('pwd') interface = do_connect(ssid, pwd, network.STA_IF, hard_reset) # Turn on Access Point only with passw apssid = 'YoT-%s' % bytes.decode(chipid) appwd = config.get_config('appwd') if hard_reset: ap_interface = do_connect(apssid, appwd, network.AP_IF) if not interface and not ap_interface: print('Restart 10"') time.sleep(10.0) machine.reset() return # Set Parameters in configuration (address, mask, gateway, dns) = interface.ifconfig() config.set_config('address', address) config.set_config('mask', mask) config.set_config('gateway', gateway) config.set_config('dns', dns) config.set_config('mac', hexlify(interface.config('mac'), ':')) config.set_config('chipid', chipid) # Set Time RTC from ntptime import settime try: settime() (y, m, d, h, mm, s, c, u) = time.localtime() starttime = '%d-%d-%d %d:%d:%d UTC' % (y, m, d, h, mm, s) except: starttime = '2016-01-01 00:00:00' print('Cannot set time') # Set hostname interface.config(dhcp_hostname=chipid) config.set_config('hostname', interface.config('dhcp_hostname')) # We will save new configuration only at powerup if hard_reset: config.set_config('starttime', starttime) config.save_config() # Free some memory ssid = pwd = None apssid = appwd = None address = mask = gateway = dns = None gc.collect() # The application hook from application import application try: application(interface) except KeyboardInterrupt: pass except Exception as e: print(e) # Restart print('Restarting') time.sleep(5.0) machine.reset()
import utime from machine import I2C, Pin, UART, unique_id import neopixel, machine id = unique_id() chipId='{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}'.format(id[0], id[1], id[2], id[3], id[4], id[5]) print('chipId shows: ', chipId) i2c = machine.I2C(scl=Pin(22), sda=Pin(21)) print('i2c bus shows: ', i2c.scan()) uart2=UART(1,rx=26,tx=27,baudrate=9600) uart1=UART(2,rx=0,tx=2,baudrate=9600) utime.sleep(2) print('uart1 shows:', uart1.read(32)) print('uart2 shows:', uart2.read(32)) RED = (255,0,0); GREEN = (0,255,0); BLUE = (0,0,255) colors = [RED, GREEN, BLUE] np = neopixel.NeoPixel(Pin(12), 1) for color in colors: np[0] = color np.write() utime.sleep(1)
""" LoPy LoRaWAN Nano Gateway configuration options """ import machine import ubinascii WIFI_MAC = ubinascii.hexlify(machine.unique_id()).upper() # Set the Gateway ID to be the first 3 bytes of MAC address + 'FFFE' + last 3 bytes of MAC address GATEWAY_ID = WIFI_MAC[:6] + "FFFE" + WIFI_MAC[6:12] SERVER = 'router.eu.thethings.network' PORT = 1700 NTP = "pool.ntp.org" NTP_PERIOD_S = 3600 WIFI_SSID = 'my-wifi' WIFI_PASS = '******' # for EU868 LORA_FREQUENCY = 868100000 LORA_GW_DR = "SF7BW125" # DR_5 LORA_NODE_DR = 5 # for US915 # LORA_FREQUENCY = 903900000 # LORA_GW_DR = "SF7BW125" # DR_3 # LORA_NODE_DR = 3
import machine import ubinascii led = Pin(16, Pin.OUT) msg1 = " " CONFIG = { # Configuration details of the MQTT broker "MQTT_BROKER": "test.mosquitto.org", "USER": "", "PASSWORD": "", "PORT": 1883, "TOPIC": b"test", # unique identifier of the chip "CLIENT_ID": b"esp8266_" + ubinascii.hexlify(machine.unique_id()) } def settimeout(duration): pass station = network.WLAN(network.STA_IF) station.active(True) station.connect("sandeep", "22122012") while (not (station.isconnected())):
def get_machine_stats(self): import machine import ubinascii id = "0x{}".format( ubinascii.hexlify(machine.unique_id()).decode().upper()) return {'freq': machine.freq(), 'unique_id': id}
print("Sending sensor data") result = th.read() while not result.is_valid(): time.sleep(.5) result = th.read() client.publish(topic_pub,'{"fipy_nc_sensor": {"dht temp":' + str(result.temperature) + ',"dht RH":' + str(result.humidity) + '}}') print('Sensor data sent ..') blink_led() client.check_msg() except (NameError, ValueError, TypeError) as err: print('Failed to send!', err) topic_pub = 'nenad/home-sens/' topic_sub = 'nenad/home-sens/control' broker_url = 'sjolab.lnu.se' client_name = ubinascii.hexlify(hashlib.md5(machine.unique_id()).digest()) # create a md5 hash of the pycom WLAN mac print('client_name:',client_name) client = MQTTClient(client_name, broker_url, user=config['user_mqtt'], password=config['pass_mqtt'], keepalive=600) client.set_callback(sub_cb) client.connect() client.subscribe(topic_sub) _thread.start_new_thread(interval_send,[30])
import machine # if there are multiple u2if connected, we must specify its serial number by this command before using it. # Test with your id (use machine_info.py test program to get it) machine.select_interface("0xE66038B713644F31") print('S/N: %s' % machine.unique_id()) print('V/N: %s' % machine.firmware_version())
networkUtils.connectToNetwork(nc.wifi_network, nc.wifi_password) print("Connecting to Mqtt...") client = MQTTClient(client_id=nc.mqtt_client, server=nc.mqtt_server, user=nc.mqtt_user, password=nc.mqtt_password, ssl=False) client.connect() print("Connected") return client # ------ Main script execution starts here ------ gc.collect() client_id = b"receiver_{}".format(ubinascii.hexlify(machine.unique_id())) topic = b'temperature' client = connect() while True: try: client.check_msg() time.sleep(1) except Exception as e: client = connect()
pass print('Network configuration:', sta_if.ifconfig()) # main # connecting to local LAN do_connect() #config mqtt change SERVER, USER, PASSWORD and TOPIC to mach your own data SERVER = "192.168.20.xxx" PORT = 1883 USER = "******" PASSWORD = "******" TOPIC = b'kapgdom/Meteo' # change it to match your desire topic #CLIENT_ID = ubinascii.hexlify(machine.unique_id()) CLIENT_ID = machine.unique_id() keepalive = 60 c = MQTTClient(CLIENT_ID, server=SERVER, port=PORT, user=USER, password=PASSWORD, keepalive=keepalive) ###pinScl = 22 #ESP8266 GPIO5 (D1) ###pinSda = 18 #ESP8266 GPIO4 (D2) addrOled = 60 #0x3c addrBME280 = 118 #0x76 hSize = 64 # display heigh in pixels wSize = 128 # display width in pixels oledIsConnected = False bmeIsConnected = False # initializing I2C bus i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
def get_eui(): id = ubinascii.hexlify(machine.unique_id()).decode() return id #mac2eui(id)
main.py read temperature from ADC pin and publish to mqtt """ import machine import math import network import time import ubinascii import uos from umqtt.simple import MQTTClient motd = "2018-11-24 bbq temperature" broker = 'jarvis' client_id = 'esp8266_'+str(ubinascii.hexlify(machine.unique_id()), 'utf-8') print("client_id = "+client_id) topic = 'strip/' + client_id client = MQTTClient(topic, broker) print("listening to ", broker, " for ", topic) adc = machine.ADC(0) def time_check(): publish("time check") client.check_msg() try: ntptime.settime() except: print(".")
if wifi.is_connected(): # 5.1. Send Specific Gravity data & battery level by MQTT if send_data_to_mqtt: from mqtt_client import MQTT hydrometer_dict = { 'temperature': temp, 'sg': sg, 'plato': plato, 'battery': battery_voltage } mqtt_data = ujson.dumps(hydrometer_dict) client = MQTT(settings) client.publish(mqtt_data) # 5.2. Send Specific Gravity data & battery level to Fermenter ESP32 by HTTP else: machine_id = int.from_bytes(machine.unique_id(), 'big') hydrometer_dict = { 'name': settings.get('apSsid'), 'ID': machine_id, 'temperature': temp, 'angle': tilt, 'battery': battery_voltage, 'fahrenheit': round(temp * 1.8 + 32, 1), 'currentGravity': sg, 'currentPlato': plato, 'batteryLevel': battery_percent, 'updateIntervalMs': int(settings['deepSleepIntervalMs']) } host = settings['fermenterAp']['host'] api = settings['fermenterAp']['api']
import utime print('main.py: Press CTRL+C to drop to REPL...') utime.sleep(3) from machine import reset, deepsleep import mqtt import SparkFun_TMP102 as tmp102 sleep_interval = 20 # Seconds sleep_type = 'normal' # normal or deep # Get Unique Client ID from ubinascii import hexlify from machine import unique_id client_id = hexlify(unique_id()).decode( 'utf-8') # String with Unique Client ID # Get MQTT Broker IP from key_store.db import key_store broker = key_store.get('mqtt_broker') topic = 'devices/' + client_id def main(): # Read Timestamp and Data timestamp = utime.time() # Epoch UTC temperature = round(tmp102.read_temp('F'), 1) # Send Data to MQTT Broker mqtt.publish(broker, topic + '/temp/value', str(temperature))
def mac(): mac=ubinascii.hexlify(machine.unique_id(),':').decode() mac=mac.replace(":","") return(mac)
from Blocky.MQTT import * from Blocky.Indicator import indicator from machine import unique_id, reset from binascii import hexlify import gc from time import sleep_ms from Blocky.Timer import * from ujson import dumps, loads #import uasyncio as asyncio import Blocky.uasyncio as asyncio from Blocky.asyn import cancellable, Cancellable BROKER = 'broker.getblocky.com' CHIP_ID = hexlify(unique_id()).decode('ascii') from machine import Timer, Pin from Blocky.Global import flag_UPCODE class Network: def __init__(self): self.state = 0 self.has_msg = False self.topic = '' self.msg = '' self.message_handlers = {} self.retry = 0 self.echo = [] from json import loads self.config = loads(open('config.json', 'r').read()) self.mqtt = MQTTClient(CHIP_ID, BROKER, 0, CHIP_ID, self.config['auth_key'], 1883) self.sysPrefix = self.config.get('auth_key') + '/sys/' + CHIP_ID + '/'
""" LoPy LoRaWAN Nano Gateway configuration options """ import machine import ubinascii WIFI_MAC = ubinascii.hexlify(machine.unique_id()).upper() # Set the Gateway ID to be the first 3 bytes of MAC address + 'FFFE' + last 3 bytes of MAC address GATEWAY_ID = WIFI_MAC[:6] + "FFFE" + WIFI_MAC[6:12] SERVER = 'lora.campusiot.imag.fr' PORT = 1700 NTP = "pool.ntp.org" NTP_PERIOD_S = 3600 WIFI_SSID = 'campusiot' WIFI_PASS = '******' # for EU868 LORA_FREQUENCY = 868300000 #LORA_FREQUENCY = 868500000 #LORA_FREQUENCY = 868700000 LORA_GW_DR = "SF7BW125" # DR_5 LORA_NODE_DR = 5 # for US915 # LORA_FREQUENCY = 903900000 # LORA_GW_DR = "SF7BW125" # DR_3 # LORA_NODE_DR = 3
# Wireless network WIFI_SSID = "LANCOMBEIA" WIFI_PASS = "******" # Use on-board sensors py = Pysense() mp = MPL3115A2(py, mode=ALTITUDE) # Returns height in meters. mpp = MPL3115A2(py, mode=PRESSURE) # Returns pressure in Pa. si = SI7006A20(py) # Returns temperature in deg C and relative humidity RH lt = LTR329ALS01(py) # Returns blue and red light intensity in lux # li = LIS2HH12(py) # MQTT configuration AIO_SERVER = "mqtt.beia-telemetrie.ro" AIO_PORT = 1883 AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id()) # Can be anything wlan = WLAN(mode=WLAN.STA) wlan.connect(WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to Wifi\n") client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT) client.connect() while True: temperature = mp.temperature() altitude = mp.altitude() pressure = mpp.pressure()
class WebApp: PRODUCT_NAME = "smartsensor" DIR = "./" ID = str(ubinascii.hexlify(machine.unique_id()).decode('utf-8')) RETRIES = 3 BROKER = '192.168.0.103' PORT = 1883 ApCfg = {"ssid": "SmartSensor-" + ID, "pwd": "mato", "ip": "192.168.0.200"} Time = None NetCon = None WebserverInterval = const(1) WebpageTitle = "SmartSensor - WiFi instellingen" Webpage = """<html><head> <title>""" + WebpageTitle + """</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="data:,"> <style>html{font-family: Helvetica; display:inline-block; margin: 0px auto; text-align: center;} h1{color: #0F3376; padding: 2vh;}p{font-size: 1.5rem;}.button{display: inline-block; background-color: #e7bd3b; border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;} .button2{background-color: #4286f4;} </style> </head> <body> <h1>""" + WebpageTitle + """</h1> <h2>Sensor ID: """ + ID + """</h2> <form action="/wifi_settings.php"> Netwerk naam (SSID): <input type="text" name="ssid" value=""><br> Wachtwoord: <input type="password" name="pwd" value=""><br> <input type="submit" value="Opslaan"> </form> </body> </html>""" Ssid = None Pwd = None def __init__(self, netcon_obj): # Create objects. self.Time = SystemTime.InstanceGet() WebApp.NetCon = netcon_obj self.Scheduler = ServiceScheduler() def Setup(self): # Create LED driver instances. self.LedRed = Led(Pins.CFG_HW_PIN_LED_RED) self.LedGreen = Led(Pins.CFG_HW_PIN_LED_GREEN) self.LedBlue = Led(Pins.CFG_HW_PIN_LED_BLUE) wlan_ap = WLAN(network.AP_IF) self.NetCon.WlanInterface(wlan_ap, NetCon.MODE_ACCESS_POINT) self.Webserver = Webserver(self.Webpage) self.Webserver.RegisterQueryHandle('ssid', WebApp.QueryHandleWifiSsid) self.Webserver.RegisterQueryHandle('pwd', WebApp.QueryHandleWifiPwd) self.Webserver.SvcDependencies( {self.NetCon: Service.DEP_TYPE_RUN_ALWAYS_BEFORE_INIT}) self.Scheduler.ServiceRegister(self.NetCon) self.Scheduler.ServiceRegister(self.Webserver) self.Webserver.SvcIntervalSet(self.WebserverInterval) def Reset(self): return def Run(self): self.Scheduler.Run() @staticmethod def QueryHandleWifiSsid(query, value): print("{}:{}".format(query, value)) WebApp.Ssid = value if WebApp.Pwd is not None: WebApp.SaveAndReset() @staticmethod def QueryHandleWifiPwd(query, value): print("{}:{}".format(query, value)) WebApp.Pwd = value if WebApp.Ssid is not None: WebApp.SaveAndReset() @staticmethod def SaveAndReset(): WebApp.NetCon.StationSettingsStore(WebApp.Ssid, WebApp.Pwd) WebApp.NetCon.AccessPointStop() utime.sleep(1) machine.reset()
import machine import time import network import socket import ubinascii import json from umqtt.robust import MQTTClient NETWORK_CONNECT_TIMEOUT = 60 #seconds DEV_ID = "uPy-{0}".format( ubinascii.hexlify(machine.unique_id()).decode('utf-8')) # TODO implement settings file for WIFI, MQTT etc. # enable settings edit after reset button pressed # you can put multiple networks here, # device will try to connect to reachable ones MY_NETS = { #"your_net1": "password1", #"your_net2": "password2", } print("sleep at the beginning...") time.sleep(1) led = machine.Pin(2, machine.Pin.OUT, value=1) led.low() # blue led on ESP8266 module is reversed mqtt_server = "10.0.0.17" # your MQTT server topic = "/socket/uPy/" + DEV_ID # button needs to be pulled down with 1kR
str(voc) + ',"bmp P":' + str(bmp_P) + ',"bmp temp":' + str(bmp_T) + ',"dht temp":' + str(dht_T) + ',"dht RH":' + str(dht_RH) + '}}') print('Sensor data sent ..') blink_led() except (NameError, ValueError, TypeError): print('Failed to send!') # topic = 'testtopic7891/1' # broker_url = 'broker.hivemq.com' # HiveMQ can be used for testing, open broker topic_pub = 'devices/office-sens/' topic_sub = 'devices/office-sens/control' broker_url = 'sjolab.lnu.se' client_name = ubinascii.hexlify(hashlib.md5( machine.unique_id()).digest()) # create a md5 hash of the pycom WLAN mac c = MQTTClient(client_name, broker_url, user=config['user_mqtt'], password=config['pass_mqtt']) c.set_callback(sub_cb) c.connect() c.subscribe(topic_sub) # not used at the moment in this code. But - if you want to have something sent # back to the device run this function in a loop (or in a thread) # def listen_command(): # while True: # if True:
def get_machine_guid(): return hexlify(unique_id())
# single led rgb handler import wifi import machine from machine import Pin, PWM import time import ubinascii from umqtt.simple import MQTTClient import config # make unique config.mqtt_client_id += b"_" + ubinascii.hexlify(machine.unique_id()) state_topic = config.mqtt_topic + b"/status" command_topic = config.mqtt_topic + b"/set" brightness_state_topic = config.mqtt_topic + b'/brightness/status' brightness_command_topic = config.mqtt_topic + b'/brightness/set' rgb_state_topic = config.mqtt_topic + b'/rgb/status' rgb_command_topic = config.mqtt_topic + b'/rgb/set' light_is_on = False brightness = 0 last_rgb = (0, 0, 0) current_rgb = (0, 0, 0) green_pin = PWM(Pin(2)) red_pin = PWM(Pin(0)) blue_pin = PWM(Pin(4)) OVERFLOW = 1000
import time from umqtt.simple import MQTTClient import json import ubinascii import machine client_id = 'esp8266-light' + ubinascii.hexlify( machine.unique_id()).decode('utf-8') esp8266_set = "home/controller/woonkamer/gordijn_lang" command_topic = 'home/woonkamer/gordijn_lang/set' state_topic = 'home/woonkamer/gordijn_lang' mqtt_server_ip = '192.168.1.10' mqtt_server_port = 1883 retries = 0 max_retries = 86400 # one day class led_pwm(): def __init__(self, pin): if pin not in ( 0, 2, 4, 5, 12, 13, 14, 15, ): raise ValueError("pin must be 0, 2, 4, 5, 12, 13, 14, or 15")
from mqtt import MQTTClient import machine import time import ubinascii from machine import Timer CLIENT_ID = ubinascii.hexlify(machine.unique_id()) SERVER = "test.mosquitto.org" #SERVER = "broker.hivemq.org" PORT = 1883 def push_heartbeat(): c_mqtt.connect() c_mqtt.publish(b"mhermans/heartbeat", b'1') c_mqtt.disconnect() global c_mqtt c_mqtt = MQTTClient(client_id = CLIENT_ID, server = SERVER, port = PORT) while True: c_mqtt.check_msg() # main loop # pub: heartbeat every 5sec. # sub: print every msg immediatly
import network # For WiFI connection from robust import MQTTClient from ubinascii import hexlify from machine import unique_id # Change the file names from where to read configuration parameters AP_FILENAME = "ap.txt" WIFI_FILENAME = "wifi.txt" MQTT_FILENAME = "mqtt.txt" info = None ID = hexlify(unique_id()) AP = network.WLAN(network.AP_IF) wlan = network.WLAN(network.STA_IF) mqttActive = False def readFile(filename): f = open(filename, 'r') text = f.read().split('\r\n') f.close() info = {} for i in text: if len(i) > 0 and i[0] != '#': info[i.split('=')[0]] = i.split('=')[1] return info # Reads configuration parameteres from a text file and sets the access point accordingly. # Bool arg, to turn off or on.