cpp
复制代码
#include <netinet/tcp.h>//包含TCP选项的头文件
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input.h>//读取输入事件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SER_PORT 8888
#define SER_IP "192.168.125.75"
#define CLI_PORT 6666
#define CLI_IP "192.168.125.114"
int main(int argc, const char *argv[])
{
int cfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == cfd){
perror("socket");
return 1;
}
printf("cfd = %d\n", cfd);
struct sockaddr_in cin = {
.sin_family = AF_INET,
//注释下行启用动态端口号
.sin_port = htons(CLI_PORT),
.sin_addr = { inet_addr(CLI_IP) },
};
if(-1 == bind(cfd, (struct sockaddr*)&cin, sizeof(cin))){
perror("bind");
return 1;
}
puts("bind success");
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_port = htons(SER_PORT),
.sin_addr = { .s_addr = inet_addr(SER_IP) },
};
if(-1 == connect(cfd, (struct sockaddr*)&sin, sizeof(sin))){
perror("connect");
return 1;
}
puts("connect success");
//设置TCP push位
int val = 1;
//TCP_NODELAY表示Nagle算法(导致粘包现象),默认置0(不关闭),置1即可关闭
if(-1 == setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val))){
perror("setsockopt");
return 1;
}
/*val = 0;
if(-1 == setsockopt(cfd, IPPROTO_TCP, TCP_CORK, &val, sizeof(val))){
perror("setsockopt");
return 1;
}*/
//设置端口快速重用
printf("val = %d\n", val);
if(-1 == setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))){
perror("setsockopt");
return 1;
}
//定义指令格式结构体
//注意字节对齐填充导致的问题,且大于1B的数据类型会自动补0
//均会导致协议解析失败
struct {//5B
char c1[3];//3B
union{
char arm_red;
unsigned char arm_blue;
}c2;//1B
char c3;//1B
}cmd = { 0xff, 0x02, 0x00, 0x00, 0xff };
//机械臂初始化
send(cfd, &cmd, sizeof(cmd), 0);
cmd.c1[2] = 0x01;
usleep(50000);
send(cfd, &cmd, sizeof(cmd), 0);
char ang_r = 0x00;
unsigned char ang_b = 0x00;
//打开/dev/input/event1
int fd = open("/dev/input/event1", O_RDONLY);
if(-1 == fd){
perror("open");
return 1;
}
//准备读取数据的结构体变量
struct input_event input;
#include <linux/input.h>
/* 结构体形式如下:
* struct input_event {
struct timeval time;
__u16 type;
__u16 code;
__s32 value;
};
*/
// system("stty raw -echo");
while(1){
//char ch = getchar();
read(fd, &input, sizeof(input));
//switch(ch){
switch(input.value * input.code){//code按下为0,弹起为1,长按为2
//case 'w'://红增 //w:17 a:30 s:31 d:32
case 17*2:
if(ang_r < 0x5A)//最大90度
ang_r += 0x02;
cmd.c2.arm_red = ang_r;
cmd.c1[2] = 0x00;
break;
//case 's'://红减
case 31*2:
if(ang_r > -0x5A)
ang_r -= 0x02;
cmd.c2.arm_red = ang_r;
cmd.c1[2] = 0x00;
break;
//case 'd'://蓝增
case 32*2:
if(ang_b < 0xB4)
ang_b += 0x02;
cmd.c2.arm_blue = ang_b;
cmd.c1[2] = 0x01;
break;
//case 'a'://蓝减
case 30*2:
if(ang_b > 0x00)
ang_b -= 0x02;
cmd.c2.arm_blue = ang_b;
cmd.c1[2] = 0x01;
break;
default:
continue;
break;
}
send(cfd, &cmd, sizeof(cmd), 0);
}
// system("stty -raw echo");
close(cfd);
close(fd);
return 0;
}