Add locking in spi

This commit is contained in:
root 2022-01-28 18:09:02 +00:00
parent 2b3f6f86c5
commit fc64706b65

View file

@ -1,5 +1,6 @@
import importlib
from threading import Thread, Lock
from threading import Thread
import multiprocessing
from enum import IntEnum
import time
import sys
@ -8,13 +9,14 @@ from compLib.LogstashLogging import Logging
SPI_BUS = 1
SPI_DEVICE = 2
SPI_SPEED = 1000000
SPI_SPEED = 4000000
SPI_BUFFER_SIZE = 32
SPI_HEALTH = True
# For development purposes
spi_found = importlib.util.find_spec("spidev") is not None
spi = None
spi_lock = multiprocessing.Lock()
if spi_found:
import spidev
spi = spidev.SpiDev()
@ -23,8 +25,6 @@ if spi_found:
spi.mode = 0
spi.bits_per_word = 8
spi_mutex = Lock()
class Register(IntEnum):
IDENTIFICATION_MODEL_ID = 1,
IDENTIFICATION_MODEL_REV_MAJOR = 2,
@ -115,13 +115,16 @@ class Spi(object):
return [] * SPI_BUFFER_SIZE
write_reg = tx_buffer[1]
tx_buffer_copy = tx_buffer.copy()
spi.xfer(tx_buffer)
rx_buffer = spi.xfer([0] * SPI_BUFFER_SIZE)
if rx_buffer[1] != write_reg:
Logging.get_logger().error(f"SPI error during read/write of register {write_reg}!")
return [0] * SPI_BUFFER_SIZE
with spi_lock:
spi.xfer(tx_buffer)
rx_buffer = spi.xfer([0] * SPI_BUFFER_SIZE)
if rx_buffer[1] != write_reg:
Logging.get_logger().error(f"SPI error during read/write of register {write_reg}! Retrying automatically")
time.sleep(0.01)
return Spi.transfer(tx_buffer_copy)
return rx_buffer
@ -202,7 +205,7 @@ class Spi(object):
def health_check_loop():
while SPI_HEALTH:
Spi.health_check()
time.sleep(0.5)
time.sleep(5)
@staticmethod
def get_version():