LAPTOP-SNT8I5JK\Boounion
2025-03-26 8942dacbc2bfaf8aec6a360671de20b0fbf32273
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
// IOMonitoringDlg.cpp: 实现文件
//
 
#include "stdafx.h"
#include "BoounionPLC.h"
#include "afxdialogex.h"
#include "IOMonitoringDlg.h"
#include "ToolUnits.h"
 
#define TIMER_INIT                1
#define TIMER_READ_PLC_DATA        2
#define TIMER_READ_UPDATE        3
 
#define LABEL_ID_BEGIN            2000
#define    ADDR_WND                _T("ADDR_WND")
 
#define ID_MSG_IO_CLICK            WM_USER + 101
 
// CIOMonitoringDlg 对话框
 
IMPLEMENT_DYNAMIC(CIOMonitoringDlg, CDialogEx)
 
CIOMonitoringDlg::CIOMonitoringDlg(CWnd* pParent /*=nullptr*/)
    : CDialogEx(IDD_DIALOG_IO_MONITORING, pParent)
{
    m_nCurrentPage = 1;
    m_nTotalPages = 1;
    m_nRowsPerPage = 16;
    m_nCols = 6;
 
    CPLC* pPLC = theApp.m_model.getCurrentPlc();
    if (pPLC != nullptr) {
        m_pPLC = pPLC;
 
        // 加载数据
        IOManager manager;
        manager.LoadFromFile(pPLC->getName());
        manager.GetMachineData(m_displayData);
 
        // 计算页数
        m_nCurrentPage = 1;
        m_nTotalPages = ((int)m_displayData.size() + m_nRowsPerPage - 1) / m_nRowsPerPage;
    } else {
        m_pPLC = nullptr;
    }
}
 
CIOMonitoringDlg::~CIOMonitoringDlg()
{
    for (auto& pair : m_mapFonts) {
        if (pair.second) {
            pair.second->DeleteObject();
            delete pair.second;
        }
    }
    m_mapFonts.clear();
 
    ClearDynamicControls();
}
 
void CIOMonitoringDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_STATIC_PAGE_NUMBER, m_staticPageNum);
}
 
CFont* CIOMonitoringDlg::GetOrCreateFont(int nFontSize)
{
    auto it = m_mapFonts.find(nFontSize);
    if (it != m_mapFonts.end()) {
        return it->second;
    }
 
    CFont* font = new CFont();
    LOGFONT logFont = { 0 };
    _tcscpy_s(logFont.lfFaceName, _T("Segoe UI"));
    logFont.lfHeight = -nFontSize;
    logFont.lfQuality = CLEARTYPE_QUALITY;
    font->CreateFontIndirect(&logFont);
    m_mapFonts[nFontSize] = font;
 
    return font;
}
 
void CIOMonitoringDlg::SetDefaultFont()
{
    CFont* defaultFont = GetOrCreateFont(12);
 
    // 遍历所有控件,应用默认字体
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        pWnd->SetFont(defaultFont, TRUE);
        pWnd = pWnd->GetNextWindow();
    }
}
 
void CIOMonitoringDlg::AdjustControls(float dScaleX, float dScaleY)
{
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1 && m_mapCtrlLayouts.find(nCtrlID) != m_mapCtrlLayouts.end()) {
            CRect originalRect = m_mapCtrlLayouts[nCtrlID];
            CRect newRect(
                static_cast<int>(originalRect.left * dScaleX),
                static_cast<int>(originalRect.top * dScaleY),
                static_cast<int>(originalRect.right * dScaleX),
                static_cast<int>(originalRect.bottom * dScaleY));
 
            pWnd->MoveWindow(&newRect);
            AdjustControlFont(pWnd, newRect.Width(), newRect.Height());
        }
        pWnd = pWnd->GetNextWindow();
    }
}
 
void CIOMonitoringDlg::AdjustControlFont(CWnd* pWnd, int nWidth, int nHeight)
{
    TCHAR szClassName[256];
    GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
 
    // 根据控件高度动态调整字体大小
    int fontSize = nHeight / 2;
    if (fontSize < 8) fontSize = 8;
    if (fontSize < 24) fontSize = 24;
 
    // 获取或创建字体
    CFont* pFont = GetOrCreateFont(fontSize);
 
    pWnd->SetFont(pFont);
    pWnd->Invalidate(); // 刷新控件显示
}
 
void CIOMonitoringDlg::UpdatePageInfo()
{
    // 格式化页码信息为 "当前页/总页数"
    CString pageInfo;
    pageInfo.Format(_T("%d/%d 页"), m_nCurrentPage, m_nTotalPages);
    m_staticPageNum.SetWindowText(pageInfo);
}
 
void CIOMonitoringDlg::CreateDynamicControls()
{
    CRect rect;
    GetClientRect(&rect);
 
    // 获取按钮的大小
    CWnd* pPrevButton = GetDlgItem(IDC_BUTTON_PREV_PAGE);
    CWnd* pNextButton = GetDlgItem(IDC_BUTTON_NEXT_PAGE);
 
    CRect prevButtonRect, nextButtonRect;
    pPrevButton->GetWindowRect(&prevButtonRect);
    pNextButton->GetWindowRect(&nextButtonRect);
 
    // 转换按钮坐标到对话框的坐标系统
    ScreenToClient(&prevButtonRect);
    ScreenToClient(&nextButtonRect);
 
    int buttonHeight = prevButtonRect.Height();     // 按钮的高度
    int topMargin = int(rect.Height() * 0.05);      // 顶部保留 5% 的高度
    int bottomMargin = buttonHeight + topMargin;    // 底部保留按钮高度加间距
    int sideMargin = topMargin;                     // 左右间距与顶部间距相同
    int groupSpacing = 20;                          // 两组之间的间距
    int verticalSpacing = 10;                       // 垂直间距
 
    // 每行高度和列宽度
    int availableHeight = rect.Height() - topMargin - bottomMargin;
    int rowHeight = (availableHeight / m_nRowsPerPage) - verticalSpacing; // 控件高度包含间距
 
    int availableWidth = rect.Width() - 2 * sideMargin; // 可用宽度(减去左右间距)
    int colWidthSmall = availableWidth / 14;            // 小宽度列更小
    int colWidthLarge = availableWidth * 4 / 14;        // 大宽度列比例
    int groupWidth = colWidthSmall * 2 + colWidthLarge; // 每组总宽度
 
    UINT id = LABEL_ID_BEGIN;
    for (int i = 0; i < m_nRowsPerPage; ++i) {
        // 每一行的起始 Y 坐标
        int y = topMargin + i * (rowHeight + verticalSpacing);
 
        // 创建第 1 组 (0, 1, 2)
        int x = sideMargin; // 从左边距开始
        CreateStaticControl(++id, x, y, colWidthSmall, rowHeight, _T("OFF"), true, AlignCenter);
        x += colWidthSmall;
        CreateStaticControl(++id, x, y, colWidthSmall, rowHeight, _T("X1000"), false, AlignCenter);
        x += colWidthSmall;
        CreateStaticControl(++id, x, y, colWidthLarge, rowHeight, _T("描述文本"), false);
 
        // 第 2 组起始位置,加上组间距
        x += colWidthLarge + groupSpacing;
 
        // 创建第 2 组 (3, 4, 5)
        id++;
        CWnd* pBtn = CreateStaticControl(id, x, y, colWidthSmall, rowHeight, _T("OFF"), true, AlignCenter, [this, id, i, x, y]() {
            // 自定义点击事件的逻辑
            auto* pControl = static_cast<CBLLabel*>(m_staticControls[i * m_nCols + 3]);
            CString currentText;
            pControl->GetWindowText(currentText);
            PostMessage(ID_MSG_IO_CLICK, id, currentText == _T("OFF") ? 1 : 0);
        });
        x += colWidthSmall;
        CWnd* pLabel = CreateStaticControl(++id, x, y, colWidthSmall, rowHeight, _T("Y1010"), false, AlignCenter);
        x += colWidthSmall;
        CreateStaticControl(++id, x, y, colWidthLarge, rowHeight, _T("描述文本"), false);
        ::SetProp(pBtn->GetSafeHwnd(), ADDR_WND, pLabel);
    }
}
 
CWnd* CIOMonitoringDlg::CreateStaticControl(UINT id, int x, int y, int width, int height, const CString& text, bool hasBorder, TextAlign alignment, std::function<void()> clickCallback)
{
    // 创建动态控件
    CBLLabel* pStatic = new CBLLabel();
    DWORD style = WS_CHILD | WS_VISIBLE | SS_CENTERIMAGE; // 确保垂直居中
    if (!hasBorder) {
        pStatic->DisableBorder();
    }
    pStatic->Create(text, style, CRect(x, y, x + width, y + height), this, id);
 
    // 设置文本对齐方式
    pStatic->SetAlignment(alignment);
 
    // 设置动态字体调整,并设置字体大小(动态字体会根据控件大小调整)
    int nSize = height / 3;
    CFont* pFont = GetOrCreateFont(nSize);
    pStatic->SetFont(pFont);
    pStatic->SetFontSize(nSize);
    pStatic->SetDynamicFont(TRUE);
 
    // 设置回调
    //UserManager& userManager = UserManager::getInstance();
    //UserRole enRole = userManager.getCurrentUserRole();
    if (clickCallback/* && (enRole == UserRole::SuperAdmin || enRole == UserRole::Operator)*/) {
        pStatic->SetClickCallback(clickCallback);
        pStatic->SetRoundedCorners(TRUE, 5);
        pStatic->DisableBorder();
    }
 
    // 存储控件指针
    m_staticControls.push_back(pStatic);
 
    return pStatic;
}
 
CWnd* CIOMonitoringDlg::GetStaticControl(UINT id)
{
    for (auto item : m_staticControls) {
        TRACE(">>id:%d\n", item->GetDlgCtrlID());
        if (item->GetDlgCtrlID() == id) {
            return item;
        }
    }
 
    return nullptr;
}
 
CString& CIOMonitoringDlg::GetStaticControlAddrText(UINT id, CString& strAddr)
{
    CWnd* pBtn = GetStaticControl(id);
    if (pBtn != nullptr) {
        CWnd* pLabel = (CWnd*)::GetProp(pBtn->GetSafeHwnd(), ADDR_WND);
        if (pLabel != nullptr) {
            pLabel->GetWindowText(strAddr);
        }
    }
 
    return strAddr;
}
 
void CIOMonitoringDlg::DisplayCurrentPage()
{
    int startIndex = (m_nCurrentPage - 1) * m_nRowsPerPage;
    int endIndex = min(startIndex + m_nRowsPerPage, static_cast<int>(m_displayData.size()));
 
    m_inputStates.clear();
    m_outputStates.clear();
    m_inputPLCAddresses.clear();
    m_outputPLCAddresses.clear();
 
    for (int i = 0; i < m_nRowsPerPage; ++i) {
        int row = i;
 
        if (startIndex + i < endIndex) {
            const auto& data = m_displayData[startIndex + i];
 
            // 添加状态到容器中
            m_inputStates.push_back(FALSE);        // 0 列
            m_outputStates.push_back(FALSE);    // 3 列
 
            // 添加 PLC 地址到容器中
            m_inputPLCAddresses.push_back(CString(data.inputAddress.c_str()));        // 1 列
            m_outputPLCAddresses.push_back(CString(data.outputAddress.c_str()));    // 4 列
 
            // 显示控件并设置内容
            m_staticControls[row * m_nCols + 0]->SetWindowText(_T("OFF"));
            m_staticControls[row * m_nCols + 0]->ShowWindow(SW_SHOW);
            m_staticControls[row * m_nCols + 0]->SetBkColor(RGB(255, 0, 0));
 
            m_staticControls[row * m_nCols + 1]->SetWindowText(CString(data.inputAddress.c_str()));
            m_staticControls[row * m_nCols + 1]->ShowWindow(SW_SHOW);
 
            m_staticControls[row * m_nCols + 2]->SetWindowText(CString(data.inputDescription.c_str()));
            m_staticControls[row * m_nCols + 2]->ShowWindow(SW_SHOW);
 
            m_staticControls[row * m_nCols + 3]->SetWindowText(_T("OFF"));
            m_staticControls[row * m_nCols + 3]->ShowWindow(SW_SHOW);
            m_staticControls[row * m_nCols + 3]->SetBkColor(RGB(255, 0, 0));
 
            m_staticControls[row * m_nCols + 4]->SetWindowText(CString(data.outputAddress.c_str()));
            m_staticControls[row * m_nCols + 4]->ShowWindow(SW_SHOW);
 
            m_staticControls[row * m_nCols + 5]->SetWindowText(CString(data.outputDescription.c_str()));
            m_staticControls[row * m_nCols + 5]->ShowWindow(SW_SHOW);
        }
        else {
            // 隐藏这一行的所有控件
            for (int col = 0; col < m_nCols; ++col) {
                m_staticControls[row * m_nCols + col]->ShowWindow(SW_HIDE);
            }
        }
    }
 
    UpdatePageInfo();
}
 
void CIOMonitoringDlg::ClearDynamicControls()
{
    for (auto* pStatic : m_staticControls) {
        if (pStatic) {
            pStatic->DestroyWindow();
            delete pStatic;
        }
    }
    m_staticControls.clear();
}
 
bool CIOMonitoringDlg::ParsePLCAddress(const CString& address, MC::SOFT_COMPONENT& component, int& addr)
{
    if (address.GetLength() < 2) {
        return false;
    }
 
    // 提取组件类型(第一个字符)
    TCHAR componentChar = address[0];
    if (address.Left(2) == _T("ZR")) {
        component = MC::SOFT_COMPONENT::ZR;
        // 提取数字部分(去除ZR前缀)
        CString numericAddress = address.Mid(2);
        addr = _tcstoul(numericAddress, nullptr, 16);
        return addr != 0 || numericAddress.CompareNoCase(_T("0")) == 0;  // 如果是 "0",也认为有效
    }
 
    // 对于其他组件,按照常规规则处理
    CString hexAddress = address.Mid(1);
    switch (componentChar) {
    case 'D':
        component = MC::SOFT_COMPONENT::D;
        addr = _ttoi(hexAddress);
        break;
    case 'M':
        component = MC::SOFT_COMPONENT::M;
        addr = _tcstoul(hexAddress, nullptr, 16);
        break;
    case 'X':
        component = MC::SOFT_COMPONENT::X;
        addr = _tcstoul(hexAddress, nullptr, 16);
        break;
    case 'Y':
        component = MC::SOFT_COMPONENT::Y;
        addr = _tcstoul(hexAddress, nullptr, 16);
        break;
    case 'W':
        component = MC::SOFT_COMPONENT::W;
        addr = _tcstoul(hexAddress, nullptr, 16);
        break;
    case 'L':
        component = MC::SOFT_COMPONENT::L;
        addr = _tcstoul(hexAddress, nullptr, 16);
        break;
    case 'S':
        component = MC::SOFT_COMPONENT::S;
        addr = _tcstoul(hexAddress, nullptr, 16);
        break;
    case 'B':
        component = MC::SOFT_COMPONENT::B;
        addr = _tcstoul(hexAddress, nullptr, 16);
        break;
    case 'F':
        component = MC::SOFT_COMPONENT::F;
        addr = _tcstoul(hexAddress, nullptr, 16);
        break;
    default:
        return false;
    }
 
    // 检查地址是否有效
    if (addr == 0 && hexAddress.CompareNoCase(_T("0")) != 0) {
        return false;
    }
 
    return true;
}
 
bool CIOMonitoringDlg::GeneratePLCAddress(MC::SOFT_COMPONENT component, int addr, CString& address, bool bHexFormat)
{
    // 根据组件类型生成前缀
    CString prefix;
    switch (component) {
    case MC::SOFT_COMPONENT::D:
        prefix = _T("D");
        break;
    case MC::SOFT_COMPONENT::M:
        prefix = _T("M");
        break;
    case MC::SOFT_COMPONENT::X:
        prefix = _T("X");
        break;
    case MC::SOFT_COMPONENT::Y:
        prefix = _T("Y");
        break;
    case MC::SOFT_COMPONENT::W:
        prefix = _T("W");
        break;
    case MC::SOFT_COMPONENT::L:
        prefix = _T("L");
        break;
    case MC::SOFT_COMPONENT::S:
        prefix = _T("S");
        break;
    case MC::SOFT_COMPONENT::B:
        prefix = _T("B");
        break;
    case MC::SOFT_COMPONENT::F:
        prefix = _T("F");
        break;
    case MC::SOFT_COMPONENT::ZR:
        prefix = _T("ZR");
        break;
    default:
        return false;  // 如果是未知组件类型,返回失败
    }
 
    // 根据 bHexFormat 判断输出格式
    CString strAddr;
    if (bHexFormat) {
        strAddr.Format(_T("%X"), addr);  // 十六进制格式
    }
    else {
        strAddr.Format(_T("%d"), addr);  // 十进制格式
    }
 
    // 生成最终的地址字符串
    address = prefix + strAddr;
    return true;
}
 
// 处理PLC数据读取的通用方法
void CIOMonitoringDlg::ReadPLCData(MC::SOFT_COMPONENT softComponent, int startAddr, int endAddr, std::function<void(IMcChannel*, int, char*, unsigned int, int)> callback)
{
    int nSize;
    // 检查地址是否有效,以及组件是否匹配
    nSize = endAddr - startAddr + 1;
    if (nSize < 1) {
        return;
    }
 
    // 读取数据
    m_pPLC->readData(softComponent, startAddr, nSize, callback);
}
 
void CIOMonitoringDlg::ReadPLCStates()
{
    if (m_displayData.empty()) {
        return;
    }
 
    auto startData = m_displayData.front();
    auto endData = m_displayData.back();
    MC::SOFT_COMPONENT startSoftComponent, endSoftComponent;
    int inputStartAddr, inputEndAddr;
    ParsePLCAddress(CString(startData.inputAddress.c_str()), startSoftComponent, inputStartAddr);
    ParsePLCAddress(CString(endData.inputAddress.c_str()), endSoftComponent, inputEndAddr);
    ASSERT(startSoftComponent == endSoftComponent);
 
    // 读取输入数据
    ReadPLCData(startSoftComponent, inputStartAddr, inputEndAddr, [this, inputStartAddr](IMcChannel* pChannel, int addr, char* pData, unsigned int nDataSize, int flag) {
        if (!::IsWindow(m_hWnd)) return;
        for (auto& data : m_displayData) {
            int nAddress;
            MC::SOFT_COMPONENT enComponent;
            if (ParsePLCAddress(CString(data.inputAddress.c_str()), enComponent, nAddress)) {
                int nOffset = nAddress - inputStartAddr;
                if (nOffset >= 0 && nOffset < (int)nDataSize) {
                    int byteIndex = nOffset / 8;
                    int bitIndex = nOffset % 8;
                    data.bInputStates = CToolUnits::getBit(pData[byteIndex], bitIndex);
                }
            }
        }
    });
 
    // 读取输出数据
    int outputStartAddr, outputEndAddr;
    ParsePLCAddress(CString(startData.outputAddress.c_str()), startSoftComponent, outputStartAddr);
    ParsePLCAddress(CString(endData.outputAddress.c_str()), endSoftComponent, outputEndAddr);
    ASSERT(startSoftComponent == endSoftComponent);
    ReadPLCData(startSoftComponent, outputStartAddr, outputEndAddr, [this, outputStartAddr](IMcChannel* pChannel, int addr, char* pData, unsigned int nDataSize, int flag) {
        if (!::IsWindow(m_hWnd)) return;
        for (auto& data : m_displayData) {
            int nAddress;
            MC::SOFT_COMPONENT enComponent;
            if (ParsePLCAddress(CString(data.outputAddress.c_str()), enComponent, nAddress)) {
                int nOffset = nAddress - outputStartAddr;
                if (nOffset >= 0 && nOffset < (int)nDataSize) {
                    int byteIndex = nOffset / 8;
                    int bitIndex = nOffset % 8;
                    data.bOutputStates = CToolUnits::getBit(pData[byteIndex], bitIndex);
                    TRACE(">>>> %d %d %d |||| %d\n", nOffset, byteIndex, bitIndex, data.bOutputStates);
                }
            }
        }
    });
}
 
void CIOMonitoringDlg::UpdatePLCStatesToUI()
{
    int startIndex = (m_nCurrentPage - 1) * m_nRowsPerPage;
    int endIndex = min(startIndex + m_nRowsPerPage, static_cast<int>(m_displayData.size()));
 
    for (int i = 0; i < m_nRowsPerPage; ++i) {
        int row = i;
 
        if (startIndex + i < endIndex) {
            const auto& data = m_displayData[startIndex + i];
            // 设置内容和背景颜色
            if (m_inputStates[i] != data.bInputStates)
            {
                m_staticControls[row * m_nCols + 0]->SetText(data.bInputStates ? _T("ON") : _T("OFF"));
                m_staticControls[row * m_nCols + 0]->SetBkColor(data.bInputStates ? RGB(0, 255, 0) : RGB(255, 0, 0));
                m_inputStates[i] = data.bInputStates;
            }
 
            if (m_outputStates[i] != data.bOutputStates)
            {
                m_staticControls[row * m_nCols + 3]->SetText(data.bOutputStates ? _T("ON") : _T("OFF"));
                m_staticControls[row * m_nCols + 3]->SetBkColor(data.bOutputStates ? RGB(0, 255, 0) : RGB(255, 0, 0));
                m_outputStates[i] = data.bOutputStates;
            }
        }
    }
}
 
BEGIN_MESSAGE_MAP(CIOMonitoringDlg, CDialogEx)
    ON_BN_CLICKED(IDC_BUTTON_PREV_PAGE, &CIOMonitoringDlg::OnBnClickedButtonPrevPage)
    ON_BN_CLICKED(IDC_BUTTON_NEXT_PAGE, &CIOMonitoringDlg::OnBnClickedButtonNextPage)
    ON_MESSAGE(ID_MSG_IO_CLICK, &CIOMonitoringDlg::OnIoClicked)
    ON_WM_SIZE()
    ON_WM_TIMER()
    ON_WM_CLOSE()
END_MESSAGE_MAP()
 
 
// CIOMonitoringDlg 消息处理程序
 
 
BOOL CIOMonitoringDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
 
    // TODO:  在此添加额外的初始化
    if (m_pPLC == nullptr || !m_pPLC->isConnected()) {
        AfxMessageBox(_T("PLC 未连接!"));
        return FALSE;
    }
 
    CString strTitle;
    strTitle.Format(_T("IO监控页面(PLC: %s)"), m_pPLC->getName().c_str());
    SetWindowText(strTitle);
 
    CRect screenRect, dlgRect, clientRect;
    SystemParametersInfo(SPI_GETWORKAREA, 0, &screenRect, 0);
 
    GetClientRect(&clientRect);
    m_nInitialWidth = clientRect.Width();
    m_nInitialHeight = clientRect.Height();
 
    // 初始化默认字体
    CFont* pDefaultFont = GetOrCreateFont(12);
 
    // 遍历所有子控件,记录初始位置并设置默认字体
    CWnd* pWnd = GetWindow(GW_CHILD);
    while (pWnd) {
        int nCtrlID = pWnd->GetDlgCtrlID();
        if (nCtrlID != -1) {
            // 记录控件初始布局
            CRect ctrlRect;
            pWnd->GetWindowRect(&ctrlRect);
            ScreenToClient(&ctrlRect);
            m_mapCtrlLayouts[nCtrlID] = ctrlRect;
 
            // 跳过特殊控件(如 MFCGridCtrl)
            TCHAR szClassName[256];
            GetClassName(pWnd->m_hWnd, szClassName, sizeof(szClassName));
            if (_tcsicmp(szClassName, _T("MFCGridCtrl")) == 0) {
                pWnd = pWnd->GetNextWindow();
                continue;
            }
 
            // 设置默认字体
            pWnd->SetFont(pDefaultFont);
        }
        pWnd = pWnd->GetNextWindow();
    }
 
    GetWindowRect(&dlgRect);
    int dlgWidth = dlgRect.Width() * 3;
    int dlgHeight = dlgRect.Height() * 3;
 
    if (dlgWidth > screenRect.Width()) {
        dlgWidth = screenRect.Width();
    }
    if (dlgHeight > screenRect.Height()) {
        dlgHeight = screenRect.Height();
    }
 
    int centerX = screenRect.left + (screenRect.Width() - dlgWidth) / 2;
    int centerY = screenRect.top + (screenRect.Height() - dlgHeight) / 2;
    MoveWindow(centerX, centerY, dlgWidth, dlgHeight);
 
    CreateDynamicControls();
    DisplayCurrentPage();
 
    GetDlgItem(IDC_BUTTON_PREV_PAGE)->EnableWindow(m_nCurrentPage > 1);
    GetDlgItem(IDC_BUTTON_NEXT_PAGE)->EnableWindow(m_nCurrentPage < m_nTotalPages);
 
    SetTimer(TIMER_READ_PLC_DATA, 500, nullptr);
    SetTimer(TIMER_READ_UPDATE, 200, nullptr);
 
    return TRUE;  // return TRUE unless you set the focus to a control
    // 异常: OCX 属性页应返回 FALSE
}
 
void CIOMonitoringDlg::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);
 
    // TODO: 在此处添加消息处理程序代码
    if (nType == SIZE_MINIMIZED || m_mapCtrlLayouts.empty()) {
        return;
    }
 
    float dScaleX = static_cast<float>(cx) / m_nInitialWidth;
    float dScaleY = static_cast<float>(cy) / m_nInitialHeight;
 
    // 遍历对话框中的所有控件
    AdjustControls(dScaleX, dScaleY);
}
 
void CIOMonitoringDlg::OnBnClickedButtonPrevPage()
{
    // TODO: 在此添加控件通知处理程序代码
    if (m_nCurrentPage > 1) {
        --m_nCurrentPage;
        DisplayCurrentPage();
    }
    else {
        AfxMessageBox(_T("已经是第一页!"));
    }
 
    GetDlgItem(IDC_BUTTON_PREV_PAGE)->EnableWindow(m_nCurrentPage > 1);
    GetDlgItem(IDC_BUTTON_NEXT_PAGE)->EnableWindow(m_nCurrentPage < m_nTotalPages);
}
 
void CIOMonitoringDlg::OnBnClickedButtonNextPage()
{
    // TODO: 在此添加控件通知处理程序代码
    if (m_nCurrentPage < m_nTotalPages) {
        ++m_nCurrentPage;
        DisplayCurrentPage();
    }
    else {
        AfxMessageBox(_T("已经是最后一页!"));
    }
    
    GetDlgItem(IDC_BUTTON_PREV_PAGE)->EnableWindow(m_nCurrentPage > 1);
    GetDlgItem(IDC_BUTTON_NEXT_PAGE)->EnableWindow(m_nCurrentPage < m_nTotalPages);
}
 
LRESULT CIOMonitoringDlg::OnIoClicked(WPARAM wParam, LPARAM lParam)
{
    CString strAddr;
    GetStaticControlAddrText((UINT)wParam, strAddr);
 
    BOOL bOn = (BOOL)lParam;
    int nAddress;
    MC::SOFT_COMPONENT component;
    if (ParsePLCAddress(strAddr, component, nAddress) && m_pPLC) {
        TRACE("地址解析成功: %s %d\n", strAddr, GetCurrentThreadId());
        int n = m_pPLC->writeBit(component, nAddress, bOn, [](IMcChannel* pChannel, int addr, DWORD value, int flag) {
            if (flag == 0) {
                TRACE("写入成功: 地址: %d, 值: %lu\n", addr, value);
            }
            else {
                TRACE("写入失败: 地址: %d, 错误码: %d\n", addr, flag);
            }
            });
        TRACE("地址解析成功2: %d\n", n);
    }
 
    return 0;
}
 
void CIOMonitoringDlg::OnTimer(UINT_PTR nIDEvent)
{
    // TODO: 在此添加消息处理程序代码和/或调用默认值
    if (TIMER_READ_PLC_DATA == nIDEvent) {
        ASSERT(m_pPLC);
        ReadPLCStates();
    }
    else if (TIMER_READ_UPDATE == nIDEvent) {
        ASSERT(m_pPLC);
        UpdatePLCStatesToUI();
    }
 
    CDialogEx::OnTimer(nIDEvent);
}
 
void CIOMonitoringDlg::OnClose()
{
    // TODO: 在此添加消息处理程序代码和/或调用默认值
    KillTimer(TIMER_READ_PLC_DATA);
    KillTimer(TIMER_READ_UPDATE);
    CDialogEx::OnClose();
}