LAPTOP-T815PCOQ\25526
2024-12-23 89bcc7791c48d8bcf8e124e56849e44563f8097c
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#include "stdafx.h"
#include "CPLC.h"
#include "Log.h"
 
void CALLBACK TimerFileProc(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
    CPLC* pPlc = (CPLC*)dwUser;
    SetEvent(pPlc->m_hTimeEvent);
}
 
unsigned __stdcall McMonitorThreadFunction(LPVOID lpParam)
{
    CPLC* pPlc = (CPLC*)lpParam;
    return pPlc->onMonitor();
}
 
CPLC::CPLC()
{
    m_nPort = 0;
    m_state = PLCSTATE::READY;
    m_listener.onStateChanged = nullptr;
    m_listener.onMonitorData = nullptr;
    m_nUnHeartBeat = 0;
    m_hMcMonitorStop = NULL;
    m_hMcMonitorThreadHandle = NULL;
    m_mcMonitorThrdaddr = 0;
    m_nTimerId = 0;
    m_hTimeEvent = nullptr;
}
 
CPLC::CPLC(const char* pszName, const char* pszIP, unsigned int nPort)
{
    m_strName = pszName;
    m_strIP = pszIP;
    m_nPort = nPort;
    m_state = PLCSTATE::READY;
    m_listener.onStateChanged = nullptr;
    m_listener.onMonitorData = nullptr;
    m_nUnHeartBeat = 0;
    m_hMcMonitorStop = NULL;
    m_hMcMonitorThreadHandle = NULL;
    m_mcMonitorThrdaddr = 0;
    m_nTimerId = 0;
    m_hTimeEvent = nullptr;
}
 
CPLC::~CPLC()
{
 
}
 
std::string& CPLC::getClassName()
{
    static std::string strClassName = "CPLC";
    return strClassName;
}
 
void CPLC::setListener(PLCListener& listener)
{
    m_listener.onStateChanged = listener.onStateChanged;
    m_listener.onMonitorData = listener.onMonitorData;
}
 
std::string& CPLC::getIP()
{
    return m_strIP;
}
 
unsigned int CPLC::getPort()
{
    return m_nPort;
}
 
int CPLC::addMonitor(int id, int beginAddr, int endAddr, MC::SOFT_COMPONENT softComponent, char* pszRecvBuffer)
{
    // ¼ì²éÊÇ·ñÓÐÖØ¸´µÄ
    Lock();
    for (auto& m : m_monitors) {
        if (m.id == id) {
            Unlock();
            return -1;
        }
    }
 
    MONITOR m;
    memset(&m, 0, sizeof(MONITOR));
    m.id = id;
    m.beginAddr = beginAddr;
    m.readLen = (endAddr - beginAddr + 1) * 2;
    m.softComponent = softComponent;
    m.szRecvBuffer = pszRecvBuffer;
    m.hEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
    m_monitors.push_back(m);
 
    Unlock();
    return 0;
}
 
void CPLC::init()
{
    // mc channel
    McChannelListener m_mcChannellistener;
    m_mcChannellistener.funOnConnected = [&](IMcChannel* pChannel, int nErrorCode) -> void {
        LOGI("<PLC-%s>Á¬½Ó½á¹û<code= %d>", m_strName.c_str(), nErrorCode);
        if (nErrorCode == 0) {
            setState(PLCSTATE::CONNECTED);
        }
        else {
            setState(PLCSTATE::DISCONNECTED);
        }
    };
    m_mcChannellistener.funOnClose = [&](IMcChannel* pChannel) -> void {
        setState(PLCSTATE::DISCONNECTED);
    };
    m_mcChannellistener.funOnClosing = [&](IMcChannel* pChannel) -> void {
    };
    m_mcChannellistener.funOnRead = [&](IMcChannel* pChannel, char* pData, unsigned int nDataSize, int nDecodeRet) -> void {
        CString strText;
        dataToHexString(pData, nDataSize, strText);
        if (nDecodeRet != 0) {
            LOGE("<PLC-%s>funOnRead[%s], nDecodeRet=%d", m_strName.c_str(), (LPTSTR)(LPCTSTR)strText, nDecodeRet);
        }
        m_nUnHeartBeat = 0;
    };
    m_mcChannellistener.funOnWrite = [&](IMcChannel* pChannel) -> void {
 
    };
 
    if (0 == MCL_CreateChannel(m_pChannel, m_strName.c_str(), m_strIP.c_str(), m_nPort, 0)
        && m_pChannel != NULL) {
        m_pChannel->setChannelListener(&m_mcChannellistener);
        m_pChannel->setActionInterval(m_nActionInterval);
        LOGI("<PLC-%s>ÕýÔÚÁ¬½ÓPLC.", m_strName.c_str());
        setState(PLCSTATE::CONNECTING);
        m_pChannel->connect();
    }
    else if (m_pChannel != NULL) {
        m_pChannel->setChannelListener(&m_mcChannellistener);
        m_pChannel->setActionInterval(m_nActionInterval);
    }
 
    m_hTimeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
    timeBeginPeriod(1);
    m_nTimerId = timeSetEvent(200, 1, TimerFileProc, (DWORD_PTR)this, TIME_PERIODIC);
 
 
    if (m_hMcMonitorStop != NULL) return;
    m_hMcMonitorStop = ::CreateEvent(NULL, TRUE, FALSE, NULL);
    m_hMcMonitorThreadHandle = (HANDLE)_beginthreadex(NULL, 0, ::McMonitorThreadFunction, this,
        0, &m_mcMonitorThrdaddr);
 
}
 
void CPLC::term()
{
    timeKillEvent(m_nTimerId);
    timeEndPeriod(1);        // Çå³ýÇ°Ãæ¶Ô¶¨Ê±Æ÷µÄÉèÖÃ
 
    ASSERT(m_hMcMonitorStop);
    SetEvent(m_hMcMonitorStop);
    if (m_hMcMonitorThreadHandle != NULL) {
        WaitForSingleObject(m_hMcMonitorThreadHandle, INFINITE);
        CloseHandle(m_hMcMonitorThreadHandle);
        m_hMcMonitorThreadHandle = NULL;
    }
    CloseHandle(m_hMcMonitorStop);
    m_hMcMonitorStop = NULL;
 
    for (auto& m : m_monitors) {
        CloseHandle(m.hEvent);
    }
}
 
unsigned CPLC::onMonitor()
{
    HANDLE hEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
 
    int nReadLen = 60 * 2;
    HANDLE hEvents[2] = { m_hMcMonitorStop, m_hTimeEvent };
 
    while (1) {
        int nRet = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
        ResetEvent(m_hTimeEvent);
        if (nRet == WAIT_OBJECT_0) {
            break;
        }
 
        if (!m_bRunning || !isConnected()) {
            continue;
        }
 
        for (auto& m : m_monitors) {
            monitorReadData(m);
        }
    }
 
    TRACE("CPLC::onMonitor Ïß³ÌÍ˳ö\n");
    return 0;
}
 
void CPLC::monitorReadData(MONITOR& monitor)
{
    BOOL bOutputLog = FALSE;
    BOOL bReadOk;
 
 
    // ÅúÁ¿¶ÁÊý¾ÝÔÙ½âÊÍ
    auto funOnReadData = [&](IMcChannel* pChannel, int addr, char* pData, unsigned int nDataSize, int flag) -> void {
        if (flag == 0) {
            if (bOutputLog) {
                CString s;
                s.Format(_T("CPLC::monitorReadData::funOnReadData %d ["), nDataSize);
                for (unsigned int i = 0; i < nDataSize; i++) {
                    s.AppendFormat(" %x", (BYTE)pData[i]);
                }
                s.Append("]");
                LOGD("<CPLC-%d-%d>Received plc data.%s", m_nIndex, monitor.id, (LPTSTR)(LPCTSTR)s);
            }
        }
        else {
            LOGE("<CPLC-%d-%d>PLCÅú¶ÁÈ¡Êý¾Ýλ³¬Ê±.flag=%d", m_nIndex, monitor.id, flag);
        }
 
        if (nDataSize == monitor.readLen && flag == 0) {
            memcpy(monitor.szRecvBuffer, pData, nDataSize);
            monitor.readCount++;
            bReadOk = TRUE;
        }
        SetEvent(monitor.hEvent);
    };
 
 
    bReadOk = FALSE;
    m_pChannel->readData(monitor.softComponent, monitor.beginAddr, monitor.readLen, funOnReadData);
    WaitForSingleObject(monitor.hEvent, INFINITE);
    ResetEvent(monitor.hEvent);
    if (bReadOk) {
        ASSERT(m_listener.onMonitorData);
        m_listener.onMonitorData(this, monitor.id);
    }
}
 
bool CPLC::isConnected()
{
    return m_pChannel != nullptr && m_pChannel->isConnected();
}
 
int CPLC::readWord(MC::SOFT_COMPONENT softComponent, unsigned int addr,
    ONREAD funOnRead)
{
    return m_pChannel->readWord(softComponent, addr, funOnRead);
}
 
int CPLC::readData(MC::SOFT_COMPONENT softComponent, unsigned int addr,
    unsigned int nReadLen, ONREADDATA funOnReadData)
{
    return m_pChannel->readData(softComponent, addr, nReadLen, funOnReadData);
}
 
int CPLC::writeBit(MC::SOFT_COMPONENT softComponent, unsigned int addr,
    BOOL bValue, ONWRITE funOnWrite)
{
    return m_pChannel->writeBit(softComponent, addr, bValue, funOnWrite);
}
 
int CPLC::writeWord(MC::SOFT_COMPONENT softComponent, unsigned int addr,
    int value, ONWRITE funOnWrite)
{
    return m_pChannel->writeWord(softComponent, addr, value, funOnWrite);
}
 
int CPLC::writeDWord(MC::SOFT_COMPONENT softComponent, unsigned int addr,
    int value, ONWRITE funOnWrite)
{
    return m_pChannel->writeDWord(softComponent, addr, value, funOnWrite);
}
 
int CPLC::writeData(MC::SOFT_COMPONENT softComponent, unsigned int addr,
    const char* pszData, unsigned int length, ONWRITE funOnWrite)
{
    return m_pChannel->writeData(softComponent, addr, pszData, length, funOnWrite);
}
 
CString& CPLC::dataToHexString(const char* pData, const int size, CString& strOut)
{
    strOut.Empty();
    for (int i = 0; i < size; i++) {
        if (i < size - 1) {
            strOut.AppendFormat(_T("%02X "), (BYTE)pData[i]);
        }
        else {
            strOut.AppendFormat(_T("%02X"), (BYTE)pData[i]);
        }
    }
 
    return strOut;
}
 
void CPLC::setActionInterval(unsigned int nInterval)
{
    m_nActionInterval = nInterval;
}
 
void CPLC::setState(PLCSTATE state)
{
    m_state = state;
    if (m_listener.onStateChanged != nullptr) {
        m_listener.onStateChanged(this, (int)m_state);
    }
}
 
void CPLC::OnTimer(UINT nTimerid)
{
    static int iii = 0;
    iii++;
    if (iii % 5 == 3) {
        if (m_pChannel != nullptr && !m_pChannel->isConnected())
            m_pChannel->connect();
    }
}