我在 ESP32 上运行以下 MicroPython 代码:
import network
wlan_sta = network.WLAN(network.STA_IF)
wlan_sta.active(True)
wlan_mac = wlan_sta.config('mac')
print("MAC Address:", wlan_mac) # Show MAC for peering
输出如下所示:
MAC Address: b'0\xae\xa4z\xa7$'
我想以更熟悉的六对十六进制数字的格式显示它,如下所示:
MAC Address: AABBCC112233
在网上寻找解决方案后,我尝试过:
print("MAC Address:", str(wlan_mac))
但显示效果与不使用 str() 时相同
print("MAC Address:", hex(wlan_mac))
但会导致 TypeError: can't conversion bytes to int
print("MAC Address:", wlan_mac.hex())
但它说 AttributeError: 'bytes' 对象没有属性 'hex'
我也对从
wlan_sta.config('mac')
检索到的字节有点怀疑。我本来期望看起来更像 b'\xaa\xbb\xcc\x11\x22\x33'
而不是 b'0\xae\xa4z\xa7$'
。 z 和 $ 对于应该是十六进制的东西来说似乎非常不合适,并且对于应该是六对数字的东西来说似乎太短了。
所以我的问题有两个:
我也对从 wlan_sta.config('mac') 检索到的字节有点怀疑。我本来期望看起来更像 b'\xaa\xbb\xcc\x11\x22\x33' 而不是 b'0\xae\xa4z\xa7$'。 z 和 $ 对于应该是十六进制的东西来说似乎非常不合适,并且对于应该是六对数字的东西来说似乎太短了。
您返回的不是十六进制字符串,而是字节字符串。因此,如果 MAC 地址包含值
7A
,则字节字符串将包含 z
(其 ASCII 值为 122(十六进制 7A
))。
我使用正确的方法获取 MAC 地址吗?
你就是!
如果正确,如何将其格式化为六对十六进制数字?
如果您想将 MAC 地址打印为十六进制字符串,您可以使用
ubinascii.hexlify
方法:
>>> import ubinascii
>>> import network
>>> wlan_sta = network.WLAN(network.STA_IF)
>>> wlan_sta.active(True)
>>> wlan_mac = wlan_sta.config('mac')
>>> print(ubinascii.hexlify(wlan_mac).decode())
30aea47aa724
或者也许:
>>> print(ubinascii.hexlify(wlan_mac).decode().upper())
30AEA47AA724
您可以使用:
def wifi_connect(ssid, pwd):
sta_if = None
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print("connecting to network...")
sta_if.active(True)
sta_if.connect(ssid, pwd)
while not sta_if.isconnected():
pass
print("----------------------------------------")
print("network config:", sta_if.ifconfig())
print("----------------------------------------")
get_my_mac_addr(sta_if)
然后:
def get_my_mac_addr(sta_if):
import ubinascii
import network
wlan_mac = sta_if.config('mac')
my_mac_addr = ubinascii.hexlify(wlan_mac).decode()
my_mac_addr = format_mac_addr(my_mac_addr)
然后:
def format_mac_addr(addr):
mac_addr = addr
mac_addr = mac_addr.upper()
new_mac = ""
for i in range(0, len(mac_addr),2):
#print(mac_addr[i] + mac_addr[i+1])
if (i == len(mac_addr) - 2):
new_mac = new_mac + mac_addr[i] + mac_addr[i+1]
else:
new_mac = new_mac + mac_addr[i] + mac_addr[i+1] + ":"
print("----------------------------------------")
print("My MAC Address:" + new_mac)
print("----------------------------------------")
return new_mac
返回:
----------------------------------------
My MAC Address:xx:xx:xx:xx:xx:xx
----------------------------------------
试试这个功能:
def mac2Str(mac):
return ':'.join([f"{b:02X}" for b in mac])
MAC = b'0\xae\xa4z\xa7$'
print(f"MAC: {MAC} -> {mac2Str(MAC)}")
MAC: b'0\xae\xa4z\xa7$' -> 30:AE:A4:7A:A7:24
使用 MicroPython ESP8266 V1.22.1 版本,就是这么简单:
wlan_sta.config('mac').hex()