本文整理汇总了Python中serial.read方法的典型用法代码示例。如果您正苦于以下问题:Python serial.read方法的具体用法?Python serial.read怎么用?Python serial.read使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类serial
的用法示例。
在下文中一共展示了serial.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: LoadFirmwareImage
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def LoadFirmwareImage(chip, filename):
""" Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images.
Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2).
"""
with open(filename, 'rb') as f:
if chip.lower() == 'esp32':
return ESP32FirmwareImage(f)
else: # Otherwise, ESP8266 so look at magic to determine the image type
magic = ord(f.read(1))
f.seek(0)
if magic == ESPLoader.ESP_IMAGE_MAGIC:
return ESP8266ROMFirmwareImage(f)
elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
return ESP8266V2FirmwareImage(f)
else:
raise FatalError("Invalid image magic number: %d" % magic)
示例2: load_extended_header
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def load_extended_header(self, load_file):
def split_byte(n):
return (n & 0x0F, (n >> 4) & 0x0F)
fields = list(struct.unpack(self.EXTENDED_HEADER_STRUCT_FMT, load_file.read(16)))
self.wp_pin = fields[0]
# SPI pin drive stengths are two per byte
self.clk_drv, self.q_drv = split_byte(fields[1])
self.d_drv, self.cs_drv = split_byte(fields[2])
self.hd_drv, self.wp_drv = split_byte(fields[3])
if fields[15] in [0, 1]:
self.append_digest = (fields[15] == 1)
else:
raise RuntimeError("Invalid value for append_digest field (0x%02x). Should be 0 or 1.", fields[15])
# remaining fields in the middle should all be zero
if any(f for f in fields[4:15] if f != 0):
print("Warning: some reserved header fields have non-zero values. This image may be from a newer esptool.py?")
示例3: _read_elf_file
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def _read_elf_file(self, f):
# read the ELF file header
LEN_FILE_HEADER = 0x34
try:
(ident,_type,machine,_version,
self.entrypoint,_phoff,shoff,_flags,
_ehsize, _phentsize,_phnum, shentsize,
shnum,shstrndx) = struct.unpack("<16sHHLLLLLHHHHHH", f.read(LEN_FILE_HEADER))
except struct.error as e:
raise FatalError("Failed to read a valid ELF header from %s: %s" % (self.name, e))
if byte(ident, 0) != 0x7f or ident[1:4] != b'ELF':
raise FatalError("%s has invalid ELF magic header" % self.name)
if machine != 0x5e:
raise FatalError("%s does not appear to be an Xtensa ELF file. e_machine=%04x" % (self.name, machine))
if shentsize != self.LEN_SEC_HEADER:
raise FatalError("%s has unexpected section header entry size 0x%x (not 0x28)" % (self.name, shentsize, self.LEN_SEC_HEADER))
if shnum == 0:
raise FatalError("%s has 0 section headers" % (self.name))
self._read_sections(f, shoff, shnum, shstrndx)
示例4: expand_file_arguments
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def expand_file_arguments():
""" Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line.
"""
new_args = []
expanded = False
for arg in sys.argv:
if arg.startswith("@"):
expanded = True
with open(arg[1:],"r") as f:
for line in f.readlines():
new_args += shlex.split(line)
else:
new_args.append(arg)
if expanded:
print("esptool.py %s" % (" ".join(new_args[1:])))
sys.argv = new_args
示例5: command
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def command(self, op=None, data=None, chk=0):
if op is not None:
pkt = struct.pack(b'<BBHI', 0x00, op, len(data), chk) + data
self.write(pkt)
# tries to get a response until that response has the
# same operation as the request or a retries limit has
# exceeded. This is needed for some esp8266s that
# reply with more sync responses than expected.
for retry in range(100):
p = self.read()
if len(p) < 8:
continue
(resp, op_ret, len_ret, val) = struct.unpack('<BBHI', p[:8])
if resp != 1:
continue
body = p[8:]
if op is None or op_ret == op:
return val, body # valid response received
raise FatalError("Response doesn't match request")
示例6: __init__
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def __init__(self, load_file=None):
super(ESPFirmwareImage, self).__init__()
self.flash_mode = 0
self.flash_size_freq = 0
self.version = 1
if load_file is not None:
(magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
# some sanity check
if magic != ESPROM.ESP_IMAGE_MAGIC or segments > 16:
raise FatalError('Invalid firmware image magic=%d segments=%d' % (magic, segments))
for i in range(segments):
self.load_segment(load_file)
self.checksum = self.read_checksum(load_file)
示例7: flash_digest
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def flash_digest(self, addr, length, digest_block_size=0):
self._esp.write(struct.pack(b'<B', self.CMD_FLASH_DIGEST))
self._esp.write(struct.pack(b'<III', addr, length, digest_block_size))
digests = []
while True:
p = self._esp.read()
if len(p) == 16:
digests.append(p)
elif len(p) == 1:
status_code = struct.unpack('<B', p)[0]
if status_code != 0:
raise FatalError('Write failure, status: %x' % status_code)
break
else:
raise FatalError('Unexpected packet: %s' % hexify(p))
return digests[-1], digests[:-1]
示例8: write_flash
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def write_flash(esp, args):
flash_params = _get_flash_params(esp, args)
flasher = CesantaFlasher(esp, args.baud)
for address, argfile in args.addr_filename:
image = argfile.read()
argfile.seek(0) # rewind in case we need it again
if address + len(image) > int(args.flash_size.split('m')[0]) * (1 << 17):
print('WARNING: Unlikely to work as data goes beyond end of flash. Hint: Use --flash_size')
image = _update_image_flash_params(address, flash_params, image)
# Pad to sector size, which is the minimum unit of writing (erasing really).
if len(image) % esp.ESP_FLASH_SECTOR != 0:
image += b'\xff' * (esp.ESP_FLASH_SECTOR - (len(image) % esp.ESP_FLASH_SECTOR))
t = time.time()
flasher.flash_write(address, image, not args.no_progress)
t = time.time() - t
print('\rWrote %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
% (len(image), address, t, len(image) / t * 8 / 1000))
print('Leaving...')
if args.verify:
print('Verifying just-written flash...')
_verify_flash(esp, args, flasher)
flasher.boot_fw()
示例9: is_flash_encryption_key_valid
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def is_flash_encryption_key_valid(self):
""" Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1
this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """
word0 = self.read_efuse(0)
rd_disable = (word0 >> 16) & 0x1
# reading of BLOCK1 is NOT ALLOWED so we assume valid key is programmed
if rd_disable:
return True
else:
# reading of BLOCK1 is ALLOWED so we will read and verify for non-zero.
# When ESP32 has not generated AES/encryption key in BLOCK1, the contents will be readable and 0.
# If the flash encryption is enabled it is expected to have a valid non-zero key. We break out on
# first occurance of non-zero value
key_word = [0] * 7
for i in range(len(key_word)):
key_word[i] = self.read_efuse(14 + i)
# key is non-zero so break & return
if key_word[i] != 0:
return True
return False
示例10: get_flash_crypt_config
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def get_flash_crypt_config(self):
""" For flash encryption related commands we need to make sure
user has programmed all the relevant efuse correctly so before
writing encrypted write_flash_encrypt esptool will verify the values
of flash_crypt_config to be non zero if they are not read
protected. If the values are zero a warning will be printed
bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config
this bit is at position 19 in EFUSE_BLK0_RDATA0_REG """
word0 = self.read_efuse(0)
rd_disable = (word0 >> 19) & 0x1
if rd_disable == 0:
""" we can read the flash_crypt_config efuse value
so go & read it (EFUSE_BLK0_RDATA5_REG[31:28]) """
word5 = self.read_efuse(5)
word5 = (word5 >> 28) & 0xF
return word5
else:
# if read of the efuse is disabled we assume it is set correctly
return 0xF
示例11: LoadFirmwareImage
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def LoadFirmwareImage(chip, filename):
""" Load a firmware image. Can be for any supported SoC.
ESP8266 images will be examined to determine if they are original ROM firmware images (ESP8266ROMFirmwareImage)
or "v2" OTA bootloader images.
Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2).
"""
chip = chip.lower().replace("-", "")
with open(filename, 'rb') as f:
if chip == 'esp32':
return ESP32FirmwareImage(f)
elif chip == "esp32s2":
return ESP32S2FirmwareImage(f)
else: # Otherwise, ESP8266 so look at magic to determine the image type
magic = ord(f.read(1))
f.seek(0)
if magic == ESPLoader.ESP_IMAGE_MAGIC:
return ESP8266ROMFirmwareImage(f)
elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
return ESP8266V2FirmwareImage(f)
else:
raise FatalError("Invalid image magic number: %d" % magic)
示例12: print_incoming_text
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def print_incoming_text(self):
"""
When starting the connection, print all the debug data until
we get to a line with the end sequence '$$$'.
"""
line = ''
# Wait for device to send data
time.sleep(1)
if self.ser.inWaiting():
line = ''
c = ''
# Look for end sequence $$$
while '$$$' not in line:
# we're supposed to get UTF8 text, but the board might behave otherwise
c = self.ser.read().decode('utf-8',
errors='replace')
line += c
print(line)
else:
self.warn("No Message")
示例13: openbci_id
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def openbci_id(self, serial):
"""
When automatically detecting port, parse the serial return for the "OpenBCI" ID.
"""
line = ''
# Wait for device to send data
time.sleep(2)
if serial.inWaiting():
line = ''
c = ''
# Look for end sequence $$$
while '$$$' not in line:
# we're supposed to get UTF8 text, but the board might behave otherwise
c = serial.read().decode('utf-8',
errors='replace')
line += c
if "OpenBCI" in line:
return True
return False
示例14: is_flash_encryption_key_valid
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def is_flash_encryption_key_valid(self):
""" Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1
this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """
word0 = self.read_efuse(0)
rd_disable = (word0 >> 16) & 0x1
# reading of BLOCK1 is NOT ALLOWED so we assume valid key is programmed
if rd_disable:
return True
else:
""" reading of BLOCK1 is ALLOWED so we will read and verify for non-zero.
When ESP32 has not generated AES/encryption key in BLOCK1, the contents will be readable and 0.
If the flash encryption is enabled it is expected to have a valid non-zero key. We break out on
first occurance of non-zero value """
key_word = [0] * 7
for i in range(len(key_word)):
key_word[i] = self.read_efuse(14 + i)
# key is non-zero so break & return
if key_word[i] != 0:
return True
return False
示例15: detect_chip
# 需要导入模块: import serial [as 别名]
# 或者: from serial import read [as 别名]
def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset', trace_enabled=False):
""" Use serial access to detect the chip type.
We use the UART's datecode register for this, it's mapped at
the same address on ESP8266 & ESP32 so we can use one
memory read and compare to the datecode register for each chip
type.
This routine automatically performs ESPLoader.connect() (passing
connect_mode parameter) as part of querying the chip.
"""
detect_port = ESPLoader(port, baud, trace_enabled=trace_enabled)
detect_port.connect(connect_mode)
try:
print('Detecting chip type...', end='')
sys.stdout.flush()
date_reg = detect_port.read_reg(ESPLoader.UART_DATA_REG_ADDR)
for cls in [ESP8266ROM, ESP32ROM]:
if date_reg == cls.DATE_REG_VALUE:
# don't connect a second time
inst = cls(detect_port._port, baud, trace_enabled=trace_enabled)
print(' %s' % inst.CHIP_NAME, end='')
return inst
finally:
print('') # end line
raise FatalError("Unexpected UART datecode value 0x%08x. Failed to autodetect chip type." % date_reg)