def test(spi=3, cs='PB0'): print("SPI flash") cs = Pin(cs, Pin.OUT) spi = SPI(spi, baudrate=42000000, polarity=0, phase=0) flash = SPIFlash(spi, cs) print("Getting chip ID...") flash.wait() id_ = flash.getid() print("ID:", ubinascii.hexlify(id_)) print("Reading block (32b) from address 0...") buf = bytearray(32) flash.read_block(0, buf) print(ubinascii.hexlify(buf)) addr = 12 * 600 + 8 print("Reading block (32b) from address {}...".format(addr)) flash.read_block(addr, buf) print(ubinascii.hexlify(buf)) addr = 524288 print("Erasing 4k block at address {}...".format(addr)) t1 = ticks_us() flash.erase(addr, '4k') # flash.erase(addr, '32k') # flash.erase(addr, '64k') # flash.erase_chip() t = ticks_diff(ticks_us(), t1) print("erase {} us".format(t)) print("Writing blocks (256b) at address {}...".format(addr)) buf = bytearray(range(256)) t1 = ticks_us() flash.write_block(addr, buf) t = ticks_diff(ticks_us(), t1) mbs = len(buf) * 8. / t print("write({}) {} us, {} mbs".format(len(buf), t, mbs)) print("Verifying write...") v = bytearray(256) flash.read_block(addr, v) if (v == buf): print("write/read ok") else: print("write/read FAILed") print("Timing 32k read from address 0...") gc.collect() buf = bytearray(32 * 1024) t1 = ticks_us() flash.read_block(0, buf) t = ticks_diff(ticks_us(), t1) mbs = len(buf) * 8. / t print("read({}) {} us, {} mbs".format(len(buf), t, mbs))
def factory(self): mac = self.interface.config('mac') mac = ubinascii.hexlify(mac).decode('utf-8')[6:] self.save({ 'essid': 'Micropython-{}'.format(mac), 'password': '******' })
def send_file_to_host(src_filename, dst_file, filesize): """Function which runs on the pyboard. Matches up with recv_file_from_remote.""" import sys import ubinascii try: with open(src_filename, 'rb') as src_file: bytes_remaining = filesize if HAS_BUFFER: buf_size = BUFFER_SIZE else: buf_size = BUFFER_SIZE // 2 while bytes_remaining > 0: read_size = min(bytes_remaining, buf_size) buf = src_file.read(read_size) if HAS_BUFFER: sys.stdout.buffer.write(buf) else: sys.stdout.write(ubinascii.hexlify(buf)) bytes_remaining -= read_size # Wait for an ack so we don't get ahead of the remote while True: ch = sys.stdin.read(1) if ch: if ch == '\x06': break # This should only happen if an error occurs sys.stdout.write(ch) return True except: return False
def get(self): ret = {} for prop in ['mac', 'essid', 'hidden', 'authmode']: ret[prop] = self.interface.config(prop) ret['authmode'] = self.authmode[ret['authmode']] ret['mac'] = ubinascii.hexlify(ret['mac']).decode('utf-8') ret['curr'] = self.interface.ifconfig() return ret
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 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(): ret = {} for prop in ['mac', 'dhcp_hostname']: ret[prop] = interface.config(prop) ret['mac'] = ubinascii.hexlify(ret['mac']).decode('utf-8') ret['isconnected'] = interface.isconnected() ret['curr'] = interface.ifconfig() return ret
def cfg(): from sta import model mac = model.interface.config('mac') import ubinascii mac = ubinascii.hexlify(mac).decode('utf-8')[6:] return { 'dhcp_hostname': 'ESP-{}'.format(mac) }
def b16encode(s): """Encode a byte string using Base16. s is the byte string to encode. The encoded byte string is returned. """ if not isinstance(s, bytes_types): raise TypeError("expected bytes, not %s" % s.__class__.__name__) return binascii.hexlify(s).upper()
def wifi(): import ubinascii ap_if = network.WLAN(network.AP_IF) wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect('gogo_mt', 'ilovecpeilovecpe') essid = b"MicroPython-%s" % ubinascii.hexlify(ap_if.config("mac")[-3:]) ap_if.config(essid=essid, authmode=network.AUTH_WPA_WPA2_PSK, password=b"micropythoN")
def get_wlan_config_stats(self, ap): import ubinascii return { 'mac': "0x{}".format(ubinascii.hexlify(ap.config('mac')).decode()), 'essid': ap.config('essid'), 'channel': ap.config('channel'), 'hidden': ap.config('hidden'), 'authmode': self.get_auth_mode(ap.config('authmode')) }
def deal(NumCardsToDeal): #card = 1 for i in range(0, NumCardsToDeal): #SelectedCards.append(random.choice(cards)) NumCards = len(Pack) if 0 < NumCards: # Select a card at random from those left in the pack card = int(ubinascii.hexlify(os.urandom(1)), 16) % NumCards SelectedCards.append(Pack[card]) Pack.remove(Pack[card])
def setsize(size): setsizecommand = [COMMANDSEND, COMMANDEND, VC0706_WRITE_DATA, 0x05, 0x04, 0x01, 0x00, 0x19, size] cmd = ''.join(map(chr, setsizecommand)) print(ubinascii.hexlify(cmd)) VC0706.uart.write(cmd) time.sleep(0.01) reply = VC0706.uart.read(17) print(reply) return True
def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ #h = self._current() #return h.hexdigest() if not self.finished: h = self._current() self.digest_bytes = h.digest() import ubinascii self.hex_bytes = ubinascii.hexlify(self.digest_bytes) del ubinascii self.finished = True return self.hex_bytes
def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. You cannot continue updating the object after calling this function. """ #h = self._current() #return h.digest() if not self.finished: h = self._current() self.digest_bytes = h.digest() import ubinascii self.hex_bytes = ubinascii.hexlify(self.digest_bytes) del ubinascii self.finished = True return self.digest_bytes
def dl(url, debug=False): import uhashlib import ubinascii proto, dummy, host, path = url.split("/", 3) ai = socket.getaddrinfo(host, 80) addr = ai[0][4] s = socket.socket() s.settimeout(10) try: s.connect(addr) s.write(b"GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host)) size = 0 hash = uhashlib.sha1() t = time.ticks_ms() buf = s.read(2000) assert buf, buf if debug: print("initial response:", buf) header, buf = buf.split(b"\r\n\r\n", 1) #print(header) #print(buf) hash.update(buf) size += len(buf) while 1: buf = s.read(1024) if buf == b"": break hash.update(buf) size += len(buf) sys.stdout.write("%dK\r" % (size >> 10)) # sta.active(False) delta = time.ticks_diff(time.ticks_ms(), t) #print() print("Size :", size) print("Speed: %s bytes/s" % (size / delta * 1000)) print("Elapsed: %s" % (delta / 1000)) sha = str(ubinascii.hexlify(hash.digest()), "ascii") print("SHA1 :", sha) return size, sha finally: s.close()
def inspect(f, nbytes=16): import stm import array import ubinascii @micropython.asm_thumb def dummy(): pass if type(f) != type(dummy): raise ValueError('expecting an inline-assembler function') baddr = bytes(array.array('O', [f])) addr = baddr[0] | baddr[1] << 8 | baddr[2] << 16 | baddr[3] << 24 print('function object at: 0x%08x' % addr) print('number of args: %u' % stm.mem32[addr + 4]) code_addr = stm.mem32[addr + 8] print('machine code at: 0x%08x' % code_addr) print('----------') print('import binascii') print("with open('code.bin', 'wb') as f:") import ubinascii hex_str = ubinascii.hexlify(bytearray([stm.mem8[code_addr + i] for i in range(nbytes)])) print(" f.write(binascii.unhexlify(%s))" % hex_str) print('----------')
import machine from umqtt.simple import MQTTClient from ubinascii import hexlify LED = machine.Pin(5, machine.Pin.OUT) CLIENT_ID = hexlify(machine.unique_id()).decode() COMMAND_TOPIC = CLIENT_ID + '/command' def mqtt_cb(topic, msg): print("接收到来自MQTT服务器的消息——topic:{t};message:{m}".format(t=topic, m=msg)) if topic == COMMAND_TOPIC.encode(): if msg == b"ON": LED.value(1) elif msg == b"OFF": LED.value(0) def main(mqtt_broker='test.mosquitto.org', mqtt_port=1883, mqtt_user=None, mqtt_password=None, client_id=None, command_topic=None): global COMMAND_TOPIC, CLIENT_ID if client_id: CLIENT_ID = client_id if command_topic:
from machine import Pin, SPI import time import ubinascii vref = 3.3 cs = Pin(15, Pin.OUT) cs.high() hspi = SPI(1, baudrate=1600000, polarity=0, phase=0) value = bytearray(2) while True: data = bytearray(2) wget = b'\xA0\x00' cs.low() hspi.write(b'\x01') hspi.write(b'\xA0') data = hspi.read(1) # data = hspi.write_readinto(wget, data) cs.high() print(str(int(ubinascii.hexlify(data & b'\x0fff'))*vref/4096)) time.sleep(1) # data = data*vref/4096 # time.sleep(1) # print(str(data & b'\x0fff'))
def checkId(): print("BEACON ID", beaconId) if beaconId != "": if str.encode(beaconId) in dangerAreas: del dangerAreas[str.encode(beaconId)] bluetooth = Bluetooth() bluetooth.start_scan(10) while bluetooth.isscanning(): adv = bluetooth.get_adv() if adv: # try to get the complete name #print(bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)) if (adv.rssi > -63): mfg_data = adv.mac #bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_MANUFACTURER_DATA) if mfg_data: # try to get the manufacturer data (Apple's iBeacon data is sent here) #print(ubinascii.hexlify(mfg_data)) tempIdValue = ubinascii.hexlify( bluetooth.resolve_adv_data( adv.data, Bluetooth.ADV_MANUFACTURER_DATA)) time.sleep(2) print(tempIdValue) if (tempIdValue == str.encode(beaconId)): print("you have arrived", adv.rssi) break else: if ubinascii.hexlify( bluetooth.resolve_adv_data( adv.data, Bluetooth. ADV_MANUFACTURER_DATA)) in dangerAreas: p_out.value(1) #Vibrate the motor time.sleep(2) p_out.value(0) time.sleep(3) if (len(locations) > 0): if (dangerAreas[ubinascii.hexlify( bluetooth.resolve_adv_data( adv.data, Bluetooth. ADV_MANUFACTURER_DATA))] != locations[-1]): locations.append( dangerAreas[ubinascii.hexlify( bluetooth.resolve_adv_data( adv.data, Bluetooth. ADV_MANUFACTURER_DATA))]) print("location: ", locations[-1]) time.sleep(3) break else: locations.append( ubinascii.hexlify( bluetooth.resolve_adv_data( adv.data, Bluetooth. ADV_MANUFACTURER_DATA))) print("location: ", locations[-1]) time.sleep(3) break print("Location size ", len(locations)) print( "Data of danger device", ubinascii.hexlify( bluetooth.resolve_adv_data( adv.data, Bluetooth.ADV_MANUFACTURER_DATA)), " strength ", adv.rssi) else: print( "Data of device", ubinascii.hexlify( bluetooth.resolve_adv_data( adv.data, Bluetooth.ADV_MANUFACTURER_DATA)), " strength ", adv.rssi) else: continue else: print("No beaconId")
wlan = network.WLAN(network.STA_IF) wlan.active(True) network.WLAN(network.AP_IF).active(False) isWifiPreset = wlan.status() != network.STAT_IDLE print('isWifiPreset: ' + str(isWifiPreset)) if isWifiPreset: for i in range(10): needResetWifi = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP).value() == 0 ledPin.value(0) utime.sleep(0.1) ledPin.value(1) utime.sleep(0.1) ID = ubinascii.hexlify( uhashlib.sha256(machine.unique_id() + 'SALTY-SALT').digest()).decode() def normalBoot(): import json import socket global client, doWater, adc, STARTUP_TIME, time, TOPIC_FROM, TOPIC_TO, command_processor, on_message print('Normal start') wlan = network.WLAN(network.STA_IF) while wlan.status() == network.STAT_CONNECTING: print('WIFI STATUS : {0}'.format(wlan.status())) utime.sleep(0.1) adc = machine.ADC(0)
#!/usr/bin/env python # # Copyright (c) 2019, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information # see the Pycom Licence v1.0 document supplied with this file, or # available at https://www.pycom.io/opensource/licensing # """ 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.au.thethings.network' PORT = 1700 NTP = "au.pool.ntp.org" NTP_PERIOD_S = 3600 WIFI_SSID = 'IOT-Network' WIFI_PASS = '******' # for AU915 LORA_FREQUENCY = 916800000 LORA_GW_DR = "SF7BW125" # DR_5 LORA_NODE_DR = 5
t = pyb.micros() - t print ("erase chip",t) print("SPI flash") cs = pyb.Pin('X5') cs.init(pyb.Pin.OUT_PP) cs.high() v = bytearray(4) spi = SPI(1, SPI.MASTER, baudrate=42000000,polarity=0,phase=0) wait() getid() buff = bytearray(32) read_block(0,buff) print (ubinascii.hexlify(buff)) read_block(12*600 +8,buff) # paul's strings filenames print (ubinascii.hexlify(buff)) print (buff) erase('4k',524288) #erase('32k',524288) #erase('64k',524288) #erase_chip() wait() buff = bytearray(256) for i in range(len(buff)): buff[i] = i t1 = pyb.micros() write_block(524288,buff)
from simple_mqtt import MQTTClient import onewire import time,ssd1306 from esp_board import WifiStation from machine import I2C, Pin from ssd1306_gfx import * import machine, ubinascii, gc, json machine.freq(160000000) gc.collect() CLIENT_ID = ubinascii.hexlify(machine.unique_id()) oled = None client = None def sub_cb(topic, msg): global oled print((topic, msg)) _obj = json.loads(msg); oled.fill(0) oled.text('MicroPython', 20, 5) draw_line(oled , 2 , 18, 126, 18) oled.text('ID: {0}'.format(_obj['id']), 10, 25) oled.text('Temp: {0}'.format(_obj['temperature']), 10, 40) if 'humidity' in _obj: oled.text('Humi: {0}'.format(_obj['humidity']), 10, 55) oled.show() def wifi(): global client global CLIENT_ID client = MQTTClient(CLIENT_ID, 'q.emqtt.com') client.set_callback(sub_cb) client.connect()
async def require_confirm_unknown_token(ctx, address_bytes): text = Text("Unknown token", ui.ICON_SEND, ui.ORANGE, new_lines=False) text.normal(ui.GREY, "Contract:", ui.FG) contract_address_hex = "0x" + hexlify(address_bytes).decode() text.mono(*split_data(contract_address_hex)) await require_confirm(ctx, text, ButtonRequestType.SignTx)
from loramesh import Loramesh from Networkmesh import * pycom.wifi_on_boot(False) pycom.heartbeat(False) #wifi = Wifi("HITRON-92B0","pepe4444") #wifi = Wifi("IDEI","lagoenelcielo") #wifi.connect() lora = LoRa(mode=LoRa.LORA, region=LoRa.US915, tx_power=20,bandwidth=LoRa.BW_125KHZ, sf=12) #lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868,frequency = 863000000, bandwidth=LoRa.BW_125KHZ, sf=11) #lora = LoRa(mode=LoRa.LORA, region=LoRa.US915,frequency=903000000,tx_power=19, bandwidth=LoRa.BW_125KHZ, sf=12) MAC = str(ubinascii.hexlify(lora.mac()))[2:-1] print("LoRa MAC: %s"%MAC) #server = Servidor("0.0.0.0",10000) loram = Loramesh(lora) mesh= NetworkMesh(loram,MAC,1) #-------------------------------------------------------------------------------- # waiting until it connected to Mesh network # se queda intentando conectarse y muestra los vecinos mesh.connect() # create UDP socket #creo un socket LoRa mesh.createSocket(1234) # infinite main loop
def get_local_mac(): try: return hexlify(WLAN(0).config("mac"), ":") except NameError: return b"00:00:00:00:00:00"
led.blink(5) credentials = cm.get_attributes('credentials.txt') utime.sleep(.5) led.blink(2) ap_if = network.WLAN(network.AP_IF) utime.sleep(.5) led.blink(3) net = cm.connect() utime.sleep(.5) led.blink(4) mac = ubinascii.hexlify(network.WLAN().config('mac'), ':').decode() utime.sleep(.5) led.blink(5) print('mac') html = """<!DOCTYPE html> <html> <head> <title>ESP8266 Car</title> </head> <center> <h3>Cloudmesh.robot</h3> <h2>ESP8266 Car Test</h2> </center> <form> <table> <tr> <td>LEFT:</td>
import time from umqtt.simple import MQTTClient import ubinascii import machine client_id = 'esp8266-light' + ubinascii.hexlify( machine.unique_id()).decode('utf-8') esp8266_set = "home/controller/woonkamer/tv_lamp" light_set = "home/woonkamer/tv_lamp/set" light_topic = "home/woonkamer/tv_lamp" mqtt_server_ip = '10.0.0.1' mqtt_server_port = 1883 retries = 0 #mqtt reconnect retries max_retries = 86400 #time ## sonoff GPIO pins # PIN 12-----------------replay # PIN 13-----------------LED # PIN 0------------Button class switch(): def __init__(self, pin, topic, set_topic): if pin not in (0, 2, 4, 5, 12, 13, 14, 15, 16): raise ValueError("pin must be 0, 2, 4, 5, 12, 13, 14, 15 or 16") self._relay = machine.Pin(pin, machine.Pin.OUT) self.switch = 'OFF' self.message = self.switch
import machine from machine import Timer from httpse import SimpleHttp from httpse.runner32 import ProcessRuner from httpse.route_system import SystemHandler from httpse.route_led import LedHandler from relay_control import RELAY from mqttse import MQTTClient import ubinascii client_id = b"esp8266_" + ubinascii.hexlify(machine.unique_id()) CONFIG = { "broker": '192.168.2.153', "port": 1883, "sensor_pin": 14, "delay_between_message": -500, "client_id": client_id, "r1_mode": "OFF", "r1_tmax": 20.5, "r1_tmin": 18, "topic": b"devices/" + client_id + "/#", "ping": b"devices/" + client_id + "/ping", "sw1_set": b"devices/" + client_id + "/sw1/set", "sw1_state": b"devices/" + client_id + "/sw1/state", "sw2_set": b"devices/" + client_id + "/sw2/set", "sw2_state": b"devices/" + client_id + "/sw2/state", "DS18B20": b"devices/" + client_id + "/18b20", "t_ctr_r1_mode_set": b"devices/" + client_id + "/t_ctr_r1/mode/set",
lcd.print(b'Testing Heating') heating(RELAY_POLARITY) time.sleep(1) heating(not RELAY_POLARITY) time.sleep(1) print('Testing cooling') lcd.print(b'Testing Cooling') cooling(RELAY_POLARITY) time.sleep(1) cooling(not RELAY_POLARITY) time.sleep(1) print('Starting WiFi') AP_ESSID = b'Beer' + ubinascii.hexlify(wlan.config("mac"))[8:].upper() AP_PASSWD = ubinascii.hexlify(wlan.config("mac"))[:8].upper() wlan.active(True) ap.active(True) ap.config(essid=AP_ESSID, password=AP_PASSWD) print('Initial setup done') def lcd_status(line1, line2): if not heating(): lcd.custom_char(0x00, [0b00100, 0b01110, 0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100]) elif not cooling(): lcd.custom_char(0x00, [0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b11111, 0b01110, 0b00100]) else:
def hexdigest(self): s = ubinascii.hexlify(self.digest()) s.__class__ = str return s
async def confirm_blob( ctx: wire.GenericContext, br_type: str, title: str, data: bytes | str, description: str | None = None, hold: bool = False, br_code: ButtonRequestType = ButtonRequestType.Other, icon: str = ui.ICON_SEND, # TODO cleanup @ redesign icon_color: int = ui.GREEN, # TODO cleanup @ redesign ask_pagination: bool = False, ) -> None: """Confirm data blob. Applicable for public keys, signatures, hashes. In general, any kind of data that is not human-readable, and can be wrapped at any character. For addresses, use `confirm_address`. Displays in monospace font. Paginates automatically. If data is provided as bytes or bytearray, it is converted to hex. """ if isinstance(data, (bytes, bytearray)): data_str = hexlify(data).decode() else: data_str = data span = Span() lines = 0 if description is not None: span.reset(description, 0, ui.NORMAL) lines += span.count_lines() data_lines = (len(data_str) + MONO_HEX_PER_LINE - 1) // MONO_HEX_PER_LINE lines += data_lines if lines <= TEXT_MAX_LINES: text = Text(title, icon, icon_color, new_lines=False) if description is not None: text.normal(description) text.br() # special case: if len(data_str) % 16 == 0: # sanity checks: # (a) we must not exceed MONO_HEX_PER_LINE assert MONO_HEX_PER_LINE > 16 # (b) we must not increase number of lines assert (len(data_str) // 16) <= data_lines # the above holds true for MONO_HEX_PER_LINE == 18 and TEXT_MAX_LINES == 5 per_line = 16 else: per_line = MONO_HEX_PER_LINE text.mono(ui.FG, *chunks_intersperse(data_str, per_line)) content: ui.Layout = HoldToConfirm(text) if hold else Confirm(text) return await raise_if_cancelled( interact(ctx, content, br_type, br_code)) elif ask_pagination: para = [(ui.MONO, line) for line in chunks(data_str, MONO_HEX_PER_LINE - 2)] para_truncated = [] if description is not None: para_truncated.append((ui.NORMAL, description)) para_truncated.extend(para[:TEXT_MAX_LINES]) return await _confirm_ask_pagination(ctx, br_type, title, para, para_truncated, br_code, icon, icon_color) else: para = [] if description is not None: para.append((ui.NORMAL, description)) para.extend((ui.MONO, line) for line in chunks(data_str, MONO_HEX_PER_LINE - 2)) paginated = paginate_paragraphs( para, title, icon, icon_color, confirm=HoldToConfirm if hold else Confirm) return await raise_if_cancelled( interact(ctx, paginated, br_type, br_code))
from umqtt.simple import MQTTClient import ubinascii, machine, time, dht from machine import Pin _dht22 = dht.DHT22(Pin(12)) _broker = '192.168.0.100' _port = 1883 _topic = b'mqtt/report' _msg = b'I am ESP8266' _alias = ubinascii.hexlify(machine.unique_id()) _client = MQTTClient(client_id=_alias, server=_broker, port=_port) _client.connect() try: for i in range(10): _dht22.measure() _t = _dht22.temperature() _h = _dht22.humidity() _msg = 'sta:{},temp:{:.2f},humd:{:.2f}'.format(_alias, _t, _h) _client.publish(_topic, _msg) time.sleep_ms(2000) finally: _client.disconnect()
# coding: utf-8 import config_mqtt if config_mqtt.IS_MICROPYTHON: import machine import ubinascii unique_id = ubinascii.hexlify(machine.unique_id()).decode() WORKER_NAME = 'NodeMCU_' + unique_id # WORKER_NAME = 'n_Lambda' # WORKER_NAME = 'n_Alpha' # WORKER_NAME = 'n_Beta' else: WORKER_NAME = 'Client_366'
# try to find Pybytes Token if include in rcv_data token = "" if rcv_data.startswith(PACK_TOCKEN_PREFIX): x = rcv_data.split(PACK_TOCKEN_SEP.encode()) if len(x)>2: token = x[1] rcv_data = rcv_data[len(PACK_TOCKEN_PREFIX) + len(token) + len(PACK_TOCKEN_SEP):] pkt = 'BR %d B from %s (%s), to %s ( %d): %s'%(len(rcv_data), token, rcv_ip, dest_ip, dest_port, str(rcv_data)) pybytes.send_signal(1, pkt) return pycom.heartbeat(False) lora = LoRa(mode=LoRa.LORA, region= LoRa.EU868) lora_mac = int(str(ubinascii.hexlify(lora.mac()))[2:-1], 16) # read config file, or set default values pymesh_config = PymeshConfig.read_config(lora_mac) #initialize Pymesh pymesh = Pymesh(pymesh_config, new_message_cb) # mac = pymesh.mac() # if mac > 10: # pymesh.end_device(True) # elif mac == 5: # pymesh.leader_priority(255) while not pymesh.is_connected(): print(pymesh.status_str())
def hex_str(s): return str(ubinascii.hexlify(s), 'ascii')
bt.start_scan(-1) except: bt.stop_scan() bt.start_scan(-1) while True: try: adv = bt.get_adv() if adv: data = str(adv.data, "utf-8") data = str(data.split("#")[1][:8], "utf-8") data = ubinascii.a2b_base64(data) temperature = extractTemperature(data) humidity = extractHumidity(data) pressure = extractPressure(data) id = str(ubinascii.hexlify(adv.mac), "utf-8") content = '{"temperature": %s, "humidity": %s, "pressure" : %s, "mac": %s, "timestamp": "%s"}' % ( temperature, humidity, pressure, id, rtc.now()) print(content) sendData.send(host='http://192.168.1.15', port=1338, data=content) pycom.rgbled(0x007f00) # green time.sleep(0.1) pycom.rgbled(0) try: bt.stop_scan() except: print("Error stopping...") time.sleep(60) try: bt.start_scan(-1)
def getid(): cs.low() spi.send(CMD_JEDEC_ID) # id r = spi.recv(3) cs.high() print (ubinascii.hexlify(r))
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(".")
</html>""" return html_webpage station = network.WLAN(network.STA_IF) station.active(True) station.connect("Y2K killed millions", "foogledoogle") # this is my phone's SSID and password while (not station.isconnected()): pass print("Oh Yes! Get Connected") print("Connected to " + str(station.config('essid'))) # prints SSID Y2K killed millions print("MAC Address: " + str( ubinascii.hexlify(station.config('mac'), ':').decode())) # prints MAC address C4:85:08:49:57:37 print("IP Address: " + str(station.ifconfig()[0])) # prints IP address sock = socket.socket() address = socket.getaddrinfo(station.ifconfig()[0], 80)[0][-1] sock.bind(address) sock.listen(4) red_led_state = "ON" gre_led_state = "ON" but1_state = 'OFF' but2_state = 'OFF' while True: connection, address = sock.accept() get_str = connection.recv(1024)
async def confirm_properties( ctx: wire.GenericContext, br_type: str, title: str, props: Sequence[PropertyType], icon: str = ui.ICON_SEND, # TODO cleanup @ redesign icon_color: int = ui.GREEN, # TODO cleanup @ redesign hold: bool = False, br_code: ButtonRequestType = ButtonRequestType.ConfirmOutput, ) -> None: span = Span() para = [] used_lines = 0 for key, val in props: span.reset(key or "", 0, ui.NORMAL, line_width=LINE_WIDTH_PAGINATED) key_lines = span.count_lines() if isinstance(val, str): span.reset(val, 0, ui.BOLD, line_width=LINE_WIDTH_PAGINATED) val_lines = span.count_lines() elif isinstance(val, bytes): val_lines = (len(val) * 2 + MONO_HEX_PER_LINE - 1) // MONO_HEX_PER_LINE else: val_lines = 0 remaining_lines = TEXT_MAX_LINES - used_lines used_lines = (used_lines + key_lines + val_lines) % TEXT_MAX_LINES if key_lines + val_lines > remaining_lines: if remaining_lines <= _SCREEN_FULL_THRESHOLD: # there are only 2 remaining lines, don't try to fit and put everything # on next page para.append(PAGEBREAK) used_lines = (key_lines + val_lines) % TEXT_MAX_LINES elif val_lines > 0 and key_lines >= remaining_lines: # more than 2 remaining lines so try to fit something -- but won't fit # at least one line of value para.append(PAGEBREAK) used_lines = (key_lines + val_lines) % TEXT_MAX_LINES elif key_lines + val_lines <= TEXT_MAX_LINES: # Whole property won't fit to the page, but it will fit on a page # by itself para.append(PAGEBREAK) used_lines = (key_lines + val_lines) % TEXT_MAX_LINES # else: # None of the above. Continue fitting on the same page. if key: para.append((ui.NORMAL, key)) if isinstance(val, bytes): para.extend((ui.MONO, line) for line in chunks( hexlify(val).decode(), MONO_HEX_PER_LINE - 2)) elif isinstance(val, str): para.append((ui.BOLD, val)) content = paginate_paragraphs(para, title, icon, icon_color, confirm=HoldToConfirm if hold else Confirm) await raise_if_cancelled(interact(ctx, content, br_type, br_code))
""" 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
def main(): # get root key from the mnemonic mnemonic = "alien visual jealous source coral memory embark certain radar capable clip edit" seed = bip39.mnemonic_to_seed(mnemonic) root = bip32.HDKey.from_seed(seed, version=NETWORKS["test"]["xprv"]) # get bip84-xpub to import to Bitcoin Core: # we will use the form [fingerprint/derivation]xpub # to import to Bitcoin Core with descriptors # first let's get the root fingerprint # we can get it from any child of the root key fingerprint = root.child(0).fingerprint hardened_derivation = "m/84h/1h/0h" # derive account according to bip84 bip84_xprv = root.derive(hardened_derivation) # corresponding master public key: bip84_xpub = bip84_xprv.to_public() print("[%s%s]%s" % (hexlify(fingerprint).decode('utf-8'), hardened_derivation[1:], bip84_xpub.to_base58())) # parse psbt transaction b64_psbt = "cHNidP8BAHICAAAAAY3LB6teEH6qJHluFYG3AQe8n0HDUcUSEuw2WIJ1ECDUAAAAAAD/////AoDDyQEAAAAAF6kU882+nVMDKGj4rKzjDB6NjyJqSBCHaPMhCgAAAAAWABQUbW8/trQg4d3PKL8WLi2kUa1BqAAAAAAAAQEfAMLrCwAAAAAWABTR6Cr4flM2A0LMGjGiaZ+fhod37SIGAhHf737H1jCUjkJ1K5DqFkaY0keihxeWBQpm1kDtVZyxGLMX7IZUAACAAQAAgAAAAIAAAAAAAAAAAAAAIgIDPtTTi27VFw59jdmWDV8b1YciQzhYGO7m8zB9CvD0brcYsxfshlQAAIABAACAAAAAgAEAAAAAAAAAAA==" # first convert it to binary raw = a2b_base64(b64_psbt) # then parse tx = psbt.PSBT.parse(raw) # print how much we are spending and where total_in = 0 for inp in tx.inputs: total_in += inp.witness_utxo.value print("Inputs:", total_in, "satoshi") change_out = 0 # value that goes back to us send_outputs = [] for i, out in enumerate(tx.outputs): # check if it is a change or not: change = False # should be one or zero for single-key addresses for pub in out.bip32_derivations: # check if it is our key if out.bip32_derivations[pub].fingerprint == fingerprint: hdkey = root.derive(out.bip32_derivations[pub].derivation) mypub = hdkey.key.get_public_key() if mypub != pub: raise ValueError("Derivation path doesn't look right") # now check if provided scriptpubkey matches sc = script.p2wpkh(mypub) if sc == tx.tx.vout[i].script_pubkey: change = True continue if change: change_out += tx.tx.vout[i].value else: send_outputs.append(tx.tx.vout[i]) print("Spending", total_in - change_out, "satoshi") fee = total_in - change_out for out in send_outputs: fee -= out.value print(out.value, "to", out.script_pubkey.address(NETWORKS["test"])) print("Fee:", fee, "satoshi") # sign the transaction tx.sign_with(root) raw = tx.serialize() # convert to base64 b64_psbt = b2a_base64(raw) # somehow b2a ends with \n... if b64_psbt[-1:] == b"\n": b64_psbt = b64_psbt[:-1] # print print("\nSigned transaction:") print(b64_psbt.decode('utf-8'))
print("connecting to network..") wlan.connect(credentials.ESSID, credentials.Password) while not wlan.isconnected(): time.sleep(0.5) print("connected.") relay = machine.Pin(0, machine.Pin.OUT) relay.off() MQTT_CONFIG = { "USER": "", "PASSWORD": "", "PORT": 1883, "TOPIC": b"loggia", # unique identifier of the chip "CLIENT_ID": b"esp8266_" + ubinascii.hexlify(machine.unique_id()) } newMessage = None def onMQTTMessage(topic, msg): global newMessage print("Topic: %s, Message: %s" % (topic, msg)) if msg == b"on": relay.on() elif msg == b"off": relay.off() newMessage = msg def bugreport(text, exception=None):
def get_eui(): id = ubinascii.hexlify(unique_id()).decode() return mac2eui(id)
# Connect to wireless network as client import network wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect("itcollege") # Synchronize clock import ntptime ntptime.settime() # Create a variable for hostname based on MAC address: import ubinascii as binascii name = "esp-%s" % binascii.hexlify(wlan.config("mac")[-3:]).decode("ascii") # Clean up import gc gc.collect()
def get_device_eui(): lora = LoRa(mode=LoRa.LORAWAN) print(ubinascii.hexlify(lora.mac()).upper().decode("utf-8"))
def get_eui(): id = ubinascii.hexlify(machine.unique_id()).decode() return id #mac2eui(id)
def join_request(_sf): global lora global DevEUI global lora_sock global active_tx global active_rx global chrono global my_slot global AppKey global DevNonce global AppSKey rmsg = DevEUI+":"+JoinEUI+":"+str(DevNonce)+":"+str(_sf) pkg = struct.pack(_LORA_PKG_FORMAT % len(rmsg), MY_ID, len(rmsg), rmsg) i = 0 while (i == 0): pycom.rgbled(blue) lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[0], power_mode=LoRa.TX_ONLY, bandwidth=LoRa.BW_125KHZ, sf=12, tx_power=7) start = chrono.read_ms() while(lora.ischannel_free(-90) == False): time.sleep(1) lora_sock.send(pkg) active_tx += chrono.read_ms()-start print("Request sent!", pkg) lora.init(mode=LoRa.LORA, rx_iq=True, region=LoRa.EU868, frequency=freqs[1], power_mode=LoRa.ALWAYS_ON, bandwidth=LoRa.BW_125KHZ, sf=12) start = chrono.read_ms() pycom.rgbled(green) while ((chrono.read_ms() - start) < 5000): recv_pkg = lora_sock.recv(50) if (len(recv_pkg) > 2): recv_pkg_len = recv_pkg[1] recv_pkg_id = recv_pkg[0] if (int(recv_pkg_id) == 1): dev_id, leng, rmsg = struct.unpack(_LORA_RCV_PKG_FORMAT % recv_pkg_len, recv_pkg) print('Device: %d - Pkg: %s' % (dev_id, rmsg)) rmsg = str(rmsg)[2:] rmsg = rmsg[:-1] (dev_id, DevAddr, JoinNonce) = str(rmsg).split(":") if (int(dev_id) == int(MY_ID)): start = -10000 pycom.rgbled(blue) lora.power_mode(LoRa.SLEEP) active_rx += chrono.read_ms()-start i = 1 break if (i == 0): lora.power_mode(LoRa.SLEEP) active_rx += chrono.read_ms()-start random_sleep(5) DevNonce += 1 # AppSKey generation text = "".join( [AppKey[:2], JoinNonce, JoinEUI, str(DevNonce)] ) while (len(str(text)) < 32): text = "".join([str(text),"0"]) encryptor = AES(AppKey, AES.MODE_ECB) AppSKey = encryptor.encrypt(binascii.unhexlify(text)) # slot generation text = "".join([DevAddr, DevEUI]) thash = uhashlib.sha256() thash.update(text) thash = int(ubinascii.hexlify(thash.digest()), 16) my_slot = thash % S print("Slot =", my_slot, "DevAddr = ", DevAddr) print("joining the network lasted (ms):", chrono.read_ms()-join_start) sync()
def getMac(): mac = ubinascii.hexlify(network.WLAN().config('mac')).decode() return mac
# This file is executed on every boot (including wake-boot from deepsleep)
rtc.alarm(rtc.ALARM0, 20000) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) if sta_if.isconnected(): print('WiFi connected!') else: sta_if.connect('WiFi網路ID', 'WiFi密碼') print(sta_if.ifconfig()) config = { 'broker': 'mqtt.thingspeak.com', 'user': '******', 'key': 'JZIYJQEQ5MOF8FE6', 'id': 'room/' + ubinascii.hexlify(machine.unique_id()).decode(), 'topic': b'channels/352801/publish/WMWBJQS44Y5TAH30' } client = MQTTClient(client_id=config['id'], server=config['broker'], user=config['user'], password=config['key']) d = dht.DHT11(Pin(2)) if machine.reset_cause() == machine.DEEPSLEEP_RESET: print('Publish data to ThingSpeak.') d.measure() data = 'field1={}&field2={}'.format(d.temperature(), d.humidity())
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
try: try: import ubinascii as binascii except ImportError: import binascii except ImportError: print("SKIP") raise SystemExit # two arguments supported in uPy but not CPython a = binascii.hexlify(b'123', ':') print(a)
from machine import Pin import micropython import network import json import esp esp.osdebug(None) import dht import gc gc.collect() ssid = 'jabatronic__' password = '******' mqtt_server = '192.168.8.88' #EXAMPLE IP ADDRESS #mqtt_server = '192.168.1.144' client_id = ubinascii.hexlify(machine.unique_id()) topic_sub = b'temp/salon/sync' topic_pub = b'temp/salon' last_message = 0 message_interval = 5 counter = 0 d = {} station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) pindht = Pin(14) ledpin = Pin(2, Pin.OUT) sensor = dht.DHT22(machine.Pin(14))
def wifi(): import ubinascii ap_if = network.WLAN(network.AP_IF) essid = b"MicroPython-%s" % ubinascii.hexlify(ap_if.mac()[-3:]) ap_if.config(essid=essid, authmode=network.AUTH_WPA_WPA2_PSK, password=b"micropythoN")
try: try: import ubinascii as binascii except ImportError: import binascii except ImportError: print("SKIP") raise SystemExit print(binascii.hexlify(b'\x00\x01\x02\x03\x04\x05\x06\x07')) print(binascii.hexlify(b'\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f')) print(binascii.hexlify(b'\x7f\x80\xff')) print(binascii.hexlify(b'1234ABCDabcd'))
def readMemoryBlockChunkHex(addr, length): return ubinascii.hexlify(readMemoryBlockChunk(addr, length)).decode().upper()
def enable_ap_mode(essid=None, password=None): from network import AP_IF, AUTH_WPA_WPA2_PSK, WLAN from ubinascii import hexlify wifi_interface = WLAN(AP_IF) if not essid: essid = b"micropython-esp8266-%s" % hexlify(wifi_interface.config("mac")[-3:]) if not password: password = b'micropybootconfig' wifi_interface.config(essid=essid, authmode=AUTH_WPA_WPA2_PSK, password=password) del hexlify