from ctypes import *
import logging
import os

logger = logging.getLogger(__name__)

# Pin definition
RST_PIN  = 17
DC_PIN   = 25
CS_PIN   = 8
BUSY_PIN = 24
PWR_PIN  = 18
MOSI_PIN = 10
SCLK_PIN = 11

import spidev
SPI = spidev.SpiDev()

# Create FIFOs in /run
os.environ['LG_WD'] = f'/run/user/{os.getuid()}'
import gpiozero
GPIO_RST_PIN    = gpiozero.LED(RST_PIN)
GPIO_DC_PIN     = gpiozero.LED(DC_PIN)
# GPIO_CS_PIN     = gpiozero.LED(CS_PIN)
GPIO_PWR_PIN    = gpiozero.LED(PWR_PIN)
GPIO_BUSY_PIN   = gpiozero.Button(BUSY_PIN, pull_up = False)

def spi_writebyte(data):
    SPI.writebytes(data)

def spi_writebyte2(data):
    SPI.writebytes2(data)

def module_init():
    GPIO_PWR_PIN.on()

    # SPI device, bus = 0, device = 0
    SPI.open(0, 0)
    SPI.max_speed_hz = 4000000
    SPI.mode = 0b00

def module_exit(cleanup=False):
    logger.debug("spi end")
    SPI.close()

    GPIO_RST_PIN.off()
    GPIO_DC_PIN.off()
    GPIO_PWR_PIN.off()
    logger.debug("close 5V, Module enters 0 power consumption ...")

    if cleanup:
        GPIO_RST_PIN.close()
        GPIO_DC_PIN.close()
        # GPIO_CS_PIN.close()
        GPIO_PWR_PIN.close()
        GPIO_BUSY_PIN.close()
