作者:hey_ha | 更新时间:2020-05-28 | 浏览量:911
```
开发环境:Virtualbox ubuntu 14.04
```
将贝壳物联对应设备的ID和APIKEY替换后,直接make运行
```
/**
* Author:xlbtlmy
* blog:https://blog.csdn.net/u011958166
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
char *welcome = "{\"M\":\"WELCOME TO BIGIOT\"}";
// ID:xxxx
// APIKEY:xxxxxxxxx
char *checkin = "{\"M\":\"checkin\",\"ID\":\"xxxx\",\"K\":\"xxxxxxxxx\"}\n";
char *beat = "{\"M\":\"beat\"}\n";
void *pthread_keepalive(void *);
void *pthread_handler(void *);
struct task {
pthread_t tidp;
int micro_seconds;
void * (*start_rtn)(void *);
};
struct task task_tbl[] = {
{ 0, 30000000, pthread_keepalive },
{ 0, 100000, pthread_handler },
};
int s;
int ret;
struct sockaddr_in bigiot_addr;
char buf[1024];
int main(int argc, char *argv[])
{
int i;
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
exit(-1);
}
bigiot_addr.sin_family = AF_INET;
bigiot_addr.sin_port = htons(8181);
bigiot_addr.sin_addr.s_addr = inet_addr("121.42.180.30");
ret = connect(s, (struct sockaddr_in *)&bigiot_addr, sizeof(bigiot_addr));
if (ret < 0) {
exit(-2);
}
memset(buf, 0, sizeof(buf));
ret = recv(s, buf, sizeof(buf), 0);
if (ret >= 0) {
printf("%s", buf);
}
#if 0
if (0 == memcmp(buf, welcome, sizeof(welcome))) {
printf("connect bigiot success!\n");
}
#endif
ret = send(s, checkin, strlen(checkin), 0);
if (ret < 0) {
printf("send error!\n");
exit(-3);
}
printf("%s", checkin);
ret = recv(s, buf, sizeof(buf), 0);
if (ret >= 0) {
printf("%s", buf);
}
for (i = 0; i < sizeof(task_tbl) / sizeof(task_tbl[0]); i ++) {
ret = pthread_create(&task_tbl[i].tidp,
NULL,
task_tbl[i].start_rtn,
&task_tbl[i].micro_seconds);
if (ret) {
printf("Create pthread error:%d\n", i);
exit(-1);
}
}
for (i = 0; i < sizeof(task_tbl) / sizeof(task_tbl[0]); i ++) {
pthread_join(task_tbl[i].tidp, NULL);
}
close(s);
return 0;
}
每30S发送一次以保持连接
void *pthread_keepalive(void *arg)
{
while (1) {
ret = send(s, beat, strlen(beat), 0);
if (ret < 0) {
printf("send error!\n");
exit(-3);
}
printf("%s", beat);
usleep(*(int *)arg);
}
return NULL;
}
打印接收到的数据
void *pthread_handler(void *arg)
{
while (1) {
memset(buf, 0, sizeof(buf));
ret = recv(s, buf, sizeof(buf), 0);
if (ret > 0) {
printf("%s", buf);
}
usleep(*(int *)arg);
}
return NULL;
}
在PC端模拟设备在线,可以做很多好玩的事情
例如,远程控制设备执行一些指令,可以结合Python及shell使用
另外可以外接串口,控制单片机去做一些事情,不用外加其它模块
后续会发出来一个python采用token获取授权方式控制设备的上位机
有兴趣的查看我的CSDN博客获取源码:https://blog.csdn.net/u011958166