【ECEN021】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

VS2017 Software Configuration

Right Click on References

Select Manage NuGet Packages

Browse Json, find Newtonsoft.Json and click install.








Make sure System.Runtime.Serialization is under the reference. If it's not under the list, right click on reference and search for Serialization to add it.


Adding Library

using:command to add namespace

Adding Library





Example

Example 1

using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Text;
namespace json_Csharp
{
    class Program
    {
        static void Main(string[] args)
        {
            String IP = "192.168.1.200";
            int port = 8055;
            Json.connectETController(IP, port);
            //Obtain robot status
            Json.Json_str getState = Json.SendCMD("getRobotState");
            if (getState.result.ToString() == "4")
            {
                //Clear Alarm
                Json.Json_str clearAlarm = Json.SendCMD("clearAlarm");
            }
            Json.Json_str getMotorStatus = Json.SendCMD("getMotorStatus");
            if (getMotorStatus.result.ToString() == "false")
            {
                //Synchronize Editor Data
                Json.Json_str set_servo_status = Json.SendCMD("syncMotorStatus");
            }
            //Obtain Robot Pose
            Json.Json_str getpose = Json.SendCMD("getRobotPose");
            Console.WriteLine("getpose:{0}", string.Join(",", getpose.robot_array));
            //Obtain Robot Position
            Json.Json_str getpos = Json.SendCMD("getRobotPos");
            Console.WriteLine("getpos:{0}", string.Join(",", getpos.robot_array));
        }
    }
    [DataContract]
class Json
    {
public static Socket ClientSocket;
[DataMember]
public string jsonrpc { get; set; }
[DataMember]
public string method { get; set; }
[DataMember]
public object param { get; set; }
[DataMember]
public int id { get; set; }
[DataMember]
public object error { get; set; }
[DataMember]
public object result { get; set; }
[DataMember]
public double[] robot_array { get; set; }
public static bool connectETController(string IP, int port)
{
try
{
IPAddress ip = IPAddress.Parse(IP); //Convert string format IP address to IPAddress format
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stre
am, ProtocolType.Tcp);//Use the specified address cluster protocol, socket type, and communication protocol
IPEndPoint endPoint = new IPEndPoint(ip, port); // Use the specified IP address and port number to initialize IPEndPoint
ClientSocket.Connect(endPoint); //Establish a connection with a remote host
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
throw;
}
}
public static Json_str SendCMD(string cmd, object param = null)
{
Json_str descJson = null;
    ArrayList d_array = new ArrayList();
string rec = "";
try
{
List<Json> send_json = new List<Json>(){
new Json(){jsonrpc="2.0",method=cmd,param=param,id=1 } };
string jsonData = JsonConvert.SerializeObject(send_json);
jsonData = jsonData.Substring(1, jsonData.Length - 2);
jsonData = jsonData.Replace("param", "params");
jsonData = jsonData.Replace("null", "[]");
jsonData += "\n";
byte[] message = Encoding.ASCII.GetBytes(jsonData); //Message sent by bytes
ClientSocket.Send(message);//Send message
byte[] receive = new byte[1024];//Identify length of data receiving
int length = ClientSocket.Receive(receive); //Save length information to an integer
rec = Encoding.ASCII.GetString(receive);
descJson = JsonConvert.DeserializeObject<Json_str>(rec);
if (descJson.result != null && descJson.result.ToString().IndexOf("["
) != -1)
{
string ret_string = descJson.result.ToString().Substring(descJson
.result.ToString().IndexOf("["), descJson.result.ToString().LastIndexOf("]"));
ret_string = ret_string.Replace("[", "");
ret_string = ret_string.Replace("]", "");
string[] s = ret_string.Split(',');
for (int i1 = 0; i1 < s.Length; i1++)
{
d_array.Add(Double.Parse(s[i1]));
}
descJson.robot_array = (double[])d_array.ToArray(typeof(double));
}
return descJson;
}
catch (Exception ex)
{
Console.Write(ex);
descJson = null;
return descJson;
}
}
public class Json_str
{
[DataMember]
    public string jsonrpc { get; set; }
[DataMember]
public object error { get; set; }
[DataMember]
public object result { get; set; }
[DataMember]
public int id { get; set; }
[DataMember]
public double[] robot_array { get; set; }
         }
    }
}   

Example 2

using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Text;
namespace json_Csharp
{
class Program
{
static void Main(string[] args)
{
String IP = "192.168.1.200";
int port = 8055;
Json.connectETController(IP, port);
//Obtain robot status
Json.Json_str getState = Json.SendCMD("getRobotState");
if ((string)getState.result == "4")
{
//Clear Alarm
Json.Json_str clearAlarm = Json.SendCMD("clearAlarm");
    }
Json.Json_str getMotorStatus = Json.SendCMD("getMotorStatus");
if ((string)getMotorStatus.result == "false")
{
//Synchronize Editor Data
Json.Json_str set_servo_status = Json.SendCMD("syncMotorStatus");
}
double[] ready = { -90,-90,90,-90,90,-90,0,0};
Json.Json_str move_J = Json.SendCMD("moveByJoint", new { targetPos =
ready, speed = 20, acc = 50, dec = 50 });
//Obtain robot status
getState = Json.SendCMD("getRobotState");
while ((string)getState.result!="0")
{
getState = Json.SendCMD("getRobotState");
}
//Obtain robot pose
Json.Json_str getpose = Json.SendCMD("getRobotPose");
Console.WriteLine("getpose:{0}", string.Join(",", getpose.robot_array
));
double[] run_pose = getpose.robot_array;
run_pose[0] = run_pose[0] + 100;
Json.Json_str run_pos = Json.SendCMD("inverseKinematic", new { target
Pose = run_pose });
Json.Json_str move_L = Json.SendCMD("moveByLine", new { targetPos = r
un_pos.robot_array, speed=100, acc=50,dec=50 });
//Obtain robot status
getState = Json.SendCMD("getRobotState");
while ((string)getState.result != "0")
{
getState = Json.SendCMD("getRobotState");
}
}
}
[DataContract]
class Json
{
public static Socket ClientSocket;
[DataMember]
public string jsonrpc { get; set; }
[DataMember]
public string method { get; set; }
[DataMember]
    public object param { get; set; }
[DataMember]
public int id { get; set; }
[DataMember]
public object error { get; set; }
[DataMember]
public object result { get; set; }
[DataMember]
public double[] robot_array { get; set; }
public static bool connectETController(string IP, int port)
{
try
{
IPAddress ip = IPAddress.Parse(IP); //Convert string format IP address to IPAddress format

ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.
Stream, ProtocolType.Tcp);//Use the specified address cluster protocol, socket type, and communication protocol
IPEndPoint endPoint = new IPEndPoint(ip, port); // Use the specified IP address and port number to initialize IPEndPoint
ClientSocket.Connect(endPoint); //Establish a connection with a remote host
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
throw;
}
}
public static Json_str SendCMD(string cmd, object param = null)
{
Json_str descJson = null;
ArrayList d_array = new ArrayList();
string rec = "";
try
{
List<Json> send_json = new List<Json>(){
new Json(){jsonrpc="2.0",method=cmd,param=param,id=1 } };
string jsonData = JsonConvert.SerializeObject(send_json);
jsonData = jsonData.Substring(1, jsonData.Length - 2);
jsonData = jsonData.Replace("param", "params");
    jsonData = jsonData.Replace("null", "[]");
jsonData += "\n";
byte[] message = Encoding.ASCII.GetBytes(jsonData); //Message sent by bytes
ClientSocket.Send(message);//Send message
byte[] receive = new byte[1024];//Identify length of data receiving
int length = ClientSocket.Receive(receive); //Save length information to an integer
rec = Encoding.ASCII.GetString(receive);
descJson = JsonConvert.DeserializeObject<Json_str>(rec);
if (descJson.result != null && descJson.result.ToString().IndexOf
("[") != -1)
{
string ret_string = descJson.result.ToString().Substring(desc
Json.result.ToString().IndexOf("["), descJson.result.ToString().LastIndexOf("]"))
;
ret_string = ret_string.Replace("[", "");
ret_string = ret_string.Replace("]", "");
string[] s = ret_string.Split(',');
for (int i1 = 0; i1 < s.Length; i1++)
{
d_array.Add(Double.Parse(s[i1]));
}
descJson.robot_array = (double[])d_array.ToArray(typeof(doubl
e));
}
return descJson;
}
catch (Exception ex)
{
Console.Write(ex);
descJson = null;
return descJson;
}
}
public class Json_str
{
[DataMember]
public string jsonrpc { get; set; }
[DataMember]
public object error { get; set; }
[DataMember]
public object result { get; set; }
    [DataMember]
public int id { get; set; }
[DataMember]
public double[] robot_array { get; set; }
}
}
}
       
点击显示全文
赞同0
发表评论
分享

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