Unity interactive device management (1)--device property configuration

foreword

Recently, I have been working on some interactive projects involving communication with hardware. The ports used include SerialPort, TCP and UDP. I hope that there is a framework that can facilitate port configuration and device management.

I will record my whole process for future optimization.

Configuration file format

When the project is deployed, due to the different host configurations, such as the serial port number, baud rate, TCP and UDP IP addresses and port numbers may change, so we need to write all relevant parameters into the configuration table. Common configuration file formats include .txt, .ini, .xml, and .json. The file format I choose here is JSON.

Regarding the use of JSON files, I choose to deserialize them into instance objects. So the main work of this article is in the deserialization of JSON.

The file format I designed is as follows (take the serial port as an example):

{
    "Devices": [{
            "Name": "Device1",
            "PortType": "SerialPort",
            "PortSettings": {
                "PortName": "COM1",
                "BaudRate": "9600",
                "Parity": "0",
                "DataBits": "8",
                "StopBits": "1"
            },
            "Signal": []
        }

    ]
}

 Different types of port port settings will be different, so either list all four types of settings, or deserialize them in the form of interfaces, so that only one common name is used to write JSON files, but Interfaces cannot be deserialized, so a custom deserialization operation is required.

 Brute force solution

Except for the public attributes, write all the port setting data into the JSON file, the example is as follows

{
    "Devices": [{
            "Name": "Device1",
            "PortType": "SerialPort",
            "SerialPortSettings": {
                "PortName": "COM1",
                "BaudRate": "9600",
                "Parity": "0",
                "DataBits": "8",
                "StopBits": "1"
            },

            "UDPSettings": {

                "Client":{

                    "IP":"127.0.0.1",

                    "Port":1234

                }

            },

            "TCPClientSettings": null,

            "TCPServerSettings": null,
            "Signal": []
        }

    ]
}

 Note

For the network communication interface involving two parameters IP and Port, the default IPAddress class cannot be deserialized, so a custom deserialization operation is required.

Do a custom deserialization of a NetPort node:

using System;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

[Serializable, JsonConverter(typeof(NetPortConvert))]
public class NetPort
{
    /// <summary>
    /// IP地址
    /// </summary>
    public IPAddress IP { get; set; }

    /// <summary>
    /// 端口号
    /// </summary>
    public int Port { get; set; }
}

public class NetPortConvert : JsonConverter
{
    //是否开启自定义反序列化
    public override bool CanRead => true;
    public override bool CanWrite => true;

    public override bool CanConvert(Type objectType)
    {
        return typeof(NetPort) == objectType;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var netPort = new NetPort();
        var jobj1 = serializer.Deserialize<JObject>(reader);
        string ip = jobj1.Value<string>("IP");
        int port = jobj1.Value<int>("Port");
        netPort.IP = IPAddress.Parse(ip);
        netPort.Port = port;
        return netPort;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var jobj = new JObject();
        var netPort = value as NetPort;
        jobj.Add("IP", netPort.IP.ToString());
        jobj.Add("Port", netPort.Port);
        var jsonstr = jobj.ToString().Replace("\r\n", "");
        
        writer.WriteValue(jsonstr);
    }
}

Deserialized instance class DeviceConfig:

using System.Collections;
using System.Collections.Generic;
using System;

[Serializable]
public class SerialPortSettings
{
    /// <summary>
    /// 接口名
    /// </summary>
    public string PortName { get; set; }
    /// <summary>
    /// 波特率
    /// </summary>
    public string BaudRate { get; set; }
    /// <summary>
    /// 校验位
    /// </summary>
    public string Parity { get; set; }
    /// <summary>
    /// 数据位
    /// </summary>
    public string DataBits { get; set; }
    /// <summary>
    /// 停止位
    /// </summary>
    public string StopBits { get; set; }
}

[Serializable]
public class UDPSettings
{
    public NetPort Local { get; set; }

    public NetPort Remote { get; set; }
}

[Serializable]
public class TCPClientSettings 
{
    public NetPort Remote { get; set; }
}

[Serializable]
public class TCPServerSettings
{
    public NetPort Local { get; set; }
}

[Serializable]
public class DeviceItem
{
    /// <summary>
    /// 连接硬件名
    /// </summary>
    public string Name { get; set; }
    /// <summary>
    /// 接口类型
    /// </summary>
    public string PortType { get; set; }
    /// <summary>
    /// 接口设置
    /// </summary>
    public SerialPortSettings SerialPortSettings { get; set; }
    public TCPClientSettings TCPClientSettings { get; set; }
    public TCPServerSettings TCPServerSettings { get; set; }
    public UDPSettings UDPSettings { get; set; }

    /// <summary>
    /// 约定信号值
    /// </summary>
    public List<string> Signal { get; set; }
}

[Serializable]
public class DeviceConfig
{
    /// <summary>
    /// 硬件集合
    /// </summary>
    public List<DeviceItem> Devices { get; set; }
}

Note

The attribute type of the serial port class refers to System.IO.Ports, and it is set to the corresponding type for convenient operation. Here only the demonstration record is made, so it will not be expanded.

actual use:

using UnityEngine;
using Newtonsoft.Json;

public class Test : MonoBehaviour
{
    DeviceConfig hardwareConfig = new DeviceConfig();

    void Start()
    {
        string str = "……JSON数据";
        
        hardwareConfig = JsonConvert.DeserializeObject<DeviceConfig>(str);

    }
}

 The time relationship is written here first, and the next chapter will use the interface to improve the port settings.

 

Guess you like

Origin blog.csdn.net/qq_40443024/article/details/124936379