Files

84 lines
2.5 KiB
C#
Raw Permalink Normal View History

2019-01-18 19:54:55 -07:00
using System;
using System.Collections;
using System.Collections.Generic;
2019-02-15 16:46:19 -07:00
using System.Diagnostics;
2019-01-18 19:54:55 -07:00
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class robotCommunication : MonoBehaviour
{
public SortedList<string, float> robotValues =
new SortedList<string, float>
{
2019-02-18 14:43:32 -07:00
{ "Yaw Angle Deg", 0.0f },
2019-02-15 16:46:19 -07:00
{ "Distance", 0.0f },
2019-02-18 14:43:32 -07:00
{ "Team", 0.0f },
2019-01-18 19:54:55 -07:00
};
2019-02-15 16:46:19 -07:00
public static int portNumber = 4388;
public int bytesAvailable;
List<string> keys = new List<string>();
2019-01-28 16:16:40 -07:00
public float encoder, navX;
public string input, request = "";
2019-01-18 19:54:55 -07:00
IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), portNumber);
2019-02-15 16:46:19 -07:00
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket clientSocket;
2019-01-18 19:54:55 -07:00
short currentIndex;
float currentValue;
2019-02-15 16:46:19 -07:00
public float latency;
2019-01-18 19:54:55 -07:00
// Start is called before the first frame update
void Start()
{
2019-02-15 16:46:19 -07:00
startRobopipe();
serverSocket.Bind(serverAddress);
serverSocket.Listen(10);
clientSocket = serverSocket.Accept();
2019-01-28 16:16:40 -07:00
foreach (var valuePair in robotValues)
{
request += valuePair.Key;
keys.Add(valuePair.Key);
request += ",";
}
request = request.Substring(0,request.Length-1);
byte[] byteRequest = Encoding.UTF8.GetBytes(request);
clientSocket.Send(byteRequest);
2019-01-18 19:54:55 -07:00
}
// Update is called once per frame
void Update()
{
2019-02-15 16:46:19 -07:00
latency = Time.deltaTime * 1000;
2019-01-18 19:54:55 -07:00
bytesAvailable = clientSocket.Available;
2019-01-28 16:16:40 -07:00
if (bytesAvailable > 10)
2019-01-18 19:54:55 -07:00
{
byte[] byteInput = new byte[100];
clientSocket.Receive(byteInput);
input = Encoding.UTF8.GetString(byteInput);
string[] values = input.Split('|');
2019-01-28 16:16:40 -07:00
int i = 0;
foreach (string key in keys)
{
robotValues[keys[i]] = float.Parse(values[i], CultureInfo.InvariantCulture.NumberFormat);
i++;
}
2019-02-15 16:46:19 -07:00
clientSocket.Send(Encoding.UTF8.GetBytes("CONT"));
2019-01-18 19:54:55 -07:00
}
}
2019-02-15 16:46:19 -07:00
private void OnApplicationQuit()
{
clientSocket.Send(Encoding.UTF8.GetBytes("EXIT"));
}
private void startRobopipe()
{
Process foo = new Process();
foo.StartInfo.FileName = "Robopipe.jar";
foo.StartInfo.Arguments = "" + portNumber;
foo.Start();
}
2019-01-18 19:54:55 -07:00
}