Files
2019-Virtual-Field/FRC 2019 Virtual Camera/Assets/Scripts/robotCommunication.cs
T

70 lines
2.1 KiB
C#
Raw Normal View History

2019-01-18 19:54:55 -07:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class robotCommunication : MonoBehaviour
{
2019-01-28 16:16:40 -07:00
public bool isData = false;
2019-01-18 19:54:55 -07:00
public static int portNumber = 4388;
public int bytesAvailable;
2019-01-28 16:16:40 -07:00
List<string> keys = new List<string>();
2019-01-18 19:54:55 -07:00
public SortedList<string, float> robotValues =
new SortedList<string, float>
{
2019-01-28 16:16:40 -07:00
{ "Left Pos Inches", 0.0f },
{ "Yaw Angle Deg", 0.0f },
{ "Right Pos Inches", 0.0f },
{ "Elevator Pos Ticks", 0.0f },
2019-01-18 19:54:55 -07:00
};
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);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
short currentIndex;
float currentValue;
// Start is called before the first frame update
void Start()
{
clientSocket.Connect(serverAddress);
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()
{
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-01-18 19:54:55 -07:00
clientSocket.Send(new byte[] { 100 });
2019-01-28 16:16:40 -07:00
isData = true;
2019-01-18 19:54:55 -07:00
}
}
}