zhangzengfei
2023-07-31 5db92d1b017db41c7f7165d085b6f9db0e962098
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
60
61
62
63
package collector
 
import (
    "context"
    "sync"
    "time"
 
    "plc-recorder/logger"
    "plc-recorder/msg"
)
 
var mapTask sync.Map
 
type collectorProc struct {
    device *msg.PLCDevice
    cancel context.CancelFunc
}
 
func InitTask() {
    device := msg.PLCDevice{
        Id:       "0",
        Ip:       "192.168.20.188",
        Address:  []int{17021},
        Interval: 1,
    }
 
    ctx, cancel := context.WithCancel(context.Background())
    proc := collectorProc{
        device: &device,
        cancel: cancel,
    }
 
    mapTask.Store(device.Id, &proc)
 
    go runCollectionTask(ctx, &device)
}
 
func runCollectionTask(ctx context.Context, device *msg.PLCDevice) {
    // 创建modbusTCP连接, 循环查询数据并上报
    for {
        err, plcConnection := NewModbusConnection(device.Ip)
        if err != nil {
            logger.Warn("Error connecting to PLC: %s, ip:", device.Name, device.Ip)
 
            time.Sleep(30 * time.Second)
            continue
        }
 
        for {
            select {
            case <-ctx.Done():
                logger.Warn("Plc device %s, ip: %s, end of collection.", device.Name, device.Ip)
                plcConnection.Close()
                return
            default:
 
                // 根据设置的地址查询数据,上报
                // 暂停
                time.Sleep(time.Duration(device.Interval) * time.Second)
            }
        }
    }
}