esp8266与Unity之间的udp连接问题
Udp connection problem between esp8266 and Unity
我正在尝试将 Wemos D1 mini ESP8266 板连接到 unity,以便将按钮状态发送到 unity。
首先,我为 Wemos D1 mini 开发了代码,并使用 UDP 终端进行了检查,它工作正常,我从终端向 Wemos 板发送一条消息,并在串行监视器上显示该消息。
我正在发回一条带有按钮状态的消息,它显示在 UDP 终端上。
然后我在 Unity 上编写了这段代码并将其附加到主摄像头,我在 Wemos D1 mini 上收到了 unity 发送的消息,但我无法读取 Wemos 发送的消息。我注意到 Socket.Available
总是 0.
除了我没有阅读 return 消息这一事实之外,有时 Unity 也会崩溃(当我 运行 时,有时实际上并不经常崩溃)。这是来自 Arduino IDE 的代码:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
//SSID of your network
char ssid[] = "TUI"; //SSID of your Wi-Fi router
char pass[] = "password"; //Password of your Wi-Fi router
int keyIndex = 0;
unsigned int localPort = 4000;
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = ""; // a string to send back
WiFiUDP Udp;
//input
const int buttonPin = 4;
const int ledpin = 5;
int buttonState = LOW;
void setup()
{
pinMode(buttonPin, INPUT);
pinMode(ledpin, OUTPUT);
IPAddress ip(192, 175, 0, 20);
IPAddress gateway(192, 175, 0, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress DNS(192, 175, 0, 1);
Serial.begin(115200);
WiFi.config(ip, gateway, subnet, DNS);
delay(100);
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200);
}
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println();
Serial.println("Fail connecting");
delay(5000);
ESP.restart();
}
Serial.print(" OK ");
Serial.print("Module IP: ");
Serial.println(WiFi.localIP());
printWifiStatus();
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop () {// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println("Contents:");
Serial.println(packetBuffer);
String str(packetBuffer);
if(str == "hello from unity"){
digitalWrite(ledpin, HIGH);
}
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH){
String str1 = "Button1 pressed";
str1.toCharArray(ReplyBuffer, 50);
}
else{
String str1 = "Button1 off";
str1.toCharArray(ReplyBuffer, 50);
}
Serial.println(ReplyBuffer);
Serial.println(Udp.remoteIP());
Serial.println(Udp.remotePort());
// send a reply, to the IP address and port that sent the packet
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
else{
digitalWrite(ledpin, LOW);
}
delay(10);
}
这是 Unity 上的脚本:
using UnityEngine;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System;
public class ArduinoConnectUDP : MonoBehaviour
{
private void Update()
{
udpSend();
}
//Port and IP Data for Socket Client
void udpSend()
{
var IP = IPAddress.Parse("192.175.0.20");
int port = 4000;
var udpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var sendEndPoint = new IPEndPoint(IP, port);
var receiveEndPoint = new IPEndPoint(IPAddress.Any, port);
var clientReturn = new UdpClient(4000);
try
{
//Sends a message to the host to which you have connected.
byte[] sendBytes = Encoding.ASCII.GetBytes("hello from unity");
udpClient1.SendTo(sendBytes, sendEndPoint);
Debug.Log(udpClient1.Available);
if (udpClient1.Available > 0)
{
// Blocks until a message returns on this socket from a remote host.
byte[] receiveBytes = clientReturn.Receive(ref receiveEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Debug.Log("Message Received: " +
returnData.ToString());
if (receiveBytes == null || receiveBytes.Length == 0)
{
Debug.Log("No Answer from Wemos");
}
}
udpClient1.Close();
clientReturn.Close();
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
}
已解决!必须更改 c# 中的接收代码并更新 arduino 代码才能发送到端口 4001(静态端口,因为我在接收随机端口上发送)。
Unity 代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class esp8266Connection : MonoBehaviour {
Thread m_Thread;
UdpClient m_Client;
void Start()
{
m_Thread = new Thread(new ThreadStart(ReceiveData));
m_Thread.IsBackground = true;
m_Thread.Start();
}
private void Update()
{
udpSend();
}
void ReceiveData()
{
try
{
m_Client = new UdpClient(4001);
m_Client.EnableBroadcast = true;
while (true)
{
IPEndPoint hostIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = m_Client.Receive(ref hostIP);
string returnData = Encoding.ASCII.GetString(data);
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()
{
var IP = IPAddress.Parse("192.175.0.20");
int port = 4000;
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());
}
}
}
arduino 代码:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
//SSID of your network
char ssid[] = "TUI"; //SSID of your Wi-Fi router
char pass[] = "password"; //Password of your Wi-Fi router
int keyIndex = 0;
unsigned int localPort = 4000;
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = ""; // a string to send back
WiFiUDP Udp;
//input
const int buttonPin = 4;
const int ledpin = D1;
int buttonState = LOW;
void setup()
{
pinMode(buttonPin, INPUT);
pinMode(ledpin, OUTPUT);
IPAddress ip(192, 175, 0, 20);
IPAddress gateway(192, 175, 0, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress DNS(192, 175, 0, 1);
Serial.begin(115200);
WiFi.config(ip, gateway, subnet, DNS);
delay(100);
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200);
}
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println();
Serial.println("Fail connecting");
delay(5000);
ESP.restart();
}
Serial.print(" OK ");
Serial.print("Module IP: ");
Serial.println(WiFi.localIP());
printWifiStatus();
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop () {// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println("Contents:");
Serial.println(packetBuffer);
String str(packetBuffer);
if(str == "hello from unity"){
digitalWrite(ledpin, HIGH);
}
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH){
String str1 = "Button1 pressed";
str1.toCharArray(ReplyBuffer, 50);
}
else{
String str1 = "Button1 off";
str1.toCharArray(ReplyBuffer, 50);
}
Serial.println(ReplyBuffer);
Serial.println(Udp.remoteIP());
Serial.println(Udp.remotePort());
// send a reply, to the IP address and port that sent the packet
Udp.beginPacket(Udp.remoteIP(), 4001);
Udp.write(ReplyBuffer);
Udp.endPacket();
}
else{
digitalWrite(ledpin, LOW);
}
delay(10);
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
我正在尝试将 Wemos D1 mini ESP8266 板连接到 unity,以便将按钮状态发送到 unity。
首先,我为 Wemos D1 mini 开发了代码,并使用 UDP 终端进行了检查,它工作正常,我从终端向 Wemos 板发送一条消息,并在串行监视器上显示该消息。
我正在发回一条带有按钮状态的消息,它显示在 UDP 终端上。
然后我在 Unity 上编写了这段代码并将其附加到主摄像头,我在 Wemos D1 mini 上收到了 unity 发送的消息,但我无法读取 Wemos 发送的消息。我注意到 Socket.Available
总是 0.
除了我没有阅读 return 消息这一事实之外,有时 Unity 也会崩溃(当我 运行 时,有时实际上并不经常崩溃)。这是来自 Arduino IDE 的代码:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
//SSID of your network
char ssid[] = "TUI"; //SSID of your Wi-Fi router
char pass[] = "password"; //Password of your Wi-Fi router
int keyIndex = 0;
unsigned int localPort = 4000;
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = ""; // a string to send back
WiFiUDP Udp;
//input
const int buttonPin = 4;
const int ledpin = 5;
int buttonState = LOW;
void setup()
{
pinMode(buttonPin, INPUT);
pinMode(ledpin, OUTPUT);
IPAddress ip(192, 175, 0, 20);
IPAddress gateway(192, 175, 0, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress DNS(192, 175, 0, 1);
Serial.begin(115200);
WiFi.config(ip, gateway, subnet, DNS);
delay(100);
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200);
}
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println();
Serial.println("Fail connecting");
delay(5000);
ESP.restart();
}
Serial.print(" OK ");
Serial.print("Module IP: ");
Serial.println(WiFi.localIP());
printWifiStatus();
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop () {// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println("Contents:");
Serial.println(packetBuffer);
String str(packetBuffer);
if(str == "hello from unity"){
digitalWrite(ledpin, HIGH);
}
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH){
String str1 = "Button1 pressed";
str1.toCharArray(ReplyBuffer, 50);
}
else{
String str1 = "Button1 off";
str1.toCharArray(ReplyBuffer, 50);
}
Serial.println(ReplyBuffer);
Serial.println(Udp.remoteIP());
Serial.println(Udp.remotePort());
// send a reply, to the IP address and port that sent the packet
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
else{
digitalWrite(ledpin, LOW);
}
delay(10);
}
这是 Unity 上的脚本:
using UnityEngine;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System;
public class ArduinoConnectUDP : MonoBehaviour
{
private void Update()
{
udpSend();
}
//Port and IP Data for Socket Client
void udpSend()
{
var IP = IPAddress.Parse("192.175.0.20");
int port = 4000;
var udpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var sendEndPoint = new IPEndPoint(IP, port);
var receiveEndPoint = new IPEndPoint(IPAddress.Any, port);
var clientReturn = new UdpClient(4000);
try
{
//Sends a message to the host to which you have connected.
byte[] sendBytes = Encoding.ASCII.GetBytes("hello from unity");
udpClient1.SendTo(sendBytes, sendEndPoint);
Debug.Log(udpClient1.Available);
if (udpClient1.Available > 0)
{
// Blocks until a message returns on this socket from a remote host.
byte[] receiveBytes = clientReturn.Receive(ref receiveEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Debug.Log("Message Received: " +
returnData.ToString());
if (receiveBytes == null || receiveBytes.Length == 0)
{
Debug.Log("No Answer from Wemos");
}
}
udpClient1.Close();
clientReturn.Close();
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
}
已解决!必须更改 c# 中的接收代码并更新 arduino 代码才能发送到端口 4001(静态端口,因为我在接收随机端口上发送)。
Unity 代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class esp8266Connection : MonoBehaviour {
Thread m_Thread;
UdpClient m_Client;
void Start()
{
m_Thread = new Thread(new ThreadStart(ReceiveData));
m_Thread.IsBackground = true;
m_Thread.Start();
}
private void Update()
{
udpSend();
}
void ReceiveData()
{
try
{
m_Client = new UdpClient(4001);
m_Client.EnableBroadcast = true;
while (true)
{
IPEndPoint hostIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = m_Client.Receive(ref hostIP);
string returnData = Encoding.ASCII.GetString(data);
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()
{
var IP = IPAddress.Parse("192.175.0.20");
int port = 4000;
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());
}
}
}
arduino 代码:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
//SSID of your network
char ssid[] = "TUI"; //SSID of your Wi-Fi router
char pass[] = "password"; //Password of your Wi-Fi router
int keyIndex = 0;
unsigned int localPort = 4000;
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = ""; // a string to send back
WiFiUDP Udp;
//input
const int buttonPin = 4;
const int ledpin = D1;
int buttonState = LOW;
void setup()
{
pinMode(buttonPin, INPUT);
pinMode(ledpin, OUTPUT);
IPAddress ip(192, 175, 0, 20);
IPAddress gateway(192, 175, 0, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress DNS(192, 175, 0, 1);
Serial.begin(115200);
WiFi.config(ip, gateway, subnet, DNS);
delay(100);
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200);
}
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println();
Serial.println("Fail connecting");
delay(5000);
ESP.restart();
}
Serial.print(" OK ");
Serial.print("Module IP: ");
Serial.println(WiFi.localIP());
printWifiStatus();
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop () {// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println("Contents:");
Serial.println(packetBuffer);
String str(packetBuffer);
if(str == "hello from unity"){
digitalWrite(ledpin, HIGH);
}
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH){
String str1 = "Button1 pressed";
str1.toCharArray(ReplyBuffer, 50);
}
else{
String str1 = "Button1 off";
str1.toCharArray(ReplyBuffer, 50);
}
Serial.println(ReplyBuffer);
Serial.println(Udp.remoteIP());
Serial.println(Udp.remotePort());
// send a reply, to the IP address and port that sent the packet
Udp.beginPacket(Udp.remoteIP(), 4001);
Udp.write(ReplyBuffer);
Udp.endPacket();
}
else{
digitalWrite(ledpin, LOW);
}
delay(10);
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}