Send a request and read the response
(
self,
op=None,
data=b"",
chk=0,
wait_response=True,
timeout=DEFAULT_TIMEOUT,
)
| 337 | return state |
| 338 | |
| 339 | def command( |
| 340 | self, |
| 341 | op=None, |
| 342 | data=b"", |
| 343 | chk=0, |
| 344 | wait_response=True, |
| 345 | timeout=DEFAULT_TIMEOUT, |
| 346 | ): |
| 347 | """Send a request and read the response""" |
| 348 | saved_timeout = self._port.timeout |
| 349 | new_timeout = min(timeout, MAX_TIMEOUT) |
| 350 | if new_timeout != saved_timeout: |
| 351 | self._port.timeout = new_timeout |
| 352 | |
| 353 | try: |
| 354 | if op is not None: |
| 355 | self.trace( |
| 356 | "command op=0x%02x data len=%s wait_response=%d " |
| 357 | "timeout=%.3f data=%s", |
| 358 | op, |
| 359 | len(data), |
| 360 | 1 if wait_response else 0, |
| 361 | timeout, |
| 362 | HexFormatter(data), |
| 363 | ) |
| 364 | pkt = struct.pack(b"<BBHI", 0x00, op, len(data), chk) + data |
| 365 | self.write(pkt) |
| 366 | |
| 367 | if not wait_response: |
| 368 | return |
| 369 | |
| 370 | # tries to get a response until that response has the |
| 371 | # same operation as the request or a retries limit has |
| 372 | # exceeded. This is needed for some esp8266s that |
| 373 | # reply with more sync responses than expected. |
| 374 | for retry in range(100): |
| 375 | p = self.read() |
| 376 | if len(p) < 8: |
| 377 | continue |
| 378 | (resp, op_ret, len_ret, val) = struct.unpack("<BBHI", p[:8]) |
| 379 | if resp != 1: |
| 380 | continue |
| 381 | data = p[8:] |
| 382 | |
| 383 | if op is None or op_ret == op: |
| 384 | return val, data |
| 385 | if byte(data, 0) != 0 and byte(data, 1) == self.ROM_INVALID_RECV_MSG: |
| 386 | # Unsupported read_reg can result in |
| 387 | # more than one error response for some reason |
| 388 | self.flush_input() |
| 389 | raise UnsupportedCommandError(self, op) |
| 390 | |
| 391 | finally: |
| 392 | if new_timeout != saved_timeout: |
| 393 | self._port.timeout = saved_timeout |
| 394 | |
| 395 | raise FatalError("Response doesn't match request") |
| 396 |
no test coverage detected