027——从GUI->Client->Server->driver实现对SR501的控制

目录

1、修改显示界面

2、 添加对SR501显示的处理和tcp消息的处理 

3、 在服务器程序中添加对SR501的处理

4、 编写驱动句柄

5、 修改底层驱动


1、修改显示界面

有个奇怪的问题这里的注释如果用''' '''就会报错不知道为啥,只能用#来注释

我把显示这里需要显示的器件的显示单独放到按键前了,都放下面大的output中显示太乱了。

2、 添加对SR501显示的处理和tcp消息的处理 

'''
fuction : 客户端程序
author  : 辛天宇
date    : 2024-4-13
-------------------------------
author     date      modify
辛天宇   2024-4-15   结合GUI和网络通信

'''
import show
import tcp
import tool
import socket
import global_var


def send_handle(window, client_socket, values):
    global_var.TX_BUF = values['txbuff'] 
    print(f"txbuff={global_var.TX_BUF}")
    # 清理input
    window['txbuff'].update(value='')
    data = global_var.TX_BUF
    client_socket.sendall(data.encode())
    # 接收服务器的响应
    data = client_socket.recv(512)
    # 将字节字符串转化为字符串
    global_var.RX_BUF = data.decode('utf-8')
    print(f"rx......{global_var.RX_BUF}") 

def quit_handel(client_socket):
    cmd='Q'
    client_socket.sendall(cmd.encode())
    tcp.disconnect_to_server(client_socket)

# 进行一次发送和接收
def send_cmd(client_socket):
    data = global_var.TX_BUF
    client_socket.sendall(data.encode())
    # 接收服务器的响应
    data = client_socket.recv(512)
    # 将字节字符串转化为字符串
    global_var.RX_BUF = data.decode('utf-8')

# 设置发送消息
def set_tx_buf(device, message): 
    if device == 'sr04':
        global_var.TX_BUF = '@002'
    if device == 'led':
        global_var.TX_BUF = '@000'+message
    elif device == 'sr501':
        global_var.TX_BUF = '@001'+message
    elif device == 'irda':
        global_var.TX_BUF = '@003'
    elif device == 'motor':
        global_var.TX_BUF = '@004'+message
    elif device == 'dht11':
        global_var.TX_BUF = '@005'+message
        print(f"dht11={global_var.TX_BUF}")
    elif device == 'ds18b20':
        global_var.TX_BUF = '@006'
    elif device == 'iic':
        global_var.TX_BUF = '@007'
    elif device == 'spi':
        global_var.TX_BUF = '@008'
    

# 处理数据
def cmd_handle(window):
    cmd = global_var.RX_BUF
    if len(cmd) < 4:
        print("cmd ERROR")
        return -1
    if '@' == cmd[0]:
        # 目前驱动设备数量只有两位数
        if cmd[1] == '0':
            # LED: @000+1位命令位+1位数据位
            if cmd[2] == '0' and cmd[3] == '0':
                if cmd[5] == '1':
                    print("LED Status change success")
                elif cmd[5] == '0':
                    print("LED Status change failure")
                else:
                    print("message ERROR")
            # SR501:@001+1位数据位
            elif cmd[2] == '0' and cmd[3] == '1':
                if cmd[4] == '1':
                    print("有人")
                    message='有人'
                    window['SR501_O'].update(message)
                elif cmd[4] == '0':
                    print("无人")
                    message='无人'
                    window['SR501_O'].update(message)
                else:
                    print("message ERROR")
            #SR04
            elif cmd[2] == '0' and cmd[3] == '2':
                print(cmd[4:])
            #irda
            elif cmd[2] == '0' and cmd[3] == '3':
                print(cmd[4:])
            #motor
            elif cmd[2] == '0' and cmd[3] == '4':
                print(cmd[4:])
            #dht11
            elif cmd[2] == '0' and cmd[3] == '5':
                print(cmd[4:])
                global_var.TEM=cmd[4]+cmd[5]
                global_var.HUM=cmd[6]+cmd[7]
            #ds18b20
            elif cmd[2] == '0' and cmd[3] == '6':
                print(cmd[4:])
            #iic
            elif cmd[2] == '0' and cmd[3] == '7':
                print(cmd[4:])
            #spi
            elif cmd[2] == '0' and cmd[3] == '8':
                print(cmd[4:])

# 处理事件
def event_handle(window, client_socket):
    led = 0
    # 事件循环  
    while True:  
        try:
            cmd_handle(window)
            event, values = window.read()
            if event == 'input':
                window['txbuff'].update(disabled=not values['input'])
            elif event == 'send':
                send_handle(window, client_socket, values)
            elif event == 'Clean':
                window['Output'].update(value='')
            elif event == 'dht11':
                set_tx_buf('dht11', '2525')
                send_cmd(client_socket)
                message = f"{global_var.TEM}°C   {global_var.HUM}%"
                window['Getvalue'].update(message)
            elif event == 'ds18b20':
                set_tx_buf('ds18b20')
                send_cmd(client_socket)
                message = f"{global_var.TEM}°C"
                window['Getvalue'].update(message)
            elif event == 'Quit': 
                quit_handel(client_socket) 
                print(f"See you.............")
                break
            elif event is None:
                print(f"xxxxxxxxxxxxxxxxxxxx")
                break
            elif event == 'LED':
                if led % 2 == 0:
                    set_tx_buf('led','p1')
                else:
                    set_tx_buf('led','p0')
                led+=1
                if led > 100:
                    led = 0
                send_cmd(client_socket)
            elif event == 'SR501':
                set_tx_buf('sr501','g')
                send_cmd(client_socket)
            # 处理其他事件...
        except Exception as e:
            window.close()
            print(f"An error occurred: {e}")
            return 0
    window.close()
    return 0  

def main():
    # 创建GUI对象
    window = show.show_window('DefaultNoMoreNagging')
    # 尝试连接到服务器  
    client_socket = tcp.connect_to_server()
    if client_socket is not None: 
        event_handle(window, client_socket)

if __name__ == '__main__':
    main()

3、 在服务器程序中添加对SR501的处理

4、 编写驱动句柄

/*
*author   : xintianyu
*function : Handle sr501 Settings
*date     : 2024-4-17
-----------------------
author date  modify

*/
int sr501_handle(int* data)
{
    char *device = "/dev/CEBSS_sr501";
    int ret;
	char buf[2];
	static int fd;
	int val;
	int timeout_ms = 5000;
	int	flags;

    /* 打开文件 */
	fd = open(device, O_RDWR);
	if (fd == -1)
	{
		printf("can not open file %s\n", device);
		return ERROR;
	}

	if (read(fd, &val, 1) > 0)
	{
		if (val  == 0x100)
		{
			data = 1;
			printf("get button: %#x ,有人\n", val);
		}
		else
		{
			data = 0;
			printf("get button: %#x ,无人\n", val);
		}
	}
	else
	{
		printf("get button: -1\n");
	    close(fd);
		return ERROR;
	}
	close(fd);
    return NOERROR;
}

编译一下报错

修改一下

 

/*
*author   : xintianyu
*function : Handle sr501 Settings
*date     : 2024-4-17
-----------------------
author date  modify

*/
int sr501_handle(int* data)
{
    char *device = "/dev/CEBSS_sr501";
    int ret = NOERROR;
	static int fd;
	int val;

    /* 打开文件 */
	fd = open(device, O_RDWR);
	if (fd == -1)
	{
		printf("can not open file %s\n", device);
		return ERROR;
	}

	if (read(fd, &val, 1) > 0)
	{
		if (val  == 0x100)
		{
			*data = 1;
			printf("get button: %#x ,有人\n", val);
		}
		else
		{
			*data = 0;
			printf("get button: %#x ,无人\n", val);
		}
	}
	else
	{
		printf("get button: -1\n");
	    ret = ERROR;
	}
	close(fd);
    return ret;
}

 

5、 修改底层驱动

韦东山老师的用中断实现的太浪费资源了,这个小东西完全没必要啊

#include <linux/module.h>  
#include <linux/fs.h>  
#include <linux/cdev.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/device.h>
#include <linux/uaccess.h>
#include <linux/slab.h>  
  
#define DEVICE_NAME "CEBSS_sr501"
#define CLASS_NAME  "sr501_gpio_pin"  
#define YOUR_GPIO_NUMBER 115
  
struct gpio_pin_dev {  
    struct cdev cdev;  
    unsigned int gpio;  
};  
  
static dev_t first_dev;  
static struct class *gpio_pin_class;
static struct gpio_pin_dev *dev;
  
static int gpio_pin_open(struct inode *inode, struct file *file)  
{  
    struct gpio_pin_dev *dev = container_of(inode->i_cdev, struct gpio_pin_dev, cdev);  
    int ret;  
  
    ret = gpio_request(dev->gpio, DEVICE_NAME);  
    if (ret) {  
        printk(KERN_ERR "%s: gpio_request failed\n", DEVICE_NAME);  
        return ret;  
    }  
  
    ret = gpio_direction_input(dev->gpio);  
    if (ret) {  
        printk(KERN_ERR "%s: gpio_direction_input failed\n", DEVICE_NAME);  
        gpio_free(dev->gpio);  
        return ret;  
    }  
  
    file->private_data = dev;  
    return 0;
}  
  
static int gpio_pin_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)  
{  
    dev = file->private_data;  
    int value;  
  
    value = gpio_get_value(dev->gpio);  
    if (copy_to_user(buf, &value, sizeof(value))) {  
        printk(KERN_ERR "%s: copy_to_user failed\n", DEVICE_NAME);  
        return -EFAULT;  
    }  
  
    return sizeof(value);   
}  
  
static int gpio_pin_release(struct inode *inode, struct file *file)  
{  
    struct gpio_pin_dev *dev = file->private_data;  
  
    gpio_free(dev->gpio);  
    return 0;  
}  
  
static const struct file_operations gpio_pin_fops = {  
    .owner = THIS_MODULE,  
    .open = gpio_pin_open,  
    .read = gpio_pin_read,  
    .release = gpio_pin_release,  
    // ... 可以添加其他操作 ...  
};  
  
static int __init gpio_pin_init(void)  
{  
    int ret;
    // 分配设备号  
    ret = alloc_chrdev_region(&first_dev, 0, 1, DEVICE_NAME);  
    if (ret < 0) {  
        printk(KERN_ERR "%s: alloc_chrdev_region failed\n", DEVICE_NAME);  
        return ret;  
    }  
  
    // 初始化设备结构体  
    dev = kzalloc(sizeof(struct gpio_pin_dev), GFP_KERNEL);  
    if (!dev) {  
        printk(KERN_ERR "%s: kzalloc failed\n", DEVICE_NAME);  
        unregister_chrdev_region(first_dev, 1);  
        return -ENOMEM;  
    }  
  
    // 设置GPIO引脚编号  
    dev->gpio = YOUR_GPIO_NUMBER;  
    dev->cdev.owner = THIS_MODULE;  
    dev->cdev.ops = &gpio_pin_fops;  
  
    // 注册字符设备  
    cdev_init(&dev->cdev, &gpio_pin_fops);
  
    ret = cdev_add(&dev->cdev, first_dev, 1);  
    if (ret) {  
        printk(KERN_ERR "%s: cdev_add failed\n", DEVICE_NAME);  
        kfree(dev);  
        unregister_chrdev_region(first_dev, 1);  
        return ret;  
    }  
  
    // 创建设备类  
    gpio_pin_class = class_create(THIS_MODULE, CLASS_NAME);  
    if (IS_ERR(gpio_pin_class)) {  
        printk(KERN_ERR "%s: class_create failed\n", DEVICE_NAME);  
        cdev_del(&dev->cdev);  
        kfree(dev);  
        unregister_chrdev_region(first_dev, 1);  
        return PTR_ERR(gpio_pin_class);  
    }  
  
    // 创建设备节点  
    device_create(gpio_pin_class, NULL, first_dev, NULL, DEVICE_NAME);  
  
    printk(KERN_INFO "%s: Device created with major %d and minor %d\n",  
           DEVICE_NAME, MAJOR(first_dev), MINOR(first_dev));  
  
    return 0;  
}
  
static void __exit gpio_pin_exit(void)  
{  
    dev_t devno = MKDEV(MAJOR(first_dev), 0);
    // 删除设备节点  
    device_destroy(gpio_pin_class, devno);  
  
    // 注销字符设备  
    cdev_del(&dev->cdev);  
  
    // 销毁设备类  
    class_destroy(gpio_pin_class);  
  
    // 释放设备号  
    unregister_chrdev_region(devno, 1);  
  
    // 释放设备结构体内存  
    kfree(dev);  
  
    printk(KERN_INFO "gpio_pin_exit: Module unloaded\n");  
}  
  
module_init(gpio_pin_init);  
module_exit(gpio_pin_exit);  
  
MODULE_LICENSE("GPL");

出现了意外貌似把板子烧了用这个器件现在一直拿不到消息了。

#include <linux/module.h>
#include <linux/poll.h>

#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/kmod.h>
#include <linux/gfp.h>
#include <linux/gpio/consumer.h>
#include <linux/platform_device.h>
#include <linux/of_gpio.h>
#include <linux/of_irq.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/timer.h>

struct gpio_desc{
	int gpio;
	int irq;
    char *name;
    int key;
	struct timer_list key_timer;
} ;

static struct gpio_desc gpios[2] = {
    {115, 0, "sr501", },
};

/* 主设备号                                                                 */
static int major = 0;
static struct class *gpio_class;

/* 环形缓冲区 */
#define BUF_LEN 128
static int g_keys[BUF_LEN];
static int r, w;

struct fasync_struct *button_fasync;

#define NEXT_POS(x) ((x+1) % BUF_LEN)

static int is_key_buf_empty(void)
{
	return (r == w);
}

static int is_key_buf_full(void)
{
	return (r == NEXT_POS(w));
}

static void put_key(int key)
{
	if (!is_key_buf_full())
	{
		g_keys[w] = key;
		w = NEXT_POS(w);
	}
}

static int get_key(void)
{
	int key = 0;
	if (!is_key_buf_empty())
	{
		key = g_keys[r];
		r = NEXT_POS(r);
	}
	return key;
}


static DECLARE_WAIT_QUEUE_HEAD(gpio_wait);


/* 实现对应的open/read/write等函数,填入file_operations结构体                   */
static ssize_t gpio_drv_read (struct file *file, char __user *buf, size_t size, loff_t *offset)
{
	//printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	int err;
	int key;

	if (is_key_buf_empty() && (file->f_flags & O_NONBLOCK))
		return -EAGAIN;
	
	wait_event_interruptible(gpio_wait, !is_key_buf_empty());
	key = get_key();
	err = copy_to_user(buf, &key, 4);
	
	return 4;
}


static unsigned int gpio_drv_poll(struct file *fp, poll_table * wait)
{
	//printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	poll_wait(fp, &gpio_wait, wait);
	return is_key_buf_empty() ? 0 : POLLIN | POLLRDNORM;
}

static int gpio_drv_fasync(int fd, struct file *file, int on)
{
	if (fasync_helper(fd, file, on, &button_fasync) >= 0)
		return 0;
	else
		return -EIO;
}


/* 定义自己的file_operations结构体                                              */
static struct file_operations gpio_key_drv = {
	.owner	 = THIS_MODULE,
	.read    = gpio_drv_read,
	.poll    = gpio_drv_poll,
	.fasync  = gpio_drv_fasync,
};


static irqreturn_t gpio_key_isr(int irq, void *dev_id)
{
	struct gpio_desc *gpio_desc = dev_id;
	int val;
	int key;

	printk("gpio_key_isr key %d irq happened\n", gpio_desc->gpio);

	val = gpio_get_value(gpio_desc->gpio);

	//printk("key_timer_expire key %d %d\n", gpio_desc->gpio, val);
	key = (gpio_desc->key) | (val<<8);
	put_key(key);
	wake_up_interruptible(&gpio_wait);
	kill_fasync(&button_fasync, SIGIO, POLL_IN);

	return IRQ_HANDLED;
}


/* 在入口函数 */
static int __init gpio_drv_init(void)
{
    int err;
    int i;
    int count = sizeof(gpios)/sizeof(gpios[0]);
    
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	
	for (i = 0; i < count; i++)
	{		
		gpios[i].irq  = gpio_to_irq(gpios[i].gpio);

		err = request_irq(gpios[i].irq, gpio_key_isr, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, gpios[i].name, &gpios[i]);
	}

	/* 注册file_operations 	*/
	major = register_chrdev(0, "100ask_gpio_key", &gpio_key_drv);  /* /dev/gpio_desc */

	gpio_class = class_create(THIS_MODULE, "100ask_gpio_key_class");
	if (IS_ERR(gpio_class)) {
		printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
		unregister_chrdev(major, "100ask_gpio_key");
		return PTR_ERR(gpio_class);
	}

	device_create(gpio_class, NULL, MKDEV(major, 0), NULL, "sr501"); /* /dev/sr501 */
	
	return err;
}

/* 有入口函数就应该有出口函数:卸载驱动程序时,就会去调用这个出口函数
 */
static void __exit gpio_drv_exit(void)
{
    int i;
    int count = sizeof(gpios)/sizeof(gpios[0]);
    
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);

	device_destroy(gpio_class, MKDEV(major, 0));
	class_destroy(gpio_class);
	unregister_chrdev(major, "100ask_gpio_key");

	for (i = 0; i < count; i++)
	{
		free_irq(gpios[i].irq, &gpios[i]);
	}
}


/* 7. 其他完善:提供设备信息,自动创建设备节点                                     */

module_init(gpio_drv_init);
module_exit(gpio_drv_exit);

MODULE_LICENSE("GPL");

啊破东西到底怎么配置才能精准啊,不是永远测不到人就是哪里都是人。

彻底疯狂了

还是导线好使

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇努力学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值