# TCP\&UDP协议

## 简介

通过TCP\&UDP自定义协议，与网关设备交互获取设备信息及控制智能家居设备

## 接入说明

使用TCP\&UDP协议接入需要网关作为服务端，使用UDP监听背景音乐主机发送过来的连接广播数据，TCP服务端用来接收协议数据

监听UDP端口：5555&#x20;

回复UDP端口：5554

## 协议格式

|  **包头**  |      **数据长度**      |   JSON数据   |                 **校验和**                 |
| :------: | :----------------: | :--------: | :-------------------------------------: |
| FF494F54 | 为JSON数据所占字节数（16进制） | DATA，字符串数据 | <p>异或校验，数据长度+数据</p><p>的字节进行异或（16进制）</p> |

### 异或算法代码

```java
public static int xorSum(byte[] datas) {
    int temp = datas[1];              // 此处首位取1是因为本协议中第一个数据不参数异或校验，转为int防止结果出现溢出变成负数
    for (int i = 2; i < datas.length; i++) {
        int preTemp = temp;
        int iData;
        if (datas[i] < 0) {
            iData = datas[i] & 0xff;      // 变为正数计算
        } else {
            iData = datas[i];
        }
        if (temp < 0) {
            temp = temp & 0xff;          // 变为正数
        }
        temp ^= iData;
    }
    return temp;
}
```

## 建立TCP连接

背景音乐主机发送隔5秒发送一次UDP广播包，网关设备收到后，回复自身TCP服务的IP地址和端口号

当背景音乐主机收到UDP广播回复后会连接网关的TCP服务

### 交互图

![](/files/-MEkdiwDZZX_IpwmbzrP)

### 请求JSON格式

```java
{
    "type":"REQUEST_LINK_HOST"
}
```

### 响应JSON格式

```java
{
    "type":"RESPONSE_LINK_HOST",
    "data":{
        "ip":"",
        "port":
    }
}
```

## 获取设备

获取智能家居设备信息

### 请求JSON格式

```java
{
    "type":"REQUEST_FIND_DEVICES"
}
```

### 响应JSON格式

```java
{
    "type":"RESPONSE_FIND_DEVICES",
    "data":{
        "appliances":[
        {
            //设备支持的操作,可不填写
            "actions": [
                "turnOn",
                "turnOff",
                "incrementBrightnessPercentage",
                "decrementBrightnessPercentage"
            ],
            //补充字段
            "additionalApplianceDetails": {},
            //设备唯一ID
            "applianceId": "设备唯一ID",
            //设备类型
            "applianceTypes": [
                "LIGHT"
            ],
            //设备属性
            "attributes": [
                {
                    "name": "name",
                    "scale": "",
                    "timestampOfSample": 1496741861,
                    "uncertaintyInMilliseconds": 10,
                    "value": "卧室的灯"
                }
            ],
            //设备友好描述
            "friendlyDescription": "展现给用户的详细介绍",
            //设备名
            "friendlyName": "卧室的灯",
            //厂商名称
            "manufacturerName": "设备制造商的名称",
            //型号名
            "modelName": "fancyLight",
            //软件版本
            "version": "your software version number here."
        }
    ]
    }
}
```

## 控制设备

设备控制时发送的数据

data的携带参数会因为aciton的不同而改变，可参考[请求类型与数据](/dev-link-host/android-link-sdk/controlrequest-dui-zhao.md)

### 请求JSON格式

```java
{
    //代表协议指令类型
    "type":"REQUEST_DEVICE_CONTROLLER",
    //控制请求的类型
    "action":"TurnOnRequest",
    "voiceStr":"语音原句",
    //控制可能携带的数据
    "data":{
        "applianceId":"设备ID",
        "values":{
            "temperature":2,
            "fanSpeedValue":2,
            "fanSpeedLevel":2,
            "mode":"",
            "fanDirection":"fanDirection",
            "color":{
                "hue":double
                "saturation":double
                "brightness":double
            },
            "isMute":2,
            "volume":2,
            "channel":2,
        }
    }
}
```

### 响应JSON格式

```java
{
    "type":"RESPONSE_DEVICE_CONTROLLER",
    "success":true/false,
    "msg":"返回的信息",
    "voiceStr":"控制完成后需要播报的语句",
    "data":{
        "applianceId":"设备ID",
        "values":{
            //控制后的数据状态上报
            "turnOnState":"ON/OFF"
            "temperature":2,
            "fanSpeedValue":2,
            "fanSpeedLevel":"",
            "mode":"",
            "fanDirection":"fanDirection",
            "color":{
                "hue":double
                "saturation":double
                "brightness":double
            },
            "isMute":2,
            "volume":2,
            "channel":2, 
        }
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.youzhuan.net/dev-link-host/tcpudp-xie-yi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
