Я пытаюсь создать плагин робота, который может передавать информацию с камеры на мой ноутбук через TCP / IP, и робот работает на программном обеспечении CPROG, в котором я могу дать команду плагину, и интерфейс запустится, и робот будет двигаться в направлении координат, заданных камерой.
Вот мой интерфейс:
using System;
namespace CPRogPluginFramework
{
public interface ICPRogPluginCmd
{
string PluginName { get; }
bool MotionTypeJoints { get; }
int PluginInterfaceVersion { get; }
int UpdatePosition(
robotStatus robState,
TimeSpan diffTime,
double ovr,
ref double[] joints,
ref float[] positionMatrix,
ref double[] orientationEuler,
bool[] digitalIn,
ref bool[] digitalOut);
int GetTargetPosition(int camNr, ref int resClass, ref float[] posCart, ref float[] oriEuler);
void SetPluginDirectoryPath(string path);
string LogMessage();
int Initialize();
void ShowGUI();
void GetPluginDescription(
ref string Version,
ref string DescriptionShort,
ref string Description);
void GetPluginManufacturer(ref string Company, ref string website, ref string supportMail);
}
}
Вот реализация интерфейса:
using CPRogPluginFramework;
using System;
using System.Collections.Generic;
namespace PluginSimple
{
class PLUGIN : ICPRogPluginCmd
{
public string logMsg = "";
string PluginDirPath = @"C:\CPRog\Data\Plugins\";
public List<TCPIP> camList = new List<TCPIP>();
public int cnt = 0;
public int cam = 0;
public int nrOfCameras = 1;
private bool flagPluginInited;
private bool flagTestMode;
private bool flagFirstRequest = true;
public string PluginName
{
get
{
return "PluginSimple";
}
}
public bool MotionTypeJoints
{
get
{
return false;
}
}
public int PluginInterfaceVersion
{
get
{
return 1;
}
}
public void GetPluginDescription(
ref string Version,
ref string DescriptionShort,
ref string Description)
{
Version = "0.0.2";
DescriptionShort = "Interface to IFM O2D smart cameras";
Description = "Cameras are connected via TCP/IP and provide position and rotation of the workpiece.";
}
public void GetPluginManufacturer(
ref string Company,
ref string website,
ref string supportMail)
{
Company = "Commonplace Robotics GmbH";
website = "www.cpr-robots.com";
supportMail = "info@cpr-robots.com";
}
public int Initialize()
{
this.camList.Add(new TCPIP());
for (int index = 0; index < this.nrOfCameras; ++index)
{
this.camList[index].Connect();
}
return 0;
}
public void ShowGUI()
{
;
}
public string LogMessage()
{
string str = this.logMsg + this.camList[0].logMsg;
this.logMsg = "";
this.camList[0].logMsg = "";
return str;
}
public int UpdatePosition(robotStatus robState, TimeSpan diffTime, double ovr, ref double[] joints, ref float[] positionMatrix, ref double[] orientationEuler, bool[] digitalIn, ref bool[] digitalOut)
{
return 0;
}
public int GetTargetPosition(int camNr, ref int resClass, ref float[] posCart, ref float[] oriEuler)
{
for (int i = 0; i < nrOfCameras; i++)
{
resClass = 3;
posCart[0] = float.Parse(this.camList[i].xcoordinateZero.ToString());
posCart[1] = float.Parse(this.camList[i].ycoordinateZero.ToString());
posCart[2] = float.Parse(this.camList[i].zCoordinateMinn.ToString());
if ((double)oriEuler[0] > 180.0)
oriEuler[0] -= 360f;
if ((double)oriEuler[0] < -180.0)
oriEuler[0] += 360f;
}
return 1;
}
public void SetPluginDirectoryPath(string path)
{
this.PluginDirPath = path;
}
}
}
Вот код, который запускает связь TCP / IP и генерирует окончательные координаты x, y и z.
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace PluginSimple
{
class TCPIP
{
public int port = 50010;
public string logMsg = "";
public string ipAdress = "169.254.104.24";
public TcpClient clientSocket;
public List<double> zcoordinate = null;
public double zaxis = 0.0;
public List<double[]> FinalCoordinates = null;
public double xCoordinateMin = 0.0;
public double yCoordinateMin = 0.0;
public List<double> xcoordinate = null;
public List<double> ycoordinate = null;
public double xcoordinateZero = 0.0;
public double ycoordinateZero = 0.0;
public double zCoordinateMinn = 0.0;
public bool connected = true;
public TCPIP()
{
clientSocket = null;
xcoordinate = new List<double>();
ycoordinate = new List<double>();
zcoordinate = new List<double>();
FinalCoordinates = new List<double[]>();
}
public void Disconnect()
{
if (clientSocket != null)
{
if (clientSocket.Connected)
{
clientSocket.Close();
}
}
}
public void Connect()
{
try
{
if (clientSocket != null)
{
readData(clientSocket);
}
else if (clientSocket == null)
{
clientSocket = new TcpClient();
connected = true;
logMsg = "Connecting to " + ipAdress + "having port number " + port;
clientSocket.Connect(ipAdress, port);
logMsg = "Connected to " + ipAdress + "having port number" + port;
readData(clientSocket);
}
}
catch (Exception excp)
{
this.logMsg = "Cant Connect 1";
this.logMsg = excp.ToString();
}
}
public async void SendToAll(string leMessage = "")
{
if (string.IsNullOrEmpty(leMessage))
{
return;
}
try
{
byte[] buffMessage = Encoding.ASCII.GetBytes(leMessage);
clientSocket.GetStream().WriteAsync(buffMessage, 0, buffMessage.Length);
Console.WriteLine("Sending succesful");
}
catch (Exception excp)
{
logMsg = excp.ToString();
}
}
public void readData(TcpClient mClient)
{
try
{
StreamReader clientStreamReader = new StreamReader(mClient.GetStream());
logMsg = "1";
char[] buff = new char[1024];
logMsg = "2";
int readByCount = 0;
connected = true;
while (connected)
{
SendToAll("1234L000000008\r\n1234T?\r\n");
readByCount = clientStreamReader.Read(buff, 0, buff.Length);
logMsg = "3";
if (readByCount > 30)
{
var output = (new string(buff).TrimEnd('\u0000'));
logMsg = "4";
var output1 = output.Split(new[] { ";;" }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(';')).ToArray();
logMsg = "5";
JToken jsonParsed = JToken.FromObject(output1);
logMsg = "6";
jsonParsed.Last.Remove();
logMsg = "7";
jsonParsed.First.Remove();
logMsg = "8";
foreach (var arrayItem in jsonParsed)
{
var innerArray = arrayItem.ToObject<double[]>();
FinalCoordinates.Add(innerArray);
zaxis = innerArray.ElementAt<double>(4);
zcoordinate.Add(zaxis);
foreach (var item in zcoordinate)
{
zCoordinateMinn = zcoordinate.Min();
}
}
logMsg = "9";
foreach (var item in FinalCoordinates)
{
if (item.ElementAt(4) == zCoordinateMinn)
{
xCoordinateMin = (item[0] + item[2]) / 2;
yCoordinateMin = (item[1] + item[3]) / 2;
xcoordinateZero = xCoordinateMin;
ycoordinateZero = yCoordinateMin;
zCoordinateMinn = 1000 * zCoordinateMinn;
Convert();
}
}
logMsg = "11";
xcoordinate.Clear();
ycoordinate.Clear();
zcoordinate.Clear();
connected = false;
}
}
Array.Clear(buff, 0, buff.Length);
}
catch (Exception ex)
{
this.logMsg = "O3D: Could not connect to camera:";
}
}
public void Convert()
{
xcoordinateZero = (530 / 131) * xcoordinateZero;
xcoordinateZero = 155 + xcoordinateZero;
Console.WriteLine(xcoordinateZero);
ycoordinateZero = (715 / 175) * ycoordinateZero;
ycoordinateZero = -320 + ycoordinateZero;
Console.WriteLine(ycoordinateZero);
zCoordinateMinn = zCoordinateMinn - 460;
zCoordinateMinn = 300 - zCoordinateMinn;
Console.WriteLine(zCoordinateMinn);
}
}
}
Я пытался запустить этот плагин в программном обеспечении робота CPROG (программное обеспечение, на котором работает робот). Например, я использовал команду плагина три раза с некоторыми движениями между ними. Я заметил в лог-файле, что координаты, которые я получал, были одинаковыми каждый раз, хотя я меняю положение компонента (камера отправляет координаты компонентов). Я увидел в камере, что три изображения были сделаны одновременно, что не должно быть так, потому что он должен делать снимок, когда программное обеспечение видит команду плагина, а затем запускать другие команды и делать снимок снова, снова увидев команду плагина. но в моем случае плагин делает все три фотографии одновременно или просто одновременно, что объясняет, почему я получаю одинаковые координаты для каждого плагина.
Есть ли у вас какие-либо идеи, которые я могу использовать, чтобы внести изменения в мой плагин, который может заставить его работать должным образом?