Search code examples
c#unity-game-enginesocket.ionode-red

How to emit events from Node-Red to a Unity client with node-red-contrib-socketio


I'm trying to use node-red-contrib-socketio package to emit a 'weather' event from Node-Red to a client based on input from Weather Underground.

Emit Weather Event from Node-Red

I'm using the following code in a node-red function to process the input from WeatherUnderground and set the event:

Setting 'weather' event

weather = msg.payload.weather;
msg.payload = {weather: weather};
msg.socketIOEvent = 'weather';
RED.util.setMessageProperty(msg, "socketIOEmit", "emit", true);
return msg;

Is this the correct way to set and emit the weather event?

For reference:

I've bound the SocketIO Out node to Node_Red (so presumably port 1880 on local host). I'm using the Unity game engine as the client to receive the event with the Socket.IO library from the asset store: https://assetstore.unity.com/packages/tools/network/socket-io-for-unity-21721

Unity is listening for the weather event on the following URL:

ws://127.0.0.1:1880/socket.io/?EIO=4&transport=websocket

Currently Unity seems to be registering the connection but not the emitted weather event.

My test C# script for handling the events in Unity is as follows:

using UnityEngine;
using SocketIO;

public class NodeNetwork : MonoBehaviour
{

    //Reference socket component
    static SocketIOComponent socket;

    void Start()
    {
        //Initialise reference to socket component
        socket = GetComponent<SocketIOComponent>();
        //Register callbacks for network events
        socket.On("open", OnConnected);
        socket.On("weather", OnWeather);
    }

    //Create a callback for the connection
    void OnConnected(SocketIOEvent e)
    {
        Debug.Log("Connected");
        //Emit a move call back to the server 
        socket.Emit("client connected");
    }

    //Create a callback for receipt of weather events
    void OnWeather(SocketIOEvent e)
    {
        Debug.Log("New weather event received" + e.data);
        socket.Emit("weather received");
    }

}

Any advice would be appreciated.


Solution

  • After further research and testing I got this working. The Node-Red flow was fine but some sort of configuration issue prevented it working. Reinstalling Node.js and Node-Red resolved the issue.

    Using msg.socketIOEmit = "emit" as advised by @hardillb works.

    I tested several SocketIO solutions for Unity and ended using SocketIO for Native and WebGL builds by DASPETE which is a $10 paid asset.

    In order to deserialise the JSON I used SaladLab's JSONNetLite Unity package which is a fork of NewtonSoft.JSon.NET.

    To successfully use the package in a Unity WebGL build you need to add a link.xml file to your assets folder. This adds exceptions to the default Unity bytecode stripping which removes unused code from DLL's like the Newtonsoft.Json package.

    I hope that helps if you have the same issues.