fix
zhangqian
2023-11-01 6afbcd88bf9c2c14a16a7c01f6f2e269d4ea2883
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package service
 
import (
    "apsClient/conf"
    "apsClient/model"
    "apsClient/pkg/logx"
    "os"
)
 
func GetDeviceIDList() (deviceIds []string, err error) {
    devices, err := model.NewDeviceSearch().SetDeviceMac(conf.Conf.System.DeviceId).FindNotTotal()
    if err != nil {
        return nil, err
    }
    deviceIds = make([]string, 0, len(devices))
    for _, device := range devices {
        deviceIds = append(deviceIds, device.DeviceID)
    }
    return deviceIds, nil
}
 
func InitCurrentDeviceID() (err error) {
    currentDeviceID := ReadDeviceIDFromFile()
    if currentDeviceID != "" {
        conf.Conf.CurrentDeviceID = currentDeviceID
        return
    }
    deviceList, err := GetDeviceIDList()
    if err != nil {
        return err
    }
    if len(deviceList) == 0 {
        conf.Conf.CurrentDeviceID = conf.Conf.System.DeviceId
        return nil
    }
    conf.Conf.CurrentDeviceID = deviceList[0]
    SetDeviceIDToFile(conf.Conf.CurrentDeviceID)
    return nil
}
 
const deviceIDFile = "currentDeviceID.txt"
 
func SetDeviceIDToFile(deviceID string) {
    err := os.WriteFile(deviceIDFile, []byte(deviceID), 0644)
    if err != nil {
        logx.Errorf("无法写入设备ID到文件: %v\n", err)
    } else {
        logx.Infof("设备ID已写入文件")
    }
}
 
func ReadDeviceIDFromFile() string {
    data, err := os.ReadFile(deviceIDFile)
    if err != nil {
        logx.Errorf("无法读取设备ID文件: %v\n", err)
        return ""
    }
    return string(data)
}