vs2017 配置 C++使用 json 协议

配置环境

用户可通过 socket 通讯向控制器控制端口 8055 发送指定格式的 json 字符串来实现相关 sdk 功能。

复制文件

只需要用到一个 json.hpp 文件。 1.1 复制 json.hpp 文件到项目.vcxproj 文件目录。

添加引用

在代码前端加入#include "json.hpp"
注明空间 using json = nlohmann::json

Examples

Example 1

#include <iostream>
#include <fstream>
#include <Winsock2.h>
#include <ctime>
#include "json.hpp"//只需包含该头文件
using json = nlohmann::json;//注明空间
using namespace std;
#pragma warning(disable:4996)
#pragma comment(lib, "Ws2_32.lib")
//定义服务端套接字,接受请求套接字
SOCKET ServerSocket;
//服务端地址客户端地址
SOCKADDR_IN server_addr;
int ServerAddrSize = sizeof(server_addr);
json params;
int connectETController(string ip, int port)
{
    //初始化套接字库
    WORD w_req = MAKEWORD(2, 2);//版本号
    WSADATA wsadata;
    int err;
    err = WSAStartup(w_req, &wsadata);
    if (err != 0) {
        cout << "初始化套接字库失败!" << endl;
    }
    else {
        cout << "初始化套接字库成功!" << endl;
    }
    //检测版本号
    if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wHighVersion) != 2) {
        cout << "套接字库版本号不符!" << endl;
        WSACleanup();
    }
    else {
        cout << "套接字库版本正确!" << endl;
    }
    //填充服务端地址信息
server_addr.sin_family = AF_INET;
server_addr.sin_addr.S_un.S_addr = inet_addr(ip.c_str());
server_addr.sin_port = htons(port);
//创建套接字
ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
//不经历由系统缓冲区到 socket 缓冲区的拷贝而影响程序的性能
int nZero = 0;
setsockopt(ServerSocket, SOL_SOCKET, SO_SNDBUF, (char *)& nZero, sizeof(nZero));
// 设置非阻塞 FIONBIO
u_long is_non_block = 1;
int ret = ioctlsocket(ServerSocket, FIONBIO, &is_non_block);
ret = connect(ServerSocket, (struct sockaddr *) &server_addr, sizeof(server_addr));
fd_set fsWrite;
FD_ZERO(&fsWrite);
FD_SET(ServerSocket, &fsWrite);
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
ret = select(0, 0, &fsWrite, 0, &timeout);
if (ret == 0) {
printf("服务器连接失败!检查网线和 ip 地址\n");
return -1;
}
else
{
is_non_block = 0;
ret = ioctlsocket(ServerSocket, FIONBIO, &is_non_block);
cout << "服务器连接成功!" << endl;
return 1;
}
}
json sendcmd(string method, json Params, int id, ...) {
json send, recv_json;
char RecvBuf[1024] = "";
string SendBuf = "";
string filname;
fstream f;
int send_len = 0, recv_len = 0, BufLen = 1024;
auto s2 = Params.size();
if (s2 == 0)
{
send = { {"jsonrpc","2.0"},{"method",method},{"id",id} };
}
else
{
send = { {"jsonrpc","2.0"},{"method",method},{"params",Params},{"id",id} };
}
string str = send.dump() + "\r\n";//将 json 转化为 string 类型序列化
cout << "序列化:" << send << endl;
//接收来自服务器返回的数据
send_len = sendto(ServerSocket, str.c_str(), str.size(), 0, (SOCKADDR*)&server_addr,
sizeof(server_addr));
recv_len = recvfrom(ServerSocket, RecvBuf, BufLen, 0, (SOCKADDR*)&server_addr, &Serv
erAddrSize);
//将字符串转化为 json 反序化
recv_json = json::parse(RecvBuf);
cout << "反序化:" << recv_json << endl;
int read_id = recv_json["id"];
if (recv_json["result"] == nullptr)
{
recv_json["result"] = false;
params.clear();
return recv_json;
}
string read_result = recv_json["result"];
int start = read_result.find("[");
if (start > -1)
{
int end = read_result.find_last_of("]");
if (end > -1)
{
string ret_str = read_result.substr(start + 1, end - 1);
start = ret_str.find("[");
while (start != -1) {
ret_str.replace(start, string("[").length(), "");
start = ret_str.find("[");
}
end = ret_str.find_last_of("]");
while (end != -1) {
ret_str.replace(end, string("]").length(), "");
end = ret_str.find("]");
}
vector<double> result;
string::size_type i = 0;
string::size_type found = ret_str.find(",");
while (found != string::npos) {
result.push_back(atof(const_cast<const char *>(ret_str.substr(i, found - i).c_str
())));
i = found + 1;
found = ret_str.find(",", i);
}
result.push_back(atof(const_cast<const char *>(ret_str.substr(i, ret_str.size() -
i).c_str())));
recv_json["result"] = result;
}
}
params.clear();
return recv_json;
}
int main()
{
json json_result;
int ret = connectETController("192.168.1.200", 8055);
if (ret == 1)
{
std::cout << "连接机器人成功\n";
}
else
{
std::cout << "机器人连接失败检查网线和 ip\n";
}
json_result = sendcmd("getRobotState", params, 1); //获取机器人状态
if (json_result["result"]=="4")
{
json_result = sendcmd("clearAlarm", params, 1); //清除报警
}
json_result = sendcmd("getMotorStatus", params, 1); //获取同步状态
if (json_result["result"]=="false")
{
json_result = sendcmd("syncMotorStatus", params, 1); //获取同步状态
}
json_result = sendcmd("getServoStatus", params, 1); //获取伺服状态
if (json_result["result"] == "false")
{
params["status"] = 1;
json_result = sendcmd("set_servo_status", params, 1); //设置伺服上电状态
}
json_result = sendcmd("getRobotPose", params, 1); //获取机器人当前位姿
json_result = sendcmd("getRobotPos", params, 1); //获取机器人当前位置
}

Example 2

#include <iostream>
#include <fstream>
#include <Winsock2.h>
#include <ctime>
#include "json.hpp"//只需包含该头文件
using json = nlohmann::json;//注明空间
using namespace std;
#pragma warning(disable:4996)
#pragma comment(lib, "Ws2_32.lib")
//定义服务端套接字,接受请求套接字
SOCKET ServerSocket;
//服务端地址客户端地址
SOCKADDR_IN server_addr;
int ServerAddrSize = sizeof(server_addr);
json params;
int connectETController(string ip, int port)
{
//初始化套接字库
WORD w_req = MAKEWORD(2, 2);//版本号
WSADATA wsadata;
int err;
err = WSAStartup(w_req, &wsadata);
if (err != 0) {
cout << "初始化套接字库失败!" << endl;
}
else {
cout << "初始化套接字库成功!" << endl;
}
//检测版本号
if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wHighVersion) != 2) {
cout << "套接字库版本号不符!" << endl;
WSACleanup();
}
else {
cout << "套接字库版本正确!" << endl;
}
//填充服务端地址信息
server_addr.sin_family = AF_INET;
server_addr.sin_addr.S_un.S_addr = inet_addr(ip.c_str());
server_addr.sin_port = htons(port);
//创建套接字
ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
//不经历由系统缓冲区到 socket 缓冲区的拷贝而影响程序的性能
int nZero = 0;
setsockopt(ServerSocket, SOL_SOCKET, SO_SNDBUF, (char *)& nZero, sizeof(nZero));
// 设置非阻塞 FIONBIO
u_long is_non_block = 1;
int ret = ioctlsocket(ServerSocket, FIONBIO, &is_non_block);
ret = connect(ServerSocket, (struct sockaddr *) &server_addr, sizeof(server_addr
));
fd_set fsWrite;
FD_ZERO(&fsWrite);
FD_SET(ServerSocket, &fsWrite);
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
ret = select(0, 0, &fsWrite, 0, &timeout);
if (ret == 0) {
printf("服务器连接失败!检查网线和 ip 地址\n");
return -1;
}
else
{
is_non_block = 0;
ret = ioctlsocket(ServerSocket, FIONBIO, &is_non_block);
cout << "服务器连接成功!" << endl;
return 1;
}
}
json sendcmd(string method, json Params, int id, ...) {
json send, recv_json;
char RecvBuf[1024] = "";
string SendBuf = "";
string filname;
fstream f;
int send_len = 0, recv_len = 0, BufLen = 1024;
auto s2 = Params.size();
if (s2 == 0)
{
send = { {"jsonrpc","2.0"},{"method",method},{"id",id} };
}
else
{
send = { {"jsonrpc","2.0"},{"method",method},{"params",Params},{"id",id} };
}
string str = send.dump() + "\r\n";//将 json 转化为 string 类型序列化
cout << "序列化:" << send << endl;
//接收来自服务器返回的数据
send_len = sendto(ServerSocket, str.c_str(), str.size(), 0, (SOCKADDR*)&server_a
ddr, sizeof(server_addr));
recv_len = recvfrom(ServerSocket, RecvBuf, BufLen, 0, (SOCKADDR*)&server_addr, &
ServerAddrSize);
//将字符串转化为 json 反序化
recv_json = json::parse(RecvBuf);
cout << "反序化:" << recv_json << endl;
int read_id = recv_json["id"];
if (recv_json["result"] == nullptr)
{
recv_json["result"] = false;
params.clear();
return recv_json;
}
string read_result = recv_json["result"];
int start = read_result.find("[");
if (start > -1)
{
int end = read_result.find_last_of("]");
if (end > -1)
{
string ret_str = read_result.substr(start + 1, end - 1);
start = ret_str.find("[");
while (start != -1) {
ret_str.replace(start, string("[").length(), "");
start = ret_str.find("[");
}
end = ret_str.find_last_of("]");
while (end != -1) {
ret_str.replace(end, string("]").length(), "");
end = ret_str.find("]");
}
vector<double> result;
string::size_type i = 0;
string::size_type found = ret_str.find(",");
while (found != string::npos) {
result.push_back(atof(const_cast<const char *>(ret_str.substr(i, found - i).c
_str())));
i = found + 1;
found = ret_str.find(",", i);
}
result.push_back(atof(const_cast<const char *>(ret_str.substr(i, ret_str.size(
) - i).c_str())));
recv_json["result"] = result;
}
}
params.clear();
return recv_json;
}
int main()
{
json json_result;
double targetPos[8] = {0,0,0,0,0,0,0,0};
double targetPose[6] = {0,0,0,0,0,0};
int ret = connectETController("192.168.1.200", 8055);
if (ret == 1)
{
std::cout << "连接机器人成功\n";
}
else
{
std::cout << "机器人连接失败检查网线和 ip\n";
}
json_result = sendcmd("getRobotState", params, 1); //获取机器人状态
if (json_result["result"]=="4")
{
json_result = sendcmd("clearAlarm", params, 1); //清除报警
}
json_result = sendcmd("getMotorStatus", params, 1); //获取同步状态
if (json_result["result"]=="false")
{
json_result = sendcmd("syncMotorStatus", params, 1); //获取同步状态
}
json_result = sendcmd("getServoStatus", params, 1); //获取伺服状态
if (json_result["result"] == "false")
{
params["status"] = 1;
json_result = sendcmd("set_servo_status", params, 1); //设置伺服上电状态
}
params["targetPos"] = {0,-90,0,-
90,90,0,0,0}, params["speed"]=20, params["acc"] = 20, params["dec"] = 20;
json_result = sendcmd("moveByJoint", params, 1); //关节运动
json_result = sendcmd("getRobotState", params, 1); //获取机器人状态
while (json_result["result"] != "0")
{
json_result = sendcmd("getRobotState", params, 1); //获取机器人状态
}
json_result = sendcmd("getRobotState", params, 1); //获取机器人状态
params["targetPos"] = { -90,-90,90,-90,90,-
90,0,0 }, params["speed"] = 20, params["acc"] = 20, params["dec"] = 20;
json_result = sendcmd("moveByJoint", params, 1); //关节运动
while (json_result["result"] != "0")
{
json_result = sendcmd("getRobotState", params, 1); //获取机器人状态
}
json_result = sendcmd("getRobotPos", params, 1); //获取机器人当前位置
for (int i = 0; i < json_result["result"].size(); i++)
{
targetPos[i] = json_result["result"][i];
}
json_result = sendcmd("getRobotPose", params, 1);
for (int i = 0; i < json_result["result"].size(); i++)
{
targetPose[i] = json_result["result"][i];
}
targetPose[0] = targetPose[0] - 100;
params["targetPose"] = targetPose, params["referencePos"] = targetPos, params["u
nit_type"] = 1;
json_result = sendcmd("inverseKinematic", params, 1); //逆解
params["targetPos"] = json_result["result"], params["speed"] = 100, params["acc"] = 20, params["dec"] = 20;
json_result = sendcmd("moveByLine", params, 1); //直线运动
}
点击显示全文
赞同0
发表评论
分享

手机扫码分享
0
1.252K
收藏
举报
收起
登录
  • 密码登录
  • 验证码登录
还没有账号,立即注册
还没有账号,立即注册
注册
已有账号,立即登录
选择发帖板块
举报
请选择举报理由
举报
举报说明