123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using UnityEngine;
- public class Crane : MonoBehaviour
- {
- private Thread receiveThread;
- private Socket client;
- private byte[] buffer;
- private string strBuffer;
- private bool isReceiving;
- private string plcAddress = "127.0.0.1";
- private int port = 8081;
- private float x;
- private float y;
- private float z = 0;
- private float xDelta;
- private float yDelta;
- private float zDelta;
- private float xOffset= 68;
- private float yOffset=72;
- private float zOffset=-409;
- // Start is called before the first frame update
- void Start()
- {
- buffer = new byte[305];
- Debug.Log("start to connect plc");
- connect();
- Debug.Log("connected plc");
-
- isReceiving = true;
- StartReceiveThread();
- }
- // Update is called once per frame
- void Update()
- {
- //Vector3 position = new Vector3(x + xOffset, y + yOffset, zOffset + z);
- //this.transform.position = position;
- this.transform.Translate(0, 0, zDelta * Time.deltaTime, Space.World);
- }
- private void connect()
- {
- try
- {
- IPAddress ip = IPAddress.Parse(plcAddress);
- IPEndPoint ipe = new IPEndPoint(ip, port);
- client = new Socket(SocketType.Stream, ProtocolType.Tcp);
- client.NoDelay = true;
- client.Connect(ipe);
-
- }
- catch(Exception ex)
- {
- Debug.LogError(ex.Message);
- }
-
- }
- private void StartReceiveThread()
- {
- receiveThread = new Thread(new ThreadStart(Receive));
- receiveThread.Start();
- }
- public void Receive()
- {
- try
- {
- while (isReceiving)
- {
- client.Receive(buffer);
- strBuffer = System.Text.Encoding.Default.GetString(buffer);
- Debug.Log(strBuffer.Length+";"+strBuffer);
- float newX = float.Parse(strBuffer.Substring(52, 7).Trim());
- float newY= float.Parse(strBuffer.Substring(59, 7).Trim());
- float newZ= float.Parse(strBuffer.Substring(66, 7).Trim());
- xDelta = newX - x;
- yDelta = newY - y;
- zDelta = newZ - z;
- x = newX/100;
- y = newY/100;
- Debug.Log("zDelta:" + zDelta);
- z = newZ;
- // x = x / 100;
- // y = y / 100;
- // z = z / 100;
- Debug.Log("X:"+x+",Y:"+y+",Z:"+z);
- }
- }
- catch(Exception ex)
- {
- Debug.LogError(ex.Message);
- }
- }
- public void OnDestroy()
- {
- client.Close();
- isReceiving = false;
- receiveThread.Abort();
-
- }
- }
|