WIP: Package waveshare CM4-NAS-Double-Deck demo app #49

Closed
lee.miller wants to merge 5 commits from lee.miller/openwrt:packages into main
26 changed files with 3903 additions and 2 deletions

View File

@ -32,14 +32,23 @@ make defconfig
# Enable collectd network encryption
echo "CONFIG_PACKAGE_COLLECTD_ENCRYPTED_NETWORK=y" >> .config
cat << "EOF" >> .config
CONFIG_PACKAGE_python3-packages=y
CONFIG_PACKAGE_python3-packages-list="RPi.GPIO==0.7.1"
CONFIG_PACKAGE_python3-packages-list-cleanup="setuptools"
EOF
make package/i2c-tools/compile
make package/kmod-nvme/compile
make package/kmod-ili9340/compile
make package/kmod-i2c-mux-pinctrl/compile
make package/kmod-rtc-pcf85063/compile
make package/nvme-cli/compile
make package/ansible-core/compile
make package/asterisk-chan-quectel/compile
make package/collectd/compile
make package/python3-packages/compile
make package/waveshare-demo/compile
sdkdir=$(pwd)
cd ${pwd}
@ -138,21 +147,29 @@ make image PROFILE=${PROFILE} EXTRA_IMAGE_NAME="dualeth" \
PACKAGES="${PACKAGES}" DISABLED_SERVICES="dropbear" FILES="files" || exit 1
sed -i "s|,i2c_csi_dsi||g" ${BOOTSOURCE}/current.txt
sed -i "s/CONFIG_TARGET_ROOTFS_PARTSIZE=.*/CONFIG_TARGET_ROOTFS_PARTSIZE=768/g" .config
cp ${pwd}/overlays/waveshare32b.dtbo ${OVERLAYSOURCE}
cp ${pwd}/overlays/waveshare.txt ${BOOTSOURCE}/current.txt
cp ${OVERLAYSOURCE}/Makefile ${OVERLAYSOURCE}/Makefile.orig
pushd ${KERNELSOURCE}
git apply ${pwd}/patches/overlay-add-waveshare.patch
popd
make image PROFILE=${PROFILE} EXTRA_IMAGE_NAME="waveshare" \
PACKAGES=" \
${PACKAGES} cryptsetup kmod-ata-ahci smartmontools hdparm fdisk parted \
kmod-hwmon-drivetemp btrfs-progs kmod-fs-btrfs kmod-nvme nvme-cli \
docker dockerd docker-compose block-mount" \
docker dockerd docker-compose block-mount \
kmod-ili9340 python3-packages python3-spidev python3-waveshare-demo" \
DISABLED_SERVICES="dropbear" FILES="files" || exit 1
cp ${pwd}/overlays/sensing.txt ${BOOTSOURCE}/current.txt
cp ${pwd}/overlays/*.dtbo ${OVERLAYSOURCE}
rm ${OVERLAYSOURCE}/waveshare32b.dtbo
cp config.txt ${BOOTCONFIG}
echo "include current.txt" >> ${BOOTCONFIG}
cp ${OVERLAYSOURCE}/Makefile.orig ${OVERLAYSOURCE}/Makefile
pushd ${KERNELSOURCE}
git apply ${pwd}/patches/overlay-add.patch
popd

View File

@ -0,0 +1,25 @@
include $(TOPDIR)/rules.mk
include $(INCLUDE_DIR)/kernel.mk
PKG_NAME:=ili9340
include $(INCLUDE_DIR)/package.mk
define KernelPackage/$(PKG_NAME)
SUBMENU:=Other modules
TITLE:=FB driver for the ILI9340 LCD Controller
DEPENDS:=+kmod-fb-tft
AUTOLOAD:=$(call AutoProbe,fb_ili9340)
FILES:=$(PKG_BUILD_DIR)/fb_ili9340.ko
KCONFIG:=
endef
define KernelPackage/$(PKG_NAME)/description
FB driver for the ILI9340 LCD Controller
endef
EXTRA_KCONFIG:= CONFIG_FB_TFT_ILI9340=m
include ../kmod.mk
$(eval $(call KernelPackage,$(PKG_NAME)))

View File

@ -0,0 +1,7 @@
# SPDX-License-Identifier: GPL-2.0
# Core module
obj-$(CONFIG_FB_TFT) += fbtft.o
fbtft-y += fbtft-core.o fbtft-sysfs.o fbtft-bus.o fbtft-io.o
# drivers
obj-$(CONFIG_FB_TFT_ILI9340) += fb_ili9340.o

View File

@ -0,0 +1,139 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* FB driver for the ILI9340 LCD Controller
*
* Copyright (C) 2013 Noralf Tronnes
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <video/mipi_display.h>
#include "fbtft.h"
#define DRVNAME "fb_ili9340"
#define WIDTH 240
#define HEIGHT 320
/* Init sequence taken from: Arduino Library for the Adafruit 2.2" display */
static int init_display(struct fbtft_par *par)
{
par->fbtftops.reset(par);
write_reg(par, 0xEF, 0x03, 0x80, 0x02);
write_reg(par, 0xCF, 0x00, 0XC1, 0X30);
write_reg(par, 0xED, 0x64, 0x03, 0X12, 0X81);
write_reg(par, 0xE8, 0x85, 0x00, 0x78);
write_reg(par, 0xCB, 0x39, 0x2C, 0x00, 0x34, 0x02);
write_reg(par, 0xF7, 0x20);
write_reg(par, 0xEA, 0x00, 0x00);
/* Power Control 1 */
write_reg(par, 0xC0, 0x23);
/* Power Control 2 */
write_reg(par, 0xC1, 0x10);
/* VCOM Control 1 */
write_reg(par, 0xC5, 0x3e, 0x28);
/* VCOM Control 2 */
write_reg(par, 0xC7, 0x86);
/* COLMOD: Pixel Format Set */
/* 16 bits/pixel */
write_reg(par, MIPI_DCS_SET_PIXEL_FORMAT, 0x55);
/* Frame Rate Control */
/* Division ratio = fosc, Frame Rate = 79Hz */
write_reg(par, 0xB1, 0x00, 0x18);
/* Display Function Control */
write_reg(par, 0xB6, 0x08, 0x82, 0x27);
/* Gamma Function Disable */
write_reg(par, 0xF2, 0x00);
/* Gamma curve selection */
write_reg(par, MIPI_DCS_SET_GAMMA_CURVE, 0x01);
/* Positive Gamma Correction */
write_reg(par, 0xE0,
0x0F, 0x31, 0x2B, 0x0C, 0x0E, 0x08, 0x4E, 0xF1,
0x37, 0x07, 0x10, 0x03, 0x0E, 0x09, 0x00);
/* Negative Gamma Correction */
write_reg(par, 0xE1,
0x00, 0x0E, 0x14, 0x03, 0x11, 0x07, 0x31, 0xC1,
0x48, 0x08, 0x0F, 0x0C, 0x31, 0x36, 0x0F);
write_reg(par, MIPI_DCS_EXIT_SLEEP_MODE);
mdelay(120);
write_reg(par, MIPI_DCS_SET_DISPLAY_ON);
return 0;
}
static void set_addr_win(struct fbtft_par *par, int xs, int ys, int xe, int ye)
{
write_reg(par, MIPI_DCS_SET_COLUMN_ADDRESS,
xs >> 8, xs & 0xFF, xe >> 8, xe & 0xFF);
write_reg(par, MIPI_DCS_SET_PAGE_ADDRESS,
ys >> 8, ys & 0xFF, ye >> 8, ye & 0xFF);
write_reg(par, MIPI_DCS_WRITE_MEMORY_START);
}
#define ILI9340_MADCTL_MV 0x20
#define ILI9340_MADCTL_MX 0x40
#define ILI9340_MADCTL_MY 0x80
static int set_var(struct fbtft_par *par)
{
u8 val;
switch (par->info->var.rotate) {
case 270:
val = ILI9340_MADCTL_MV;
break;
case 180:
val = ILI9340_MADCTL_MY;
break;
case 90:
val = ILI9340_MADCTL_MV | ILI9340_MADCTL_MY | ILI9340_MADCTL_MX;
break;
default:
val = ILI9340_MADCTL_MX;
break;
}
/* Memory Access Control */
write_reg(par, MIPI_DCS_SET_ADDRESS_MODE, val | (par->bgr << 3));
return 0;
}
static struct fbtft_display display = {
.regwidth = 8,
.width = WIDTH,
.height = HEIGHT,
.fbtftops = {
.init_display = init_display,
.set_addr_win = set_addr_win,
.set_var = set_var,
},
};
FBTFT_REGISTER_DRIVER(DRVNAME, "ilitek,ili9340", &display);
MODULE_ALIAS("spi:" DRVNAME);
MODULE_ALIAS("platform:" DRVNAME);
MODULE_ALIAS("spi:ili9340");
MODULE_ALIAS("platform:ili9340");
MODULE_DESCRIPTION("FB driver for the ILI9340 LCD Controller");
MODULE_AUTHOR("Noralf Tronnes");
MODULE_LICENSE("GPL");

View File

@ -0,0 +1,243 @@
// SPDX-License-Identifier: GPL-2.0
#include <linux/export.h>
#include <linux/errno.h>
#include <linux/gpio/consumer.h>
#include <linux/spi/spi.h>
#include "fbtft.h"
/*****************************************************************************
*
* void (*write_reg)(struct fbtft_par *par, int len, ...);
*
*****************************************************************************/
#define define_fbtft_write_reg(func, buffer_type, data_type, modifier) \
void func(struct fbtft_par *par, int len, ...) \
{ \
va_list args; \
int i, ret; \
int offset = 0; \
buffer_type *buf = (buffer_type *)par->buf; \
\
if (unlikely(par->debug & DEBUG_WRITE_REGISTER)) { \
va_start(args, len); \
for (i = 0; i < len; i++) { \
buf[i] = modifier((data_type)va_arg(args, \
unsigned int)); \
} \
va_end(args); \
fbtft_par_dbg_hex(DEBUG_WRITE_REGISTER, par, \
par->info->device, buffer_type, buf, len, \
"%s: ", __func__); \
} \
\
va_start(args, len); \
\
if (par->startbyte) { \
*(u8 *)par->buf = par->startbyte; \
buf = (buffer_type *)(par->buf + 1); \
offset = 1; \
} \
\
*buf = modifier((data_type)va_arg(args, unsigned int)); \
ret = fbtft_write_buf_dc(par, par->buf, sizeof(data_type) + offset, \
0); \
if (ret < 0) \
goto out; \
len--; \
\
if (par->startbyte) \
*(u8 *)par->buf = par->startbyte | 0x2; \
\
if (len) { \
i = len; \
while (i--) \
*buf++ = modifier((data_type)va_arg(args, \
unsigned int)); \
fbtft_write_buf_dc(par, par->buf, \
len * (sizeof(data_type) + offset), 1); \
} \
out: \
va_end(args); \
} \
EXPORT_SYMBOL(func);
define_fbtft_write_reg(fbtft_write_reg8_bus8, u8, u8, )
define_fbtft_write_reg(fbtft_write_reg16_bus8, __be16, u16, cpu_to_be16)
define_fbtft_write_reg(fbtft_write_reg16_bus16, u16, u16, )
void fbtft_write_reg8_bus9(struct fbtft_par *par, int len, ...)
{
va_list args;
int i, ret;
int pad = 0;
u16 *buf = (u16 *)par->buf;
if (unlikely(par->debug & DEBUG_WRITE_REGISTER)) {
va_start(args, len);
for (i = 0; i < len; i++)
*(((u8 *)buf) + i) = (u8)va_arg(args, unsigned int);
va_end(args);
fbtft_par_dbg_hex(DEBUG_WRITE_REGISTER, par,
par->info->device, u8, buf, len, "%s: ",
__func__);
}
if (len <= 0)
return;
if (par->spi && (par->spi->bits_per_word == 8)) {
/* we're emulating 9-bit, pad start of buffer with no-ops
* (assuming here that zero is a no-op)
*/
pad = (len % 4) ? 4 - (len % 4) : 0;
for (i = 0; i < pad; i++)
*buf++ = 0x000;
}
va_start(args, len);
*buf++ = (u8)va_arg(args, unsigned int);
i = len - 1;
while (i--) {
*buf = (u8)va_arg(args, unsigned int);
*buf++ |= 0x100; /* dc=1 */
}
va_end(args);
ret = par->fbtftops.write(par, par->buf, (len + pad) * sizeof(u16));
if (ret < 0) {
dev_err(par->info->device,
"write() failed and returned %d\n", ret);
return;
}
}
EXPORT_SYMBOL(fbtft_write_reg8_bus9);
/*****************************************************************************
*
* int (*write_vmem)(struct fbtft_par *par);
*
*****************************************************************************/
/* 16 bit pixel over 8-bit databus */
int fbtft_write_vmem16_bus8(struct fbtft_par *par, size_t offset, size_t len)
{
u16 *vmem16;
__be16 *txbuf16 = par->txbuf.buf;
size_t remain;
size_t to_copy;
size_t tx_array_size;
int i;
int ret = 0;
size_t startbyte_size = 0;
fbtft_par_dbg(DEBUG_WRITE_VMEM, par, "%s(offset=%zu, len=%zu)\n",
__func__, offset, len);
remain = len / 2;
vmem16 = (u16 *)(par->info->screen_buffer + offset);
gpiod_set_value(par->gpio.dc, 1);
/* non buffered write */
if (!par->txbuf.buf)
return par->fbtftops.write(par, vmem16, len);
/* buffered write */
tx_array_size = par->txbuf.len / 2;
if (par->startbyte) {
txbuf16 = par->txbuf.buf + 1;
tx_array_size -= 2;
*(u8 *)(par->txbuf.buf) = par->startbyte | 0x2;
startbyte_size = 1;
}
while (remain) {
to_copy = min(tx_array_size, remain);
dev_dbg(par->info->device, "to_copy=%zu, remain=%zu\n",
to_copy, remain - to_copy);
for (i = 0; i < to_copy; i++)
txbuf16[i] = cpu_to_be16(vmem16[i]);
vmem16 = vmem16 + to_copy;
ret = par->fbtftops.write(par, par->txbuf.buf,
startbyte_size + to_copy * 2);
if (ret < 0)
return ret;
remain -= to_copy;
}
return ret;
}
EXPORT_SYMBOL(fbtft_write_vmem16_bus8);
/* 16 bit pixel over 9-bit SPI bus: dc + high byte, dc + low byte */
int fbtft_write_vmem16_bus9(struct fbtft_par *par, size_t offset, size_t len)
{
u8 *vmem8;
u16 *txbuf16 = par->txbuf.buf;
size_t remain;
size_t to_copy;
size_t tx_array_size;
int i;
int ret = 0;
fbtft_par_dbg(DEBUG_WRITE_VMEM, par, "%s(offset=%zu, len=%zu)\n",
__func__, offset, len);
if (!par->txbuf.buf) {
dev_err(par->info->device, "%s: txbuf.buf is NULL\n", __func__);
return -1;
}
remain = len;
vmem8 = par->info->screen_buffer + offset;
tx_array_size = par->txbuf.len / 2;
while (remain) {
to_copy = min(tx_array_size, remain);
dev_dbg(par->info->device, "to_copy=%zu, remain=%zu\n",
to_copy, remain - to_copy);
#ifdef __LITTLE_ENDIAN
for (i = 0; i < to_copy; i += 2) {
txbuf16[i] = 0x0100 | vmem8[i + 1];
txbuf16[i + 1] = 0x0100 | vmem8[i];
}
#else
for (i = 0; i < to_copy; i++)
txbuf16[i] = 0x0100 | vmem8[i];
#endif
vmem8 = vmem8 + to_copy;
ret = par->fbtftops.write(par, par->txbuf.buf, to_copy * 2);
if (ret < 0)
return ret;
remain -= to_copy;
}
return ret;
}
EXPORT_SYMBOL(fbtft_write_vmem16_bus9);
int fbtft_write_vmem8_bus8(struct fbtft_par *par, size_t offset, size_t len)
{
dev_err(par->info->device, "%s: function not implemented\n", __func__);
return -1;
}
EXPORT_SYMBOL(fbtft_write_vmem8_bus8);
/* 16 bit pixel over 16-bit databus */
int fbtft_write_vmem16_bus16(struct fbtft_par *par, size_t offset, size_t len)
{
u16 *vmem16;
fbtft_par_dbg(DEBUG_WRITE_VMEM, par, "%s(offset=%zu, len=%zu)\n",
__func__, offset, len);
vmem16 = (u16 *)(par->info->screen_buffer + offset);
/* no need for buffered write with 16-bit bus */
return fbtft_write_buf_dc(par, vmem16, len, 1);
}
EXPORT_SYMBOL(fbtft_write_vmem16_bus16);

View File

@ -0,0 +1,1337 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (C) 2013 Noralf Tronnes
*
* This driver is inspired by:
* st7735fb.c, Copyright (C) 2011, Matt Porter
* broadsheetfb.c, Copyright (C) 2008, Jaya Kumar
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/fb.h>
#include <linux/gpio/consumer.h>
#include <linux/spi/spi.h>
#include <linux/delay.h>
#include <linux/uaccess.h>
#include <linux/backlight.h>
#include <linux/platform_device.h>
#include <linux/property.h>
#include <linux/spinlock.h>
#include <video/mipi_display.h>
#include "fbtft.h"
#include "internal.h"
static unsigned long debug;
module_param(debug, ulong, 0000);
MODULE_PARM_DESC(debug, "override device debug level");
int fbtft_write_buf_dc(struct fbtft_par *par, void *buf, size_t len, int dc)
{
int ret;
gpiod_set_value(par->gpio.dc, dc);
ret = par->fbtftops.write(par, buf, len);
if (ret < 0)
dev_err(par->info->device,
"write() failed and returned %d\n", ret);
return ret;
}
EXPORT_SYMBOL(fbtft_write_buf_dc);
void fbtft_dbg_hex(const struct device *dev, int groupsize,
void *buf, size_t len, const char *fmt, ...)
{
va_list args;
static char textbuf[512];
char *text = textbuf;
size_t text_len;
va_start(args, fmt);
text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
va_end(args);
hex_dump_to_buffer(buf, len, 32, groupsize, text + text_len,
512 - text_len, false);
if (len > 32)
dev_info(dev, "%s ...\n", text);
else
dev_info(dev, "%s\n", text);
}
EXPORT_SYMBOL(fbtft_dbg_hex);
static int fbtft_request_one_gpio(struct fbtft_par *par,
const char *name, int index,
struct gpio_desc **gpiop)
{
struct device *dev = par->info->device;
*gpiop = devm_gpiod_get_index_optional(dev, name, index,
GPIOD_OUT_LOW);
if (IS_ERR(*gpiop))
return dev_err_probe(dev, PTR_ERR(*gpiop), "Failed to request %s GPIO\n", name);
fbtft_par_dbg(DEBUG_REQUEST_GPIOS, par, "%s: '%s' GPIO\n",
__func__, name);
return 0;
}
static int fbtft_request_gpios(struct fbtft_par *par)
{
int i;
int ret;
ret = fbtft_request_one_gpio(par, "reset", 0, &par->gpio.reset);
if (ret)
return ret;
ret = fbtft_request_one_gpio(par, "dc", 0, &par->gpio.dc);
if (ret)
return ret;
ret = fbtft_request_one_gpio(par, "rd", 0, &par->gpio.rd);
if (ret)
return ret;
ret = fbtft_request_one_gpio(par, "wr", 0, &par->gpio.wr);
if (ret)
return ret;
ret = fbtft_request_one_gpio(par, "cs", 0, &par->gpio.cs);
if (ret)
return ret;
ret = fbtft_request_one_gpio(par, "latch", 0, &par->gpio.latch);
if (ret)
return ret;
for (i = 0; i < 16; i++) {
ret = fbtft_request_one_gpio(par, "db", i,
&par->gpio.db[i]);
if (ret)
return ret;
ret = fbtft_request_one_gpio(par, "led", i,
&par->gpio.led[i]);
if (ret)
return ret;
ret = fbtft_request_one_gpio(par, "aux", i,
&par->gpio.aux[i]);
if (ret)
return ret;
}
return 0;
}
static int fbtft_backlight_update_status(struct backlight_device *bd)
{
struct fbtft_par *par = bl_get_data(bd);
bool polarity = par->polarity;
fbtft_par_dbg(DEBUG_BACKLIGHT, par,
"%s: polarity=%d, power=%d, fb_blank=%d\n",
__func__, polarity, bd->props.power, bd->props.fb_blank);
if ((bd->props.power == FB_BLANK_UNBLANK) &&
(bd->props.fb_blank == FB_BLANK_UNBLANK))
gpiod_set_value(par->gpio.led[0], polarity);
else
gpiod_set_value(par->gpio.led[0], !polarity);
return 0;
}
static int fbtft_backlight_get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
void fbtft_unregister_backlight(struct fbtft_par *par)
{
if (par->info->bl_dev) {
par->info->bl_dev->props.power = FB_BLANK_POWERDOWN;
backlight_update_status(par->info->bl_dev);
backlight_device_unregister(par->info->bl_dev);
par->info->bl_dev = NULL;
}
}
EXPORT_SYMBOL(fbtft_unregister_backlight);
static const struct backlight_ops fbtft_bl_ops = {
.get_brightness = fbtft_backlight_get_brightness,
.update_status = fbtft_backlight_update_status,
};
void fbtft_register_backlight(struct fbtft_par *par)
{
struct backlight_device *bd;
struct backlight_properties bl_props = { 0, };
if (!par->gpio.led[0]) {
fbtft_par_dbg(DEBUG_BACKLIGHT, par,
"%s(): led pin not set, exiting.\n", __func__);
return;
}
bl_props.type = BACKLIGHT_RAW;
/* Assume backlight is off, get polarity from current state of pin */
bl_props.power = FB_BLANK_POWERDOWN;
if (!gpiod_get_value(par->gpio.led[0]))
par->polarity = true;
bd = backlight_device_register(dev_driver_string(par->info->device),
par->info->device, par,
&fbtft_bl_ops, &bl_props);
if (IS_ERR(bd)) {
dev_err(par->info->device,
"cannot register backlight device (%ld)\n",
PTR_ERR(bd));
return;
}
par->info->bl_dev = bd;
if (!par->fbtftops.unregister_backlight)
par->fbtftops.unregister_backlight = fbtft_unregister_backlight;
}
EXPORT_SYMBOL(fbtft_register_backlight);
static void fbtft_set_addr_win(struct fbtft_par *par, int xs, int ys, int xe,
int ye)
{
write_reg(par, MIPI_DCS_SET_COLUMN_ADDRESS,
(xs >> 8) & 0xFF, xs & 0xFF, (xe >> 8) & 0xFF, xe & 0xFF);
write_reg(par, MIPI_DCS_SET_PAGE_ADDRESS,
(ys >> 8) & 0xFF, ys & 0xFF, (ye >> 8) & 0xFF, ye & 0xFF);
write_reg(par, MIPI_DCS_WRITE_MEMORY_START);
}
static void fbtft_reset(struct fbtft_par *par)
{
if (!par->gpio.reset)
return;
fbtft_par_dbg(DEBUG_RESET, par, "%s()\n", __func__);
gpiod_set_value_cansleep(par->gpio.reset, 1);
usleep_range(20, 40);
gpiod_set_value_cansleep(par->gpio.reset, 0);
msleep(120);
gpiod_set_value_cansleep(par->gpio.cs, 1); /* Activate chip */
}
static void fbtft_update_display(struct fbtft_par *par, unsigned int start_line,
unsigned int end_line)
{
size_t offset, len;
ktime_t ts_start, ts_end;
long fps, throughput;
bool timeit = false;
int ret = 0;
if (unlikely(par->debug & (DEBUG_TIME_FIRST_UPDATE |
DEBUG_TIME_EACH_UPDATE))) {
if ((par->debug & DEBUG_TIME_EACH_UPDATE) ||
((par->debug & DEBUG_TIME_FIRST_UPDATE) &&
!par->first_update_done)) {
ts_start = ktime_get();
timeit = true;
}
}
/* Sanity checks */
if (start_line > end_line) {
dev_warn(par->info->device,
"%s: start_line=%u is larger than end_line=%u. Shouldn't happen, will do full display update\n",
__func__, start_line, end_line);
start_line = 0;
end_line = par->info->var.yres - 1;
}
if (start_line > par->info->var.yres - 1 ||
end_line > par->info->var.yres - 1) {
dev_warn(par->info->device,
"%s: start_line=%u or end_line=%u is larger than max=%d. Shouldn't happen, will do full display update\n",
__func__, start_line,
end_line, par->info->var.yres - 1);
start_line = 0;
end_line = par->info->var.yres - 1;
}
fbtft_par_dbg(DEBUG_UPDATE_DISPLAY, par, "%s(start_line=%u, end_line=%u)\n",
__func__, start_line, end_line);
if (par->fbtftops.set_addr_win)
par->fbtftops.set_addr_win(par, 0, start_line,
par->info->var.xres - 1, end_line);
offset = start_line * par->info->fix.line_length;
len = (end_line - start_line + 1) * par->info->fix.line_length;
ret = par->fbtftops.write_vmem(par, offset, len);
if (ret < 0)
dev_err(par->info->device,
"%s: write_vmem failed to update display buffer\n",
__func__);
if (unlikely(timeit)) {
ts_end = ktime_get();
if (!ktime_to_ns(par->update_time))
par->update_time = ts_start;
fps = ktime_us_delta(ts_start, par->update_time);
par->update_time = ts_start;
fps = fps ? 1000000 / fps : 0;
throughput = ktime_us_delta(ts_end, ts_start);
throughput = throughput ? (len * 1000) / throughput : 0;
throughput = throughput * 1000 / 1024;
dev_info(par->info->device,
"Display update: %ld kB/s, fps=%ld\n",
throughput, fps);
par->first_update_done = true;
}
}
static void fbtft_mkdirty(struct fb_info *info, int y, int height)
{
struct fbtft_par *par = info->par;
struct fb_deferred_io *fbdefio = info->fbdefio;
/* special case, needed ? */
if (y == -1) {
y = 0;
height = info->var.yres;
}
/* Mark display lines/area as dirty */
spin_lock(&par->dirty_lock);
if (y < par->dirty_lines_start)
par->dirty_lines_start = y;
if (y + height - 1 > par->dirty_lines_end)
par->dirty_lines_end = y + height - 1;
spin_unlock(&par->dirty_lock);
/* Schedule deferred_io to update display (no-op if already on queue)*/
schedule_delayed_work(&info->deferred_work, fbdefio->delay);
}
static void fbtft_deferred_io(struct fb_info *info, struct list_head *pagelist)
{
struct fbtft_par *par = info->par;
unsigned int dirty_lines_start, dirty_lines_end;
struct page *page;
unsigned long index;
unsigned int y_low = 0, y_high = 0;
int count = 0;
spin_lock(&par->dirty_lock);
dirty_lines_start = par->dirty_lines_start;
dirty_lines_end = par->dirty_lines_end;
/* set display line markers as clean */
par->dirty_lines_start = par->info->var.yres - 1;
par->dirty_lines_end = 0;
spin_unlock(&par->dirty_lock);
/* Mark display lines as dirty */
list_for_each_entry(page, pagelist, lru) {
count++;
index = page->index << PAGE_SHIFT;
y_low = index / info->fix.line_length;
y_high = (index + PAGE_SIZE - 1) / info->fix.line_length;
dev_dbg(info->device,
"page->index=%lu y_low=%d y_high=%d\n",
page->index, y_low, y_high);
if (y_high > info->var.yres - 1)
y_high = info->var.yres - 1;
if (y_low < dirty_lines_start)
dirty_lines_start = y_low;
if (y_high > dirty_lines_end)
dirty_lines_end = y_high;
}
par->fbtftops.update_display(info->par,
dirty_lines_start, dirty_lines_end);
}
static void fbtft_fb_fillrect(struct fb_info *info,
const struct fb_fillrect *rect)
{
struct fbtft_par *par = info->par;
dev_dbg(info->dev,
"%s: dx=%d, dy=%d, width=%d, height=%d\n",
__func__, rect->dx, rect->dy, rect->width, rect->height);
sys_fillrect(info, rect);
par->fbtftops.mkdirty(info, rect->dy, rect->height);
}
static void fbtft_fb_copyarea(struct fb_info *info,
const struct fb_copyarea *area)
{
struct fbtft_par *par = info->par;
dev_dbg(info->dev,
"%s: dx=%d, dy=%d, width=%d, height=%d\n",
__func__, area->dx, area->dy, area->width, area->height);
sys_copyarea(info, area);
par->fbtftops.mkdirty(info, area->dy, area->height);
}
static void fbtft_fb_imageblit(struct fb_info *info,
const struct fb_image *image)
{
struct fbtft_par *par = info->par;
dev_dbg(info->dev,
"%s: dx=%d, dy=%d, width=%d, height=%d\n",
__func__, image->dx, image->dy, image->width, image->height);
sys_imageblit(info, image);
par->fbtftops.mkdirty(info, image->dy, image->height);
}
static ssize_t fbtft_fb_write(struct fb_info *info, const char __user *buf,
size_t count, loff_t *ppos)
{
struct fbtft_par *par = info->par;
ssize_t res;
dev_dbg(info->dev,
"%s: count=%zd, ppos=%llu\n", __func__, count, *ppos);
res = fb_sys_write(info, buf, count, ppos);
/* TODO: only mark changed area update all for now */
par->fbtftops.mkdirty(info, -1, 0);
return res;
}
/* from pxafb.c */
static unsigned int chan_to_field(unsigned int chan, struct fb_bitfield *bf)
{
chan &= 0xffff;
chan >>= 16 - bf->length;
return chan << bf->offset;
}
static int fbtft_fb_setcolreg(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
unsigned int transp, struct fb_info *info)
{
unsigned int val;
int ret = 1;
dev_dbg(info->dev,
"%s(regno=%u, red=0x%X, green=0x%X, blue=0x%X, trans=0x%X)\n",
__func__, regno, red, green, blue, transp);
switch (info->fix.visual) {
case FB_VISUAL_TRUECOLOR:
if (regno < 16) {
u32 *pal = info->pseudo_palette;
val = chan_to_field(red, &info->var.red);
val |= chan_to_field(green, &info->var.green);
val |= chan_to_field(blue, &info->var.blue);
pal[regno] = val;
ret = 0;
}
break;
}
return ret;
}
static int fbtft_fb_blank(int blank, struct fb_info *info)
{
struct fbtft_par *par = info->par;
int ret = -EINVAL;
dev_dbg(info->dev, "%s(blank=%d)\n",
__func__, blank);
if (!par->fbtftops.blank)
return ret;
switch (blank) {
case FB_BLANK_POWERDOWN:
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_NORMAL:
ret = par->fbtftops.blank(par, true);
break;
case FB_BLANK_UNBLANK:
ret = par->fbtftops.blank(par, false);
break;
}
return ret;
}
static void fbtft_merge_fbtftops(struct fbtft_ops *dst, struct fbtft_ops *src)
{
if (src->write)
dst->write = src->write;
if (src->read)
dst->read = src->read;
if (src->write_vmem)
dst->write_vmem = src->write_vmem;
if (src->write_register)
dst->write_register = src->write_register;
if (src->set_addr_win)
dst->set_addr_win = src->set_addr_win;
if (src->reset)
dst->reset = src->reset;
if (src->mkdirty)
dst->mkdirty = src->mkdirty;
if (src->update_display)
dst->update_display = src->update_display;
if (src->init_display)
dst->init_display = src->init_display;
if (src->blank)
dst->blank = src->blank;
if (src->request_gpios_match)
dst->request_gpios_match = src->request_gpios_match;
if (src->request_gpios)
dst->request_gpios = src->request_gpios;
if (src->verify_gpios)
dst->verify_gpios = src->verify_gpios;
if (src->register_backlight)
dst->register_backlight = src->register_backlight;
if (src->unregister_backlight)
dst->unregister_backlight = src->unregister_backlight;
if (src->set_var)
dst->set_var = src->set_var;
if (src->set_gamma)
dst->set_gamma = src->set_gamma;
}
/**
* fbtft_framebuffer_alloc - creates a new frame buffer info structure
*
* @display: pointer to structure describing the display
* @dev: pointer to the device for this fb, this can be NULL
* @pdata: platform data for the display in use
*
* Creates a new frame buffer info structure.
*
* Also creates and populates the following structures:
* info->fbops
* info->fbdefio
* info->pseudo_palette
* par->fbtftops
* par->txbuf
*
* Returns the new structure, or NULL if an error occurred.
*
*/
struct fb_info *fbtft_framebuffer_alloc(struct fbtft_display *display,
struct device *dev,
struct fbtft_platform_data *pdata)
{
struct fb_info *info;
struct fbtft_par *par;
struct fb_ops *fbops = NULL;
struct fb_deferred_io *fbdefio = NULL;
u8 *vmem = NULL;
void *txbuf = NULL;
void *buf = NULL;
unsigned int width;
unsigned int height;
int txbuflen = display->txbuflen;
unsigned int bpp = display->bpp;
unsigned int fps = display->fps;
int vmem_size;
const s16 *init_sequence = display->init_sequence;
char *gamma = display->gamma;
u32 *gamma_curves = NULL;
/* sanity check */
if (display->gamma_num * display->gamma_len >
FBTFT_GAMMA_MAX_VALUES_TOTAL) {
dev_err(dev, "FBTFT_GAMMA_MAX_VALUES_TOTAL=%d is exceeded\n",
FBTFT_GAMMA_MAX_VALUES_TOTAL);
return NULL;
}
/* defaults */
if (!fps)
fps = 20;
if (!bpp)
bpp = 16;
if (!pdata) {
dev_err(dev, "platform data is missing\n");
return NULL;
}
/* override driver values? */
if (pdata->fps)
fps = pdata->fps;
if (pdata->txbuflen)
txbuflen = pdata->txbuflen;
if (pdata->display.init_sequence)
init_sequence = pdata->display.init_sequence;
if (pdata->gamma)
gamma = pdata->gamma;
if (pdata->display.debug)
display->debug = pdata->display.debug;
if (pdata->display.backlight)
display->backlight = pdata->display.backlight;
if (pdata->display.width)
display->width = pdata->display.width;
if (pdata->display.height)
display->height = pdata->display.height;
if (pdata->display.buswidth)
display->buswidth = pdata->display.buswidth;
if (pdata->display.regwidth)
display->regwidth = pdata->display.regwidth;
display->debug |= debug;
fbtft_expand_debug_value(&display->debug);
switch (pdata->rotate) {
case 90:
case 270:
width = display->height;
height = display->width;
break;
default:
width = display->width;
height = display->height;
}
vmem_size = display->width * display->height * bpp / 8;
vmem = vzalloc(vmem_size);
if (!vmem)
goto alloc_fail;
fbops = devm_kzalloc(dev, sizeof(struct fb_ops), GFP_KERNEL);
if (!fbops)
goto alloc_fail;
fbdefio = devm_kzalloc(dev, sizeof(struct fb_deferred_io), GFP_KERNEL);
if (!fbdefio)
goto alloc_fail;
buf = devm_kzalloc(dev, 128, GFP_KERNEL);
if (!buf)
goto alloc_fail;
if (display->gamma_num && display->gamma_len) {
gamma_curves = devm_kcalloc(dev,
display->gamma_num *
display->gamma_len,
sizeof(gamma_curves[0]),
GFP_KERNEL);
if (!gamma_curves)
goto alloc_fail;
}
info = framebuffer_alloc(sizeof(struct fbtft_par), dev);
if (!info)
goto alloc_fail;
info->screen_buffer = vmem;
info->fbops = fbops;
info->fbdefio = fbdefio;
fbops->owner = dev->driver->owner;
fbops->fb_read = fb_sys_read;
fbops->fb_write = fbtft_fb_write;
fbops->fb_fillrect = fbtft_fb_fillrect;
fbops->fb_copyarea = fbtft_fb_copyarea;
fbops->fb_imageblit = fbtft_fb_imageblit;
fbops->fb_setcolreg = fbtft_fb_setcolreg;
fbops->fb_blank = fbtft_fb_blank;
fbdefio->delay = HZ / fps;
fbdefio->deferred_io = fbtft_deferred_io;
fb_deferred_io_init(info);
snprintf(info->fix.id, sizeof(info->fix.id), "%s", dev->driver->name);
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.visual = FB_VISUAL_TRUECOLOR;
info->fix.xpanstep = 0;
info->fix.ypanstep = 0;
info->fix.ywrapstep = 0;
info->fix.line_length = width * bpp / 8;
info->fix.accel = FB_ACCEL_NONE;
info->fix.smem_len = vmem_size;
info->var.rotate = pdata->rotate;
info->var.xres = width;
info->var.yres = height;
info->var.xres_virtual = info->var.xres;
info->var.yres_virtual = info->var.yres;
info->var.bits_per_pixel = bpp;
info->var.nonstd = 1;
/* RGB565 */
info->var.red.offset = 11;
info->var.red.length = 5;
info->var.green.offset = 5;
info->var.green.length = 6;
info->var.blue.offset = 0;
info->var.blue.length = 5;
info->var.transp.offset = 0;
info->var.transp.length = 0;
info->flags = FBINFO_FLAG_DEFAULT | FBINFO_VIRTFB;
par = info->par;
par->info = info;
par->pdata = pdata;
par->debug = display->debug;
par->buf = buf;
spin_lock_init(&par->dirty_lock);
par->bgr = pdata->bgr;
par->startbyte = pdata->startbyte;
par->init_sequence = init_sequence;
par->gamma.curves = gamma_curves;
par->gamma.num_curves = display->gamma_num;
par->gamma.num_values = display->gamma_len;
mutex_init(&par->gamma.lock);
info->pseudo_palette = par->pseudo_palette;
if (par->gamma.curves && gamma) {
if (fbtft_gamma_parse_str(par, par->gamma.curves, gamma,
strlen(gamma)))
goto release_framebuf;
}
/* Transmit buffer */
if (txbuflen == -1)
txbuflen = vmem_size + 2; /* add in case startbyte is used */
if (txbuflen >= vmem_size + 2)
txbuflen = 0;
#ifdef __LITTLE_ENDIAN
if ((!txbuflen) && (bpp > 8))
txbuflen = PAGE_SIZE; /* need buffer for byteswapping */
#endif
if (txbuflen > 0) {
txbuf = devm_kzalloc(par->info->device, txbuflen, GFP_KERNEL);
if (!txbuf)
goto release_framebuf;
par->txbuf.buf = txbuf;
par->txbuf.len = txbuflen;
}
/* default fbtft operations */
par->fbtftops.write = fbtft_write_spi;
par->fbtftops.read = fbtft_read_spi;
par->fbtftops.write_vmem = fbtft_write_vmem16_bus8;
par->fbtftops.write_register = fbtft_write_reg8_bus8;
par->fbtftops.set_addr_win = fbtft_set_addr_win;
par->fbtftops.reset = fbtft_reset;
par->fbtftops.mkdirty = fbtft_mkdirty;
par->fbtftops.update_display = fbtft_update_display;
if (display->backlight)
par->fbtftops.register_backlight = fbtft_register_backlight;
/* use driver provided functions */
fbtft_merge_fbtftops(&par->fbtftops, &display->fbtftops);
return info;
release_framebuf:
framebuffer_release(info);
alloc_fail:
vfree(vmem);
return NULL;
}
EXPORT_SYMBOL(fbtft_framebuffer_alloc);
/**
* fbtft_framebuffer_release - frees up all memory used by the framebuffer
*
* @info: frame buffer info structure
*
*/
void fbtft_framebuffer_release(struct fb_info *info)
{
fb_deferred_io_cleanup(info);
vfree(info->screen_buffer);
framebuffer_release(info);
}
EXPORT_SYMBOL(fbtft_framebuffer_release);
/**
* fbtft_register_framebuffer - registers a tft frame buffer device
* @fb_info: frame buffer info structure
*
* Sets SPI driverdata if needed
* Requests needed gpios.
* Initializes display
* Updates display.
* Registers a frame buffer device @fb_info.
*
* Returns negative errno on error, or zero for success.
*
*/
int fbtft_register_framebuffer(struct fb_info *fb_info)
{
int ret;
char text1[50] = "";
char text2[50] = "";
struct fbtft_par *par = fb_info->par;
struct spi_device *spi = par->spi;
/* sanity checks */
if (!par->fbtftops.init_display) {
dev_err(fb_info->device, "missing fbtftops.init_display()\n");
return -EINVAL;
}
if (spi)
spi_set_drvdata(spi, fb_info);
if (par->pdev)
platform_set_drvdata(par->pdev, fb_info);
ret = par->fbtftops.request_gpios(par);
if (ret < 0)
goto reg_fail;
if (par->fbtftops.verify_gpios) {
ret = par->fbtftops.verify_gpios(par);
if (ret < 0)
goto reg_fail;
}
ret = par->fbtftops.init_display(par);
if (ret < 0)
goto reg_fail;
if (par->fbtftops.set_var) {
ret = par->fbtftops.set_var(par);
if (ret < 0)
goto reg_fail;
}
/* update the entire display */
par->fbtftops.update_display(par, 0, par->info->var.yres - 1);
if (par->fbtftops.set_gamma && par->gamma.curves) {
ret = par->fbtftops.set_gamma(par, par->gamma.curves);
if (ret)
goto reg_fail;
}
if (par->fbtftops.register_backlight)
par->fbtftops.register_backlight(par);
ret = register_framebuffer(fb_info);
if (ret < 0)
goto reg_fail;
fbtft_sysfs_init(par);
if (par->txbuf.buf && par->txbuf.len >= 1024)
sprintf(text1, ", %zu KiB buffer memory", par->txbuf.len >> 10);
if (spi)
sprintf(text2, ", spi%d.%d at %d MHz", spi->master->bus_num,
spi->chip_select, spi->max_speed_hz / 1000000);
dev_info(fb_info->dev,
"%s frame buffer, %dx%d, %d KiB video memory%s, fps=%lu%s\n",
fb_info->fix.id, fb_info->var.xres, fb_info->var.yres,
fb_info->fix.smem_len >> 10, text1,
HZ / fb_info->fbdefio->delay, text2);
/* Turn on backlight if available */
if (fb_info->bl_dev) {
fb_info->bl_dev->props.power = FB_BLANK_UNBLANK;
fb_info->bl_dev->ops->update_status(fb_info->bl_dev);
}
return 0;
reg_fail:
if (par->fbtftops.unregister_backlight)
par->fbtftops.unregister_backlight(par);
return ret;
}
EXPORT_SYMBOL(fbtft_register_framebuffer);
/**
* fbtft_unregister_framebuffer - releases a tft frame buffer device
* @fb_info: frame buffer info structure
*
* Frees SPI driverdata if needed
* Frees gpios.
* Unregisters frame buffer device.
*
*/
int fbtft_unregister_framebuffer(struct fb_info *fb_info)
{
struct fbtft_par *par = fb_info->par;
if (par->fbtftops.unregister_backlight)
par->fbtftops.unregister_backlight(par);
fbtft_sysfs_exit(par);
unregister_framebuffer(fb_info);
return 0;
}
EXPORT_SYMBOL(fbtft_unregister_framebuffer);
/**
* fbtft_init_display_from_property() - Device Tree init_display() function
* @par: Driver data
*
* Return: 0 if successful, negative if error
*/
static int fbtft_init_display_from_property(struct fbtft_par *par)
{
struct device *dev = par->info->device;
int buf[64], count, index, i, j, ret;
u32 *values;
u32 val;
count = device_property_count_u32(dev, "init");
if (count < 0)
return count;
if (count == 0)
return -EINVAL;
values = kmalloc_array(count + 1, sizeof(*values), GFP_KERNEL);
if (!values)
return -ENOMEM;
ret = device_property_read_u32_array(dev, "init", values, count);
if (ret)
goto out_free;
par->fbtftops.reset(par);
index = -1;
val = values[++index];
while (index < count) {
if (val & FBTFT_OF_INIT_CMD) {
val &= 0xFFFF;
i = 0;
while ((index < count) && !(val & 0xFFFF0000)) {
if (i > 63) {
dev_err(dev,
"%s: Maximum register values exceeded\n",
__func__);
ret = -EINVAL;
goto out_free;
}
buf[i++] = val;
val = values[++index];
}
/* make debug message */
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par,
"init: write_register:\n");
for (j = 0; j < i; j++)
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par,
"buf[%d] = %02X\n", j, buf[j]);
par->fbtftops.write_register(par, i,
buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5], buf[6], buf[7],
buf[8], buf[9], buf[10], buf[11],
buf[12], buf[13], buf[14], buf[15],
buf[16], buf[17], buf[18], buf[19],
buf[20], buf[21], buf[22], buf[23],
buf[24], buf[25], buf[26], buf[27],
buf[28], buf[29], buf[30], buf[31],
buf[32], buf[33], buf[34], buf[35],
buf[36], buf[37], buf[38], buf[39],
buf[40], buf[41], buf[42], buf[43],
buf[44], buf[45], buf[46], buf[47],
buf[48], buf[49], buf[50], buf[51],
buf[52], buf[53], buf[54], buf[55],
buf[56], buf[57], buf[58], buf[59],
buf[60], buf[61], buf[62], buf[63]);
} else if (val & FBTFT_OF_INIT_DELAY) {
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par,
"init: msleep(%u)\n", val & 0xFFFF);
msleep(val & 0xFFFF);
val = values[++index];
} else {
dev_err(dev, "illegal init value 0x%X\n", val);
ret = -EINVAL;
goto out_free;
}
}
out_free:
kfree(values);
return ret;
}
/**
* fbtft_init_display() - Generic init_display() function
* @par: Driver data
*
* Uses par->init_sequence to do the initialization
*
* Return: 0 if successful, negative if error
*/
int fbtft_init_display(struct fbtft_par *par)
{
int buf[64];
char msg[128];
char str[16];
int i = 0;
int j;
/* sanity check */
if (!par->init_sequence) {
dev_err(par->info->device,
"error: init_sequence is not set\n");
return -EINVAL;
}
/* make sure stop marker exists */
for (i = 0; i < FBTFT_MAX_INIT_SEQUENCE; i++)
if (par->init_sequence[i] == -3)
break;
if (i == FBTFT_MAX_INIT_SEQUENCE) {
dev_err(par->info->device,
"missing stop marker at end of init sequence\n");
return -EINVAL;
}
par->fbtftops.reset(par);
i = 0;
while (i < FBTFT_MAX_INIT_SEQUENCE) {
if (par->init_sequence[i] == -3) {
/* done */
return 0;
}
if (par->init_sequence[i] >= 0) {
dev_err(par->info->device,
"missing delimiter at position %d\n", i);
return -EINVAL;
}
if (par->init_sequence[i + 1] < 0) {
dev_err(par->info->device,
"missing value after delimiter %d at position %d\n",
par->init_sequence[i], i);
return -EINVAL;
}
switch (par->init_sequence[i]) {
case -1:
i++;
/* make debug message */
strcpy(msg, "");
j = i + 1;
while (par->init_sequence[j] >= 0) {
sprintf(str, "0x%02X ", par->init_sequence[j]);
strcat(msg, str);
j++;
}
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par,
"init: write(0x%02X) %s\n",
par->init_sequence[i], msg);
/* Write */
j = 0;
while (par->init_sequence[i] >= 0) {
if (j > 63) {
dev_err(par->info->device,
"%s: Maximum register values exceeded\n",
__func__);
return -EINVAL;
}
buf[j++] = par->init_sequence[i++];
}
par->fbtftops.write_register(par, j,
buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5], buf[6], buf[7],
buf[8], buf[9], buf[10], buf[11],
buf[12], buf[13], buf[14], buf[15],
buf[16], buf[17], buf[18], buf[19],
buf[20], buf[21], buf[22], buf[23],
buf[24], buf[25], buf[26], buf[27],
buf[28], buf[29], buf[30], buf[31],
buf[32], buf[33], buf[34], buf[35],
buf[36], buf[37], buf[38], buf[39],
buf[40], buf[41], buf[42], buf[43],
buf[44], buf[45], buf[46], buf[47],
buf[48], buf[49], buf[50], buf[51],
buf[52], buf[53], buf[54], buf[55],
buf[56], buf[57], buf[58], buf[59],
buf[60], buf[61], buf[62], buf[63]);
break;
case -2:
i++;
fbtft_par_dbg(DEBUG_INIT_DISPLAY, par,
"init: mdelay(%d)\n",
par->init_sequence[i]);
mdelay(par->init_sequence[i++]);
break;
default:
dev_err(par->info->device,
"unknown delimiter %d at position %d\n",
par->init_sequence[i], i);
return -EINVAL;
}
}
dev_err(par->info->device,
"%s: something is wrong. Shouldn't get here.\n", __func__);
return -EINVAL;
}
EXPORT_SYMBOL(fbtft_init_display);
/**
* fbtft_verify_gpios() - Generic verify_gpios() function
* @par: Driver data
*
* Uses @spi, @pdev and @buswidth to determine which GPIOs is needed
*
* Return: 0 if successful, negative if error
*/
static int fbtft_verify_gpios(struct fbtft_par *par)
{
struct fbtft_platform_data *pdata = par->pdata;
int i;
fbtft_par_dbg(DEBUG_VERIFY_GPIOS, par, "%s()\n", __func__);
if (pdata->display.buswidth != 9 && par->startbyte == 0 &&
!par->gpio.dc) {
dev_err(par->info->device,
"Missing info about 'dc' gpio. Aborting.\n");
return -EINVAL;
}
if (!par->pdev)
return 0;
if (!par->gpio.wr) {
dev_err(par->info->device, "Missing 'wr' gpio. Aborting.\n");
return -EINVAL;
}
for (i = 0; i < pdata->display.buswidth; i++) {
if (!par->gpio.db[i]) {
dev_err(par->info->device,
"Missing 'db%02d' gpio. Aborting.\n", i);
return -EINVAL;
}
}
return 0;
}
/* returns 0 if the property is not present */
static u32 fbtft_property_value(struct device *dev, const char *propname)
{
int ret;
u32 val = 0;
ret = device_property_read_u32(dev, propname, &val);
if (ret == 0)
dev_info(dev, "%s: %s = %u\n", __func__, propname, val);
return val;
}
static struct fbtft_platform_data *fbtft_properties_read(struct device *dev)
{
struct fbtft_platform_data *pdata;
if (!dev_fwnode(dev)) {
dev_err(dev, "Missing platform data or properties\n");
return ERR_PTR(-EINVAL);
}
pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return ERR_PTR(-ENOMEM);
pdata->display.width = fbtft_property_value(dev, "width");
pdata->display.height = fbtft_property_value(dev, "height");
pdata->display.regwidth = fbtft_property_value(dev, "regwidth");
pdata->display.buswidth = fbtft_property_value(dev, "buswidth");
pdata->display.backlight = fbtft_property_value(dev, "backlight");
pdata->display.bpp = fbtft_property_value(dev, "bpp");
pdata->display.debug = fbtft_property_value(dev, "debug");
pdata->rotate = fbtft_property_value(dev, "rotate");
pdata->bgr = device_property_read_bool(dev, "bgr");
pdata->fps = fbtft_property_value(dev, "fps");
pdata->txbuflen = fbtft_property_value(dev, "txbuflen");
pdata->startbyte = fbtft_property_value(dev, "startbyte");
device_property_read_string(dev, "gamma", (const char **)&pdata->gamma);
if (device_property_present(dev, "led-gpios"))
pdata->display.backlight = 1;
if (device_property_present(dev, "init"))
pdata->display.fbtftops.init_display =
fbtft_init_display_from_property;
pdata->display.fbtftops.request_gpios = fbtft_request_gpios;
return pdata;
}
/**
* fbtft_probe_common() - Generic device probe() helper function
* @display: Display properties
* @sdev: SPI device
* @pdev: Platform device
*
* Allocates, initializes and registers a framebuffer
*
* Either @sdev or @pdev should be NULL
*
* Return: 0 if successful, negative if error
*/
int fbtft_probe_common(struct fbtft_display *display,
struct spi_device *sdev,
struct platform_device *pdev)
{
struct device *dev;
struct fb_info *info;
struct fbtft_par *par;
struct fbtft_platform_data *pdata;
int ret;
if (sdev)
dev = &sdev->dev;
else
dev = &pdev->dev;
if (unlikely(display->debug & DEBUG_DRIVER_INIT_FUNCTIONS))
dev_info(dev, "%s()\n", __func__);
pdata = dev->platform_data;
if (!pdata) {
pdata = fbtft_properties_read(dev);
if (IS_ERR(pdata))
return PTR_ERR(pdata);
}
info = fbtft_framebuffer_alloc(display, dev, pdata);
if (!info)
return -ENOMEM;
par = info->par;
par->spi = sdev;
par->pdev = pdev;
if (display->buswidth == 0) {
dev_err(dev, "buswidth is not set\n");
return -EINVAL;
}
/* write register functions */
if (display->regwidth == 8 && display->buswidth == 8)
par->fbtftops.write_register = fbtft_write_reg8_bus8;
else if (display->regwidth == 8 && display->buswidth == 9 && par->spi)
par->fbtftops.write_register = fbtft_write_reg8_bus9;
else if (display->regwidth == 16 && display->buswidth == 8)
par->fbtftops.write_register = fbtft_write_reg16_bus8;
else if (display->regwidth == 16 && display->buswidth == 16)
par->fbtftops.write_register = fbtft_write_reg16_bus16;
else
dev_warn(dev,
"no default functions for regwidth=%d and buswidth=%d\n",
display->regwidth, display->buswidth);
/* write_vmem() functions */
if (display->buswidth == 8)
par->fbtftops.write_vmem = fbtft_write_vmem16_bus8;
else if (display->buswidth == 9)
par->fbtftops.write_vmem = fbtft_write_vmem16_bus9;
else if (display->buswidth == 16)
par->fbtftops.write_vmem = fbtft_write_vmem16_bus16;
/* GPIO write() functions */
if (par->pdev) {
if (display->buswidth == 8)
par->fbtftops.write = fbtft_write_gpio8_wr;
else if (display->buswidth == 16)
par->fbtftops.write = fbtft_write_gpio16_wr;
}
/* 9-bit SPI setup */
if (par->spi && display->buswidth == 9) {
if (par->spi->master->bits_per_word_mask & SPI_BPW_MASK(9)) {
par->spi->bits_per_word = 9;
} else {
dev_warn(&par->spi->dev,
"9-bit SPI not available, emulating using 8-bit.\n");
/* allocate buffer with room for dc bits */
par->extra = devm_kzalloc(par->info->device,
par->txbuf.len +
(par->txbuf.len / 8) + 8,
GFP_KERNEL);
if (!par->extra) {
ret = -ENOMEM;
goto out_release;
}
par->fbtftops.write = fbtft_write_spi_emulate_9;
}
}
if (!par->fbtftops.verify_gpios)
par->fbtftops.verify_gpios = fbtft_verify_gpios;
/* make sure we still use the driver provided functions */
fbtft_merge_fbtftops(&par->fbtftops, &display->fbtftops);
/* use init_sequence if provided */
if (par->init_sequence)
par->fbtftops.init_display = fbtft_init_display;
/* use platform_data provided functions above all */
fbtft_merge_fbtftops(&par->fbtftops, &pdata->display.fbtftops);
ret = fbtft_register_framebuffer(info);
if (ret < 0)
goto out_release;
return 0;
out_release:
fbtft_framebuffer_release(info);
return ret;
}
EXPORT_SYMBOL(fbtft_probe_common);
/**
* fbtft_remove_common() - Generic device remove() helper function
* @dev: Device
* @info: Framebuffer
*
* Unregisters and releases the framebuffer
*
* Return: 0 if successful, negative if error
*/
int fbtft_remove_common(struct device *dev, struct fb_info *info)
{
struct fbtft_par *par;
if (!info)
return -EINVAL;
par = info->par;
if (par)
fbtft_par_dbg(DEBUG_DRIVER_INIT_FUNCTIONS, par,
"%s()\n", __func__);
fbtft_unregister_framebuffer(info);
fbtft_framebuffer_release(info);
return 0;
}
EXPORT_SYMBOL(fbtft_remove_common);
MODULE_LICENSE("GPL");

View File

@ -0,0 +1,236 @@
// SPDX-License-Identifier: GPL-2.0
#include <linux/export.h>
#include <linux/errno.h>
#include <linux/gpio/consumer.h>
#include <linux/spi/spi.h>
#include "fbtft.h"
int fbtft_write_spi(struct fbtft_par *par, void *buf, size_t len)
{
struct spi_transfer t = {
.tx_buf = buf,
.len = len,
};
struct spi_message m;
fbtft_par_dbg_hex(DEBUG_WRITE, par, par->info->device, u8, buf, len,
"%s(len=%zu): ", __func__, len);
if (!par->spi) {
dev_err(par->info->device,
"%s: par->spi is unexpectedly NULL\n", __func__);
return -1;
}
spi_message_init(&m);
spi_message_add_tail(&t, &m);
return spi_sync(par->spi, &m);
}
EXPORT_SYMBOL(fbtft_write_spi);
/**
* fbtft_write_spi_emulate_9() - write SPI emulating 9-bit
* @par: Driver data
* @buf: Buffer to write
* @len: Length of buffer (must be divisible by 8)
*
* When 9-bit SPI is not available, this function can be used to emulate that.
* par->extra must hold a transformation buffer used for transfer.
*/
int fbtft_write_spi_emulate_9(struct fbtft_par *par, void *buf, size_t len)
{
u16 *src = buf;
u8 *dst = par->extra;
size_t size = len / 2;
size_t added = 0;
int bits, i, j;
u64 val, dc, tmp;
fbtft_par_dbg_hex(DEBUG_WRITE, par, par->info->device, u8, buf, len,
"%s(len=%zu): ", __func__, len);
if (!par->extra) {
dev_err(par->info->device, "%s: error: par->extra is NULL\n",
__func__);
return -EINVAL;
}
if ((len % 8) != 0) {
dev_err(par->info->device,
"error: len=%zu must be divisible by 8\n", len);
return -EINVAL;
}
for (i = 0; i < size; i += 8) {
tmp = 0;
bits = 63;
for (j = 0; j < 7; j++) {
dc = (*src & 0x0100) ? 1 : 0;
val = *src & 0x00FF;
tmp |= dc << bits;
bits -= 8;
tmp |= val << bits--;
src++;
}
tmp |= ((*src & 0x0100) ? 1 : 0);
*(__be64 *)dst = cpu_to_be64(tmp);
dst += 8;
*dst++ = (u8)(*src++ & 0x00FF);
added++;
}
return spi_write(par->spi, par->extra, size + added);
}
EXPORT_SYMBOL(fbtft_write_spi_emulate_9);
int fbtft_read_spi(struct fbtft_par *par, void *buf, size_t len)
{
int ret;
u8 txbuf[32] = { 0, };
struct spi_transfer t = {
.speed_hz = 2000000,
.rx_buf = buf,
.len = len,
};
struct spi_message m;
if (!par->spi) {
dev_err(par->info->device,
"%s: par->spi is unexpectedly NULL\n", __func__);
return -ENODEV;
}
if (par->startbyte) {
if (len > 32) {
dev_err(par->info->device,
"len=%zu can't be larger than 32 when using 'startbyte'\n",
len);
return -EINVAL;
}
txbuf[0] = par->startbyte | 0x3;
t.tx_buf = txbuf;
fbtft_par_dbg_hex(DEBUG_READ, par, par->info->device, u8,
txbuf, len, "%s(len=%zu) txbuf => ",
__func__, len);
}
spi_message_init(&m);
spi_message_add_tail(&t, &m);
ret = spi_sync(par->spi, &m);
fbtft_par_dbg_hex(DEBUG_READ, par, par->info->device, u8, buf, len,
"%s(len=%zu) buf <= ", __func__, len);
return ret;
}
EXPORT_SYMBOL(fbtft_read_spi);
/*
* Optimized use of gpiolib is twice as fast as no optimization
* only one driver can use the optimized version at a time
*/
int fbtft_write_gpio8_wr(struct fbtft_par *par, void *buf, size_t len)
{
u8 data;
int i;
#ifndef DO_NOT_OPTIMIZE_FBTFT_WRITE_GPIO
static u8 prev_data;
#endif
fbtft_par_dbg_hex(DEBUG_WRITE, par, par->info->device, u8, buf, len,
"%s(len=%zu): ", __func__, len);
while (len--) {
data = *(u8 *)buf;
/* Start writing by pulling down /WR */
gpiod_set_value(par->gpio.wr, 1);
/* Set data */
#ifndef DO_NOT_OPTIMIZE_FBTFT_WRITE_GPIO
if (data == prev_data) {
gpiod_set_value(par->gpio.wr, 1); /* used as delay */
} else {
for (i = 0; i < 8; i++) {
if ((data & 1) != (prev_data & 1))
gpiod_set_value(par->gpio.db[i],
data & 1);
data >>= 1;
prev_data >>= 1;
}
}
#else
for (i = 0; i < 8; i++) {
gpiod_set_value(par->gpio.db[i], data & 1);
data >>= 1;
}
#endif
/* Pullup /WR */
gpiod_set_value(par->gpio.wr, 0);
#ifndef DO_NOT_OPTIMIZE_FBTFT_WRITE_GPIO
prev_data = *(u8 *)buf;
#endif
buf++;
}
return 0;
}
EXPORT_SYMBOL(fbtft_write_gpio8_wr);
int fbtft_write_gpio16_wr(struct fbtft_par *par, void *buf, size_t len)
{
u16 data;
int i;
#ifndef DO_NOT_OPTIMIZE_FBTFT_WRITE_GPIO
static u16 prev_data;
#endif
fbtft_par_dbg_hex(DEBUG_WRITE, par, par->info->device, u8, buf, len,
"%s(len=%zu): ", __func__, len);
while (len) {
data = *(u16 *)buf;
/* Start writing by pulling down /WR */
gpiod_set_value(par->gpio.wr, 1);
/* Set data */
#ifndef DO_NOT_OPTIMIZE_FBTFT_WRITE_GPIO
if (data == prev_data) {
gpiod_set_value(par->gpio.wr, 1); /* used as delay */
} else {
for (i = 0; i < 16; i++) {
if ((data & 1) != (prev_data & 1))
gpiod_set_value(par->gpio.db[i],
data & 1);
data >>= 1;
prev_data >>= 1;
}
}
#else
for (i = 0; i < 16; i++) {
gpiod_set_value(par->gpio.db[i], data & 1);
data >>= 1;
}
#endif
/* Pullup /WR */
gpiod_set_value(par->gpio.wr, 0);
#ifndef DO_NOT_OPTIMIZE_FBTFT_WRITE_GPIO
prev_data = *(u16 *)buf;
#endif
buf += 2;
len -= 2;
}
return 0;
}
EXPORT_SYMBOL(fbtft_write_gpio16_wr);
int fbtft_write_gpio16_wr_latched(struct fbtft_par *par, void *buf, size_t len)
{
dev_err(par->info->device, "%s: function not implemented\n", __func__);
return -1;
}
EXPORT_SYMBOL(fbtft_write_gpio16_wr_latched);

View File

@ -0,0 +1,220 @@
// SPDX-License-Identifier: GPL-2.0
#include "fbtft.h"
#include "internal.h"
static int get_next_ulong(char **str_p, unsigned long *val, char *sep, int base)
{
char *p_val;
if (!str_p || !(*str_p))
return -EINVAL;
p_val = strsep(str_p, sep);
if (!p_val)
return -EINVAL;
return kstrtoul(p_val, base, val);
}
int fbtft_gamma_parse_str(struct fbtft_par *par, u32 *curves,
const char *str, int size)
{
char *str_p, *curve_p = NULL;
char *tmp;
unsigned long val = 0;
int ret = 0;
int curve_counter, value_counter;
int _count;
fbtft_par_dbg(DEBUG_SYSFS, par, "%s() str=\n", __func__);
if (!str || !curves)
return -EINVAL;
fbtft_par_dbg(DEBUG_SYSFS, par, "%s\n", str);
tmp = kmemdup(str, size + 1, GFP_KERNEL);
if (!tmp)
return -ENOMEM;
/* replace optional separators */
str_p = tmp;
while (*str_p) {
if (*str_p == ',')
*str_p = ' ';
if (*str_p == ';')
*str_p = '\n';
str_p++;
}
str_p = strim(tmp);
curve_counter = 0;
while (str_p) {
if (curve_counter == par->gamma.num_curves) {
dev_err(par->info->device, "Gamma: Too many curves\n");
ret = -EINVAL;
goto out;
}
curve_p = strsep(&str_p, "\n");
value_counter = 0;
while (curve_p) {
if (value_counter == par->gamma.num_values) {
dev_err(par->info->device,
"Gamma: Too many values\n");
ret = -EINVAL;
goto out;
}
ret = get_next_ulong(&curve_p, &val, " ", 16);
if (ret)
goto out;
_count = curve_counter * par->gamma.num_values +
value_counter;
curves[_count] = val;
value_counter++;
}
if (value_counter != par->gamma.num_values) {
dev_err(par->info->device, "Gamma: Too few values\n");
ret = -EINVAL;
goto out;
}
curve_counter++;
}
if (curve_counter != par->gamma.num_curves) {
dev_err(par->info->device, "Gamma: Too few curves\n");
ret = -EINVAL;
goto out;
}
out:
kfree(tmp);
return ret;
}
static ssize_t
sprintf_gamma(struct fbtft_par *par, u32 *curves, char *buf)
{
ssize_t len = 0;
unsigned int i, j;
mutex_lock(&par->gamma.lock);
for (i = 0; i < par->gamma.num_curves; i++) {
for (j = 0; j < par->gamma.num_values; j++)
len += scnprintf(&buf[len], PAGE_SIZE,
"%04x ", curves[i * par->gamma.num_values + j]);
buf[len - 1] = '\n';
}
mutex_unlock(&par->gamma.lock);
return len;
}
static ssize_t store_gamma_curve(struct device *device,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct fb_info *fb_info = dev_get_drvdata(device);
struct fbtft_par *par = fb_info->par;
u32 tmp_curves[FBTFT_GAMMA_MAX_VALUES_TOTAL];
int ret;
ret = fbtft_gamma_parse_str(par, tmp_curves, buf, count);
if (ret)
return ret;
ret = par->fbtftops.set_gamma(par, tmp_curves);
if (ret)
return ret;
mutex_lock(&par->gamma.lock);
memcpy(par->gamma.curves, tmp_curves,
par->gamma.num_curves * par->gamma.num_values *
sizeof(tmp_curves[0]));
mutex_unlock(&par->gamma.lock);
return count;
}
static ssize_t show_gamma_curve(struct device *device,
struct device_attribute *attr, char *buf)
{
struct fb_info *fb_info = dev_get_drvdata(device);
struct fbtft_par *par = fb_info->par;
return sprintf_gamma(par, par->gamma.curves, buf);
}
static struct device_attribute gamma_device_attrs[] = {
__ATTR(gamma, 0660, show_gamma_curve, store_gamma_curve),
};
void fbtft_expand_debug_value(unsigned long *debug)
{
switch (*debug & 0x7) {
case 1:
*debug |= DEBUG_LEVEL_1;
break;
case 2:
*debug |= DEBUG_LEVEL_2;
break;
case 3:
*debug |= DEBUG_LEVEL_3;
break;
case 4:
*debug |= DEBUG_LEVEL_4;
break;
case 5:
*debug |= DEBUG_LEVEL_5;
break;
case 6:
*debug |= DEBUG_LEVEL_6;
break;
case 7:
*debug = 0xFFFFFFFF;
break;
}
}
static ssize_t store_debug(struct device *device,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct fb_info *fb_info = dev_get_drvdata(device);
struct fbtft_par *par = fb_info->par;
int ret;
ret = kstrtoul(buf, 10, &par->debug);
if (ret)
return ret;
fbtft_expand_debug_value(&par->debug);
return count;
}
static ssize_t show_debug(struct device *device,
struct device_attribute *attr, char *buf)
{
struct fb_info *fb_info = dev_get_drvdata(device);
struct fbtft_par *par = fb_info->par;
return snprintf(buf, PAGE_SIZE, "%lu\n", par->debug);
}
static struct device_attribute debug_device_attr =
__ATTR(debug, 0660, show_debug, store_debug);
void fbtft_sysfs_init(struct fbtft_par *par)
{
device_create_file(par->info->dev, &debug_device_attr);
if (par->gamma.curves && par->fbtftops.set_gamma)
device_create_file(par->info->dev, &gamma_device_attrs[0]);
}
void fbtft_sysfs_exit(struct fbtft_par *par)
{
device_remove_file(par->info->dev, &debug_device_attr);
if (par->gamma.curves && par->fbtftops.set_gamma)
device_remove_file(par->info->dev, &gamma_device_attrs[0]);
}

View File

@ -0,0 +1,423 @@
/* SPDX-License-Identifier: GPL-2.0+ */
/* Copyright (C) 2013 Noralf Tronnes */
#ifndef __LINUX_FBTFT_H
#define __LINUX_FBTFT_H
#include <linux/fb.h>
#include <linux/spinlock.h>
#include <linux/spi/spi.h>
#include <linux/platform_device.h>
#define FBTFT_ONBOARD_BACKLIGHT 2
#define FBTFT_GPIO_NO_MATCH 0xFFFF
#define FBTFT_GPIO_NAME_SIZE 32
#define FBTFT_MAX_INIT_SEQUENCE 512
#define FBTFT_GAMMA_MAX_VALUES_TOTAL 128
#define FBTFT_OF_INIT_CMD BIT(24)
#define FBTFT_OF_INIT_DELAY BIT(25)
/**
* struct fbtft_gpio - Structure that holds one pinname to gpio mapping
* @name: pinname (reset, dc, etc.)
* @gpio: GPIO number
*
*/
struct fbtft_gpio {
char name[FBTFT_GPIO_NAME_SIZE];
struct gpio_desc *gpio;
};
struct fbtft_par;
/**
* struct fbtft_ops - FBTFT operations structure
* @write: Writes to interface bus
* @read: Reads from interface bus
* @write_vmem: Writes video memory to display
* @write_reg: Writes to controller register
* @set_addr_win: Set the GRAM update window
* @reset: Reset the LCD controller
* @mkdirty: Marks display lines for update
* @update_display: Updates the display
* @init_display: Initializes the display
* @blank: Blank the display (optional)
* @request_gpios_match: Do pinname to gpio matching
* @request_gpios: Request gpios from the kernel
* @free_gpios: Free previously requested gpios
* @verify_gpios: Verify that necessary gpios is present (optional)
* @register_backlight: Used to register backlight device (optional)
* @unregister_backlight: Unregister backlight device (optional)
* @set_var: Configure LCD with values from variables like @rotate and @bgr
* (optional)
* @set_gamma: Set Gamma curve (optional)
*
* Most of these operations have default functions assigned to them in
* fbtft_framebuffer_alloc()
*/
struct fbtft_ops {
int (*write)(struct fbtft_par *par, void *buf, size_t len);
int (*read)(struct fbtft_par *par, void *buf, size_t len);
int (*write_vmem)(struct fbtft_par *par, size_t offset, size_t len);
void (*write_register)(struct fbtft_par *par, int len, ...);
void (*set_addr_win)(struct fbtft_par *par,
int xs, int ys, int xe, int ye);
void (*reset)(struct fbtft_par *par);
void (*mkdirty)(struct fb_info *info, int from, int to);
void (*update_display)(struct fbtft_par *par,
unsigned int start_line, unsigned int end_line);
int (*init_display)(struct fbtft_par *par);
int (*blank)(struct fbtft_par *par, bool on);
unsigned long (*request_gpios_match)(struct fbtft_par *par,
const struct fbtft_gpio *gpio);
int (*request_gpios)(struct fbtft_par *par);
int (*verify_gpios)(struct fbtft_par *par);
void (*register_backlight)(struct fbtft_par *par);
void (*unregister_backlight)(struct fbtft_par *par);
int (*set_var)(struct fbtft_par *par);
int (*set_gamma)(struct fbtft_par *par, u32 *curves);
};
/**
* struct fbtft_display - Describes the display properties
* @width: Width of display in pixels
* @height: Height of display in pixels
* @regwidth: LCD Controller Register width in bits
* @buswidth: Display interface bus width in bits
* @backlight: Backlight type.
* @fbtftops: FBTFT operations provided by driver or device (platform_data)
* @bpp: Bits per pixel
* @fps: Frames per second
* @txbuflen: Size of transmit buffer
* @init_sequence: Pointer to LCD initialization array
* @gamma: String representation of Gamma curve(s)
* @gamma_num: Number of Gamma curves
* @gamma_len: Number of values per Gamma curve
* @debug: Initial debug value
*
* This structure is not stored by FBTFT except for init_sequence.
*/
struct fbtft_display {
unsigned int width;
unsigned int height;
unsigned int regwidth;
unsigned int buswidth;
unsigned int backlight;
struct fbtft_ops fbtftops;
unsigned int bpp;
unsigned int fps;
int txbuflen;
const s16 *init_sequence;
char *gamma;
int gamma_num;
int gamma_len;
unsigned long debug;
};
/**
* struct fbtft_platform_data - Passes display specific data to the driver
* @display: Display properties
* @gpios: Pointer to an array of pinname to gpio mappings
* @rotate: Display rotation angle
* @bgr: LCD Controller BGR bit
* @fps: Frames per second (this will go away, use @fps in @fbtft_display)
* @txbuflen: Size of transmit buffer
* @startbyte: When set, enables use of Startbyte in transfers
* @gamma: String representation of Gamma curve(s)
* @extra: A way to pass extra info
*/
struct fbtft_platform_data {
struct fbtft_display display;
unsigned int rotate;
bool bgr;
unsigned int fps;
int txbuflen;
u8 startbyte;
char *gamma;
void *extra;
};
/**
* struct fbtft_par - Main FBTFT data structure
*
* This structure holds all relevant data to operate the display
*
* See sourcefile for documentation since nested structs is not
* supported by kernel-doc.
*
*/
/* @spi: Set if it is a SPI device
* @pdev: Set if it is a platform device
* @info: Pointer to framebuffer fb_info structure
* @pdata: Pointer to platform data
* @ssbuf: Not used
* @pseudo_palette: Used by fb_set_colreg()
* @txbuf.buf: Transmit buffer
* @txbuf.len: Transmit buffer length
* @buf: Small buffer used when writing init data over SPI
* @startbyte: Used by some controllers when in SPI mode.
* Format: 6 bit Device id + RS bit + RW bit
* @fbtftops: FBTFT operations provided by driver or device (platform_data)
* @dirty_lock: Protects dirty_lines_start and dirty_lines_end
* @dirty_lines_start: Where to begin updating display
* @dirty_lines_end: Where to end updating display
* @gpio.reset: GPIO used to reset display
* @gpio.dc: Data/Command signal, also known as RS
* @gpio.rd: Read latching signal
* @gpio.wr: Write latching signal
* @gpio.latch: Bus latch signal, eg. 16->8 bit bus latch
* @gpio.cs: LCD Chip Select with parallel interface bus
* @gpio.db[16]: Parallel databus
* @gpio.led[16]: Led control signals
* @gpio.aux[16]: Auxiliary signals, not used by core
* @init_sequence: Pointer to LCD initialization array
* @gamma.lock: Mutex for Gamma curve locking
* @gamma.curves: Pointer to Gamma curve array
* @gamma.num_values: Number of values per Gamma curve
* @gamma.num_curves: Number of Gamma curves
* @debug: Pointer to debug value
* @current_debug:
* @first_update_done: Used to only time the first display update
* @update_time: Used to calculate 'fps' in debug output
* @bgr: BGR mode/\n
* @extra: Extra info needed by driver
*/
struct fbtft_par {
struct spi_device *spi;
struct platform_device *pdev;
struct fb_info *info;
struct fbtft_platform_data *pdata;
u16 *ssbuf;
u32 pseudo_palette[16];
struct {
void *buf;
size_t len;
} txbuf;
u8 *buf;
u8 startbyte;
struct fbtft_ops fbtftops;
spinlock_t dirty_lock;
unsigned int dirty_lines_start;
unsigned int dirty_lines_end;
struct {
struct gpio_desc *reset;
struct gpio_desc *dc;
struct gpio_desc *rd;
struct gpio_desc *wr;
struct gpio_desc *latch;
struct gpio_desc *cs;
struct gpio_desc *db[16];
struct gpio_desc *led[16];
struct gpio_desc *aux[16];
} gpio;
const s16 *init_sequence;
struct {
struct mutex lock;
u32 *curves;
int num_values;
int num_curves;
} gamma;
unsigned long debug;
bool first_update_done;
ktime_t update_time;
bool bgr;
void *extra;
bool polarity;
};
#define NUMARGS(...) (sizeof((int[]){__VA_ARGS__}) / sizeof(int))
#define write_reg(par, ...) \
((par)->fbtftops.write_register(par, NUMARGS(__VA_ARGS__), __VA_ARGS__))
/* fbtft-core.c */
int fbtft_write_buf_dc(struct fbtft_par *par, void *buf, size_t len, int dc);
__printf(5, 6)
void fbtft_dbg_hex(const struct device *dev, int groupsize,
void *buf, size_t len, const char *fmt, ...);
struct fb_info *fbtft_framebuffer_alloc(struct fbtft_display *display,
struct device *dev,
struct fbtft_platform_data *pdata);
void fbtft_framebuffer_release(struct fb_info *info);
int fbtft_register_framebuffer(struct fb_info *fb_info);
int fbtft_unregister_framebuffer(struct fb_info *fb_info);
void fbtft_register_backlight(struct fbtft_par *par);
void fbtft_unregister_backlight(struct fbtft_par *par);
int fbtft_init_display(struct fbtft_par *par);
int fbtft_probe_common(struct fbtft_display *display, struct spi_device *sdev,
struct platform_device *pdev);
int fbtft_remove_common(struct device *dev, struct fb_info *info);
/* fbtft-io.c */
int fbtft_write_spi(struct fbtft_par *par, void *buf, size_t len);
int fbtft_write_spi_emulate_9(struct fbtft_par *par, void *buf, size_t len);
int fbtft_read_spi(struct fbtft_par *par, void *buf, size_t len);
int fbtft_write_gpio8_wr(struct fbtft_par *par, void *buf, size_t len);
int fbtft_write_gpio16_wr(struct fbtft_par *par, void *buf, size_t len);
int fbtft_write_gpio16_wr_latched(struct fbtft_par *par, void *buf, size_t len);
/* fbtft-bus.c */
int fbtft_write_vmem8_bus8(struct fbtft_par *par, size_t offset, size_t len);
int fbtft_write_vmem16_bus16(struct fbtft_par *par, size_t offset, size_t len);
int fbtft_write_vmem16_bus8(struct fbtft_par *par, size_t offset, size_t len);
int fbtft_write_vmem16_bus9(struct fbtft_par *par, size_t offset, size_t len);
void fbtft_write_reg8_bus8(struct fbtft_par *par, int len, ...);
void fbtft_write_reg8_bus9(struct fbtft_par *par, int len, ...);
void fbtft_write_reg16_bus8(struct fbtft_par *par, int len, ...);
void fbtft_write_reg16_bus16(struct fbtft_par *par, int len, ...);
#define FBTFT_REGISTER_DRIVER(_name, _compatible, _display) \
\
static int fbtft_driver_probe_spi(struct spi_device *spi) \
{ \
return fbtft_probe_common(_display, spi, NULL); \
} \
\
static int fbtft_driver_remove_spi(struct spi_device *spi) \
{ \
struct fb_info *info = spi_get_drvdata(spi); \
\
return fbtft_remove_common(&spi->dev, info); \
} \
\
static int fbtft_driver_probe_pdev(struct platform_device *pdev) \
{ \
return fbtft_probe_common(_display, NULL, pdev); \
} \
\
static int fbtft_driver_remove_pdev(struct platform_device *pdev) \
{ \
struct fb_info *info = platform_get_drvdata(pdev); \
\
return fbtft_remove_common(&pdev->dev, info); \
} \
\
static const struct of_device_id dt_ids[] = { \
{ .compatible = _compatible }, \
{}, \
}; \
\
MODULE_DEVICE_TABLE(of, dt_ids); \
\
\
static struct spi_driver fbtft_driver_spi_driver = { \
.driver = { \
.name = _name, \
.of_match_table = dt_ids, \
}, \
.probe = fbtft_driver_probe_spi, \
.remove = fbtft_driver_remove_spi, \
}; \
\
static struct platform_driver fbtft_driver_platform_driver = { \
.driver = { \
.name = _name, \
.owner = THIS_MODULE, \
.of_match_table = dt_ids, \
}, \
.probe = fbtft_driver_probe_pdev, \
.remove = fbtft_driver_remove_pdev, \
}; \
\
static int __init fbtft_driver_module_init(void) \
{ \
int ret; \
\
ret = spi_register_driver(&fbtft_driver_spi_driver); \
if (ret < 0) \
return ret; \
ret = platform_driver_register(&fbtft_driver_platform_driver); \
if (ret < 0) \
spi_unregister_driver(&fbtft_driver_spi_driver); \
return ret; \
} \
\
static void __exit fbtft_driver_module_exit(void) \
{ \
spi_unregister_driver(&fbtft_driver_spi_driver); \
platform_driver_unregister(&fbtft_driver_platform_driver); \
} \
\
module_init(fbtft_driver_module_init); \
module_exit(fbtft_driver_module_exit);
/* Debug macros */
/* shorthand debug levels */
#define DEBUG_LEVEL_1 DEBUG_REQUEST_GPIOS
#define DEBUG_LEVEL_2 (DEBUG_LEVEL_1 | DEBUG_DRIVER_INIT_FUNCTIONS \
| DEBUG_TIME_FIRST_UPDATE)
#define DEBUG_LEVEL_3 (DEBUG_LEVEL_2 | DEBUG_RESET | DEBUG_INIT_DISPLAY \
| DEBUG_BLANK | DEBUG_REQUEST_GPIOS \
| DEBUG_FREE_GPIOS \
| DEBUG_VERIFY_GPIOS \
| DEBUG_BACKLIGHT | DEBUG_SYSFS)
#define DEBUG_LEVEL_4 (DEBUG_LEVEL_2 | DEBUG_FB_READ | DEBUG_FB_WRITE \
| DEBUG_FB_FILLRECT \
| DEBUG_FB_COPYAREA \
| DEBUG_FB_IMAGEBLIT | DEBUG_FB_BLANK)
#define DEBUG_LEVEL_5 (DEBUG_LEVEL_3 | DEBUG_UPDATE_DISPLAY)
#define DEBUG_LEVEL_6 (DEBUG_LEVEL_4 | DEBUG_LEVEL_5)
#define DEBUG_LEVEL_7 0xFFFFFFFF
#define DEBUG_DRIVER_INIT_FUNCTIONS BIT(3)
#define DEBUG_TIME_FIRST_UPDATE BIT(4)
#define DEBUG_TIME_EACH_UPDATE BIT(5)
#define DEBUG_DEFERRED_IO BIT(6)
#define DEBUG_FBTFT_INIT_FUNCTIONS BIT(7)
/* fbops */
#define DEBUG_FB_READ BIT(8)
#define DEBUG_FB_WRITE BIT(9)
#define DEBUG_FB_FILLRECT BIT(10)
#define DEBUG_FB_COPYAREA BIT(11)
#define DEBUG_FB_IMAGEBLIT BIT(12)
#define DEBUG_FB_SETCOLREG BIT(13)
#define DEBUG_FB_BLANK BIT(14)
#define DEBUG_SYSFS BIT(16)
/* fbtftops */
#define DEBUG_BACKLIGHT BIT(17)
#define DEBUG_READ BIT(18)
#define DEBUG_WRITE BIT(19)
#define DEBUG_WRITE_VMEM BIT(20)
#define DEBUG_WRITE_REGISTER BIT(21)
#define DEBUG_SET_ADDR_WIN BIT(22)
#define DEBUG_RESET BIT(23)
#define DEBUG_MKDIRTY BIT(24)
#define DEBUG_UPDATE_DISPLAY BIT(25)
#define DEBUG_INIT_DISPLAY BIT(26)
#define DEBUG_BLANK BIT(27)
#define DEBUG_REQUEST_GPIOS BIT(28)
#define DEBUG_FREE_GPIOS BIT(29)
#define DEBUG_REQUEST_GPIOS_MATCH BIT(30)
#define DEBUG_VERIFY_GPIOS BIT(31)
#define fbtft_init_dbg(dev, format, arg...) \
do { \
if (unlikely((dev)->platform_data && \
(((struct fbtft_platform_data *)(dev)->platform_data)->display.debug & DEBUG_DRIVER_INIT_FUNCTIONS))) \
dev_info(dev, format, ##arg); \
} while (0)
#define fbtft_par_dbg(level, par, format, arg...) \
do { \
if (unlikely((par)->debug & (level))) \
dev_info((par)->info->device, format, ##arg); \
} while (0)
#define fbtft_par_dbg_hex(level, par, dev, type, buf, num, format, arg...) \
do { \
if (unlikely((par)->debug & (level))) \
fbtft_dbg_hex(dev, sizeof(type), buf,\
(num) * sizeof(type), format, ##arg); \
} while (0)
#endif /* __LINUX_FBTFT_H */

View File

@ -0,0 +1,13 @@
/* SPDX-License-Identifier: GPL-2.0+ */
/* Copyright (C) 2013 Noralf Tronnes */
#ifndef __LINUX_FBTFT_INTERNAL_H
#define __LINUX_FBTFT_INTERNAL_H
void fbtft_sysfs_init(struct fbtft_par *par);
void fbtft_sysfs_exit(struct fbtft_par *par);
void fbtft_expand_debug_value(unsigned long *debug);
int fbtft_gamma_parse_str(struct fbtft_par *par, u32 *curves,
const char *str, int size);
#endif /* __LINUX_FBTFT_INTERNAL_H */

36
feed/spidev/Makefile Normal file
View File

@ -0,0 +1,36 @@
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=spidev
PKG_VERSION:=3.6
PKG_RELEASE:=$(AUTORELEASE)
PYPI_NAME:=$(PKG_NAME)
PKG_HASH:=14dbc37594a4aaef85403ab617985d3c3ef464d62bc9b769ef552db53701115b
PKG_MAINTAINER:=Lee Miller <lee.miller@tutanota.com>
PKG_LICENSE:=MIT
include $(TOPDIR)/feeds/packages/lang/python/pypi.mk
include $(INCLUDE_DIR)/package.mk
include $(TOPDIR)/feeds/packages/lang/python/python3-package.mk
define Package/python3-$(PKG_NAME)
SECTION:=lang
CATEGORY:=Languages
SUBMENU:=Python
TITLE:=Python bindings for Linux SPI access through spidev
URL:=http://github.com/doceme/py-spidev
DEPENDS:=+python3 +python3-setuptools
endef
define Package/python3-$(PKG_NAME)/description
This project contains a python module for interfacing with SPI devices
from user space via the spidev linux kernel driver.
endef
$(eval $(call Py3Package,python3-$(PKG_NAME)))
$(eval $(call BuildPackage,python3-$(PKG_NAME)))
$(eval $(call BuildPackage,python3-$(PKG_NAME)-src))

View File

@ -0,0 +1,32 @@
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=waveshare-demo
PKG_VERSION:=0.0.2
PKG_RELEASE:=1
PKG_MAINTAINER:=Lee Miller <lee.miller@tutanota.com>
PKG_LICENSE:=BSD
include $(INCLUDE_DIR)/package.mk
include $(TOPDIR)/feeds/packages/lang/python/python3-package.mk
define Package/python3-$(PKG_NAME)
SECTION:=lang
CATEGORY:=Languages
SUBMENU:=Python
TITLE:=CM4-NAS-Double-Deck Demo
URL:=https://www.waveshare.com/wiki/CM4-NAS-Double-Deck
DEPENDS:=+python3 +python3-setuptools +python3-numpy +python3-pillow \
+python3-spidev +lsblk +procps-ng
endef
define Package/python3-$(PKG_NAME)/description
CM4-NAS-Double-Deck Demo
endef
$(eval $(call Py3Package,python3-$(PKG_NAME)))
$(eval $(call BuildPackage,python3-$(PKG_NAME)))

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

View File

@ -0,0 +1,15 @@
from setuptools import setup
setup(
name='waveshare',
version='0.0.2',
description='CM4-NAS-Double-Deck Demo packaged',
url='https://www.waveshare.com/wiki/CM4-NAS-Double-Deck',
install_requires=['spidev', 'RPi.GPIO', 'numpy'],
packages=['waveshare', 'waveshare.lib'],
package_data={
'waveshare': ['Font/*.ttf', 'pic/*.jpg']},
entry_points={'console_scripts': ['waveshare-demo = waveshare.main']}
)

View File

@ -0,0 +1,572 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import time
import logging
import math
import re
import threading
from PIL import Image, ImageDraw, ImageFont
import RPi.GPIO as GPIO
from .lib import LCD_2inch
from .lib import Gain_Param
logging.basicConfig(level=logging.DEBUG)
app_dir = os.path.dirname(os.path.realpath(__file__))
class image():
flgh = True
def __init__(self):
# display with hardware SPI:
''' Warning!!!Don't creation of multiple displayer objects!!! '''
self.gain = Gain_Param.Gain_Param()
GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.IN)
GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP)
t1 = threading.Thread(target=self.gain.Hard_data, name="thread1")
t2 = threading.Thread(target=self.key, name="thread2")
t1.daemon = True
t2.daemon = True
t1.start()
t2.start()
self.disp = LCD_2inch.LCD_2inch()
# Initialize library.
self.disp.Init()
# Clear display.
self.disp.clear()
# Create blank image for drawing.
self.image1 = Image.new(
"RGB", (self.disp.height, self.disp.width), "WHITE")
self.draw = ImageDraw.Draw(self.image1)
def key(self):
count = 0
while True:
if GPIO.input(20) == 0:
count = count + 1
else:
if count > 5:
self.flgh = not self.flgh
count = 0
def HMI1(self):
try:
self.image = Image.open(os.path.join(app_dir, "pic", "BL.jpg"))
self.draw = ImageDraw.Draw(self.image)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 28)
self.draw.text((90, 2), 'Device Status', fill=0xf7ba47, font=Font1)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
self.draw.text((267, 141), 'TEMP', fill=0xf7ba47, font=Font1)
self.draw.text((190, 141), 'RAM', fill=0xf7ba47, font=Font1)
self.draw.text((267, 141), 'TEMP', fill=0xf7ba47, font=Font1)
self.draw.text((30, 141), 'CPU', fill=0xf7ba47, font=Font1)
self.draw.text((107, 141), 'Disk', fill=0xf7ba47, font=Font1)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 10)
self.draw.text(
(205, 170), 'R X', fill=0xffffff, font=Font1, stroke_width=1)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 10)
self.draw.text(
(270, 170), 'T X', fill=0xffffff, font=Font1, stroke_width=1)
# TIME 时间
time_t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
self.draw.text((5, 50), time_t, fill=0xf7ba47, font=Font1)
# IP
ip = self.gain.GET_IP()
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
self.draw.text((170, 50), 'IP : ' + ip, fill=0xf7ba47, font=Font1)
# CPU usage CPU使用率
self.CPU_usage = os.popen(
'top -bi -n 2 -d 0.02'
).read().split('\n\n\n')[0].split('\n')[2]
self.CPU_usage = re.sub('[a-zA-z%(): ]', '', self.CPU_usage)
self.CPU_usage = self.CPU_usage.split(',')
self.CPU_usagex = 100 - eval(self.CPU_usage[3])
if self.CPU_usagex >= 100:
self.draw.text(
(27, 100), str(math.floor(self.CPU_usagex)) + '%',
fill=0xf1b400, font=Font1)
elif self.CPU_usagex >= 10:
self.draw.text(
(30, 100), str(math.floor(self.CPU_usagex)) + '%',
fill=0xf1b400, font=Font1)
else:
self.draw.text(
(34, 100), str(math.floor(self.CPU_usagex)) + '%',
fill=0xf1b400, font=Font1)
self.draw.arc((10, 80, 70, 142), 0, 360, fill=0xffffff, width=8)
self.draw.arc(
(10, 80, 70, 142), -90, -90 + self.CPU_usagex * 360 / 100,
fill=0x60ad4c, width=8)
# System disk usage 系统磁盘使用率
x = os.popen('df -h /')
i2 = 0
while 1:
i2 = i2 + 1
line = x.readline()
if i2 == 2:
# Memory usage (%) 使用内存(百分值)
self.Capacity_usage = line.split()[4]
self.Hard_capacity = int(
re.sub('[%]', '', self.Capacity_usage))
break
if self.Hard_capacity >= 100:
self.draw.text(
(107, 100), str(math.floor(self.Hard_capacity)) + '%',
fill=0xf1b400, font=Font1)
elif self.Hard_capacity >= 10:
self.draw.text(
(111, 100), str(math.floor(self.Hard_capacity)) + '%',
fill=0xf1b400, font=Font1)
else:
self.draw.text(
(114, 100), str(math.floor(self.Hard_capacity)) + '%',
fill=0xf1b400, font=Font1)
self.draw.arc((90, 80, 150, 142), 0, 360, fill=0xffffff, width=8)
self.draw.arc(
(90, 80, 150, 142), -90, -90 + self.Hard_capacity * 360 / 100,
fill=0x7f35e9, width=8)
# TEMP 温度
self.temp_t = self.gain.GET_Temp()
if self.temp_t < 45:
self.disp._pwm1.ChangeDutyCycle(50)
elif self.temp_t < 50:
self.disp._pwm1.ChangeDutyCycle(70)
elif self.temp_t < 55:
self.disp._pwm1.ChangeDutyCycle(80)
else:
self.disp._pwm1.ChangeDutyCycle(100)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 18)
self.draw.text(
(268, 100), str(math.floor(self.temp_t)) + '',
fill=0x0088ff, font=Font1)
self.draw.arc((253, 80, 313, 142), 0, 360, fill=0xffffff, width=8)
self.draw.arc(
(253, 80, 313, 142), -90, -90 + self.temp_t * 360 / 100,
fill=0x0088ff, width=8)
# speed 网速
TX = self.gain.TX_speed() * 1024
if TX < 1024: # B
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 18)
self.draw.text(
(250, 190), str(math.floor(TX)) + 'B/s',
fill=0x00ff00, font=Font1)
elif TX < 1024 * 1024: # K
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 17)
self.draw.text(
(249, 190), str(math.floor(TX/1024)) + 'KB/s',
fill=0x00ffff, font=Font1)
else: # M
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 18)
self.draw.text(
(250, 190), str(math.floor(TX/1024/1024)) + 'M/s',
fill=0x008fff, font=Font1)
TX = self.gain.RX_speed() * 1024
if TX < 1024: # B
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 18)
self.draw.text(
(183, 190), str(math.floor(TX)) + 'B/s',
fill=0x00ff00, font=Font1)
elif TX < 1024 * 1024: # K
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 17)
self.draw.text(
(180, 190), str(math.floor(TX/1024)) + 'KB/s',
fill=0x008fff, font=Font1)
else: # M
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 18)
self.draw.text(
(181, 190), str(math.floor(TX/1024/1024)) + 'M/s',
fill=0x008fff, font=Font1)
# memory_percentage 内存百分比
tot_m, used_m, free_m = map(
int, os.popen('free -t -m').readlines()[-1].split()[1:])
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 18)
memory_percentage = 100 - free_m / tot_m * 100
if memory_percentage >= 100:
self.draw.text(
(186, 100), str(math.floor(memory_percentage)) + '%',
fill=0xf1b400, font=Font1)
elif memory_percentage >= 10:
self.draw.text(
(189, 100), str(math.floor(memory_percentage)) + '%',
fill=0xf1b400, font=Font1)
else:
self.draw.text(
(195, 100), str(math.floor(memory_percentage)) + '%',
fill=0xf1b400, font=Font1)
self.draw.arc((173, 80, 233, 142), 0, 360, fill=0xffffff, width=8)
self.draw.arc(
(173, 80, 233, 142), -90, -90 + memory_percentage * 360 / 100,
fill=0xf1b400, width=8)
# Disk 使用情况
if self.gain.Get_back[0] == 0:
self.draw.rectangle((40, 177, 142, 190))
self.draw.rectangle((41, 178, 141, 189), fill=0x000000)
else:
self.draw.rectangle((40, 177, 142, 190))
self.draw.rectangle(
(41, 178, 41 + self.gain.Get_back[2], 189), fill=0x7f35e9)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 13)
self.draw.text(
(80, 176), str(math.floor(self.gain.Get_back[2])) + '%',
fill=0xf1b400, font=Font1)
if self.gain.Get_back[1] == 0:
self.draw.rectangle((40, 197, 142, 210))
self.draw.rectangle((41, 198, 141, 209), fill=0x000000)
else:
self.draw.rectangle((40, 197, 142, 210))
self.draw.rectangle(
(41, 198, 41 + self.gain.Get_back[3], 209), fill=0x7f35e9)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 13)
self.draw.text(
(80, 196), str(math.floor(self.gain.Get_back[3])) + '%',
fill=0xf1b400, font=Font1)
if self.gain.Get_back[4] == 1:
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
self.draw.text((40, 161), 'RAID', fill=0xf7ba47, font=Font1)
if (
(self.gain.Get_back[0] == 0 and self.gain.Get_back[1] == 0)
or (self.gain.Get_back[0] != 0 and self.gain.Get_back[1] == 0)
or (self.gain.Get_back[0] == 0 and self.gain.Get_back[1] != 0)
):
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
if self.gain.flag > 0:
self.draw.text(
(30, 210), 'Detected but not installed',
fill=0xf7ba47, font=Font1)
else:
self.draw.text(
(50, 210), 'Unpartitioned/NC',
fill=0xf7ba47, font=Font1)
self.image = self.image.rotate(180)
self.disp.ShowImage(self.image)
# time.sleep(0.5)
except IOError as e:
logging.info(e)
except KeyboardInterrupt:
self.disp.module_exit()
logging.info("quit:")
exit()
def HMI2(self):
try:
self.image = Image.open(os.path.join(app_dir, "pic", 'Disk.jpg'))
self.draw = ImageDraw.Draw(self.image)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 20)
self.draw.text((60, 55), 'CPU Used', fill=0xC1C0BE, font=Font1)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 13)
self.draw.text((45, 140), 'Used', fill=0xC1C0BE, font=Font1)
self.draw.text((45, 163), 'Free', fill=0xC1C0BE, font=Font1)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 14)
self.draw.text((185, 93), 'Disk0:', fill=0xC1C0BE, font=Font1)
self.draw.text((185, 114), 'Disk1:', fill=0xC1C0BE, font=Font1)
self.draw.text((188, 155), 'TX:', fill=0xC1C0BE, font=Font1)
self.draw.text((188, 175), 'RX:', fill=0xC1C0BE, font=Font1)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
self.draw.text((133, 205), 'TEMP:', fill=0x0088ff, font=Font1)
# TIME 时间
time_t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
self.draw.text((40, 10), time_t, fill=0xffffff, font=Font1)
# IP
ip = self.gain.GET_IP()
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 17)
self.draw.text((155, 58), 'IP : ' + ip, fill=0xC1C0BE, font=Font1)
# CPU usage CPU使用率
self.CPU_usage = os.popen(
'top -bi -n 2 -d 0.02'
).read().split('\n\n\n')[0].split('\n')[2]
self.CPU_usage = re.sub('[a-zA-z%(): ]', '', self.CPU_usage)
self.CPU_usage = self.CPU_usage.split(',')
self.CPU_usagex = 100 - eval(self.CPU_usage[3])
if self.CPU_usagex >= 100:
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 10)
self.draw.text(
(80, 107), str(math.floor(self.CPU_usagex)) + '%',
fill=0xf1b400, font=Font1)
elif self.CPU_usagex >= 10:
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 13)
self.draw.text(
(79, 105), str(math.floor(self.CPU_usagex)) + '%',
fill=0xf1b400, font=Font1)
else:
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
self.draw.text(
(81, 104), str(math.floor(self.CPU_usagex)) + '%',
fill=0xf1b400, font=Font1)
self.draw.arc(
(66, 90, 111, 135), -90, -90 + self.CPU_usagex * 360 / 100,
fill=0x7f35e9, width=3)
# System disk usage 系统磁盘使用率
x = os.popen('df -h /')
i2 = 0
while 1:
i2 = i2 + 1
line = x.readline()
if i2 == 2:
self.Capacity_Used = line.split()[2]
self.Capacity_Avail = line.split()[3]
if (
self.Capacity_Used.count('G')
and self.Capacity_Avail.count('G')
):
self.Used_capacity = float(
re.sub('[A-Z]', '', self.Capacity_Used)) * 1024
self.Avail_capacity = float(
re.sub('[A-Z]', '', self.Capacity_Avail)) * 1024
elif (
self.Capacity_Used.count('G')
and self.Capacity_Avail.count('M')
):
self.Used_capacity = float(
re.sub('[A-Z]', '', self.Capacity_Used)) * 1024
self.Avail_capacity = float(
re.sub('[A-Z]', '', self.Capacity_Avail))
elif (
self.Capacity_Used.count('M')
and self.Capacity_Avail.count('G')
):
self.Used_capacity = float(
re.sub('[A-Z]', '', self.Capacity_Used))
self.Avail_capacity = float(
re.sub('[A-Z]', '', self.Capacity_Avail)) * 1024
else:
self.Used_capacity = float(
re.sub('[A-Z]', '', self.Capacity_Used))
self.Avail_capacity = float(
re.sub('[A-Z]', '', self.Capacity_Avail))
break
if(self.Used_capacity > 1024 and self.Avail_capacity > 1024):
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 13)
self.draw.text((125, 140), 'G', fill=0xC1C0BE, font=Font1)
self.draw.text((125, 163), 'G', fill=0xC1C0BE, font=Font1)
self.Used_capacity = self.Used_capacity / 1024
self.Avail_capacity = self.Avail_capacity / 1024
self.Disk_always = self.Used_capacity + self.Avail_capacity
if self.Disk_always <= 99:
self.draw.text(
(100, 140), str(round(self.Used_capacity, 2)),
fill=0xC1C0BE, font=Font1)
self.draw.text(
(100, 163), str(round(self.Avail_capacity, 2)),
fill=0xC1C0BE, font=Font1,)
elif self.Disk_always > 99:
self.draw.text(
(85, 140), str(round(self.Used_capacity, 2)),
fill=0xC1C0BE, font=Font1)
self.draw.text(
(85, 163), str(round(self.Avail_capacity, 2)),
fill=0xC1C0BE, font=Font1)
else:
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 13)
self.draw.text((125, 140), 'M', fill=0xC1C0BE, font=Font1)
self.draw.text((125, 163), 'M', fill=0xC1C0BE, font=Font1)
self.Disk_always = self.Used_capacity + self.Avail_capacity
self.draw.text(
(80, 140), str(round(self.Used_capacity, 2)),
fill=0xC1C0BE, font=Font1)
self.draw.text(
(80, 163), str(round(self.Avail_capacity, 2)),
fill=0xC1C0BE, font=Font1)
self.draw.rectangle((
45, 157, 45 + self.Used_capacity / self.Disk_always * 87, 160
), fill=0x7f35e9)
self.draw.rectangle((
45, 180, 45 + self.Avail_capacity / self.Disk_always * 87, 183
), fill=0x7f35e9)
# TEMP 温度
temp_t = self.gain.GET_Temp()
if self.temp_t < 45:
self.disp._pwm1.ChangeDutyCycle(50)
elif self.temp_t < 50:
self.disp._pwm1.ChangeDutyCycle(70)
elif self.temp_t < 55:
self.disp._pwm1.ChangeDutyCycle(80)
else:
self.disp._pwm1.ChangeDutyCycle(100)
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
self.draw.text(
(170, 205), str(math.floor(temp_t))+'',
fill=0x0088ff, font=Font1)
# speed 网速
TX = self.gain.TX_speed() * 1024
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 15)
if TX < 1024: # B
self.draw.text(
(210, 154), str(math.floor(TX)) + 'B/s',
fill=0x00ff00, font=Font1)
elif TX < 1024*1024: # K
self.draw.text(
(210, 154), str(math.floor(TX/1024)) + 'KB/s',
fill=0x00ffff, font=Font1)
else: # M
self.draw.text(
(210, 154), str(math.floor(TX/1024/1024)) + 'M/s',
fill=0x008fff, font=Font1)
TX = self.gain.RX_speed() * 1024
if TX < 1024: # B
self.draw.text(
(210, 174), str(math.floor(TX)) + 'B/s',
fill=0x00ff00, font=Font1)
elif TX < 1024*1024: # K
self.draw.text(
(210, 174), str(math.floor(TX/1024)) + 'KB/s',
fill=0x008fff, font=Font1)
else: # M
self.draw.text(
(210, 174), str(math.floor(TX/1024/1024)) + 'M/s',
fill=0x008fff, font=Font1)
# Disk 使用情况
self.Disk0_Avail = self.gain.Get_back[0] - (
self.gain.Get_back[0] * self.gain.Get_back[2] // 100)
self.Disk1_Avail = self.gain.Get_back[1] - (
self.gain.Get_back[1] * self.gain.Get_back[3] // 100)
self.draw.text(
(240, 93), str(math.floor(self.Disk0_Avail)) + 'G',
fill=0xC1C0BE, font=Font1)
self.draw.text(
(240, 114), str(math.floor(self.Disk1_Avail)) + 'G',
fill=0xC1C0BE, font=Font1)
if self.gain.Get_back[0] == 0:
self.draw.rectangle((186, 110, 273, 113), fill=0x000000)
else:
self.draw.rectangle(
(186, 110, 186 + self.gain.Get_back[2] * 87 / 100, 113),
fill=0x7f35e9)
if self.gain.Get_back[1] == 0:
self.draw.rectangle((186, 131, 273, 134), fill=0x000000)
else:
self.draw.rectangle(
(186, 131, 186 + self.gain.Get_back[3] * 87 / 100, 134),
fill=0x7f35e9)
if self.gain.Get_back[4] == 1:
self.draw.text((160, 78), 'RAID', fill=0xC1C0BE, font=Font1)
if (
(self.gain.Get_back[0] == 0 and self.gain.Get_back[1] == 0)
or (self.gain.Get_back[0] != 0 and self.gain.Get_back[1] == 0)
or (self.gain.Get_back[0] == 0 and self.gain.Get_back[1] != 0)
):
Font1 = ImageFont.truetype(
os.path.join(app_dir, "Font", "Font02.ttf"), 14)
if self.gain.flag > 0:
self.draw.text(
(155, 135), 'Detected but not installed',
fill=0xC1C0BE, font=Font1)
else:
self.draw.text(
(190, 135), 'Unpartitioned/NC',
fill=0xC1C0BE, font=Font1)
self.image = self.image.rotate(180)
self.disp.ShowImage(self.image)
# time.sleep(0.5)
except IOError as e:
logging.info(e)
except KeyboardInterrupt:
self.disp.module_exit()
logging.info("quit:")
exit()

View File

@ -0,0 +1,233 @@
# -*- coding: utf-8 -*-
import os
import re
import time
import socket
class Gain_Param():
Get_back = [0, 0, 0, 0, 0] # 返回Disk的内存
flag = 0 # 未挂载还是未分区
def GET_IP(self):
# 会存在异常 卡死 谨慎获取
# There will be exceptions, get stuck, get it carefully
# Threading is better
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect_ex(('8.8.8.8', 80))
ip = s.getsockname()[0]
s.close()
return ip
def GET_Temp(self):
with open('/sys/class/thermal/thermal_zone0/temp', 'rt') as f:
temp = int(f.read()) / 1000.0
# print(temp)
return temp
def net_speed(self, interface, is_download):
# Get the corresponding value 获取对应值
which_num = 0 if is_download else 8
# Read the file 读取文件
with open('/proc/net/dev') as f:
lines = f.readlines()
# Get result value 获取结果值
for line in lines:
if line.rstrip().split(':')[0].strip() == interface:
return line.rstrip().split(':')[1].split()[which_num]
def RX_speed(self):
interface = 'eth0'
is_upload = True # False
get_time = 0.1
# Computation part 计算部分
begin = int(self.net_speed(interface, is_upload))
time.sleep(get_time)
end = int(self.net_speed(interface, is_upload))
return ((end - begin) / get_time / 1024)
def TX_speed(self):
interface = 'eth0'
is_upload = False
get_time = 0.1
# Computation part 计算部分
begin = int(self.net_speed(interface, is_upload))
time.sleep(get_time)
end = int(self.net_speed(interface, is_upload))
return ((end - begin) / get_time / 1024)
def Hard_data(self):
while True:
Hard_capacity1 = os.popen('lsblk -f ').read().split('\n\n\n')[0]
Disk_number = sum(
1 for i in re.finditer(r'^[a-z]', Hard_capacity1, re.MULTILINE)
)
Hard_segmentation = Hard_capacity1.split('\n\n\n')[0].split('\n')
k = 0 # Counting migration 计数偏移
j = 0 # 连接盘的数量
Disk0_capacity = 0 # total capacity 总容量
Disk0_usege = 0 # have been used 已使用
Disk1_capacity = 0
Disk1_usege = 0
for i in range(0, Disk_number):
if i == 0:
a = Hard_segmentation[k+1].strip().split()
if len(a) != 1:
if a[1].count('raid') == 1:
self.Get_back[4] = 1 # 检测是否组RAID '1'表示组了
else:
self.Get_back[4] = 0
if(a[0].count('mmcblk') == 1):
continue
name0 = a[0]
else:
a = Hard_segmentation[k+1].strip().split()
if a[0].count('mmcblk') == 1:
continue
if len(a) != 1:
if a[1].count('raid') == 1:
self.Get_back[4] = 1 # 检测是否组RAID '1'表示组了
else:
self.Get_back[4] = 0
flgh = 0
j = j + 1
if len(a) == 1:
disk_partition_Number = Hard_capacity1.count(''+a[0])
self.Get_back[4] = 0
else:
if a[1].count('raid') == 0:
self.Get_back[4] = 0
disk_partition_Number = Hard_capacity1.count(''+a[0])
else:
disk_partition_Number = 1
self.Get_back[4] = 1
if(disk_partition_Number == 0):
disk_partition_Number = 1
flgh = 1
for i1 in range(0, disk_partition_Number):
if (disk_partition_Number > 0 and flgh == 0):
Partition_data_split = ' '.join(
Hard_segmentation[i1+2+k].split()).split(' ')
else:
Partition_data_split = ' '.join(
Hard_segmentation[i1+1+k].split()).split(' ')
if (
len(Partition_data_split) <= 5
and len(Partition_data_split) > 0
):
# name = re.sub('[├─└]', '', Partition_data_split[0])
if len(Partition_data_split) == 1:
self.flag = 0
else:
# print(
# "%s This drive letter is not mounted\n"
# % name)
self.flag = 1 # 检测是否挂载盘 1表示没有挂载
# continue
else:
# print("%s The drive letter is properly mounted\n" % (
# re.sub('[├─└]', '', Partition_data_split[0])))
if (
disk_partition_Number > 0 and name0 == a[0]
or self.Get_back[4] == 1
):
p = os.popen(
"df -h " + Partition_data_split[len(
Partition_data_split) - 1])
i2 = 0
while 1:
i2 = i2 + 1
line = p.readline()
if i2 == 2:
#: Total cost of the partition 分区总值
Capacity = line.split()[1]
x = int(re.sub('[A-Za-z]', '', Capacity))
Disk0_capacity = Disk0_capacity + x
Capacity = "".join(list(filter(
str.isdigit, Capacity)))
# Partition memory usage 分区使用内存
Capacity_usage = line.split()[2]
if Capacity_usage.count('G'):
x = float(re.sub(
'[A-Z]', '', Capacity_usage))
Disk0_usege = Disk0_usege + x
break
else:
x = float(re.sub(
'[A-Z]', '', Capacity_usage)
) / 1024
Disk0_usege = Disk0_usege + x
break
else:
p = os.popen(
"df -h " + Partition_data_split[len(
Partition_data_split) - 1])
i2 = 0
while 1:
i2 = i2 + 1
line = p.readline()
if i2 == 2:
# Total cost of the partition 分区总值
Capacity = line.split()[1]
x = int(re.sub('[A-Za-z]', '', Capacity))
Disk1_capacity = Disk1_capacity + x
# Partition memory usage 分区使用内存
Capacity_usage = line.split()[2]
if(Capacity_usage.count('G')):
x = float(re.sub(
'[A-Z]', '', Capacity_usage))
Disk1_usege = Disk1_usege + x
break
else:
x = float(re.sub(
'[A-Z]', '', Capacity_usage)
) / 1024
Disk1_usege = Disk1_usege + x
break
if(flgh == 0):
k = k + disk_partition_Number + 1
else:
k = k + disk_partition_Number
if j == 1 and len(Partition_data_split) > 5:
self.flag = 0
if self.Get_back[4] == 1:
Disk1_capacity = Disk0_capacity / 2
Disk0_capacity = Disk1_capacity
Disk1_usege = Disk0_usege / 2
Disk0_usege = Disk1_usege
if Disk0_capacity == 0 and Disk1_capacity == 0:
self.Get_back = [
Disk0_capacity, Disk1_capacity, Disk0_usege, Disk1_usege,
self.Get_back[4]]
elif Disk0_capacity == 0 and Disk1_capacity != 0:
Disk1_usege = round(Disk1_usege / Disk1_capacity * 100, 0)
self.Get_back = [
Disk0_capacity, Disk1_capacity, Disk0_usege, Disk1_usege,
self.Get_back[4]]
elif Disk0_capacity != 0 and Disk1_capacity == 0:
Disk0_usege = round(Disk0_usege / Disk0_capacity * 100, 0)
self.Get_back = [
Disk0_capacity, Disk1_capacity, Disk0_usege, Disk1_usege,
self.Get_back[4]]
else:
Disk0_usege = round(Disk0_usege / Disk0_capacity * 100, 0)
Disk1_usege = round(Disk1_usege / Disk1_capacity * 100, 0)
self.Get_back = [
Disk0_capacity, Disk1_capacity, Disk0_usege, Disk1_usege,
self.Get_back[4]]
time.sleep(1.5)

View File

@ -0,0 +1,185 @@
import time
from . import lcdconfig
class LCD_2inch(lcdconfig.RaspberryPi):
width = 240
height = 320
def command(self, cmd):
self.digital_write(self.DC_PIN, self.GPIO.LOW)
self.spi_writebyte([cmd])
def data(self, val):
self.digital_write(self.DC_PIN, self.GPIO.HIGH)
self.spi_writebyte([val])
def reset(self):
"""Reset the display"""
self.GPIO.output(self.RST_PIN, self.GPIO.HIGH)
time.sleep(0.01)
self.GPIO.output(self.RST_PIN, self.GPIO.LOW)
time.sleep(0.01)
self.GPIO.output(self.RST_PIN, self.GPIO.HIGH)
time.sleep(0.01)
def Init(self):
"""Initialize dispaly"""
self.module_init()
self.reset()
self.command(0x36)
self.data(0x00)
self.command(0x3A)
self.data(0x05)
self.command(0x21)
self.command(0x2A)
self.data(0x00)
self.data(0x00)
self.data(0x01)
self.data(0x3F)
self.command(0x2B)
self.data(0x00)
self.data(0x00)
self.data(0x00)
self.data(0xEF)
self.command(0xB2)
self.data(0x0C)
self.data(0x0C)
self.data(0x00)
self.data(0x33)
self.data(0x33)
self.command(0xB7)
self.data(0x35)
self.command(0xBB)
self.data(0x1F)
self.command(0xC0)
self.data(0x2C)
self.command(0xC2)
self.data(0x01)
self.command(0xC3)
self.data(0x12)
self.command(0xC4)
self.data(0x20)
self.command(0xC6)
self.data(0x0F)
self.command(0xD0)
self.data(0xA4)
self.data(0xA1)
self.command(0xE0)
self.data(0xD0)
self.data(0x08)
self.data(0x11)
self.data(0x08)
self.data(0x0C)
self.data(0x15)
self.data(0x39)
self.data(0x33)
self.data(0x50)
self.data(0x36)
self.data(0x13)
self.data(0x14)
self.data(0x29)
self.data(0x2D)
self.command(0xE1)
self.data(0xD0)
self.data(0x08)
self.data(0x10)
self.data(0x08)
self.data(0x06)
self.data(0x06)
self.data(0x39)
self.data(0x44)
self.data(0x51)
self.data(0x0B)
self.data(0x16)
self.data(0x14)
self.data(0x2F)
self.data(0x31)
self.command(0x21)
self.command(0x11)
self.command(0x29)
def SetWindows(self, Xstart, Ystart, Xend, Yend):
self.command(0x2A)
#: set the X coordinates
self.data(Xstart >> 8)
#: Set the horizontal starting point to the high octet
self.data(Xstart & 0xff)
#: Set the horizontal starting point to the low octet
self.data(Xend >> 8)
#: Set the horizontal end to the high octet
self.data((Xend - 1) & 0xff)
#: Set the horizontal end to the low octet
self.command(0x2B)
#: set the Y coordinates
self.data(Ystart >> 8)
self.data((Ystart & 0xff))
self.data(Yend >> 8)
self.data((Yend - 1) & 0xff)
self.command(0x2C)
def ShowImage(self, Image, Xstart=0, Ystart=0):
"""Set buffer to value of Python Imaging Library image."""
"""Write display buffer to physical display"""
imwidth, imheight = Image.size
if imwidth == self.height and imheight == self.width:
img = self.np.asarray(Image)
pix = self.np.zeros(
(self.width, self.height, 2), dtype=self.np.uint8)
# RGB888 >> RGB565
pix[...,[0]] = self.np.add(self.np.bitwise_and(img[...,[0]],0xF8),self.np.right_shift(img[...,[1]],5))
pix[...,[1]] = self.np.add(self.np.bitwise_and(self.np.left_shift(img[...,[1]],3),0xE0), self.np.right_shift(img[...,[2]],3))
pix = pix.flatten().tolist()
self.command(0x36)
self.data(0x70)
self.SetWindows(0, 0, self.height, self.width)
self.digital_write(self.DC_PIN, self.GPIO.HIGH)
for i in range(0, len(pix), 4096):
self.spi_writebyte(pix[i:i+4096])
else:
img = self.np.asarray(Image)
pix = self.np.zeros((imheight, imwidth, 2), dtype=self.np.uint8)
pix[...,[0]] = self.np.add(self.np.bitwise_and(img[...,[0]],0xF8),self.np.right_shift(img[...,[1]],5))
pix[...,[1]] = self.np.add(self.np.bitwise_and(self.np.left_shift(img[...,[1]],3),0xE0), self.np.right_shift(img[...,[2]],3))
pix = pix.flatten().tolist()
self.command(0x36)
self.data(0x00)
self.SetWindows(0, 0, self.width, self.height)
self.digital_write(self.DC_PIN, self.GPIO.HIGH)
for i in range(0, len(pix), 4096):
self.spi_writebyte(pix[i:i+4096])
def clear(self):
"""Clear contents of image buffer"""
_buffer = [0xff]*(self.width * self.height * 2)
self.SetWindows(0, 0, self.width, self.height)
self.digital_write(self.DC_PIN, self.GPIO.HIGH)
for i in range(0, len(_buffer), 4096):
self.spi_writebyte(_buffer[i:i+4096])

View File

@ -0,0 +1,118 @@
# /*****************************************************************************
# * | File : epdconfig.py
# * | Author : Waveshare team
# * | Function : Hardware underlying interface
# * | Info :
# *----------------
# * | This version: V1.0
# * | Date : 2019-06-21
# * | Info :
# ******************************************************************************
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import logging
import time
import spidev
class RaspberryPi:
def __init__(
self, spi=spidev.SpiDev(0, 0), spi_freq=40000000, rst=27, dc=25, bl=18,
fan=19, bl_freq=1000, i2c=None, i2c_freq=100000
):
import RPi.GPIO
import numpy as np
self.np = np
self.RST_PIN = rst
self.DC_PIN = dc
self.BL_PIN = bl
self.FAN_PIN = fan
self.SPEED = spi_freq
self.BL_freq = bl_freq
self.GPIO = RPi.GPIO
# self.GPIO.cleanup()
self.GPIO.setmode(self.GPIO.BCM)
self.GPIO.setwarnings(False)
self.GPIO.setup(self.RST_PIN, self.GPIO.OUT)
self.GPIO.setup(self.DC_PIN, self.GPIO.OUT)
self.GPIO.setup(self.BL_PIN, self.GPIO.OUT)
self.GPIO.output(self.BL_PIN, self.GPIO.HIGH)
# Initialize SPI
self.SPI = spi
if self.SPI is not None:
self.SPI.max_speed_hz = spi_freq
self.SPI.mode = 0b00
def digital_write(self, pin, value):
self.GPIO.output(pin, value)
def digital_read(self, pin):
return self.GPIO.input(pin)
def delay_ms(self, delaytime):
time.sleep(delaytime / 1000.0)
def spi_writebyte(self, data):
if self.SPI is not None:
self.SPI.writebytes(data)
def bl_DutyCycle(self, duty):
self._pwm.ChangeDutyCycle(duty)
def bl_Frequency(self, freq):
self._pwm.ChangeFrequency(freq)
def module_init(self):
self.GPIO.setup(self.RST_PIN, self.GPIO.OUT)
self.GPIO.setup(self.DC_PIN, self.GPIO.OUT)
self.GPIO.setup(self.BL_PIN, self.GPIO.OUT)
self.GPIO.setup(self.FAN_PIN, self.GPIO.OUT)
# self.GPIO.output(self.FAN_PIN, 1)
self._pwm = self.GPIO.PWM(self.BL_PIN, self.BL_freq)
self._pwm.start(100)
self._pwm1 = self.GPIO.PWM(self.FAN_PIN, self.BL_freq)
self._pwm1.start(75)
if self.SPI is not None:
self.SPI.max_speed_hz = self.SPEED
self.SPI.mode = 0b00
return 0
def module_exit(self):
logging.debug("spi end")
if self.SPI is not None:
self.SPI.close()
logging.debug("gpio cleanup...")
self.GPIO.output(self.RST_PIN, 1)
self.GPIO.output(self.DC_PIN, 0)
self._pwm.stop()
self._pwm1.stop()
# self.GPIO.cleanup()
'''
if os.path.exists('/sys/bus/platform/drivers/gpiomem-bcm2835'):
implementation = RaspberryPi()
for func in [x for x in dir(implementation) if not x.startswith('_')]:
setattr(sys.modules[__name__], func, getattr(implementation, func))
'''

View File

@ -0,0 +1,19 @@
'''
Select images as required
True for image1
False for image2
'''
import time
from . import image
Img = image.image()
while True:
if Img.flgh:
Img.HMI1()
else:
Img.HMI2()
time.sleep(1)

21
overlays/waveshare.txt Normal file
View File

@ -0,0 +1,21 @@
dtparam=i2c_vc=on
dtoverlay=i2c-rtc,pcf85063a
# Waveshare config-32 for 2.8inch RPi LCD (A)
enable_uart=1
# Enable audio (loads snd_bcm2835)
dtparam=audio=on
dtoverlay=waveshare32b:rotate=270
# uncomment if hdmi display is not detected and composite is being output
hdmi_force_hotplug=1
hdmi_group=2
hdmi_mode=1
hdmi_mode=87
hdmi_cvt 480 320 60 6 0 0 0
hdmi_drive=2
[all]
[cm4]
otg_mode=1

BIN
overlays/waveshare32b.dtbo Normal file

Binary file not shown.

View File

@ -0,0 +1,10 @@
--- a/arch/arm64/boot/dts/overlays/Makefile 2023-07-04 16:38:37.955239160 +0300
+++ b/arch/arm64/boot/dts/overlays/Makefile 2023-07-04 16:40:54.058192471 +0300
@@ -3,6 +3,7 @@
dtb-$(CONFIG_ARCH_BCM2835) += overlay_map.dtb
dtbo-$(CONFIG_ARCH_BCM2835) += \
+ waveshare32b.dtbo \
act-led.dtbo \
adafruit18.dtbo \
adau1977-adc.dtbo \