Linux下的蓝牙网关

查看系统中连接的串口设备的符号链接。 

ls -l /dev/serial/by-id/

网络调试助手 

 

手机APP 

 

 

 蓝牙接收

#include <stdio.h>       // 引入标准输入输出库
#include <stdlib.h>      // 引入标准库(如:malloc和free等函数)
#include <string.h>      // 引入字符串操作函数库
#include <unistd.h>      // 引入UNIX标准函数库
#include <fcntl.h>       // 文件控制库
#include <termios.h>     // 终端I/O函数库

int main() {

    int fd;                          // 文件描述符用于串行通信
    struct termios options;          // 用于存储和配置串行端口设置的结构
    unsigned char buffer[256];       // 用于读取串口数据的缓冲区
    int bytes_read;                  // 从串口读取的字节数

    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);  // 尝试打开串行端口ttyUSB0

    if (fd == -1) {                  // 如果打开失败
        perror("Unable to open port"); // 打印错误信息
        return 1;                    // 退出程序
    } else {
        fcntl(fd, F_SETFL, 0);       // 设置文件描述符属性
        printf("Port is open.\n");  // 端口打开成功,打印消息
    }

    tcgetattr(fd, &options);         // 获取当前设备的配置

    cfsetispeed(&options, B115200);  // 设置输入波特率为115200
    cfsetospeed(&options, B115200);  // 设置输出波特率为115200

    options.c_cflag &= ~CSIZE;       // 清除数据位
    options.c_cflag |= CS8;          // 设置数据位为8
    options.c_cflag &= ~PARENB;      // 无奇偶校验
    options.c_cflag &= ~CSTOPB;      // 停止位为1
    options.c_iflag &= ~(IXON | IXOFF | IXANY);  // 不使用软件流控制
    options.c_cflag &= ~CRTSCTS;     // 不使用硬件流控制
    options.c_cflag |= (CLOCAL | CREAD);  // 忽略调制解调器的状态线,使能接收

    tcsetattr(fd, TCSANOW, &options);  // 将修改后的配置应用到设备

    printf("Port is configured.\n");  // 打印端口配置完成的消息

    while (1) {  // 无限循环
        tcflush(fd, TCIFLUSH);          // 清空输入缓冲区
        bytes_read = read(fd, buffer, sizeof(buffer) - 1);  // 从串行端口读取数据

        if (bytes_read > 0) {         // 如果读取到了数据
            printf("Received: ");     
            for (int i = 0; i < bytes_read; i++) {
                printf("%02X ", buffer[i]);  // 以16进制打印数据
            }
            printf("\n");              
        } else if (bytes_read < 0) {  
            perror("Error reading from serial port");  // 如果读取时发生错误,则打印错误信息
            break;                     // 跳出无限循环
        }
    }

    close(fd);                        // 关闭串行端口

    return 0;                         // 退出程序
}

蓝牙发送 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

int configure_serial(int fd) {
    struct termios options;

    tcgetattr(fd, &options);  // 获取当前设备的配置

    cfsetispeed(&options, B115200);  // 设置输入波特率为115200
    cfsetospeed(&options, B115200);  // 设置输出波特率为115200

    options.c_cflag &= ~CSIZE;       // 清除数据位
    options.c_cflag |= CS8;          // 设置数据位为8
    options.c_cflag &= ~PARENB;      // 无奇偶校验
    options.c_cflag &= ~CSTOPB;      // 停止位为1
    options.c_iflag &= ~(IXON | IXOFF | IXANY);  // 不使用软件流控制
    options.c_cflag &= ~CRTSCTS;     // 不使用硬件流控制
    options.c_cflag |= (CLOCAL | CREAD);  // 忽略调制解调器的状态线,使能接收

    tcsetattr(fd, TCSANOW, &options);  // 将修改后的配置应用到设备
    return 0;
}

int main() {
    int fd;
    unsigned char data_to_send[] = {0x11, 0x34, 0x0D};  // 要发送的数据

    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);  // 尝试打开串行端口ttyUSB0

    if (fd == -1) {
        perror("Unable to open port");
        return 1;
    } else {
        fcntl(fd, F_SETFL, 0);
        printf("Port is open.\n");
    }

    configure_serial(fd);  // 配置串行端口

    printf("Port is configured.\n");
    printf("Sending data...\n");

    ssize_t bytes_written = write(fd, data_to_send, sizeof(data_to_send));  // 将数据写入串行端口

    if (bytes_written < 0) {
        perror("Error writing to serial port");
    } else {
        printf("Data sent successfully.\n");
    }

    close(fd);  // 关闭串行端口
    return 0;
}

 数据的上传

   实现根据解包后的协议类型实现数据的发送

tcp,udp:实现将数据转发给网络调试助手,注意在使用网络调试助手时要注意协议类型和端口号。

MQTT:实现将数据通过服务器发送给订阅端。

#include <stdio.h>       // 引入标准输入输出库
#include <stdlib.h>      // 引入标准库(如:malloc和free等函数)
#include <string.h>      // 引入字符串操作函数库
#include <unistd.h>      // 引入UNIX标准函数库
#include <fcntl.h>       // 文件控制库
#include <termios.h>     // 终端I/O函数库
#include "mosquitto.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <mysql/mysql.h>

void my_sql(char *arg1,char *arg2);

int main() {

    int fd;
    struct termios options;
    unsigned char buffer[256];
    int bytes_read;

    fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);

    if (fd == -1) {
        perror("Unable to open port");
        return 1;
    } else {
        fcntl(fd, F_SETFL, 0);
        printf("Port is open.\n");
    }

    tcgetattr(fd, &options);

    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);

    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_iflag &= ~(IXON | IXOFF | IXANY);
    options.c_cflag &= ~CRTSCTS;
    options.c_cflag |= (CLOCAL | CREAD);

    tcsetattr(fd, TCSANOW, &options);

    printf("Port is configured.\n");

    while (1) {
        tcflush(fd, TCIFLUSH);
        bytes_read = read(fd, buffer, sizeof(buffer) - 1);
/*
        if (bytes_read > 0) {
            printf("Received: ");
            for (int i = 0; i < bytes_read; i++) {
                char character = buffer[2];
                printf("%c",character);
            }
            printf("\n");
        }
        */
        if (bytes_read < 0) {
            perror("Error reading from serial port");
            break;
        }
        char buf[128]="";
        strcpy(buf, buffer);
        char* tokens[4];  // 存储切割后的子字符串
        int i = 0;

        char* token = strtok(buf, ",");
        while (token != NULL && i < 4)
        {
            tokens[i++] = token;
            token = strtok(NULL, ",");
        }
        char *newline_ptr = strchr(tokens[3], '\n');
        if (newline_ptr != NULL) {
            *newline_ptr = '\0';
        }
        
        int type = atoi(tokens[0]);
        int port = atoi(tokens[2]);
/*
        if (type==0)
        {
            printf("%s\n",tokens[3]);
            char *token1;
            char cont[3][128];
            int i=0;
    
            // 使用空格作为分隔符,将字符串拆分为多个子字符串
            token1 = strtok(tokens[3], " ");
    
            while (token1 != NULL) {
                strcpy(cont[i],token1);
                printf("Token: %s\n", cont[i]);
                token1 = strtok(NULL, " ");
                i++;
            }
        }
*/        

        if (type==1)
        {
            printf("为TCP\n");
            int sockfd=socket(AF_INET,SOCK_STREAM,0);
            if (sockfd<0)
            {
                perror("sockfd:");
                return 0;
            }

            struct sockaddr_in dst_addr;
            bzero(&dst_addr, sizeof(dst_addr));
            dst_addr.sin_family = AF_INET;
            dst_addr.sin_port = htons(port);
            inet_pton(AF_INET, tokens[1], &dst_addr.sin_addr.s_addr);
            //使用连接函数连接
            connect(sockfd,(struct sockaddr *)&dst_addr,sizeof(dst_addr));

            send(sockfd,tokens[3],strlen(tokens[3]),0);

            close(sockfd);

        }

        if (type==2)
        {
            printf("为UDP\n");
                //创建套接字
            int sockfd= socket(AF_INET,SOCK_DGRAM,0);
            if (sockfd<0)
            {
                perror("sockfd:");
                return 0;
            }
            
            //定义结构体
            struct sockaddr_in dst_addr;
            bzero(&dst_addr,sizeof(dst_addr));
            dst_addr.sin_family=AF_INET;       //IPV4
            dst_addr.sin_port=htons(port);    //哪个端口发
            inet_pton(AF_INET,tokens[1],&dst_addr.sin_addr.s_addr); //IPV4地址
    
            //发送数据
            sendto(sockfd,tokens[3],strlen(tokens[3]),0,(struct sockaddr *)&dst_addr,sizeof(dst_addr));

            //关闭套接字
            close(sockfd);   
        }
        
        

        if (type==4)
        {
            printf("为MQTT\n");
            //printf("type:%d\nIP:%s\nport:%s\n内容为:%d\n",type,ip,port,buffer+6);
            //1.初始化lib库函数
            mosquitto_lib_init();

            //2.创建一个mosquitto类型的结构体指针
            //  创建一个客户端,返回值类型是mosquitto类型结构体指针
            struct mosquitto *msq;
            msq=mosquitto_new("sub",true,"CD2303");//创建一个客户端
    
            //3.连接到MQTT服务器
            mosquitto_connect(msq,tokens[1],1883,2);
    
            //4.发布消息
            mosquitto_publish(msq,NULL,"CD2303",strlen(tokens[3]),tokens[3],1,true);

            char *token1;
            char cont[3][128];
            int i=0;
    
            // 使用空格作为分隔符,将字符串拆分为多个子字符串
            token1 = strtok(tokens[3], " ");
    
            while (token1 != NULL) {
                strcpy(cont[i],token1);
                //printf("%s ", cont[i]);
                token1 = strtok(NULL, " ");
                i++;
            }
            printf("%s %s",cont[0],cont[1]);

            my_sql(cont[0],cont[1]);

            //5.销毁mosquitto客户端对象
            mosquitto_destroy(msq);
            //6.清理mosquitto库
            mosquitto_lib_cleanup();
        }
       
    }

    return 0;
}

void my_sql(char *arg1,char *arg2)
{
    MYSQL mysql, *sock; // 定义mysql实例和指针

    //初始化数据库环境
    mysql_init(&mysql); // 用于初始化MYSQL对象,为后续的连接做准备。参数是要初始化的MYSQL对象的地址。

    //连接数据库
    sock = mysql_real_connect(&mysql, "192.168.50.130", "root", "123456", "wjy", 3306, NULL, 0);
    // 这个函数用于创建与MySQL服务器的连接。参数依次为:MYSQL对象的地址、服务器的IP地址、用户名、密码、数据库名、服务器的端口号、unix套接字(在这里没有使用,所以为NULL)、客户端标志(在这里没有使用,所以为0)
    
    if (sock == NULL) 
    {
        fprintf(stderr, "连接失败: %s\n", mysql_error(&mysql));
        return;
    }
    char sql_str[512];  // 或者根据实际情况分配足够的内存空间

    sprintf(sql_str, "insert into msq_table(temp, time) values('%s', '%s')", arg1, arg2);

    int ret=mysql_real_query(&mysql,sql_str,strlen(sql_str));
    if(ret !=0)
    {
        perror("mysql_query:");
        return;
    }
    //关闭连接
    MYSQL_RES *res=mysql_store_result(&mysql);
    mysql_free_result(res);
    mysql_close(sock);

}

数据的接收 

实现网络调试助手和MQTT客户端将数据发送给蓝牙网关并且在app中能够接收到数据。

#include <stdio.h>
#include <sys/socket.h> //socket
#include <unistd.h>     //close
#include <netinet/in.h> //struct sockadd_in
#include <string.h>     //bzero
#include <arpa/inet.h>  //inet_pton
#include <fcntl.h>
#include <termios.h>
#include <pthread.h>
#include "mosquitto.h"

int configure_serial(int fd) {
    struct termios options;

    tcgetattr(fd, &options);  // 获取当前设备的配置

    cfsetispeed(&options, B115200);  // 设置输入波特率为115200
    cfsetospeed(&options, B115200);  // 设置输出波特率为115200

    options.c_cflag &= ~CSIZE;       // 清除数据位
    options.c_cflag |= CS8;          // 设置数据位为8
    options.c_cflag &= ~PARENB;      // 无奇偶校验
    options.c_cflag &= ~CSTOPB;      // 停止位为1
    options.c_iflag &= ~(IXON | IXOFF | IXANY);  // 不使用软件流控制
    options.c_cflag &= ~CRTSCTS;     // 不使用硬件流控制
    options.c_cflag |= (CLOCAL | CREAD);  // 忽略调制解调器的状态线,使能接收

    tcsetattr(fd, TCSANOW, &options);  // 将修改后的配置应用到设备
    return 0;
}

void my_msg_callback(struct mosquitto *msq, void *obj, const struct mosquitto_message *msg)
{
    //struct mosquitto *msq  客户端指针
    //void *obj  创建客户端时候的第三个参数,在此处是"CD2303"
    //msg就是我们订阅到的数据
    char buf[128]="";
    strcpy(buf,(char *)msg->payload);

    int fd;

    fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);  // 尝试打开串行端口ttyUSB0

    if (fd == -1)
    {
        perror("Unable to open port");
        return;
    }
    else
    {
        fcntl(fd, F_SETFL, 0);
        printf("Port is open.\n");
    }

    configure_serial(fd);  // 配置串行端口

    printf("Port is configured.\n");
    printf("Sending data...\n");

    ssize_t bytes_written = write(fd, buf, sizeof(buf));  // 将数据写入串行端口

    if (bytes_written < 0) {
        perror("Error writing to serial port");
    } else {
        printf("Data sent successfully.\n");
    }

    close(fd);  // 关闭串行端口
    
}

void *udp_rcv(){
    //创建通信的套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    printf("%d\n",sockfd);
    if (sockfd < 0)
    {
        perror("socket:");
        return 0;
    }

    //定义IPv4地址结构
    struct sockaddr_in my_addr;
    bzero(&my_addr, sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(9000);
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY); // INADDR_ANY 绑定本地机的所有IP地址

    // bind固定的端口IP信息
    int ret=bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr));
    if (ret <0)
    {
        perror("bind");
        close(sockfd);
        return 0;
    }

    while (1)
    {
        unsigned char buf[512]="";
        int len=0;
        len=recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL);
        if (len>0)
        {
            int fd;

            fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);  // 尝试打开串行端口ttyUSB0
            if (fd == -1)
            {
                perror("Unable to open port");
                return 0;
            }
            else
            {
                fcntl(fd, F_SETFL, 0);
                printf("Port is open.\n");
            }
            configure_serial(fd);  // 配置串行端口
            printf("Port is configured.\n");
            printf("Sending data...\n");

            ssize_t bytes_written = write(fd, buf, sizeof(buf));  // 将数据写入串行端口

            if (bytes_written < 0)
            {
                perror("Error writing to serial port");
            }
            else
            {
                printf("Data sent successfully.\n");
            }
            close(fd);  // 关闭串行端口

        }
        
    }
    
    close(sockfd);
}

void *tcp_rcv(){
    int sockfd= socket(AF_INET,SOCK_STREAM,0);
    if (sockfd<0)
    {
      perror("sockfd:");
      return 0;
    }
    printf("sockfd=%d\n",sockfd);
    
    //2.连接服务器connect
    //创建目的地址结构体
    struct sockaddr_in dst_addr;
    bzero(&dst_addr, sizeof(dst_addr));
    dst_addr.sin_family = AF_INET;
    dst_addr.sin_port = htons(9000);
    inet_pton(AF_INET, "192.168.50.1", &dst_addr.sin_addr.s_addr);
    //使用连接函数连接
    connect(sockfd,(struct sockaddr *)&dst_addr,sizeof(dst_addr));
    
    //3.具体的功能
    while (1)
    { 
        unsigned char buf[512]="";
        int len=0;
        len=recv(sockfd, buf,sizeof(buf), 0);
        if (len>0)
        {
            int fd;
            fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);  // 尝试打开串行端口ttyUSB0
            if (fd == -1)
            {
                perror("Unable to open port");
                return 0;
            }
            else
            {
                fcntl(fd, F_SETFL, 0);
                printf("Port is open.\n");
            }
            configure_serial(fd);  // 配置串行端口
            printf("Port is configured.\n");
            printf("Sending data...\n");

            ssize_t bytes_written = write(fd, buf, sizeof(buf));  // 将数据写入串行端口

            if (bytes_written < 0)
            {
                perror("Error writing to serial port");
            }
            else
            {
                printf("Data sent successfully.\n");
            }
            close(fd);  // 关闭串行端口
        }
        else if (len ==0)
        {
            printf("连接结束\n");
            break;
        }
        else
        {
            break;
        }
        
    }
    
    //4.关闭套接字
    close(sockfd);
}

void *mqtt_rcv(){
     //1.初始化lib库函数
    mosquitto_lib_init();

    //2.创建一个mosquitto类型的结构体指针
    //  创建一个客户端,返回值类型是mosquitto类型结构体指针
    struct mosquitto *msq;
    msq=mosquitto_new("pub",true,"CD2303");//创建一个客户端
    
    //3.设置回调函数
    //设置订阅消息回调函数,当客户端接收到服务器发来的消息,调用callback
    mosquitto_message_callback_set(msq,my_msg_callback);

    //4.连接到MQTT服务器
    mosquitto_connect(msq,"192.168.50.130",1883,2);

    //5.订阅MQTT主题
    mosquitto_subscribe(msq,NULL,"CD2303",1);
    //6.开始网络处理循环(循环接收消息)
    mosquitto_loop_start(msq);

    //7.停止网络处理循环
    mosquitto_loop_stop(msq,false);

    //8.销毁mosquitto客户端对象
    mosquitto_destroy(msq);
    //9.清理mosquitto库
    mosquitto_lib_cleanup();
}

int main(){
    //创建三个线程号
    pthread_t udp_pid=0,tcp_pid=0,mqtt_pid=0;

    //建立三个线程
    int ret1=pthread_create(&udp_pid,NULL,udp_rcv,NULL);
    int ret2=pthread_create(&tcp_pid,NULL,tcp_rcv,NULL);
    int ret3=pthread_create(&mqtt_pid,NULL,mqtt_rcv,NULL);

    //阻塞
    pthread_join(udp_pid,NULL);
    pthread_join(tcp_pid,NULL);
    pthread_join(mqtt_pid,NULL);

    return 0;
}

htlm网页 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="./16_js.js"></script>
    <style>
        .container {
            display: flex;
            margin-top: 20px;
            margin-left: 50px;
            margin-bottom: 30px;
        }
        .item {
            margin-right: 50px;
            margin-right: 10px;
        }
        caption {
            font-size: 50px;
            font-weight: bold;
        }
        table {
            margin: 0 auto;
            width: 50%;
            height: 400px;
            margin-top: 30px;
        }
    </style>
</head>

<body>
    <div class="container">
        <input type="text" id="ret" style="position: absolute; left: 6%; top: 266px; width: 190px; height: 50px;">
        <br>
        <input type="button" value="1" style="position: absolute; top: 220px; left: 20%; width: 100px; height: 50px;" onclick="my_calc(1);">
        <input type="button" value="0" style="position: absolute; top: 320px; left: 20%; width: 100px; height: 50px"  onclick="my_calc(0);">
        <input type="button" id="tem" value="发送" style="position: absolute; top: 420px; left: 20%; width: 100px; height: 50px"  onclick="my_sent();">
        <input type="text" id="wjy" style="position: absolute; left: 6%; top: 420px; width: 190px; height: 50px;">
        
        <table border="4">
            <caption>环境室温</caption>
            <tr>
                <th>序号</th>
                <th>温度</th>
                <th>时间</th>
            </tr>
            <tr>
                <th>1</th>
                <td id="tem1"></td>
                <td id="tim1"></td>       
            </tr>
            <tr>
                <th>2</th>
                <td id="tem2"></td>
                <td id="tim2"></td>       
            </tr>
            <tr>
                <th>3</th>
                <td id="tem3"></td>
                <td id="tim3"></td>       
            </tr>
            <tr>
                <th>4</th>
                <td id="tem4"></td>
                <td id="tim4"></td>       
            </tr>
        </table>
        <input type="button" style="position: absolute; top: 300px; right: 10%; width: 100px; height: 50px;" value="刷新缓存" onclick="my_send()">

        </div>
</body>

</html>

js文件 

function getXMLHttpRequest() {
    var xmlhttp = null;
    if (window.XMLHttpRequest)//自动检测当前浏览器的版本,如果是 IE5.0 以上的高版本的浏览器
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();//创建请求对象
    }
    else如果浏览器是底版本的
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//创建请求对象
    }
    return xmlhttp;
}
function my_calc(arg) {
    //1、创建XMLHttpRequest对象
    var xmlhttp = getXMLHttpRequest();

    //3、创建请求POST方式 数据不能放在url的?后面
    //var url="/cgi-bin/14_cgi.cgi"
    var url = "./cgi-bin/cgi1.cgi";
    var data = "";//存放数据

    if (arg == "1") {
        data += "1";
    }
    else if (arg == "0") {
        data += "0";
    }

    xmlhttp.open("POST", url, false);

    //4、发送请求
    xmlhttp.send(data);

    //判断服务器的状态(4 完成   200找到)
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        //获取服务器的应答
        var text = xmlhttp.responseText;

        //将结构 局部更新到网页的标签上
        document.getElementById('ret').value = text;
    }
}

function my_send() {
    // 1、创建XMLHttpRequest对象
    var xmlhttp = new XMLHttpRequest();

    // 2、创建请求POST方式 数据不能放在url的?后面
    var url = "./cgi-bin/cgi2.cgi";

    // 3、打开请求,使用GET方法发送请求
    xmlhttp.open("GET", url, true);

    // 4、注册onreadystatechange事件处理函数
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            // 获取服务器的应答
            var text = xmlhttp.responseText;

            // 将结构局部更新到网页的标签上
            var parts = text.split(",");
            var c0 = parts[0];
            var c1 = parts[1];

            var tem1 = document.getElementById("tem1");
            tem1.innerText = c0;
            var tim1 = document.getElementById("tim1");
            tim1.innerText = c1;

            var tem2 = document.getElementById("tem2");
            tem2.innerText = parts[2];
            var tim2 = document.getElementById("tim2");
            tim2.innerText = parts[3];

            var tem3 = document.getElementById("tem3");
            tem3.innerText = parts[4];
            var tim3 = document.getElementById("tim3");
            tim3.innerText = parts[5];

            var tem4 = document.getElementById("tem4");
            tem4.innerText = parts[6];
            var tim4 = document.getElementById("tim4");
            tim4.innerText = parts[7];
        }
    };

    // 5、发送请求
    xmlhttp.send();
}

function my_sent() {
    var value=document.getElementById('wjy').value;
    // 使用fetch API发起一个GET请求到指定的URL,并附带提供的value值。
    fetch(`/cgi-bin/mqtt_publish.cgi?${value}`)
    .then(response => response.text())  // 当fetch请求成功时,将响应转化为文本。
    .then(data => {
        console.log(data);  // 将文本响应输出到控制台。
    });
}

cgi.c (读取数据库)

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <time.h>
#include <string.h>
#include <mysql/mysql.h>
#include "mosquitto.h"

int main(int argc, char const *argv[])
{
    MYSQL mysql, *sock;

    mysql_init(&mysql);

    sock = mysql_real_connect(&mysql, "192.168.50.130", "root", "123456", "wjy", 3306, NULL, 0);
    if (sock == NULL) 
    {
        fprintf(stderr, "连接失败: %s\n", mysql_error(&mysql));
        return 0;
    }

    char buff[]="select *from msq_table order by time DESC";
    int ret1 = mysql_real_query(&mysql,buff,sizeof(buff));
    if(ret1 != 0)
    {
        printf("mysql_real_query erro\n");
        return  -1;
    }

    MYSQL_RES *result=mysql_store_result(&mysql);
    if (result==NULL)
    {
        printf("mysql_store_result erro");
        return 0;
    }

    //printf("content-type:text/html;charset=utf-8\n\n");
    
    MYSQL_ROW  buff2;
    char rev[128]="";
    int row=0;
    while((buff2 = mysql_fetch_row(result)) != NULL)
    {
        row++;
        if (row>row-4)
        {
            strcat(rev,buff2[0]);
            strcat(rev,",");
            strcat(rev,buff2[1]);
            strcat(rev,",");
        }
    }
    //释放结果集
    int len = strlen(rev);
        if (len > 0)
        {
            rev[len-1] = '\0';
        }
    mysql_free_result(result);
    
    //释放msql句柄
    mysql_close(&mysql);
    
    //3.把数据发送给JS
    printf("content-type:text/html;charset=utf-8\n\n");//固定的,作用是,之后所有的printf输出给js
    //储存在xmlhttp.responseText

    printf("%s\n",rev);

    return 0;
}

cgi.c(实现MQTT发送) 

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include "mosquitto.h"
#include  <mysql/mysql.h>

#include <pcap/pcap.h>
#include <arpa/inet.h>
#include <libnet.h>
#include <netinet/in.h>
#include <time.h>
int main(int argc, char const *argv[])
{
    const char *light_status = argv[1];
     //1初始化lib函数
    mosquitto_lib_init();
    //2创建一个mosquitto类型的结构体指针
    //创建一个客户端(订阅端),返回值类型是mosquitto结构体指针
    struct mosquitto *msq;
    msq=mosquitto_new("save",true,"CD2303");//"CD2303"占位

    //3连接到MQTTf服务器
    mosquitto_connect(msq,"10.7.173.175",1883,2);


    //4send
	mosquitto_publish(msq,NULL,"CD2303",strlen(light_status),light_status,1,false);
	
    //5清理网络处理器
    mosquitto_destroy(msq);
    //6清理lib库
    mosquitto_lib_cleanup();

    return 0;
}

 以上便是有关蓝牙网关的大部分重要代码。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值