Crane.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. using UnityEngine;
  8. public class Crane : MonoBehaviour
  9. {
  10. private Thread receiveThread;
  11. private Socket client;
  12. private byte[] buffer;
  13. private string strBuffer;
  14. private bool isReceiving;
  15. private string plcAddress = "127.0.0.1";
  16. private int port = 8081;
  17. private float x;
  18. private float y;
  19. private float z = 0;
  20. private float xDelta;
  21. private float yDelta;
  22. private float zDelta;
  23. private float xOffset= 68;
  24. private float yOffset=72;
  25. private float zOffset=-409;
  26. // Start is called before the first frame update
  27. void Start()
  28. {
  29. buffer = new byte[305];
  30. Debug.Log("start to connect plc");
  31. connect();
  32. Debug.Log("connected plc");
  33. isReceiving = true;
  34. StartReceiveThread();
  35. }
  36. // Update is called once per frame
  37. void Update()
  38. {
  39. //Vector3 position = new Vector3(x + xOffset, y + yOffset, zOffset + z);
  40. //this.transform.position = position;
  41. this.transform.Translate(0, 0, zDelta * Time.deltaTime, Space.World);
  42. }
  43. private void connect()
  44. {
  45. try
  46. {
  47. IPAddress ip = IPAddress.Parse(plcAddress);
  48. IPEndPoint ipe = new IPEndPoint(ip, port);
  49. client = new Socket(SocketType.Stream, ProtocolType.Tcp);
  50. client.NoDelay = true;
  51. client.Connect(ipe);
  52. }
  53. catch(Exception ex)
  54. {
  55. Debug.LogError(ex.Message);
  56. }
  57. }
  58. private void StartReceiveThread()
  59. {
  60. receiveThread = new Thread(new ThreadStart(Receive));
  61. receiveThread.Start();
  62. }
  63. public void Receive()
  64. {
  65. try
  66. {
  67. while (isReceiving)
  68. {
  69. client.Receive(buffer);
  70. strBuffer = System.Text.Encoding.Default.GetString(buffer);
  71. Debug.Log(strBuffer.Length+";"+strBuffer);
  72. float newX = float.Parse(strBuffer.Substring(52, 7).Trim());
  73. float newY= float.Parse(strBuffer.Substring(59, 7).Trim());
  74. float newZ= float.Parse(strBuffer.Substring(66, 7).Trim());
  75. xDelta = newX - x;
  76. yDelta = newY - y;
  77. zDelta = newZ - z;
  78. x = newX/100;
  79. y = newY/100;
  80. Debug.Log("zDelta:" + zDelta);
  81. z = newZ;
  82. // x = x / 100;
  83. // y = y / 100;
  84. // z = z / 100;
  85. Debug.Log("X:"+x+",Y:"+y+",Z:"+z);
  86. }
  87. }
  88. catch(Exception ex)
  89. {
  90. Debug.LogError(ex.Message);
  91. }
  92. }
  93. public void OnDestroy()
  94. {
  95. client.Close();
  96. isReceiving = false;
  97. receiveThread.Abort();
  98. }
  99. }