Example_vcDlg.cpp
资源名称:test.rar [点击查看]
上传用户:wuxg88
上传日期:2022-05-28
资源大小:814k
文件大小:17k
源码类别:
通讯编程
开发平台:
C++ Builder
- // Example_vcDlg.cpp : implementation file
- //
- #include "stdafx.h"
- #include "Example_vc.h"
- #include "Example_vcDlg.h"
- #include "winsock2.h"
- #pragma comment(lib, "ws2_32.lib")
- #ifndef DYNAMIC_LOAD // Static load if marked
- #include "DMT.h" // Static load: Step 1/2
- #pragma comment(lib, "DMT.lib") // Static load: Step 2/2
- #endif
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static char THIS_FILE[] = __FILE__;
- #endif
- /////////////////////////////////////////////////////////////////////////////
- // CAboutDlg dialog used for App About
- class CAboutDlg : public CDialog
- {
- public:
- CAboutDlg();
- // Dialog Data
- //{{AFX_DATA(CAboutDlg)
- enum { IDD = IDD_ABOUTBOX };
- //}}AFX_DATA
- // ClassWizard generated virtual function overrides
- //{{AFX_VIRTUAL(CAboutDlg)
- protected:
- virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
- //}}AFX_VIRTUAL
- // Implementation
- protected:
- //{{AFX_MSG(CAboutDlg)
- //}}AFX_MSG
- DECLARE_MESSAGE_MAP()
- };
- CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
- {
- //{{AFX_DATA_INIT(CAboutDlg)
- //}}AFX_DATA_INIT
- }
- void CAboutDlg::DoDataExchange(CDataExchange* pDX)
- {
- CDialog::DoDataExchange(pDX);
- //{{AFX_DATA_MAP(CAboutDlg)
- //}}AFX_DATA_MAP
- }
- BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
- //{{AFX_MSG_MAP(CAboutDlg)
- // No message handlers
- //}}AFX_MSG_MAP
- END_MESSAGE_MAP()
- /////////////////////////////////////////////////////////////////////////////
- // CExample_vcDlg dialog
- CExample_vcDlg::CExample_vcDlg(CWnd* pParent /*=NULL*/)
- : CDialog(CExample_vcDlg::IDD, pParent)
- {
- //{{AFX_DATA_INIT(CExample_vcDlg)
- //}}AFX_DATA_INIT
- // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
- m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
- }
- void CExample_vcDlg::DoDataExchange(CDataExchange* pDX)
- {
- CDialog::DoDataExchange(pDX);
- //{{AFX_DATA_MAP(CExample_vcDlg)
- DDX_Control(pDX, IDC_EDIT6, m_modbus_func_r);
- DDX_Control(pDX, IDC_EDIT5, m_modbus_addr_r);
- DDX_Control(pDX, IDC_COMBO6, m_comport);
- DDX_Control(pDX, IDC_COMBO2, m_modbus_mode);
- DDX_Control(pDX, IDC_COMBO1, m_comm_type);
- DDX_Control(pDX, IDC_EDIT3, m_modbus_data_r);
- DDX_Control(pDX, IDC_IPADDRESS1, m_ipaddress1);
- DDX_Control(pDX, IDC_EDIT1, m_modbus_addr_s);
- DDX_Control(pDX, IDC_EDIT2, m_modbus_func_s);
- DDX_Control(pDX, IDC_EDIT4, m_modbus_data_s);
- //}}AFX_DATA_MAP
- }
- BEGIN_MESSAGE_MAP(CExample_vcDlg, CDialog)
- //{{AFX_MSG_MAP(CExample_vcDlg)
- ON_WM_SYSCOMMAND()
- ON_WM_PAINT()
- ON_WM_QUERYDRAGICON()
- ON_CBN_SELCHANGE(IDC_COMBO1, OnSelchangeCombo1)
- ON_WM_DESTROY()
- //}}AFX_MSG_MAP
- END_MESSAGE_MAP()
- /////////////////////////////////////////////////////////////////////////////
- // CExample_vcDlg message handlers
- BOOL CExample_vcDlg::OnInitDialog()
- {
- CDialog::OnInitDialog();
- // Add "About..." menu item to system menu.
- // IDM_ABOUTBOX must be in the system command range.
- ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
- ASSERT(IDM_ABOUTBOX < 0xF000);
- CMenu* pSysMenu = GetSystemMenu(FALSE);
- if (pSysMenu != NULL)
- {
- CString strAboutMenu;
- strAboutMenu.LoadString(IDS_ABOUTBOX);
- if (!strAboutMenu.IsEmpty())
- {
- pSysMenu->AppendMenu(MF_SEPARATOR);
- pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
- }
- }
- // Set the icon for this dialog. The framework does this automatically
- // when the application's main window is not a dialog
- SetIcon(m_hIcon, TRUE); // Set big icon
- SetIcon(m_hIcon, FALSE); // Set small icon
- // TODO: Add extra initialization here
- // Check registry serial list ----------------------------------
- HKEY hKey;
- LONG lReturn;
- DWORD dwValue = 0, dwType, dwData;
- DWORD dwValName;
- TCHAR szValueName[256];
- TCHAR szData[256];
- BOOL bIsPath;
- if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,"HARDWARE\DEVICEMAP\SERIALCOMM",
- 0, KEY_READ, &hKey) != ERROR_SUCCESS)
- {
- RegCloseKey(hKey);
- }
- else
- bIsPath = TRUE;
- while (bIsPath == TRUE)
- {
- dwData = sizeof(szData);
- dwValName = sizeof(szValueName);
- lReturn = RegEnumValue(hKey, dwValue++, szValueName, &dwValName,
- NULL, &dwType, (UCHAR*)szData, &dwData);
- if (lReturn == ERROR_NO_MORE_ITEMS)
- break;
- //AfxMessageBox(szData); // Print COM port name
- m_comport.AddString(szData); // Add to ComboBox
- }
- RegCloseKey(hKey);
- // Initial dialog controls
- m_comm_type.SetCurSel(0);
- m_modbus_mode.SetCurSel(0);
- m_comport.SetCurSel(0);
- m_modbus_addr_s.SetWindowText("1");
- m_modbus_func_s.SetWindowText("5");
- m_modbus_data_s.SetWindowText("0500FF00");
- OnSelchangeCombo1();
- #ifdef DYNAMIC_LOAD // Dynamic load
- if (!InitDMT()) // Dynamic load: Step 2/3
- exit(0);
- #endif
- return TRUE; // return TRUE unless you set the focus to a control
- }
- void CExample_vcDlg::OnDestroy()
- {
- CDialog::OnDestroy();
- #ifdef DYNAMIC_LOAD // Dynamic load
- FreeLibrary(hDMTDll);
- #endif
- }
- void CExample_vcDlg::OnSysCommand(UINT nID, LPARAM lParam)
- {
- if ((nID & 0xFFF0) == IDM_ABOUTBOX)
- {
- CAboutDlg dlgAbout;
- dlgAbout.DoModal();
- }
- else
- {
- CDialog::OnSysCommand(nID, lParam);
- }
- }
- // If you add a minimize button to your dialog, you will need the code below
- // to draw the icon. For MFC applications using the document/view model,
- // this is automatically done for you by the framework.
- void CExample_vcDlg::OnPaint()
- {
- if (IsIconic())
- {
- CPaintDC dc(this); // device context for painting
- SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
- // Center icon in client rectangle
- int cxIcon = GetSystemMetrics(SM_CXICON);
- int cyIcon = GetSystemMetrics(SM_CYICON);
- CRect rect;
- GetClientRect(&rect);
- int x = (rect.Width() - cxIcon + 1) / 2;
- int y = (rect.Height() - cyIcon + 1) / 2;
- // Draw the icon
- dc.DrawIcon(x, y, m_hIcon);
- }
- else
- {
- CDialog::OnPaint();
- }
- }
- // The system calls this to obtain the cursor to display while the user drags
- // the minimized window.
- HCURSOR CExample_vcDlg::OnQueryDragIcon()
- {
- return (HCURSOR) m_hIcon;
- }
- void CExample_vcDlg::OnOK()
- {
- CString strTmp = "";
- CString strTmp1 = "";
- CString strTmp3 = "";
- char charTmp[8];
- int conn_num = 1; // Connection index 0-256 connection
- int comm_type = m_comm_type.GetCurSel(); // Communication Type, 0:Serial, 1:Ethernet
- int status = 0;
- unsigned char ASC[2] = {0}; // Used to Convert HEX value to ASCII
- unsigned char ASCI[2] = {0};
- int i = 0, l = 0, sendlen = 0;
- // Declare send variable
- unsigned char sendbuf[10];
- int modbus_addr;
- int modbus_func;
- // Declare receive variable
- unsigned char recvbuf[20] = {0};
- int modbus_addr_r = 0;
- int modbus_func_r = 0;
- // Fetch input ip
- DWORD remote_addr;
- m_ipaddress1.GetAddress(remote_addr);
- // Fetch input modbus address (Decimal)
- m_modbus_addr_s.GetWindowText(strTmp);
- modbus_addr = atoi((LPCTSTR)strTmp);
- // Fetch input modbus function (Decimal)
- m_modbus_func_s.GetWindowText(strTmp);
- strncpy(charTmp, (LPCTSTR)strTmp, sizeof(charTmp));
- // Convert Hex String to Integer
- modbus_func = HexStr_to_Int(charTmp);
- // Fetch input modbus data (Hexadecimal )
- m_modbus_data_s.GetWindowText(strTmp);
- // strTmp.MakeUpper(); // Conver to upper case
- // Check if Modbus data length is even
- if (strTmp.GetLength()%2 != 0)
- {
- AfxMessageBox("Modbus data length must be even numbers");
- return;
- }
- // Convert ASCII to HEX value
- if (strTmp.GetLength() > 0)
- {
- // Convert 2bytes string to hex
- for (i=0; i < strTmp.GetLength(); i+=2)
- {
- ASCI[0] = strTmp[i]; //High byte
- ASCI[1] = strTmp[i+1]; //Lowb yte
- sendbuf[l] = ASCI_to_HEX(ASCI);
- l++;
- }
- sendlen = l;
- }
- // Select Communication Type
- switch (comm_type)
- {
- case 0: // Modbus
- {
- CString strTmp = "";
- int numTmp = 0, conn_num = 0;
- // Get COM port name
- m_comport.GetWindowText(strTmp);
- // Get Modbus mode
- numTmp = m_modbus_mode.GetCurSel();
- strTmp.Delete(0, 3);
- // Get COM number
- conn_num = atoi(strTmp);
- if (numTmp == 0)
- status = OpenModbusSerial(conn_num, 9600, 7, 'E', 1, numTmp+1); // Modbus Type, 1:MODBUS_ASCII, 2:MODBUS_RTU
- else
- status = OpenModbusSerial(conn_num, 9600, 8, 'N', 1, numTmp+1);
- if (status > 0)
- {
- int a, b;
- // Send & Receive Data
- a = RequestData(comm_type, conn_num, 1, modbus_func, sendbuf, sendlen); // Send
- b = ResponseData(comm_type, conn_num, &modbus_addr_r, &modbus_func_r, recvbuf); // Receive
- if (b > 0)
- {
- // Convert HEX value to ASCII
- for (int j = 0; j < b; j++)
- {
- HEX_to_ASCI(recvbuf[j], ASC);
- strTmp.Format("%C%C", ASC[0],ASC[1]);
- strTmp1.Insert(strTmp1.GetLength()+1,(LPCTSTR)strTmp);
- }
- strTmp3.Format("%d" ,modbus_addr_r);
- m_modbus_addr_r.SetWindowText(strTmp3); // Response address
- strTmp3.Format("%X" ,modbus_func_r);
- m_modbus_func_r.SetWindowText(strTmp3); // Response function code
- m_modbus_data_r.SetWindowText(strTmp1); // Show response data
- }
- else
- {
- AfxMessageBox("No data received.");
- m_modbus_addr_r.SetWindowText("");
- m_modbus_func_r.SetWindowText("");
- m_modbus_data_r.SetWindowText("");
- }
- CloseSerial(conn_num);
- }
- else
- AfxMessageBox("Serial Error");
- break;
- }
- case 1: // Modbus/TCP
- {
- conn_num = 0; // Connection number
- // Open TCP Socket
- status = OpenModbusTCPSocket(conn_num, htonl(remote_addr));
- if (status > 0)
- {
- int a, b;
- // Send & Receive Data
- a = RequestData(comm_type, conn_num, modbus_addr, modbus_func, sendbuf, sendlen); // Send
- if (ReadSelect(conn_num, 100))
- b = ResponseData(comm_type, conn_num, &modbus_addr_r, &modbus_func_r, recvbuf); // Receive
- if (b > 0)
- {
- // Convert HEX value to ASCII
- for (int j = 0; j < b; j++)
- {
- HEX_to_ASCI(recvbuf[j], ASC);
- strTmp.Format("%C%C", ASC[0],ASC[1]);
- strTmp1.Insert(strTmp1.GetLength()+1,(LPCTSTR)strTmp);
- }
- strTmp3.Format("%d" ,modbus_addr_r);
- m_modbus_addr_r.SetWindowText(strTmp3); // Response address
- strTmp3.Format("%X" ,modbus_func_r);
- m_modbus_func_r.SetWindowText(strTmp3); // Response function code
- m_modbus_data_r.SetWindowText(strTmp1); // Show response data
- }
- else
- {
- AfxMessageBox("No data received.");
- m_modbus_addr_r.SetWindowText("");
- m_modbus_func_r.SetWindowText("");
- m_modbus_data_r.SetWindowText("");
- }
- CloseSocket(conn_num);
- }
- else
- AfxMessageBox("Socket Error");
- break;
- }
- }
- m_modbus_data_s.GetWindowText(strTmp);
- if (strTmp == "0500FF00")
- m_modbus_data_s.SetWindowText("05000000");
- else
- m_modbus_data_s.SetWindowText("0500FF00");
- // CDialog::OnOK();
- }
- // Convert ASCII to Hex
- unsigned char CExample_vcDlg::ASCI_to_HEX(unsigned char asci[])
- {
- unsigned char value_hex = 0x00;
- int i;
- for (i=0;i<2;i++) //High byte 0, Low byte 1
- {
- if (asci[i] >= 0x30 && asci[i] <= 0x39) // 0 - 9
- value_hex = (unsigned char)((value_hex*16)+(asci[i]-0x30));
- else if (asci[i] >= 0x41 && asci[i] <= 0x46) // A - F
- value_hex = (unsigned char)((value_hex*16)+(asci[i]-0x37));
- else if (asci[i] >= 0x61 && asci[i] <= 0x66) // a - f
- value_hex = (unsigned char)((value_hex*16)+(asci[i]-0x57));
- }
- return value_hex;
- }
- // Convert Hex to ASCII
- void CExample_vcDlg::HEX_to_ASCI(unsigned char value_hex, unsigned char *asci)
- {
- unsigned char reglow,reghigh;
- reghigh = (unsigned char)((value_hex & 0xf0) >> 4);
- reglow = (unsigned char)(value_hex & 0x0f);
- if (reghigh <= 9)
- asci[0] = (unsigned char)(reghigh + 0x30); //low byte
- else
- asci[0] = (unsigned char)((reghigh - 10) + 0x41);
- if (reglow <= 9)
- asci[1] = (unsigned char)(reglow + 0x30); //high byte
- else
- asci[1] = (unsigned char)((reglow - 10) + 0x41);
- }
- // Convert a "Hex String" to an Integer
- int CExample_vcDlg::HexStr_to_Int(const TCHAR *value)
- {
- struct CHexMap
- {
- TCHAR chr;
- int value;
- };
- const int HexMapL = 16;
- CHexMap HexMap[HexMapL] =
- {
- {'0', 0}, {'1', 1},
- {'2', 2}, {'3', 3},
- {'4', 4}, {'5', 5},
- {'6', 6}, {'7', 7},
- {'8', 8}, {'9', 9},
- {'A', 10}, {'B', 11},
- {'C', 12}, {'D', 13},
- {'E', 14}, {'F', 15}
- };
- TCHAR *mstr = _tcsupr(_tcsdup(value));
- TCHAR *s = mstr;
- int result = 0;
- if (*s == '0' && *(s + 1) == 'X') s += 2;
- bool firsttime = true;
- while (*s != ' ')
- {
- bool found = false;
- for (int i = 0; i < HexMapL; i++)
- {
- if (*s == HexMap[i].chr)
- {
- if (!firsttime) result <<= 4;
- result |= HexMap[i].value;
- found = true;
- break;
- }
- }
- if (!found) break;
- s++;
- firsttime = false;
- }
- free(mstr);
- return result;
- }
- void CExample_vcDlg::OnSelchangeCombo1()
- {
- int numTmp = m_comm_type.GetCurSel();
- switch (numTmp)
- {
- case 0:
- m_modbus_mode.SetCurSel(0);
- m_comport.EnableWindow(TRUE);
- m_modbus_mode.EnableWindow(TRUE);
- m_ipaddress1.EnableWindow(FALSE);
- break;
- case 1:
- m_modbus_mode.SetCurSel(1);
- m_comport.EnableWindow(FALSE);
- m_modbus_mode.EnableWindow(FALSE);
- m_ipaddress1.EnableWindow(TRUE);
- break;
- }
- }
- #ifdef DYNAMIC_LOAD // Dynamic load
- // Dynamic load: Step 3/3
- BOOL CExample_vcDlg::InitDMT()
- {
- // Load Communication Library
- hDMTDll = LoadLibraryEx("DMT", NULL, 0);
- if (hDMTDll == NULL)
- {
- AfxMessageBox(_T("Can't load DMT !!"));
- return FALSE;
- }
- // Open Modbus Serial
- OpenModbusSerial = (int (WINAPI *)(int, int, int, char, int, int))GetProcAddress(hDMTDll, "OpenModbusSerial");
- if (OpenModbusSerial == NULL)
- {
- AfxMessageBox(_T("OpenModbusSerial function not in DMT.dll !!"));
- return FALSE;
- }
- // Close Serial
- CloseSerial = (void (WINAPI *)(int))GetProcAddress(hDMTDll, "CloseSerial");
- if (CloseSerial == NULL)
- {
- AfxMessageBox(_T("CloseSerial function not in DMT.dll !!"));
- return FALSE;
- }
- // Get Serial Error Message Function
- GetLastSerialErr = (int (WINAPI *)())GetProcAddress(hDMTDll, "GetLastSerialErr");
- if (GetLastSerialErr == NULL)
- {
- AfxMessageBox(_T("GetLastSerialErr function not in DMT.dll !!"));
- return FALSE;
- }
- // Clear Serial Error Message Function
- ResetSerialErr = (void (WINAPI *)())GetProcAddress(hDMTDll, "ResetSerialErr");
- if (ResetSerialErr == NULL)
- {
- AfxMessageBox(_T("ResetSerialErr function not in DMT.dll !!"));
- return FALSE;
- }
- // Open Modbus TCP Socket
- OpenModbusTCPSocket = (int (WINAPI *)(int, int))GetProcAddress(hDMTDll, "OpenModbusTCPSocket");
- if (OpenModbusTCPSocket == NULL)
- {
- AfxMessageBox("OpenModbusTCPSocket function not in DMT.dll !!!");
- return FALSE;
- }
- // Close Socket
- CloseSocket = (void (WINAPI *)(int))GetProcAddress(hDMTDll, "CloseSocket");
- if (CloseSocket == NULL)
- {
- AfxMessageBox(_T("CloseSocket function not in DMT.dll !!"));
- return FALSE;
- }
- // Read Select
- ReadSelect = (int (WINAPI *)(int, int))GetProcAddress(hDMTDll, "ReadSelect");
- if (ReadSelect == NULL)
- {
- AfxMessageBox(_T("ReadSelect function not in DMT.dll !!"));
- return FALSE;
- }
- // Get Socket Error Message Function
- GetLastSocketErr = (int (WINAPI *)())GetProcAddress(hDMTDll, "GetLastSocketErr");
- if (GetLastSocketErr == NULL)
- {
- AfxMessageBox(_T("GetLastSocketErr function not in DMT.dll !!"));
- return FALSE;
- }
- // Clear Socket Error Message Function
- ResetSocketErr = (void (WINAPI *)())GetProcAddress(hDMTDll, "ResetSocketErr");
- if (ResetSocketErr == NULL)
- {
- AfxMessageBox(_T("ResetSocketErr function not in DMT.dll !!"));
- return FALSE;
- }
- // Request Modbus Data
- RequestData = (int (WINAPI *)(int, int, int, int, const unsigned char *,int))GetProcAddress(hDMTDll, "RequestData");
- if (RequestData == NULL)
- {
- AfxMessageBox(_T("RequestData function not in DMT.dll !!"));
- return FALSE;
- }
- // Response Modbus Data
- ResponseData = (int (WINAPI *)(int, int, int *, int *, unsigned char *))GetProcAddress(hDMTDll, "ResponseData");
- if (ResponseData == NULL)
- {
- AfxMessageBox(_T("ResponseData function not in DMT.dll !!"));
- return FALSE;
- }
- return TRUE;
- }
- #endif