Files
HDRobotics/Assets/Scripts/Model/ProgramModel.cs

470 lines
15 KiB
C#
Raw Normal View History

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Palmmedia.ReportGenerator.Core;
using System;
using System.Collections.Generic;
2025-10-30 09:31:05 +09:00
using System.IO;
using System.Linq;
using System.Net.Http;
2025-11-06 15:28:16 +09:00
using System.Net.Mail;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UdpClientLib;
2025-11-06 15:28:16 +09:00
using UnityEditor.PackageManager;
using UnityEngine;
public interface IProgramModel
{
}
public class ProgramModel : IProgramModel
{
2025-10-24 14:36:33 +09:00
private string tcpBaseUrl;
private string udpBaseUrl;
HttpClient httpClient = new HttpClient();
2025-11-06 15:28:16 +09:00
private SingleTcpClient tcpClient;
private SingleUdpClient udpClient;
2025-10-24 14:36:33 +09:00
public UdpClientManager manager = new UdpClientManager();
private List<JobInfoDTO> allProgramsCache = new List<JobInfoDTO>();
public RobotProgram CurrentProgram { get; private set; }
2025-10-24 14:36:33 +09:00
private RobotData robotData;
private RobotController robotController;
2025-10-24 14:36:33 +09:00
private readonly object lockObject = new object();
private bool hasNewData;
2025-10-30 09:31:05 +09:00
public bool IsMoving;
2025-11-06 15:28:16 +09:00
public bool isError;
2025-10-30 09:31:05 +09:00
private Vector3 startMovementPosition;
2025-10-24 14:36:33 +09:00
public ProgramModel(string hostip, int tcpPort, int udpPort, RobotController robotController)
{
2025-10-24 14:36:33 +09:00
tcpBaseUrl = $"http://{hostip}:{tcpPort}";
udpBaseUrl = $"http://{hostip}:{udpPort}";
2025-11-06 15:28:16 +09:00
_ = HandleAsyncWork(hostip, tcpPort, udpPort);
}
public async Task HandleAsyncWork(string hostip, int tcpPort, int udpPort)
{
tcpClient = new SingleTcpClient();
await tcpClient.ConnectAsync("Tcp-Client", hostip, tcpPort);
udpClient = manager.AddClient("Udp-client", hostip, udpPort);
manager.PrintStatus();
}
public async Task InitializeAsync()
{
await LoadAllPrograms();
2025-10-24 14:36:33 +09:00
hasNewData = false;
2025-10-30 09:31:05 +09:00
IsMoving = false;
2025-11-06 15:28:16 +09:00
isError = false;
return;
}
2025-10-24 14:36:33 +09:00
public bool IsNewDataAvailable()
{
lock (lockObject)
{
return hasNewData;
}
}
public RobotData GetLatestRobotData()
{
lock (lockObject)
{
hasNewData = false; // <20><><EFBFBD><EFBFBD><EFBFBD>͸<EFBFBD> <20>о<EFBFBD><D0BE><EFBFBD><EFBFBD>Ƿ<EFBFBD> <20>÷<EFBFBD><C3B7>׸<EFBFBD> <20><><EFBFBD><EFBFBD>
2025-10-30 09:31:05 +09:00
return robotData;
2025-10-24 14:36:33 +09:00
}
}
2025-10-30 09:31:05 +09:00
/// <summary>
/// <20><><EFBFBD>α׷<CEB1> <20><><EFBFBD><EFBFBD>/<2F>ҷ<EFBFBD><D2B7><EFBFBD><EFBFBD><EFBFBD> <20>ý<EFBFBD><C3BD><EFBFBD>
/// </summary>
public async Task<bool> CheckProgramExists(string jobProgramName)
{
2025-10-24 14:36:33 +09:00
string requestUri = $"{tcpBaseUrl}/file_manager/file_exist?pathname=project/jobs/{jobProgramName}";
HttpResponseMessage result = await httpClient.GetAsync(requestUri);
string jsonResponse = await result.Content.ReadAsStringAsync();
return jsonResponse.Equals("true");
}
public async Task<bool> CreateNewProgram(string userInputId)
{
string robotModelName;
if (string.IsNullOrEmpty(userInputId)) return false;
string newProgramId = $"{userInputId}.job";
if (await CheckProgramExists(newProgramId))
{
Debug.LogError("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>̹<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>մϴ<D5B4>.");
return false;
}
else
Debug.Log($"{newProgramId} <20><><EFBFBD><EFBFBD>");
try
{
robotModelName = await GetRobotModelNameAsync();
}
catch (Exception e)
{
Debug.LogError($"<22>κ<EFBFBD> <20>𵨸<EFBFBD><F0B5A8B8><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>߽<EFBFBD><DFBD>ϴ<EFBFBD>: {e.Message}");
return false;
}
NewJobRequestDTO newJob = new NewJobRequestDTO
{
fname = newProgramId,
model_name = robotModelName,
n_add_ax = 0
};
string jsonString = JsonConvert.SerializeObject(newJob);
HttpContent jsonPayload = new StringContent(jsonString, Encoding.UTF8, "application/json");
2025-11-06 15:28:16 +09:00
2025-10-24 14:36:33 +09:00
string requestUri = $"{tcpBaseUrl}/project/jobs/create_job";
try
{
HttpResponseMessage result = await httpClient.PostAsync(requestUri, jsonPayload);
if (result.IsSuccessStatusCode)
{
await LoadProgram(userInputId);
return true;
}
else
return false;
}
catch (Exception e)
{
Debug.LogError($"<22><><EFBFBD>α׷<CEB1> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>: {userInputId}, {e.Message}");
return false;
}
}
private async Task<string> GetRobotModelNameAsync()
{
2025-10-24 14:36:33 +09:00
string requestUri = $"{tcpBaseUrl}/project/rgen";
HttpResponseMessage result = await httpClient.GetAsync(requestUri);
string jsonResponse = await result.Content.ReadAsStringAsync();
JObject data = JObject.Parse(jsonResponse);
string modelName = (string)data.SelectToken("robot_model");
if (string.IsNullOrEmpty(modelName))
{
throw new Exception("<22>κ<EFBFBD> <20><><EFBFBD><EFBFBD> API <20><><EFBFBD><EFBFBD><E4BFA1> <20>𵨸<EFBFBD><F0B5A8B8><EFBFBD> ã<><C3A3> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD>.");
}
return modelName;
}
2025-10-24 11:55:43 +09:00
public async Task<bool> GetRobotMotorStateAsync()
{
2025-10-24 14:36:33 +09:00
string requestUri = $"{tcpBaseUrl}/project/rgen";
2025-10-24 11:55:43 +09:00
HttpResponseMessage result = await httpClient.GetAsync(requestUri);
string jsonResponse = await result.Content.ReadAsStringAsync();
JObject data = JObject.Parse(jsonResponse);
int motorState = (int)data.SelectToken("enable_state");
if (motorState == 0 || motorState == 256)
2025-10-24 11:55:43 +09:00
return true;
else if (motorState == 1)
return false;
else
{
throw new Exception("<22>κ<EFBFBD> <20><><EFBFBD><EFBFBD> API <20><><EFBFBD><EFBFBD><E4BFA1> <20><><EFBFBD><EFBFBD> <20><><EFBFBD>¸<EFBFBD> ã<><C3A3> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD>.");
}
}
2025-11-06 15:28:16 +09:00
public async Task<int> GetRobotToolNum()
{
string requestUri = $"{tcpBaseUrl}/project/rgen";
HttpResponseMessage result = await httpClient.GetAsync(requestUri);
string jsonResponse = await result.Content.ReadAsStringAsync();
JObject data = JObject.Parse(jsonResponse);
int toolNum = (int)data.SelectToken("tool_no");
return toolNum;
}
2025-10-30 09:31:05 +09:00
public async Task GetTCPAsync(CancellationToken token)
2025-10-24 14:36:33 +09:00
{
while (!token.IsCancellationRequested)
2025-10-24 14:36:33 +09:00
{
try
{
string requestUri = $"{tcpBaseUrl}/project/robot/po_cur";
HttpResponseMessage result = await httpClient.GetAsync(requestUri);
string jsonResponse = await result.Content.ReadAsStringAsync();
var tempRobotData = JsonConvert.DeserializeObject<RobotData>(jsonResponse, new JsonSerializerSettings { CheckAdditionalContent = false });
lock (lockObject)
{
robotData = tempRobotData;
hasNewData = true;
}
await Task.Delay(50);
}
catch (Exception e)
2025-10-24 14:36:33 +09:00
{
Debug.Log(e);
await Task.Delay(1000); // <20><><EFBFBD><EFBFBD> <20><> <20><> <20><> <20><><EFBFBD><EFBFBD>
}
}
}
public async Task<bool> LoadProgram(string programId)
{
2025-10-24 14:36:33 +09:00
string requestUri = $"{tcpBaseUrl}/file_manager/files?pathname=project/jobs/{programId}&common";
HttpResponseMessage result = await httpClient.GetAsync(requestUri);
string rawTextContent = await result.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(rawTextContent))
{
return false;
}
CurrentProgram = new RobotProgram(programId, rawTextContent);
2025-10-24 14:36:33 +09:00
return true;
}
private async Task LoadAllPrograms()
{
allProgramsCache.Clear();
string jsonResponse = null;
string wrappedJson = null;
try
{
2025-10-24 14:36:33 +09:00
HttpResponseMessage result = await httpClient.GetAsync($"{tcpBaseUrl}/project/jobs_info");
jsonResponse = await result.Content.ReadAsStringAsync();
wrappedJson = $"{{\"jobs\":{jsonResponse}}}";
JobListWrapper wrapper = JsonUtility.FromJson<JobListWrapper>(wrappedJson);
if (wrapper != null && wrapper.jobs != null)
{
allProgramsCache = wrapper.jobs;
}
else
{
Debug.LogError("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> job <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>Ľ<EFBFBD><C4BD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD>: " + jsonResponse);
}
}
catch (ArgumentException e)
{
Debug.LogError($"JSON <20>Ľ<EFBFBD> <20><><EFBFBD><EFBFBD>: {e.Message}");
}
catch (Exception e)
{
Debug.LogError($"LoadAllPrograms <20><> <20><> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>: {e.Message}");
}
}
public List<string> GetAllProgramIds()
{
List<string> ids = new List<string>();
foreach (var jobInfo in allProgramsCache)
{
ids.Add(jobInfo.fname);
}
return ids;
}
2025-10-24 14:36:33 +09:00
2025-10-30 09:31:05 +09:00
/// <summary>
/// <20>κ<EFBFBD> <20><>ġ <20><><EFBFBD><EFBFBD> <20>ý<EFBFBD><C3BD><EFBFBD>
/// </summary>
public async Task<bool> SavePointToProgramAsync(RobotData pointData, int index = -1)
{
if (CurrentProgram == null)
{
Debug.LogError("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD>α׷<CEB1><D7B7><EFBFBD> <20>ε<EFBFBD><CEB5><EFBFBD><EFBFBD><EFBFBD> <20>ʾҽ<CABE><D2BD>ϴ<EFBFBD>.");
return false;
}
2025-11-06 15:28:16 +09:00
// <20><><EFBFBD><EFBFBD> <20><>ü <20><><EFBFBD><EFBFBD>
2025-10-30 09:31:05 +09:00
var payload = new
{
programId = CurrentProgram.ProgramId,
indexToUpdate = index, // -1<≯<EFBFBD> <20><> <20><><EFBFBD><EFBFBD>Ʈ, 0 <20>̻<EFBFBD><CCBB≯<EFBFBD> <20>ش<EFBFBD> <20>ε<EFBFBD><CEB5><EFBFBD> <20><><EFBFBD><EFBFBD>
pose = pointData
};
string jsonPayload = JsonConvert.SerializeObject(payload);
HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
string requestUri = (index == -1)
? $"{tcpBaseUrl}/project/jobs/{CurrentProgram.ProgramId}/ins_cmd_line"
: $"{tcpBaseUrl}/project/jobs/{CurrentProgram.ProgramId}/pose_modify";
try
{
HttpResponseMessage result = await httpClient.PostAsync(requestUri, content);
if (result.IsSuccessStatusCode)
{
// <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϸ<EFBFBD>, <20>޸<EFBFBD><DEB8><EFBFBD>(CurrentProgram)<29><><EFBFBD><EFBFBD> <20>ݿ<EFBFBD>
if (index == -1)
CurrentProgram.AddStep(pointData); // RobotProgram<61><6D> <20><> RobotMoveStep <20>߰<EFBFBD>
else
CurrentProgram.UpdateStep(index, pointData); // RobotProgram<61><6D> <20>ش<EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
return true;
}
return false;
}
catch (Exception e)
{
Debug.LogError($"<22><><EFBFBD><EFBFBD>Ʈ <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>: {e.Message}");
return false;
}
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ʈ <20><><EFBFBD><EFBFBD> <20><>û
public async Task<bool> DeletePointFromProgramAsync(int index)
{
if (CurrentProgram == null) return false;
var payload = new { programId = CurrentProgram.ProgramId, indexToDelete = index };
string jsonPayload = JsonConvert.SerializeObject(payload);
HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
string requestUri = $"{tcpBaseUrl}/project/jobs/{CurrentProgram.ProgramId}/del_cmd_line";
try
{
HttpResponseMessage result = await httpClient.PostAsync(requestUri, content);
if (result.IsSuccessStatusCode)
{
2025-11-06 15:28:16 +09:00
// <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><>, <20>޸𸮿<DEB8><F0B8AEBF><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
2025-10-30 09:31:05 +09:00
CurrentProgram.DeleteStep(index);
return true;
}
return false;
}
catch (Exception e)
{
Debug.LogError($"<22><><EFBFBD><EFBFBD>Ʈ <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>: {e.Message}");
return false;
}
}
// Ÿ<><C5B8> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>̵<EFBFBD>
2025-11-06 15:28:16 +09:00
public async Task<bool> MoveToPoseTcpAsync(Vector3 position)
2025-10-30 09:31:05 +09:00
{
try
2025-10-30 09:31:05 +09:00
{
2025-11-06 15:28:16 +09:00
startMovementPosition.x = Convert.ToSingle(Math.Round(-1 * position.x * 1000, 2));
startMovementPosition.y = Convert.ToSingle(Math.Round(-1 * position.z * 1000, 2));
startMovementPosition.z = Convert.ToSingle(Math.Round(position.y * 1000, 2));
2025-11-06 15:28:16 +09:00
string jsonResponse = await tcpClient.SendPostRequestAsync("/project/robot/move_to_pose_manual", $"{{\"pose_tg\":{{\"crd\":\"robot\",\"_type\":\"Pose\",\"mechinfo\":1,\"x\":{startMovementPosition.x},\"y\":{startMovementPosition.y},\"z\":{startMovementPosition.z}, \"rx\":{robotData.rx}, \"ry\":{robotData.ry}, \"rz\":{robotData.rz}}}}}");
2025-11-06 15:28:16 +09:00
if (jsonResponse.Contains("200"))
2025-10-30 09:31:05 +09:00
{
Debug.Log("TCP POST (Move) <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>");
2025-11-06 15:28:16 +09:00
IsMoving = true;
return true;
}
else
{
2025-11-06 15:28:16 +09:00
Debug.LogError($"TCP POST (Move) <20><><EFBFBD><EFBFBD>");
return false;
2025-10-30 09:31:05 +09:00
}
}
catch (Exception e)
{
Debug.Log(e);
return false;
2025-10-30 09:31:05 +09:00
}
}
// TCP POST <20>̵<EFBFBD> <20><><EFBFBD><EFBFBD> üũ
public async Task StartMovementCheckLoopAsync(CancellationToken token)
2025-10-30 09:31:05 +09:00
{
2025-11-06 15:28:16 +09:00
try
2025-10-30 09:31:05 +09:00
{
2025-11-06 15:28:16 +09:00
while (!token.IsCancellationRequested)
2025-10-30 09:31:05 +09:00
{
2025-11-06 15:28:16 +09:00
if (IsMoving)
2025-10-30 09:31:05 +09:00
{
2025-11-06 15:28:16 +09:00
await udpClient.SendFilledBytesAsync(new Dictionary<int, byte> { { 2, 0x20 } });
await Task.Delay(100);
RobotData currentPose = null;
2025-11-06 15:28:16 +09:00
lock (lockObject) { currentPose = this.robotData; }
if (currentPose != null)
{
bool isApproximatelyX = Mathf.Approximately(startMovementPosition.x, Convert.ToSingle(Math.Round(currentPose.x, 2)));
bool isApproximatelyY = Mathf.Approximately(startMovementPosition.y, Convert.ToSingle(Math.Round(currentPose.y, 2)));
bool isApproximatelyZ = Mathf.Approximately(startMovementPosition.z, Convert.ToSingle(Math.Round(currentPose.z, 2)));
if (isApproximatelyX && isApproximatelyY && isApproximatelyZ)
{
2025-11-06 15:28:16 +09:00
IsMoving = false;
}
}
}
2025-11-06 15:28:16 +09:00
else
{
2025-11-06 15:28:16 +09:00
await Task.Delay(500, token);
2025-10-30 09:31:05 +09:00
}
}
}
2025-11-06 15:28:16 +09:00
catch (TaskCanceledException)
{
2025-11-06 15:28:16 +09:00
Debug.Log("MovementCheckLoopAsync Canceled.");
}
catch (Exception e)
{
Debug.LogError($"MovementCheckLoopAsync Error: {e.Message}\n{e.StackTrace}");
2025-10-30 09:31:05 +09:00
}
}
2025-11-06 15:28:16 +09:00
//private async Task GetMovementState()
//{
// while (!cancellationTokenSource.Token.IsCancellationRequested)
// {
// try
// {
// var jsonResponse = await tcpClient.SendGetRequestAsync("/project/rgen");
// var pasrsingJsonResponse = HttpResponseParser.ExtractJsonFromHttpResponse(jsonResponse);
// var tempRobotData = JsonConvert.DeserializeObject<RobotStateData>(pasrsingJsonResponse, new JsonSerializerSettings { CheckAdditionalContent = false });
// jsonResponse = await tcpClient.SendGetRequestAsync($"/logManager/search?cat_p=E&id_min={Convert.ToInt32(tempRobotData.eid_last_err) - 3}&id_max={tempRobotData.eid_last_err}");
// pasrsingJsonResponse = HttpResponseParser.ExtractJsonFromHttpResponse(jsonResponse);
// tempRobotData = JsonConvert.DeserializeObject<RobotStateData>(pasrsingJsonResponse, new JsonSerializerSettings { CheckAdditionalContent = false });
// isError = tempRobotData != null && tempRobotData.code != null && (tempRobotData.code.Contains("228") || tempRobotData.code.Contains("6037"));
// Debug.Log(isError);
// await Task.Delay(100);
// }
// catch (System.Exception)
// {
// }
// }
//}
public async Task<string> GetMovingState()
2025-10-24 14:36:33 +09:00
{
2025-11-06 15:28:16 +09:00
return await tcpClient.SendGetRequestAsync("/project/robot/moving_to_pose_manual");
2025-10-24 14:36:33 +09:00
}
}