Unity Arduino发送接收Json数据

#include 
#include 
#include 
#include 

// 舵机驱动板
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

//WIFI连接
const char* ssid = "601";        // Wi-Fi网络名称
const char* password = "950819961018";    // Wi-Fi网络密码
WiFiServer server(80);    // 创建一个Wi-Fi服务器对象,监听端口80


///Json数据
DynamicJsonDocument jsonDoc(1024);
int id;
double value;
 
void setup() {
  pwm.begin();
  pwm.setPWMFreq(50);

  Serial.begin(115200);
  while (!Serial) {}  // 等待串口连接
 
  // 连接到Wi-Fi网络
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  // 打印IP地址
  Serial.println(WiFi.localIP());
  // 开始监听客户端连接
  server.begin();

  //初始化舵机角度
  Seat();
}



void loop() {
  // 等待客户端连接
  WiFiClient client = server.available();
  if (client) {
    Serial.println("客户端连入");
    
    // 等待客户端发送数据
    while (client.connected()) {
      if (client.available()) {
        // 读取客户端发送的数据
        String request = client.readStringUntil('\r');
        Serial.println(request);
        
        // 解析JSON数据
        DeserializationError error = deserializeJson(jsonDoc, request);
        
        // 检查JSON解析错误
        if (error) {
          Serial.print(F("JSON parsing failed: "));
          Serial.println(error.c_str());
          break; // 终止循环
        }
        
        // 提取整数和浮点数字段
        id = jsonDoc["id"].as();
        value = jsonDoc["angle"].as();

      // 在定时器回调函数中执行pwm.setPWM()函数
      if(id>1000)
      {
        if (id == 1001)
        {
          Seat();
        } else if (id == 1002) 
        {
          Stand();
        } else if (id == 1003) 
        {
          Sway();
        }
      }
      else
      {
        pwm.setPWM(id, 0, value);
      }
        // 清空JSON文档,以便接收下一条消息
        jsonDoc.clear();
      }
    }
    
    // 断开客户端连接
    client.stop();
    Serial.println("Client disconnected");
  }
}

//坐下
void Seat()
{
  pwm.setPWM(0, 0, 301);
  delay(10);
  pwm.setPWM(4, 0, 301);
  delay(10);
  pwm.setPWM(2, 0, 301);
  delay(10);
  pwm.setPWM(6, 0, 301);
  delay(10);
  pwm.setPWM(7, 0, 406);
  delay(10);
  pwm.setPWM(5, 0, 209);
  delay(10);
  pwm.setPWM(1, 0, 209);
  delay(10);
  pwm.setPWM(3, 0, 373);
}

//站起来
void Stand()
{
  pwm.setPWM(0, 0, 510);
  delay(10);
  pwm.setPWM(4, 0, 102);
  delay(10);
  pwm.setPWM(2, 0, 102);
  delay(10);
  pwm.setPWM(6, 0, 510);
  delay(10);
  pwm.setPWM(7, 0, 406);
  delay(10);
  pwm.setPWM(5, 0, 209);
  delay(10);
  pwm.setPWM(1, 0, 209);
  delay(10);
  pwm.setPWM(3, 0, 373);
}

//左右摇摆
void Sway()
{

  pwm.setPWM(7, 0, 510);
  delay(10);
  pwm.setPWM(5, 0, 102);
  delay(10);
  pwm.setPWM(1, 0, 102);
  delay(10);
  pwm.setPWM(3, 0, 490);

  delay(500);
  delay(10);
  pwm.setPWM(0, 0, 510);
  delay(10);
  pwm.setPWM(4, 0, 300);
  delay(10);
  pwm.setPWM(2, 0, 300);
  delay(10);
  pwm.setPWM(6, 0, 510);

  delay(500);
  pwm.setPWM(0, 0, 300);
  delay(10);
  pwm.setPWM(4, 0, 102);
  delay(10);
  pwm.setPWM(2, 0, 102);
  delay(10);
  pwm.setPWM(6, 0, 300);

}
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;
using XFrameWork;

public class Machine : BasePanel
{
    [Header("Slider的回调触发时间,让它不要发送太频繁")]
    public float callbackDelay = 0.5f;

    public CustomSlider[] sliderArray;
    public Slider[] sliders;

    private float lastCallbackTime;
    Root root;
    void Start()
    {
        if (NetMgr.Instance == null)
        {
            GameObject obj = new GameObject("Net");
            obj.AddComponent();
        }
        NetMgr.Instance.Connect("192.168.1.7", 80);


        StartCoroutine(TextReader("Data.json", (str) =>
        {
            root = JsonUtility.FromJson(str);
        }));

        for (int i = 0; i < sliderArray.Length; i++) 
        {
            int index = i;
            sliderArray[index].OnValueChangedEnd.AddListener(() => {
                Debug.Log(sliderArray[index].name);
                switch (sliderArray[index].name)
                {
                    case "Slider_0":
                        root.id = 0;
                        root.angle = sliders[index].value;
                        break;
                    case "Slider_1":
                        root.id = 1;
                        root.angle = sliders[index].value;
                        break;
                    case "Slider_2":
                        root.id = 2;
                        root.angle = sliders[index].value;
                        break;
                    case "Slider_3":
                        root.id = 3;
                        root.angle = sliders[index].value;
                        break;
                    case "Slider_4":
                        root.id = 4;
                        root.angle = sliders[index].value;
                        break;
                    case "Slider_5":
                        root.id = 5;
                        root.angle = sliders[index].value;
                        break;
                    case "Slider_6":
                        root.id = 6;
                        root.angle = sliders[index].value;
                        break;
                    case "Slider_7":
                        root.id = 7;
                        root.angle = sliders[index].value;
                        break;
                }
                NetMgr.Instance.Send(root);
            });
        }
    }

    /*----------动作函数----------*/

    // |   0  |             |   4  |
    //  ----- -----   ----- -----
    //       |   7  | |  5   |
    //        -----   -----
    //       |   1  | |  3   |
    //  ----- -----   ----- -----
    // |  6   |             |  2   |
    private bool isSliderCallbackAllowed = true;
    //protected override void OnValueChanged(string sliderName, float sliderValue)
    //{
    //    base.OnValueChanged(sliderName, sliderValue);

    //    if (Time.time - lastCallbackTime >= callbackDelay)
    //    {
    //        lastCallbackTime = Time.time;

    //        switch (sliderName)
    //        {
    //            case "Slider_0":
    //                root.id = 0;
    //                root.angle = sliderValue;
    //                break;
    //            case "Slider_1":
    //                root.id = 1;
    //                root.angle = sliderValue;
    //                break;
    //            case "Slider_2":
    //                root.id = 2;
    //                root.angle = sliderValue;
    //                break;
    //            case "Slider_3":
    //                root.id = 3;
    //                root.angle = sliderValue;
    //                break;
    //            case "Slider_4":
    //                root.id = 4;
    //                root.angle = sliderValue;
    //                break;
    //            case "Slider_5":
    //                root.id = 5;
    //                root.angle = sliderValue;
    //                break;
    //            case "Slider_6":
    //                root.id = 6;
    //                root.angle = sliderValue;
    //                break;
    //            case "Slider_7":
    //                root.id = 7;
    //                root.angle = sliderValue;
    //                break;
    //        }
    //        NetMgr.Instance.Send(root);
    //    }
    //}


    protected override void OnClick(string btnName)
    {
        base.OnClick(btnName);
        switch (btnName)
        {
            case "Btn_坐下":
                root.id = 1001;
                root.angle = 0;
                NetMgr.Instance.Send(root);
                break;
            case "Btn_站立":
                root.id = 1002;
                root.angle = 0;
                NetMgr.Instance.Send(root);
                break;
            case "Btn_左右摇摆":
                root.id = 1003;
                root.angle = 0;
                NetMgr.Instance.Send(root);
                break;
        }
    }

    /// 
    /// 读取StreamingAsset中的配置文件
    /// 
    /// 
    /// 
    /// 
    public static IEnumerator TextReader(string configName, UnityAction action = null)
    {
        string path = Application.streamingAssetsPath + "/" + configName;
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(path);
        yield return unityWebRequest.SendWebRequest();

        if (unityWebRequest.error != null)
            Debug.Log(unityWebRequest.error);
        else
        {
            string content = unityWebRequest.downloadHandler.text;
            if (action != null)
                action(content);
        }
    }
}

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class CustomSlider : MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
    public UnityEvent OnValueChangedEnd;
    Slider slider;

    public float totalTime = 1;
    private float currentTime = 0;

    private bool isStart = false;

    private void Awake()
    {
        slider = GetComponent();
    }

    private void Start()
    {
        isStart = false;
    }

    private void Update()
    {
        if (isStart) 
        {
            currentTime += Time.deltaTime;
            if (currentTime >= totalTime)
            {
                currentTime = 0;
                OnValueChangedEnd?.Invoke();
            }
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        isStart = true;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        isStart = false;
        currentTime = 0;
        OnValueChangedEnd?.Invoke();
    }
}

你可能感兴趣的:(unity,json,apache)