【ECEN022】Configure C++ with json format in VS2017

Configuration Environment

The user can implement sdk functions by sending a json format string to the port 8055 of robot controller through socket communication

Copy File

Copy json.hpp file to project folder under .vcxproj folder.



Add Reference

Add #include "json.hpp" to front of the code.

Indicate namespace with using json = nlohmann::json


Examples

Example 1

#include <iostream>
#include <fstream>
#include <winsock.h>
#include <ctime>
#include "json.hpp"//need to be in same directroy as the script
using json = nlohmann::json;//Indicate namespace
using namespace std;
#pragma warning(disable:4996)
#pragma comment(lib, "Ws2_32.lib")
//Define the server socket, accept the request socket
SOCKET ServerSocket;
//Server address
SOCKADDR_IN server_addr;
int ServerAddrSize = sizeof(server_addr);
json params;
int connectETController(string ip, int port){
    WORD w_req = MAKEWORD(2, 2);//version
    WSADATA wsadata;
    int err;
    err = WSAStartup(w_req, &wsadata);
    if (err != 0) std::cout << "Initialize socket library FAILED!" << std::endl;
    else std::cout << "Initialize socket library SUCCESSED!" << std::endl;
    if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wHighVersion) != 2) {//Check the version number
        std::cout << "Socket library version doesn't match!" << std::endl;
        WSACleanup();
    }
    else std::cout << "Socket library version correct!" << std::endl;
    // Fill in the server address information
    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);
    // Create socket
    ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
    // Copying files from the system buffer to the socket buffer doesn't affect the program performance
    int nZero = 0;
    setsockopt(ServerSocket, SOL_SOCKET, SO_SNDBUF, (char *)& nZero, sizeof(nZero));
    // Setup non-blocking 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("Connecting to server failed! Please check network cable and IP address\n");
        return -1;
    }
    else{
        is_non_block = 0;
        ret = ioctlsocket(ServerSocket, FIONBIO, &is_non_block);
        cout << "Connecting to server succeeded!" << 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";//Convert json to string type serialization
    cout << "serializing:" << send << endl;
//Receive data returned from the server
    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, &ServerAddrSize);
//convert string to json deserialization
    recv_json = json::parse(RecvBuf);
    cout << "Deserialize:" << 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.2.100", 8055);
    if (ret == 1){
        std::cout << "Connecting to Robot succeeded\n";
    }
    else{
        std::cout << "Connecting to robot failed! Please check network cable and IP address\n";
    }
    json_result = sendcmd("getRobotState", params, 1); //Obtain robot status
    if (json_result["result"]=="4"){
        json_result = sendcmd("clearAlarm", params, 1); //Clear Alarm
    }
    json_result = sendcmd("getMotorStatus", params, 1); //Obtain motor status
    if (json_result["result"]=="false"){
        json_result = sendcmd("syncMotorStatus", params, 1); //Motor synchronization
    }
    json_result = sendcmd("getServoStatus", params, 1); //Obtain Servo Status
    if (json_result["result"] == "false"){
        params["status"] = 1;
        json_result = sendcmd("set_servo_status", params, 1); //Set Servo to ON
    }
    json_result = sendcmd("getRobotPose", params, 1); //Obtain robot pose
    json_result = sendcmd("getRobotPos", params, 1); //Obtain robot position
}

Example 2

#include <iostream>
#include <fstream>
#include <Winsock2.h>
#include <ctime>
#include "json.hpp"//need to be in same directroy as the script
using json = nlohmann::json;//Indicate namespace
using namespace std;
#pragma warning(disable:4996)
#pragma comment(lib, "Ws2_32.lib")
//Define the server socket, accept the request socket
SOCKET ServerSocket;
//Server address
SOCKADDR_IN server_addr;
int ServerAddrSize = sizeof(server_addr);
json params;
int connectETController(string ip, int port){
    //Initialize the socket library
    WORD w_req = MAKEWORD(2, 2);//version
    WSADATA wsadata;
    int err;
    err = WSAStartup(w_req, &wsadata);
    if (err != 0) {
        cout << "Initialize socket library FAILED!" << endl;
    }
    else {
        cout << "Initialize socket library SUCCESSED!" << endl;
    }
    //检测版本号
    if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wHighVersion) != 2) {
        cout << "Socket library version doesn't match!" << endl;
        WSACleanup();
    }
    else {
        cout << "Socket library version correct!" << endl;
    }
    // Fill in the server address information
    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);
    // Create socket
    ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
    // Copying files from the system buffer to the socket buffer doesn't affect the program performance
    int nZero = 0;
    setsockopt(ServerSocket, SOL_SOCKET, SO_SNDBUF, (char *)& nZero, sizeof(nZero));
    // Setup non-blocking 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("Connecting to server failed! Please check network cable and IP address\n");
        return -1;
    }
    else{
        is_non_block = 0;
        ret = ioctlsocket(ServerSocket, FIONBIO, &is_non_block);
        cout << "Connecting to server succeeded!" << 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";//Convert json to string type serialization
    cout << "serializing:" << send << endl;
    //Receive data returned from the server
    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, &ServerAddrSize);
    //convert string to json deserialization
    recv_json = json::parse(RecvBuf);
    cout << "Deserialize:" << 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.2.100", 8055);
    if (ret == 1){
        std::cout << "Connecting to Robot succeeded\n";
    }
    else{
        std::cout << "Connecting to robot failed! Please check network cable and IP address\n";
    }
    json_result = sendcmd("getRobotState", params, 1); //Obtain robot status
    if (json_result["result"]=="4"){
        json_result = sendcmd("clearAlarm", params, 1); //Clear Alarm
    }
    json_result = sendcmd("getMotorStatus", params, 1); //Obtain motor status
    if (json_result["result"]=="false"){
        json_result = sendcmd("syncMotorStatus", params, 1); //Motor synchronization
    }
    json_result = sendcmd("getServoStatus", params, 1); //Obtain Servo Status
    if (json_result["result"] == "false"){
        params["status"] = 1;
        json_result = sendcmd("set_servo_status", params, 1); //Set Servo to ON
    }
    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); //Joint Move
    json_result = sendcmd("getRobotState", params, 1); //Obtain robot status
    while (json_result["result"] != "0"){
        json_result = sendcmd("getRobotState", params, 1); //Obtain robot status
    }
    json_result = sendcmd("getRobotState", params, 1); //Obtain robot status
    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); //Joint Move
    while (json_result["result"] != "0"){
        json_result = sendcmd("getRobotState", params, 1); //Obtain robot status
    }
    json_result = sendcmd("getRobotPos", params, 1); //Obtain robot pose
    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["unit_type"] = 1;
    json_result = sendcmd("inverseKinematic", params, 1); //Inverse Kinematics
    params["targetPos"] = json_result["result"], params["speed"] = 100, params["acc"] = 20, params["dec"] = 20;
    json_result = sendcmd("moveByLine", params, 1); //Linear Move
}
点击显示全文
赞同0
发表评论
分享

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