#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>

// disp驱动部分命令（与背光相关，内核目录：/include/video/sunxi_display2.h)
#define DISP_LCD_SET_BRIGHTNESS 0x102
#define DISP_LCD_GET_BRIGHTNESS 0x103
#define DISP_LCD_BACKLIGHT_ENABLE 0x104
#define DISP_LCD_BACKLIGHT_DISABLE 0x105

#define BRIGHTNESS_MAX 255 // 最大亮度

int changeBgLight(int argc, int argv)
{
    int fd;
    unsigned long args[3] = {0};
    /*打开disp设备文件*/
    fd = open("/dev/disp", O_RDWR, 0);
    if (fd < 0)
    {
        printf("open /dev/disp failed.\n");
        return -1;
    }
    /*打印旧的背光值*/
    args[0] = 0; // 选择fb0(lcd0)
    // printf("the old lcd%d brightness is %d\n",\args[0], ioctl(fd, DISP_LCD_GET_BRIGHTNESS, args));

    if (argc != 2)
    {
        printf("ERROR: the right format: ./app [brightness]\n");
        return -1;
    }

    int brightness = argv;

    if (brightness < 0 || brightness > BRIGHTNESS_MAX)
    {
        printf("ERROR: the range is 0 to %d\n", BRIGHTNESS_MAX);
        return -1;
    }

    /*参数数组填参*/
    args[0] = 0;
    args[1] = brightness; // 背光值(本人配置里最高为255)
    args[2] = 0;          // 暂时用不到的参数
    ioctl(fd, DISP_LCD_SET_BRIGHTNESS, args);
    // printf("the new lcd%d brightness is %d\n",\args[0], ioctl(fd, DISP_LCD_GET_BRIGHTNESS, args));
    close(fd);
    return 0;
}
