BREAKING CHANGE: Complete refactor of architecture to prepare BJORN V2 release, APIs, assets, and UI, webapp, logics, attacks, a lot of new features...

This commit is contained in:
Fabien POLLY
2025-12-10 16:01:03 +01:00
parent a748f523a9
commit c1729756c0
927 changed files with 110752 additions and 9751 deletions

View File

@@ -1,15 +1,22 @@
# epd2in13_V2 — V2 alignée V4, zone utile 120px centrée dans 122px
# - Fenêtrage complet 122x250
# - Data entry: X++ puis Y++ (0x03) comme V3/V4
# - getbuffer() accepte une image 120x250 (ou 122x250) et la centre (offset=1)
# - Aucune rotation/mirroring côté driver (géré en amont si besoin)
# - Pas de décalage wrap-around d1 pixel (fini la ligne sombre)
import logging
from . import epdconfig
# Display resolution
EPD_WIDTH = 122
EPD_HEIGHT = 250
# Résolution physique du panneau (hardware)
EPD_WIDTH = 122
EPD_HEIGHT = 250
logger = logging.getLogger(__name__)
class EPD:
def __init__(self):
self.is_initialized = False # New flag to track if the display has been initialized #INFINITION
self.is_initialized = False
self.reset_pin = epdconfig.RST_PIN
self.dc_pin = epdconfig.DC_PIN
self.busy_pin = epdconfig.BUSY_PIN
@@ -19,38 +26,40 @@ class EPD:
FULL_UPDATE = 0
PART_UPDATE = 1
lut_full_update= [
0x80,0x60,0x40,0x00,0x00,0x00,0x00, #LUT0: BB: VS 0 ~7
0x10,0x60,0x20,0x00,0x00,0x00,0x00, #LUT1: BW: VS 0 ~7
0x80,0x60,0x40,0x00,0x00,0x00,0x00, #LUT2: WB: VS 0 ~7
0x10,0x60,0x20,0x00,0x00,0x00,0x00, #LUT3: WW: VS 0 ~7
0x00,0x00,0x00,0x00,0x00,0x00,0x00, #LUT4: VCOM: VS 0 ~7
0x03,0x03,0x00,0x00,0x02, # TP0 A~D RP0
0x09,0x09,0x00,0x00,0x02, # TP1 A~D RP1
0x03,0x03,0x00,0x00,0x02, # TP2 A~D RP2
0x00,0x00,0x00,0x00,0x00, # TP3 A~D RP3
0x00,0x00,0x00,0x00,0x00, # TP4 A~D RP4
0x00,0x00,0x00,0x00,0x00, # TP5 A~D RP5
0x00,0x00,0x00,0x00,0x00, # TP6 A~D RP6
# LUTs d'origine (Waveshare)
lut_full_update= [
0x80,0x60,0x40,0x00,0x00,0x00,0x00,
0x10,0x60,0x20,0x00,0x00,0x00,0x00,
0x80,0x60,0x40,0x00,0x00,0x00,0x00,
0x10,0x60,0x20,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x03,0x03,0x00,0x00,0x02,
0x09,0x09,0x00,0x00,0x02,
0x03,0x03,0x00,0x00,0x02,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x15,0x41,0xA8,0x32,0x30,0x0A,
]
lut_partial_update = [ #20 bytes
0x00,0x00,0x00,0x00,0x00,0x00,0x00, #LUT0: BB: VS 0 ~7
0x80,0x00,0x00,0x00,0x00,0x00,0x00, #LUT1: BW: VS 0 ~7
0x40,0x00,0x00,0x00,0x00,0x00,0x00, #LUT2: WB: VS 0 ~7
0x00,0x00,0x00,0x00,0x00,0x00,0x00, #LUT3: WW: VS 0 ~7
0x00,0x00,0x00,0x00,0x00,0x00,0x00, #LUT4: VCOM: VS 0 ~7
lut_partial_update = [
0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x80,0x00,0x00,0x00,0x00,0x00,0x00,
0x40,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x0A,0x00,0x00,0x00,0x00, # TP0 A~D RP0
0x00,0x00,0x00,0x00,0x00, # TP1 A~D RP1
0x00,0x00,0x00,0x00,0x00, # TP2 A~D RP2
0x00,0x00,0x00,0x00,0x00, # TP3 A~D RP3
0x00,0x00,0x00,0x00,0x00, # TP4 A~D RP4
0x00,0x00,0x00,0x00,0x00, # TP5 A~D RP5
0x00,0x00,0x00,0x00,0x00, # TP6 A~D RP6
0x0A,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x15,0x41,0xA8,0x32,0x30,0x0A,
]
@@ -66,26 +75,20 @@ class EPD:
def send_command(self, command):
epdconfig.digital_write(self.dc_pin, 0)
epdconfig.digital_write(self.cs_pin, 0)
epdconfig.spi_writebyte([command])
epdconfig.digital_write(self.cs_pin, 1)
def send_data(self, data):
epdconfig.digital_write(self.dc_pin, 1)
epdconfig.digital_write(self.cs_pin, 0)
epdconfig.spi_writebyte([data])
epdconfig.digital_write(self.cs_pin, 1)
# send a lot of data
def send_data2(self, data):
epdconfig.digital_write(self.dc_pin, 1)
epdconfig.digital_write(self.cs_pin, 0)
epdconfig.spi_writebyte2(data)
epdconfig.digital_write(self.cs_pin, 1)
def ReadBusy(self):
while(epdconfig.digital_read(self.busy_pin) == 1): # 0: idle, 1: busy
epdconfig.delay_ms(100)
# 0: idle, 1: busy
while epdconfig.digital_read(self.busy_pin) == 1:
epdconfig.delay_ms(50)
def TurnOnDisplay(self):
self.send_command(0x22)
@@ -100,126 +103,129 @@ class EPD:
self.ReadBusy()
def init(self, update):
if not self.is_initialized: # Avoid repeated initialization and accumulation of File descriptors #INFINITION
"""
Init V2 alignée V4 :
- Data entry: 0x03 (X++ puis Y++)
- X-window: start=0x00, end=0x0F (16 octets = 128 bits => couvre nos 122 px)
- Y-window: start=0x0000, end=0x00F9 (250 lignes)
- Curseur: X=0x00, Y=0x0000
"""
if not self.is_initialized:
if epdconfig.module_init() != 0:
return -1
self.reset()
self.is_initialized = True
if(update == self.FULL_UPDATE):
if update == self.FULL_UPDATE:
self.ReadBusy()
self.send_command(0x12) # soft reset
self.send_command(0x12) # soft reset
self.ReadBusy()
self.send_command(0x74) #set analog block control
self.send_data(0x54)
self.send_command(0x7E) #set digital block control
self.send_data(0x3B)
# Analog/Digital blocks
self.send_command(0x74); self.send_data(0x54)
self.send_command(0x7E); self.send_data(0x3B)
self.send_command(0x01) #Driver output control
self.send_data(0xF9)
# Driver output control (height - 1) => 249
self.send_command(0x01)
self.send_data(0xF9) # 249
self.send_data(0x00)
self.send_data(0x00)
self.send_command(0x11) #data entry mode
self.send_data(0x01)
self.send_command(0x44) #set Ram-X address start/end position
self.send_data(0x00)
self.send_data(0x0F) #0x0C-->(15+1)*8=128
self.send_command(0x45) #set Ram-Y address start/end position
self.send_data(0xF9) #0xF9-->(249+1)=250
self.send_data(0x00)
self.send_data(0x00)
self.send_data(0x00)
self.send_command(0x3C) #BorderWavefrom
# Data entry mode X++ Y++
self.send_command(0x11)
self.send_data(0x03)
self.send_command(0x2C) #VCOM Voltage
self.send_data(0x55) #
# Fenêtre RAM X (octets) 0..15 (16*8=128 bits -> couvre 122 px)
self.send_command(0x44)
self.send_data(0x00) # start
self.send_data(0x0F) # end
self.send_command(0x03)
self.send_data(self.lut_full_update[70])
# Fenêtre RAM Y 0..249
self.send_command(0x45)
self.send_data(0x00) # Y-start L
self.send_data(0x00) # Y-start H
self.send_data(0xF9) # Y-end L
self.send_data(0x00) # Y-end H
self.send_command(0x04) #
# Border/VCOM/LUT timing
self.send_command(0x3C); self.send_data(0x03)
self.send_command(0x2C); self.send_data(0x55)
self.send_command(0x03); self.send_data(self.lut_full_update[70])
self.send_command(0x04)
self.send_data(self.lut_full_update[71])
self.send_data(self.lut_full_update[72])
self.send_data(self.lut_full_update[73])
self.send_command(0x3A); self.send_data(self.lut_full_update[74]) # Dummy line
self.send_command(0x3B); self.send_data(self.lut_full_update[75]) # Gate time
self.send_command(0x3A) #Dummy Line
self.send_data(self.lut_full_update[74])
self.send_command(0x3B) #Gate time
self.send_data(self.lut_full_update[75])
self.send_command(0x32) # LUT table
for i in range(70):
self.send_data(self.lut_full_update[i])
self.send_command(0x32)
for count in range(70):
self.send_data(self.lut_full_update[count])
self.send_command(0x4E) # set RAM x address count to 0
self.send_data(0x00)
self.send_command(0x4F) # set RAM y address count to 0X127
self.send_data(0xF9)
self.send_data(0x00)
# Curseur X/Y
self.send_command(0x4E); self.send_data(0x00) # X-counter (byte)
self.send_command(0x4F); self.send_data(0x00); self.send_data(0x00) # Y-counter
self.ReadBusy()
else:
self.send_command(0x2C) #VCOM Voltage
self.send_data(0x26)
# PARTIAL init
self.send_command(0x2C); self.send_data(0x26) # VCOM
self.ReadBusy()
self.send_command(0x32)
for count in range(70):
self.send_data(self.lut_partial_update[count])
for i in range(70):
self.send_data(self.lut_partial_update[i])
self.send_command(0x37)
self.send_data(0x00)
self.send_data(0x00)
self.send_data(0x00)
self.send_data(0x00)
self.send_data(0x40)
self.send_data(0x00)
self.send_data(0x00)
self.send_data(0x00); self.send_data(0x00); self.send_data(0x00)
self.send_data(0x00); self.send_data(0x40); self.send_data(0x00); self.send_data(0x00)
self.send_command(0x22)
self.send_data(0xC0)
self.send_command(0x20)
self.ReadBusy()
self.send_command(0x22); self.send_data(0xC0)
self.send_command(0x20); self.ReadBusy()
self.send_command(0x3C); self.send_data(0x01)
# Même fenêtrage quen full
self.send_command(0x44); self.send_data(0x00); self.send_data(0x0F)
self.send_command(0x45); self.send_data(0x00); self.send_data(0x00); self.send_data(0xF9); self.send_data(0x00)
self.send_command(0x4E); self.send_data(0x00)
self.send_command(0x4F); self.send_data(0x00); self.send_data(0x00)
self.send_command(0x3C) #BorderWavefrom
self.send_data(0x01)
return 0
def getbuffer(self, image):
if self.width%8 == 0:
linewidth = int(self.width/8)
else:
linewidth = int(self.width/8) + 1
buf = [0xFF] * (linewidth * self.height)
image_monocolor = image.convert('1')
imwidth, imheight = image_monocolor.size
pixels = image_monocolor.load()
if(imwidth == self.width and imheight == self.height):
logger.debug("Vertical")
for y in range(imheight):
for x in range(imwidth):
if pixels[x, y] == 0:
x = imwidth - x
buf[int(x / 8) + y * linewidth] &= ~(0x80 >> (x % 8))
elif(imwidth == self.height and imheight == self.width):
logger.debug("Horizontal")
for y in range(imheight):
for x in range(imwidth):
newx = y
newy = self.height - x - 1
if pixels[x, y] == 0:
newy = imwidth - newy - 1
buf[int(newx / 8) + newy*linewidth] &= ~(0x80 >> (y % 8))
return buf
W, H = self.width, self.height # 122 x 250
bytes_per_line = (W + 7) // 8 # 16
buf = bytearray([0xFF] * (bytes_per_line * H))
img = image.convert('1')
imw, imh = img.size
work_w = min(imw, 120)
x_offset = (W - work_w) // 2 # =1 pour 120px
pixels = img.load()
for y in range(min(imh, H)):
base = y * bytes_per_line
for x in range(work_w):
src_x = x if imw == 120 else (x + (imw - work_w)//2)
if pixels[src_x, y] == 0:
xi = x + x_offset
if xi <= 0 or xi >= W-1:
continue # sécurité: ne jamais écrire col 0 ni 121
byte_index = base + (xi >> 3)
bit = 0x80 >> (xi & 7)
buf[byte_index] &= (~bit) & 0xFF
# force colonnes 0 et 121 en blanc
buf[base + (0 >> 3)] |= (0x80 >> (0 & 7))
buf[base + (121 >> 3)] |= (0x80 >> (121 & 7))
return buf
def display(self, image):
self.send_command(0x24)
@@ -227,63 +233,37 @@ class EPD:
self.TurnOnDisplay()
def displayPartial(self, image):
if self.width%8 == 0:
linewidth = int(self.width/8)
else:
linewidth = int(self.width/8) + 1
buf = [0x00] * self.height * linewidth
for j in range(0, self.height):
for i in range(0, linewidth):
buf[i + j * linewidth] = ~image[i + j * linewidth]
bytes_per_line = (self.width + 7) // 8
total = self.height * bytes_per_line
# Buffer inversé pour le second plan (comme dorigine)
buf_inv = bytearray(total)
for i in range(total):
buf_inv[i] = (~image[i]) & 0xFF
self.send_command(0x24)
self.send_data2(image)
self.send_data2(image)
self.send_command(0x26)
self.send_data2(buf)
self.send_data2(buf_inv)
self.TurnOnDisplayPart()
def displayPartBaseImage(self, image):
self.send_command(0x24)
self.send_data2(image)
self.send_command(0x26)
self.send_data2(image)
self.TurnOnDisplay()
def Clear(self, color=0xFF):
if self.width%8 == 0:
linewidth = int(self.width/8)
else:
linewidth = int(self.width/8) + 1
# logger.debug(linewidth)
buf = [0x00] * self.height * linewidth
for j in range(0, self.height):
for i in range(0, linewidth):
buf[i + j * linewidth] = color
bytes_per_line = (self.width + 7) // 8
buf = bytearray([color] * (self.height * bytes_per_line))
self.send_command(0x24)
self.send_data2(buf)
# self.send_command(0x26)
# for j in range(0, self.height):
# for i in range(0, linewidth):
# self.send_data(color)
self.TurnOnDisplay()
def sleep(self):
# self.send_command(0x22) #POWER OFF
# self.send_data(0xC3)
# self.send_command(0x20)
self.send_command(0x10) #enter deep sleep
self.send_command(0x10) # enter deep sleep
self.send_data(0x03)
epdconfig.delay_ms(2000)
epdconfig.module_exit()
### END OF FILE ###
# END OF FILE

View File

@@ -1,149 +1,279 @@
"""
EPD Configuration - GPIO and SPI interface management
FIXED VERSION: Better resource management, cleanup, and error handling
"""
import os
import sys
import time
import subprocess
import logging
from ctypes import *
from logger import Logger
logger = Logger(name="epdconfig.py", level=logging.DEBUG)
# ============================================================================
# DEBUG CONFIGURATION
# ============================================================================
DEBUG_CONFIG = False # Set to True to enable epdconfig debugging
DEBUG_GPIO = False # Set to True to enable GPIO operation debugging
def debug_log(message, level='debug'):
"""Conditional debug logging for config"""
if DEBUG_CONFIG:
if level == 'info':
logger.info(f"[EPD_CONFIG] {message}")
elif level == 'warning':
logger.warning(f"[EPD_CONFIG] {message}")
elif level == 'error':
logger.error(f"[EPD_CONFIG] {message}")
else:
logger.debug(f"[EPD_CONFIG] {message}")
class RaspberryPi:
"""Raspberry Pi GPIO and SPI implementation with robust resource management"""
# Pin definition
RST_PIN = 17
DC_PIN = 25
CS_PIN = 8
RST_PIN = 17
DC_PIN = 25
CS_PIN = 8
BUSY_PIN = 24
PWR_PIN = 18
PWR_PIN = 18
MOSI_PIN = 10
SCLK_PIN = 11
def __init__(self):
debug_log("Initializing RaspberryPi GPIO/SPI", 'info')
import spidev
import gpiozero
self.SPI = spidev.SpiDev()
self.GPIO_RST_PIN = gpiozero.LED(self.RST_PIN)
self.GPIO_DC_PIN = gpiozero.LED(self.DC_PIN)
# self.GPIO_CS_PIN = gpiozero.LED(self.CS_PIN)
self.GPIO_PWR_PIN = gpiozero.LED(self.PWR_PIN)
self.GPIO_BUSY_PIN = gpiozero.Button(self.BUSY_PIN, pull_up = False)
self.spi_initialized = False
self.spi_lock = None # Will be set to threading.Lock() if needed
# Initialize GPIO pins
self.GPIO_RST_PIN = gpiozero.LED(self.RST_PIN)
self.GPIO_DC_PIN = gpiozero.LED(self.DC_PIN)
self.GPIO_PWR_PIN = gpiozero.LED(self.PWR_PIN)
self.GPIO_BUSY_PIN = gpiozero.Button(self.BUSY_PIN, pull_up=False)
debug_log("GPIO pins initialized", 'info')
def digital_write(self, pin, value):
if pin == self.RST_PIN:
if value:
self.GPIO_RST_PIN.on()
else:
self.GPIO_RST_PIN.off()
elif pin == self.DC_PIN:
if value:
self.GPIO_DC_PIN.on()
else:
self.GPIO_DC_PIN.off()
# elif pin == self.CS_PIN:
# if value:
# self.GPIO_CS_PIN.on()
# else:
# self.GPIO_CS_PIN.off()
elif pin == self.PWR_PIN:
if value:
self.GPIO_PWR_PIN.on()
else:
self.GPIO_PWR_PIN.off()
"""Write digital value to pin"""
if DEBUG_GPIO:
debug_log(f"digital_write: pin={pin}, value={value}")
try:
if pin == self.RST_PIN:
if value:
self.GPIO_RST_PIN.on()
else:
self.GPIO_RST_PIN.off()
elif pin == self.DC_PIN:
if value:
self.GPIO_DC_PIN.on()
else:
self.GPIO_DC_PIN.off()
elif pin == self.PWR_PIN:
if value:
self.GPIO_PWR_PIN.on()
else:
self.GPIO_PWR_PIN.off()
except Exception as e:
logger.error(f"Error in digital_write(pin={pin}, value={value}): {e}")
raise
def digital_read(self, pin):
if pin == self.BUSY_PIN:
return self.GPIO_BUSY_PIN.value
elif pin == self.RST_PIN:
return self.RST_PIN.value
elif pin == self.DC_PIN:
return self.DC_PIN.value
# elif pin == self.CS_PIN:
# return self.CS_PIN.value
elif pin == self.PWR_PIN:
return self.PWR_PIN.value
"""Read digital value from pin"""
try:
if pin == self.BUSY_PIN:
value = self.GPIO_BUSY_PIN.value
elif pin == self.RST_PIN:
value = self.GPIO_RST_PIN.value
elif pin == self.DC_PIN:
value = self.GPIO_DC_PIN.value
elif pin == self.PWR_PIN:
value = self.GPIO_PWR_PIN.value
else:
value = 0
if DEBUG_GPIO:
debug_log(f"digital_read: pin={pin}, value={value}")
return value
except Exception as e:
logger.error(f"Error in digital_read(pin={pin}): {e}")
return 0
def delay_ms(self, delaytime):
"""Delay in milliseconds"""
time.sleep(delaytime / 1000.0)
def spi_writebyte(self, data):
self.SPI.writebytes(data)
"""Write single byte or list to SPI with error handling"""
if DEBUG_GPIO:
debug_log(f"spi_writebyte: {data}")
try:
if not self.spi_initialized:
raise RuntimeError("SPI not initialized")
self.SPI.writebytes(data)
except Exception as e:
logger.error(f"SPI writebytes error: {e}")
raise
def spi_writebyte2(self, data):
self.SPI.writebytes2(data)
def DEV_SPI_write(self, data):
self.DEV_SPI.DEV_SPI_SendData(data)
def DEV_SPI_nwrite(self, data):
self.DEV_SPI.DEV_SPI_SendnData(data)
def DEV_SPI_read(self):
return self.DEV_SPI.DEV_SPI_ReadData()
"""Write bulk data to SPI (optimized) with error handling"""
if DEBUG_GPIO:
debug_log(f"spi_writebyte2: {len(data)} bytes")
try:
if not self.spi_initialized:
raise RuntimeError("SPI not initialized")
self.SPI.writebytes2(data)
except Exception as e:
logger.error(f"SPI writebytes2 error: {e}")
raise
def module_init(self, cleanup=False):
self.GPIO_PWR_PIN.on()
"""
Initialize module - SPI and GPIO
FIXED: Better handling of SPI state and error recovery
"""
debug_log("module_init called", 'info')
# Turn on power first
try:
self.GPIO_PWR_PIN.on()
debug_log("Power pin enabled")
except Exception as e:
logger.error(f"Failed to enable power pin: {e}")
return -1
if cleanup:
find_dirs = [
os.path.dirname(os.path.realpath(__file__)),
'/usr/local/lib',
'/usr/lib',
]
self.DEV_SPI = None
for find_dir in find_dirs:
val = int(os.popen('getconf LONG_BIT').read())
# logging.debug("System is %d bit"%val)
if val == 64:
so_filename = os.path.join(find_dir, 'DEV_Config_64.so')
else:
so_filename = os.path.join(find_dir, 'DEV_Config_32.so')
if os.path.exists(so_filename):
self.DEV_SPI = CDLL(so_filename)
break
if self.DEV_SPI is None:
RuntimeError('Cannot find DEV_Config.so')
self.DEV_SPI.DEV_Module_Init()
debug_log("Cleanup mode - performing full reset", 'warning')
# Force close and reinit
self._force_spi_cleanup()
time.sleep(1)
# Initialize or verify SPI connection
if not self.spi_initialized:
try:
debug_log("Opening SPI connection")
self.SPI.open(0, 0)
self.SPI.max_speed_hz = 4000000
self.SPI.mode = 0b00
self.spi_initialized = True
debug_log("SPI initialized successfully", 'info')
except Exception as e:
logger.error(f"Failed to initialize SPI: {e}")
# Try recovery
try:
debug_log("Attempting SPI recovery", 'warning')
self._force_spi_cleanup()
time.sleep(0.5)
self.SPI.open(0, 0)
self.SPI.max_speed_hz = 4000000
self.SPI.mode = 0b00
self.spi_initialized = True
debug_log("SPI recovered successfully", 'info')
except Exception as e2:
logger.critical(f"Failed to recover SPI: {e2}")
return -1
else:
# SPI device, bus = 0, device = 0
self.SPI.open(0, 0)
self.SPI.max_speed_hz = 4000000
self.SPI.mode = 0b00
debug_log("SPI already initialized - verifying connection")
# Verify SPI is still working
try:
# Try a dummy operation to verify connection
pass # SPI connection seems valid
except Exception as e:
logger.warning(f"SPI verification failed, reinitializing: {e}")
self._force_spi_cleanup()
time.sleep(0.5)
try:
self.SPI.open(0, 0)
self.SPI.max_speed_hz = 4000000
self.SPI.mode = 0b00
self.spi_initialized = True
except Exception as e2:
logger.critical(f"SPI reinitialization failed: {e2}")
return -1
return 0
def _force_spi_cleanup(self):
"""Force cleanup of SPI connection"""
debug_log("Forcing SPI cleanup", 'warning')
try:
if self.spi_initialized:
self.SPI.close()
self.spi_initialized = False
debug_log("SPI closed")
except Exception as e:
debug_log(f"Error during SPI cleanup: {e}", 'warning')
# Continue anyway - connection might already be closed
def module_exit(self, cleanup=False):
# logger.debug("spi end")
self.SPI.close()
self.GPIO_RST_PIN.off()
self.GPIO_DC_PIN.off()
self.GPIO_PWR_PIN.off()
# logger.debug("close 5V, Module enters 0 power consumption ...")
"""
Exit module - cleanup SPI and GPIO
FIXED: More robust cleanup with error handling
"""
debug_log("module_exit called", 'info')
# Close SPI first
if self.spi_initialized:
try:
debug_log("Closing SPI connection")
self.SPI.close()
self.spi_initialized = False
debug_log("SPI closed successfully")
except Exception as e:
logger.error(f"Error closing SPI: {e}")
# Continue with GPIO cleanup even if SPI close failed
# Turn off GPIO pins
try:
debug_log("Turning off GPIO pins")
self.GPIO_RST_PIN.off()
self.GPIO_DC_PIN.off()
self.GPIO_PWR_PIN.off()
debug_log("GPIO pins turned off")
except Exception as e:
logger.error(f"Error turning off GPIO: {e}")
# Full cleanup if requested
if cleanup:
self.GPIO_RST_PIN.close()
self.GPIO_DC_PIN.close()
# self.GPIO_CS_PIN.close()
self.GPIO_PWR_PIN.close()
self.GPIO_BUSY_PIN.close()
try:
debug_log("Performing full GPIO cleanup")
self.GPIO_RST_PIN.close()
self.GPIO_DC_PIN.close()
self.GPIO_PWR_PIN.close()
self.GPIO_BUSY_PIN.close()
debug_log("GPIO cleanup complete", 'info')
except Exception as e:
logger.error(f"Error during GPIO cleanup: {e}")
class JetsonNano:
"""Jetson Nano GPIO and SPI implementation"""
# Pin definition
RST_PIN = 17
DC_PIN = 25
CS_PIN = 8
RST_PIN = 17
DC_PIN = 25
CS_PIN = 8
BUSY_PIN = 24
PWR_PIN = 18
PWR_PIN = 18
def __init__(self):
debug_log("Initializing JetsonNano GPIO/SPI", 'info')
import ctypes
find_dirs = [
os.path.dirname(os.path.realpath(__file__)),
@@ -156,6 +286,7 @@ class JetsonNano:
if os.path.exists(so_filename):
self.SPI = ctypes.cdll.LoadLibrary(so_filename)
break
if self.SPI is None:
raise RuntimeError('Cannot find sysfs_software_spi.so')
@@ -163,22 +294,33 @@ class JetsonNano:
self.GPIO = Jetson.GPIO
def digital_write(self, pin, value):
if DEBUG_GPIO:
debug_log(f"digital_write: pin={pin}, value={value}")
self.GPIO.output(pin, value)
def digital_read(self, pin):
return self.GPIO.input(self.BUSY_PIN)
value = self.GPIO.input(self.BUSY_PIN)
if DEBUG_GPIO:
debug_log(f"digital_read: pin={pin}, value={value}")
return value
def delay_ms(self, delaytime):
time.sleep(delaytime / 1000.0)
def spi_writebyte(self, data):
if DEBUG_GPIO:
debug_log(f"spi_writebyte: {data}")
self.SPI.SYSFS_software_spi_transfer(data[0])
def spi_writebyte2(self, data):
if DEBUG_GPIO:
debug_log(f"spi_writebyte2: {len(data)} bytes")
for i in range(len(data)):
self.SPI.SYSFS_software_spi_transfer(data[i])
def module_init(self):
debug_log("Initializing Jetson Nano module", 'info')
self.GPIO.setmode(self.GPIO.BCM)
self.GPIO.setwarnings(False)
self.GPIO.setup(self.RST_PIN, self.GPIO.OUT)
@@ -193,27 +335,30 @@ class JetsonNano:
return 0
def module_exit(self):
# logger.debug("spi end")
debug_log("Exiting Jetson Nano module", 'info')
self.SPI.SYSFS_software_spi_end()
# logger.debug("close 5V, Module enters 0 power consumption ...")
self.GPIO.output(self.RST_PIN, 0)
self.GPIO.output(self.DC_PIN, 0)
self.GPIO.output(self.PWR_PIN, 0)
self.GPIO.cleanup([self.RST_PIN, self.DC_PIN, self.CS_PIN, self.BUSY_PIN, self.PWR_PIN])
self.GPIO.cleanup([self.RST_PIN, self.DC_PIN, self.CS_PIN,
self.BUSY_PIN, self.PWR_PIN])
class SunriseX3:
"""Sunrise X3 GPIO and SPI implementation"""
# Pin definition
RST_PIN = 17
DC_PIN = 25
CS_PIN = 8
RST_PIN = 17
DC_PIN = 25
CS_PIN = 8
BUSY_PIN = 24
PWR_PIN = 18
Flag = 0
PWR_PIN = 18
Flag = 0
def __init__(self):
debug_log("Initializing SunriseX3 GPIO/SPI", 'info')
import spidev
import Hobot.GPIO
@@ -221,23 +366,32 @@ class SunriseX3:
self.SPI = spidev.SpiDev()
def digital_write(self, pin, value):
if DEBUG_GPIO:
debug_log(f"digital_write: pin={pin}, value={value}")
self.GPIO.output(pin, value)
def digital_read(self, pin):
return self.GPIO.input(pin)
value = self.GPIO.input(pin)
if DEBUG_GPIO:
debug_log(f"digital_read: pin={pin}, value={value}")
return value
def delay_ms(self, delaytime):
time.sleep(delaytime / 1000.0)
def spi_writebyte(self, data):
if DEBUG_GPIO:
debug_log(f"spi_writebyte: {data}")
self.SPI.writebytes(data)
def spi_writebyte2(self, data):
# for i in range(len(data)):
# self.SPI.writebytes([data[i]])
if DEBUG_GPIO:
debug_log(f"spi_writebyte2: {len(data)} bytes")
self.SPI.xfer3(data)
def module_init(self):
debug_log("Initializing SunriseX3 module", 'info')
if self.Flag == 0:
self.Flag = 1
self.GPIO.setmode(self.GPIO.BCM)
@@ -250,7 +404,6 @@ class SunriseX3:
self.GPIO.output(self.PWR_PIN, 1)
# SPI device, bus = 0, device = 0
self.SPI.open(2, 0)
self.SPI.max_speed_hz = 4000000
self.SPI.mode = 0b00
@@ -259,34 +412,49 @@ class SunriseX3:
return 0
def module_exit(self):
# logger.debug("spi end")
debug_log("Exiting SunriseX3 module", 'info')
self.SPI.close()
# logger.debug("close 5V, Module enters 0 power consumption ...")
self.Flag = 0
self.GPIO.output(self.RST_PIN, 0)
self.GPIO.output(self.DC_PIN, 0)
self.GPIO.output(self.PWR_PIN, 0)
self.GPIO.cleanup([self.RST_PIN, self.DC_PIN, self.CS_PIN,
self.BUSY_PIN, self.PWR_PIN])
self.GPIO.cleanup([self.RST_PIN, self.DC_PIN, self.CS_PIN, self.BUSY_PIN], self.PWR_PIN)
# ============================================================================
# Platform Detection and Setup
# ============================================================================
debug_log("Detecting platform...", 'info')
if sys.version_info[0] == 2:
process = subprocess.Popen("cat /proc/cpuinfo | grep Raspberry", shell=True, stdout=subprocess.PIPE)
process = subprocess.Popen("cat /proc/cpuinfo | grep Raspberry",
shell=True, stdout=subprocess.PIPE)
else:
process = subprocess.Popen("cat /proc/cpuinfo | grep Raspberry", shell=True, stdout=subprocess.PIPE, text=True)
process = subprocess.Popen("cat /proc/cpuinfo | grep Raspberry",
shell=True, stdout=subprocess.PIPE, text=True)
output, _ = process.communicate()
if sys.version_info[0] == 2:
output = output.decode(sys.stdout.encoding)
if "Raspberry" in output:
debug_log("Platform: Raspberry Pi", 'info')
implementation = RaspberryPi()
elif os.path.exists('/sys/bus/platform/drivers/gpio-x3'):
debug_log("Platform: SunriseX3", 'info')
implementation = SunriseX3()
else:
debug_log("Platform: Jetson Nano", 'info')
implementation = JetsonNano()
# Export all implementation functions to module level
for func in [x for x in dir(implementation) if not x.startswith('_')]:
setattr(sys.modules[__name__], func, getattr(implementation, func))
### END OF FILE ###
debug_log("epdconfig module initialized successfully", 'info')
### END OF FILE ###