Unity error when sending/listening for UDP packets, "A socket operation was attempted to an unreachable network"

-1

Im making a system in which there are two esp setups and a computer, one being an access point and the other a station, and the station connects to the access point along with your computer, and they broadcast UDP messages to your computer where they are picked up in unity. The setup goes that the esp's do not send and values untill the computer has sent one test packet so that we know unity's remoteIP(), unfortionatly, when trying to send the initial test message, I get the error:

System.Net.Sockets.SocketException (0x80004005): A socket operation was attempted to an unreachable network.

  at System.Net.Sockets.Socket.SendTo (System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) [0x00082] in <ae22a4e8f83c41d69684ae7f557133d9>:0 
  at System.Net.Sockets.Socket.SendTo (System.Byte[] buffer, System.Net.EndPoint remoteEP) [0x00000] in <ae22a4e8f83c41d69684ae7f557133d9>:0 
  at UDPRecieve.udpSend (System.String IPaddress) [0x00030] in C:\Users\mlfre\OneDrive\Desktop\VRtest\Assets\Scripts\UDPRecieve.cs:93 
UnityEngine.Debug:Log(Object)
UDPRecieve:udpSend(String) (at Assets/Scripts/UDPRecieve.cs:100)
UDPRecieve:Start() (at Assets/Scripts/UDPRecieve.cs:37)

I cannot find a good explanation on google as to why this would happen, so I am turing to you guys. :) This is the script I have to receive data in unity:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class UDPRecieve : MonoBehaviour
{

    Thread m_Thread;
    UdpClient m_Client;

    public int port;
    public string IPAddressESP1;
    public string IPAddressESP2;
    string returnData;

    public Quaternion leftQuaternion = Quaternion.identity;
    public Vector3 leftAcceleration = Vector3.zero;
    public bool leftButtonA = false;
    public bool leftButtonB = false;


    public Quaternion rightQuaternion = Quaternion.identity;
    public Vector3 rightAcceleration = Vector3.zero;
    public bool rightButtonA = false;
    public bool rightButtonB = false;


    void Start()
    {
        m_Thread = new Thread(new ThreadStart(ReceiveData));
        m_Thread.IsBackground = true;
        m_Thread.Start();
        udpSend(IPAddressESP1);
        udpSend(IPAddressESP2);
    }

    void ReceiveData()
    {

        try
        {

            m_Client = new UdpClient(port);
            m_Client.EnableBroadcast = true;
            while (true)
            {

                IPEndPoint hostIP = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = m_Client.Receive(ref hostIP);
                returnData = Encoding.ASCII.GetString(data);
                updateVars(returnData);

                Debug.Log(returnData);
            }
        }
        catch (Exception e)
        {
            Debug.Log(e);

            OnApplicationQuit();
        }
    }

    private void OnApplicationQuit()
    {
        if (m_Thread != null)
        {
            m_Thread.Abort();
        }

        if (m_Client != null)
        {
            m_Client.Close();
        }
    }
    void udpSend(string IPaddress)
    {
        var IP = IPAddress.Parse(IPaddress);

        var udpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        var sendEndPoint = new IPEndPoint(IP, port);


        try
        {

            //Sends a message to the host to which you have connected.
            byte[] sendBytes = Encoding.ASCII.GetBytes("hello from unity");

            udpClient1.SendTo(sendBytes, sendEndPoint);



        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }

    }
    public void updateVars(String recievedData)
    {
        int commas = 0;
        char letter;
        int start = 2;
        for (int index = 0; index < recievedData.Length; index++)
        {
            letter = recievedData[index];
            if (letter == ',' || letter == ':' || index == recievedData.Length - 1)
            {
                if (commas == 1)
                {

                    leftQuaternion.w = recievedData[0] == 'L' ? float.Parse(recievedData.Substring(start, index - start)) : leftQuaternion.w;
                    rightQuaternion.w = recievedData[0] == 'R' ? float.Parse(recievedData.Substring(start, index - start)) : rightQuaternion.w;
                }
                else if (commas == 2)
                {
                    leftQuaternion.x = recievedData[0] == 'L' ? float.Parse(recievedData.Substring(start, index - start)) : leftQuaternion.x;
                    rightQuaternion.x = recievedData[0] == 'R' ? float.Parse(recievedData.Substring(start, index - start)) : rightQuaternion.x;
                }
                else if (commas == 3)
                {
                    leftQuaternion.y = recievedData[0] == 'L' ? float.Parse(recievedData.Substring(start, index - start)) : leftQuaternion.y;
                    rightQuaternion.y = recievedData[0] == 'R' ? float.Parse(recievedData.Substring(start, index - start)) : rightQuaternion.y;
                }
                else if (commas == 4)
                {
                    leftQuaternion.z = recievedData[0] == 'L' ? float.Parse(recievedData.Substring(start, index - start)) : leftQuaternion.z;
                    rightQuaternion.z = recievedData[0] == 'R' ? float.Parse(recievedData.Substring(start, index - start)) : rightQuaternion.z;
                }
                else if (commas == 5)
                {
                    leftAcceleration.x = recievedData[0] == 'L' ? float.Parse(recievedData.Substring(start, index - start)) : leftAcceleration.x;
                    rightAcceleration.x = recievedData[0] == 'R' ? float.Parse(recievedData.Substring(start, index - start)) : rightAcceleration.x;
                }
                else if (commas == 6)
                {
                    leftAcceleration.y = recievedData[0] == 'L' ? float.Parse(recievedData.Substring(start, index - start)) : leftAcceleration.y;
                    rightAcceleration.y = recievedData[0] == 'R' ? float.Parse(recievedData.Substring(start, index - start)) : rightAcceleration.y;
                }
                else if (commas == 7)
                {
                    leftAcceleration.z = recievedData[0] == 'L' ? float.Parse(recievedData.Substring(start, index - start)) : leftAcceleration.z;
                    rightAcceleration.z = recievedData[0] == 'R' ? float.Parse(recievedData.Substring(start, index - start)) : rightAcceleration.z;

                    if (recievedData[0] == 'L' && recievedData[index + 3] == 'U')
                    {
                        leftButtonB = false;
                    }
                    else if (recievedData[0] == 'L' && recievedData[index + 3] == 'D')
                    {
                        leftButtonB = true;
                    }
                    else if (recievedData[0] == 'R' && recievedData[index + 3] == 'U')
                    {
                        rightButtonB = false;
                    }
                    else
                    {
                        rightButtonB = true;
                    }
                }
                else if (commas == 8)
                {
                    if (recievedData[0] == 'L' && recievedData[index + 3] == 'U')
                    {
                        leftButtonA = false;
                    }
                    else if (recievedData[0] == 'L' && recievedData[index + 3] == 'D')
                    {
                        leftButtonA = true;
                    }
                    else if (recievedData[0] == 'R' && recievedData[index + 3] == 'U')
                    {
                        rightButtonA = false;
                    }
                    else
                    {
                        rightButtonA = true;
                    }
                }

                start = index + 1;
                commas++;
            }
        }
    }
}

and this is the access point script for my esp in arduino. I dont think that attatching the station script would be nessecary, as they are mostly the same and probably have the same intrinsic problem, but I can attatch if requested. here is the access point script:

/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg
==============================

  GY-521  NodeMCU
  MPU6050 devkit 1.0
  board   Lolin         Description
  ======= ==========    ====================================================
  VCC     VU (5V USB)   Not available on all boards so use 3.3V if needed.
  GND     G             Ground
  SCL     D1 (GPIO05)   I2C clock
  SDA     D2 (GPIO04)   I2C data
  XDA     not connected
  XCL     not connected
  AD0     not connected
  INT     D8 (GPIO15)   Interrupt pin
*/
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#include "MPU6050_6Axis_MotionApps20.h" //might need (0x03)
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high


// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer, can be set to 1024 instead

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
#define OUTPUT_READABLE_WORLDACCEL


// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector

#ifdef OUTPUT_READABLE_EULER
float euler[3];         // [psi, theta, phi]    Euler angle container
#endif
#ifdef OUTPUT_READABLE_YAWPITCHROLL
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
#endif

#define INTERRUPT_PIN 15 // use pin 15 on ESP8266

const char DEVICE_NAME[] = "mpu6050";

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void ICACHE_RAM_ATTR dmpDataReady() {
    mpuInterrupt = true;
}

void mpu_setup()
{
  // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif

  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);

  // verify connection
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  // load and configure the DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }
}

// push buttons
int aButtonPin = 12; //D6
int bButtonPin = 13; //D7
int aVal = 0; 
int bVal = 0;

String message = "L";
char messagePacket[255];

WiFiUDP Udp;
unsigned int localUdpPort = 4001;  // local port to listen on

//wifi config
WiFiServer server(localUdpPort);
IPAddress IP(192,175,0,21);
IPAddress gateway(192,175,0,2);
IPAddress mask = (255, 255, 255, 0);

IPAddress sendTo;
bool ipKnown = false;

const char* ssid = "VRControllers";
const char* password = "VRControllers";

void setup()
{
  Serial.begin(9600);
  delay(10);

  //setup the access point
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
  bool result = WiFi.softAPConfig(IP, gateway, mask);
  server.begin();
  server.setNoDelay(true);
  Udp.begin(localUdpPort);
  Serial.println(result ? "Server started." : "Server failed to start");

  //set up buttons
  pinMode(aButtonPin, INPUT);
  pinMode(bButtonPin, INPUT); 
  //set up accelerometer 
  mpu_setup();
}

void mpu_loop()
{
  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  if (!mpuInterrupt && fifoCount < packetSize) return;

  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & 0x10) || fifoCount == 1024) { // if fifoCount is 1024 change conditional to 16384
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize){
      fifoCount = mpu.getFIFOCount();
    }

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);
    //mpu.resetFIFO();

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

#ifdef OUTPUT_READABLE_YAWPITCHROLL
    // display Euler angles in degrees
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    String x = String(ypr[0] * 180/M_PI);
    String y = String(ypr[1] * 180/M_PI);
    String z = String(ypr[2] * 180/M_PI);
    mpu.resetFIFO();
    message += ":" + x + "," + y + "," + z;
#endif

#ifdef OUTPUT_READABLE_QUATERNION
    // display quaternion values in easy matrix form: w x y z
    mpu.dmpGetQuaternion(&q, fifoBuffer);

    mpu.resetFIFO();
    message += ":" + String(q.w) + "," + String(q.x) + "," + String(q.y) + "," + String(q.z);
#endif

#ifdef OUTPUT_READABLE_EULER
    // display Euler angles in degrees
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetEuler(euler, &q);

    String x = String(euler[0] * 180/M_PI);
    String y = String(euler[1] * 180/M_PI);
    String z = String(euler[2] * 180/M_PI);
    mpu.resetFIFO();
    message += ":" + x + "," + y + "," + z;
#endif

#ifdef OUTPUT_READABLE_REALACCEL
    // display real acceleration, adjusted to remove gravity
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetAccel(&aa, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);

    mpu.resetFIFO();
    message += ":" + String(aaReal.x) + "," + String(aaReal.y) + "," + String(aaReal.z);
#endif

#ifdef OUTPUT_READABLE_WORLDACCEL
    // display initial world-frame acceleration, adjusted to remove gravity
    // and rotated based on known orientation from quaternion
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetAccel(&aa, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
    mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);

    mpu.resetFIFO();
    message += ":" + String(aaWorld.x) + "," + String(aaWorld.y) + "," + String(aaWorld.z);
#endif
  }
}

void buttonLoop(){
  aVal = digitalRead(aButtonPin);
  bVal = digitalRead(bButtonPin);

  message += bVal == HIGH ? ":B_DOWN" : ":B_UP";
  message += aVal == HIGH ? ",A_DOWN\n" : ",A_UP\n";
}

void loop()
{
  mpu_loop();
  buttonLoop();
  Serial.print(message);
  int packetSize = Udp.parsePacket();

  if(ipKnown){
    message.toCharArray(messagePacket, 255);
    Udp.beginPacket(sendTo, localUdpPort);
    Udp.write(messagePacket);
    Udp.endPacket();
  }
  else if (!ipKnown && packetSize){
    ipKnown = true;
    sendTo = Udp.remoteIP();
  }

  message = "L";
}

Thank you guys so much! Help is always appreciated.

c#
c++
unity3d
networking
udp
asked on Stack Overflow May 20, 2020 by TryingMyBest

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0