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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace LB_VisionProcesses.Communicators.TCom
{
    [JsonObject(MemberSerialization.OptOut)]
    public class LocalMonitor : BaseCommunicator
    {
        // 使用 FileSystemWatcher 来实时监听文件夹变化
        FileSystemWatcher watcher = null;
 
        string DirectoryPath = string.Empty;
        string TriggerFileName = string.Empty;
        string ReturnFileName = string.Empty;
 
        public LocalMonitor(string name = "本地监控")
        {
            CommunicatorConnections.Add("地址", @"\LocalMonitor\Start.txt");
            CommunicatorConnections.Add("端口", "result.txt");
            CommunicatorBrand = CommunicatorBrand.LocalMonitor;
            CommunicatorName = name;
        }
 
        public override bool Connect()
        {
            try
            {
                Disconnect();
 
                if (string.IsNullOrEmpty(CommunicatorConnections["地址"].ToString())
                    || string.IsNullOrEmpty(CommunicatorConnections["端口"].ToString()))
                    return false;
 
                DirectoryPath = Path.GetDirectoryName(CommunicatorConnections["地址"].ToString());
                TriggerFileName = Path.GetFileName(CommunicatorConnections["地址"].ToString());
                ReturnFileName = CommunicatorConnections["端口"].ToString();
 
                if (string.IsNullOrEmpty(DirectoryPath) || string.IsNullOrEmpty(TriggerFileName) || string.IsNullOrEmpty(ReturnFileName))
                    return false;
 
                if (!Directory.Exists(DirectoryPath))
                    Directory.CreateDirectory(DirectoryPath);
 
                if (File.Exists(CommunicatorConnections["地址"].ToString()))
                    File.Delete(CommunicatorConnections["地址"].ToString());
 
                watcher = new FileSystemWatcher(DirectoryPath)
                {
                    Filter = TriggerFileName,
                    NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite
                };
 
                watcher.Created += MonitorTrigger;
                watcher.EnableRaisingEvents = true;
                bConnected = true;
 
                this.CommunicatorBrand = CommunicatorBrand.LocalMonitor;
                this.CommunicatorName = CommunicatorName;
                return true;
            }
            catch (Exception ex)
            {
                Msg = $"失败,本地监控未启动: {ex.Message}";
                return false;
            }
        }
 
        public override bool Disconnect()
        {
            try
            {
                bConnected = false;
                if (watcher == null)
                    return true;
 
                // 移除所有事件处理程序
                watcher.Created -= MonitorTrigger;
                // 停止并释放
                watcher.EnableRaisingEvents = false;
                watcher.Dispose();
                watcher = null;
                return true;
            }
            catch
            {
                bConnected = false;
                return true;
            }
        }
 
        void MonitorTrigger(object sender, FileSystemEventArgs e)
        {
            string path = e.FullPath; // 获取创建的文件路径
            try
            {
                Thread.Sleep(50);
                string[] lines = File.ReadAllLines(path);
                string message = string.Empty;
                if (lines.Length >= 1)
                    message = lines[0];
 
                strReceiveMsg = message;
                try
                {
                    MessageReceived?.Invoke(strReceiveMsg); // 触发回调
                }
                catch { }
                try
                {
                    TriggerRunMessageReceived?.Invoke(CommunicatorName, strReceiveMsg);  // 触发运行事件
                }
                catch { }
            }
            catch (Exception ex)
            {
                Msg = $"本地监控处理文件时发生异常: {ex.Message}";
            }
            finally
            {
                File.Delete(path);
            }
        }
 
        // 发送消息到服务器
        public override bool SendMessage(string message)
        {
            if (!bConnected || watcher == null)
            {
                Msg = "尚未创建本地监控";
                return false;
            }
 
            try
            {
                if (!Directory.Exists(DirectoryPath))
                    Directory.CreateDirectory(DirectoryPath);
 
                if (File.Exists(CommunicatorConnections["地址"].ToString()))
                    File.Delete(CommunicatorConnections["地址"].ToString());
 
                string FileFullPath = Path.Combine(DirectoryPath, ReturnFileName);
 
                if (File.Exists(FileFullPath))
                    File.Delete(FileFullPath);
 
                FileStream fs = new FileStream(FileFullPath, FileMode.Create);
                byte[] data = System.Text.Encoding.Default.GetBytes(message);
                fs.Write(data, 0, data.Length);
                fs.Flush();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                Msg = $"发送消息时发生错误: {ex.Message}";
                return false;
            }
        }
    }
}