You can only use a single Ext.MessageBox at a time.

本文讨论了 Ext.MessageBox 的使用限制,即同一时间只能使用一个对话框。如果尝试同时弹出两个对话框,则第一个将被第二个替换。因此,在某些情况下,需要检查是否存在活动的对话框,以避免意外覆盖正在显示的消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You can only use a single Ext.MessageBox at a time. If you try to pop
up two boxes at the same time, the first will be replaced by the second. So
in some cases, you'll want to check for the presence of an existing dialog
in case you inadvertently overwrite the message it is presenting.

我做了一个宠物智能投喂系统,现在我有一个stm32f103c6单片机外接8MHz的晶振,其PA1连作为RXD,PA2作为TXD,PB0、PB1连接了发光二极管的负极,发光二极管的正极接的电源,发光二极管用来模拟电机转动状态,在收到喂食的指令后PB0先亮两秒,PB1先不亮,然后在PB1亮两秒PB0熄灭,最后一起闪烁两秒表示喂食已完成,我创建了一个mfc程序(PCMFCDLG),添加了5个Combo Box控件分别用来选择端口号(控件类,m_cbPort)、波特率(控件类,m_cbBaud)、校验位(控件类,m_cbParity)、数据位(控件类,m_cbDate)以及停止位(控件类,m_cbStop),4个按钮控件分别用来打开串口连接stm32单片机、关闭串口、立即投喂、定时投喂,3个Edit control控件(value类,m_strTime1/2/3)用来定时3个时间点实现定时投喂,最后还有一个List Box(控件类,m_listStatus)用来显示执行状态,在PC机与单片机没有建立连接的时候除了连接按钮,其他按钮都不能点击,在定时按钮没有按下的时候edit control控件不能输入,在单片机执行完相应操作后,会返还给PC机信息,然后显示在list box里面如mfc界面点击立即投喂,单片机执行完操作后返回给pc端mfc界面一个标志,告诉pc端操作已完成,然后在mfc界面的list里面显示对应操作已完成。 /* Module : SerialPort.h Purpose: Interface for an C++ wrapper class for serial ports Copyright (c) 1999 - 2015 by PJ Naughter. All rights reserved. Copyright / Usage Details: You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) when your product is released in binary form. You are allowed to modify the source code in any way you want except you cannot modify the copyright details at the top of each module. If you want to distribute source code with your application, then you are only allowed to distribute versions released by the author. This is to maintain a single distribution point for the source code. */ // Macros / Structs etc #pragma once #ifndef __SERIALPORT_H__ #define __SERIALPORT_H__ #ifndef CSERIALPORT_EXT_CLASS #define CSERIALPORT_EXT_CLASS #endif //#ifndef CSERIALPORT_EXT_CLASS #ifndef _Out_writes_bytes_ #define _Out_writes_bytes_(X) #endif //#ifndef _Out_writes_bytes_ #ifndef __out_data_source #define __out_data_source(X) #endif //#ifndef __out_data_source #ifndef _Out_writes_bytes_to_opt_ #define _Out_writes_bytes_to_opt_(X,Y) #endif //#ifndef _Out_writes_bytes_to_opt_ #ifndef _Out_writes_bytes_opt_ #define _Out_writes_bytes_opt_(X) #endif //#ifndef _Out_writes_bytes_opt_ #ifndef _In_reads_bytes_opt_ #define _In_reads_bytes_opt_(X) #endif //#ifndef _In_reads_bytes_opt_ #ifndef _In_ #define _In_ #endif //#ifndef _In_ #ifndef _In_z_ #define _In_z_ #endif //#ifndef _In_z_ #ifndef _Inout_opt_ #define _Inout_opt_ #endif //#ifndef _Inout_opt_ #ifndef _Out_opt_ #define _Out_opt_ #endif //#ifndef _Out_opt_ #ifndef _Out_ #define _Out_ #endif //#ifndef _Out_ #ifndef _Inout_ #define _Inout_ #endif //#ifndef _Inout_ #ifndef _In_opt_ #define _In_opt_ #endif //#ifndef _In_opt_ // Includes /// #include <sal.h> #ifndef CSERIALPORT_MFC_EXTENSTIONS #include <exception> #include <string> #endif //#ifndef CSERIALPORT_MFC_EXTENSTIONS /// Classes /// #ifdef CSERIALPORT_MFC_EXTENSIONS class CSERIALPORT_EXT_CLASS CSerialException : public CException #else class CSERIALPORT_EXT_CLASS CSerialException : public std::exception #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS { public: //Constructors / Destructors CSerialException(DWORD dwError); //Methods #ifdef CSERIALPORT_MFC_EXTENSIONS #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif //#ifdef _DEBUG #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS #if _MSC_VER >= 1700 virtual BOOL GetErrorMessage(_Out_z_cap_(nMaxError) LPTSTR lpszError, _In_ UINT nMaxError, _Out_opt_ PUINT pnHelpContext = NULL); #else virtual BOOL GetErrorMessage(__out_ecount_z(nMaxError) LPTSTR lpszError, __in UINT nMaxError, __out_opt PUINT pnHelpContext = NULL); #endif #ifdef CSERIALPORT_MFC_EXTENSIONS CString GetErrorMessage(); #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS //Data members DWORD m_dwError; }; class CSERIALPORT_EXT_CLASS CSerialPort { public: //Enums enum FlowControl { NoFlowControl, CtsRtsFlowControl, CtsDtrFlowControl, DsrRtsFlowControl, DsrDtrFlowControl, XonXoffFlowControl }; enum Parity { NoParity = 0, OddParity = 1, EvenParity = 2, MarkParity = 3, SpaceParity = 4 }; enum StopBits { OneStopBit, OnePointFiveStopBits, TwoStopBits }; //Constructors / Destructors CSerialPort(); virtual ~CSerialPort(); //General Methods void Open(_In_ int nPort, _In_ DWORD dwBaud = 9600, _In_ Parity parity = NoParity, _In_ BYTE DataBits = 8, _In_ StopBits stopBits = OneStopBit, _In_ FlowControl fc = NoFlowControl, _In_ BOOL bOverlapped = FALSE); void Open(_In_z_ LPCTSTR pszPort, _In_ DWORD dwBaud = 9600, _In_ Parity parity = NoParity, _In_ BYTE DataBits = 8, _In_ StopBits stopBits = OneStopBit, _In_ FlowControl fc = NoFlowControl, _In_ BOOL bOverlapped = FALSE); void Close(); void Attach(_In_ HANDLE hComm); HANDLE Detach(); operator HANDLE() const { return m_hComm; }; BOOL IsOpen() const { return m_hComm != INVALID_HANDLE_VALUE; }; #ifdef CSERIALPORT_MFC_EXTENSIONS #ifdef _DEBUG void Dump(_In_ CDumpContext& dc) const; #endif //#ifdef _DEBUG #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS //Reading / Writing Methods void Read(_Out_writes_bytes_(dwNumberOfBytesToRead) __out_data_source(FILE) void* lpBuffer, _In_ DWORD dwNumberOfBytesToRead); void Read(_Out_writes_bytes_to_opt_(dwNumberOfBytesToRead, *lpNumberOfBytesRead) __out_data_source(FILE) void* lpBuffer, _In_ DWORD dwNumberOfBytesToRead, _In_ OVERLAPPED& overlapped, _Inout_opt_ DWORD* lpNumberOfBytesRead = NULL); void ReadEx(_Out_writes_bytes_opt_(dwNumberOfBytesToRead) __out_data_source(FILE) LPVOID lpBuffer, _In_ DWORD dwNumberOfBytesToRead, _Inout_ LPOVERLAPPED lpOverlapped, _In_ LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine); DWORD Write(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) const void* lpBuffer, _In_ DWORD dwNumberOfBytesToWrite); void Write(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) const void* lpBuffer, _In_ DWORD dwNumberOfBytesToWrite, _In_ OVERLAPPED& overlapped, _Out_opt_ DWORD* lpNumberOfBytesWritten = NULL); void WriteEx(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) LPCVOID lpBuffer, _In_ DWORD dwNumberOfBytesToWrite, _Inout_ LPOVERLAPPED lpOverlapped, _In_ LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine); void TransmitChar(_In_ char cChar); DWORD GetOverlappedResult(_In_ OVERLAPPED& overlapped, _Out_ DWORD& dwBytesTransferred, _In_ BOOL bWait); void CancelIo(); DWORD BytesWaiting(); DWORD BytesPending(); //Configuration Methods void GetConfig(_In_ COMMCONFIG& config); static void GetDefaultConfig(_In_ int nPort, _Out_ COMMCONFIG& config); static void GetDefaultConfig(_In_z_ LPCTSTR pszPort, _Out_ COMMCONFIG& config); void SetConfig(_In_ COMMCONFIG& Config); static void SetDefaultConfig(_In_ int nPort, _In_ COMMCONFIG& config); static void SetDefaultConfig(_In_z_ LPCTSTR pszPort, _In_ COMMCONFIG& config); //Misc RS232 Methods void ClearBreak(); void SetBreak(); void ClearError(_Out_ DWORD& dwErrors); void GetStatus(_Out_ COMSTAT& stat); void GetState(_Out_ DCB& dcb); void SetState(_In_ DCB& dcb); void Escape(_In_ DWORD dwFunc); void ClearDTR(); void ClearRTS(); void SetDTR(); void SetRTS(); void SetXOFF(); void SetXON(); void GetProperties(_Inout_ COMMPROP& properties); void GetModemStatus(_Out_ DWORD& dwModemStatus); //Timeouts void SetTimeouts(_In_ COMMTIMEOUTS& timeouts); void GetTimeouts(_Out_ COMMTIMEOUTS& timeouts); void Set0Timeout(); void Set0WriteTimeout(); void Set0ReadTimeout(); //Event Methods void SetMask(_In_ DWORD dwMask); void GetMask(_Out_ DWORD& dwMask); void WaitEvent(_Inout_ DWORD& dwMask); BOOL WaitEvent(_Inout_ DWORD& dwMask, _Inout_ OVERLAPPED& overlapped); //Queue Methods void Flush(); void Purge(_In_ DWORD dwFlags); void TerminateOutstandingWrites(); void TerminateOutstandingReads(); void ClearWriteBuffer(); void ClearReadBuffer(); void Setup(_In_ DWORD dwInQueue, _In_ DWORD dwOutQueue); //Static methods static void ThrowSerialException(_In_ DWORD dwError = 0); protected: //Member variables HANDLE m_hComm; //Handle to the comms port }; #endif //#ifndef __SERIALPORT_H__ /* Module : SerialPort.cpp Purpose: Implementation for an C++ wrapper class for serial ports Created: PJN / 31-05-1999 History: PJN / 03-06-1999 1. Fixed problem with code using CancelIo which does not exist on 95. 2. Fixed leaks which can occur in sample app when an exception is thrown PJN / 16-06-1999 1. Fixed a bug whereby CString::ReleaseBuffer was not being called in CSerialException::GetErrorMessage PJN / 29-09-1999 1. Fixed a simple copy and paste bug in CSerialPort::SetDTR PJN / 08-05-2000 1. Fixed an unreferrenced variable in CSerialPort::GetOverlappedResult in VC 6 PJN / 10-12-2000 1. Made class destructor virtual PJN / 15-01-2001 1. Attach method now also allows you to specify whether the serial port is being attached to in overlapped mode 2. Removed some ASSERTs which were unnecessary in some of the functions 3. Updated the Read method which uses OVERLAPPED IO to also return the bytes read. This allows calls to WriteFile with a zeroed overlapped structure (This is required when dealing with TAPI and serial communications) 4. Now includes copyright message in the source code and documentation. PJN / 24-03-2001 1. Added a BytesWaiting method PJN / 04-04-2001 1. Provided an overriden version of BytesWaiting which specifies a timeout PJN / 23-04-2001 1. Fixed a memory leak in DataWaiting method PJN / 01-05-2002 1. Fixed a problem in Open method which was failing to initialize the DCB structure incorrectly, when calling GetState. Thanks to Ben Newson for this fix. PJN / 29-05-2002 1. Fixed an problem where the GetProcAddress for CancelIO was using the wrong calling convention PJN / 07-08-2002 1. Changed the declaration of CSerialPort::WaitEvent to be consistent with the rest of the methods in CSerialPort which can operate in "OVERLAPPED" mode. A note about the usage of this: If the method succeeds then the overlapped operation has completed synchronously and there is no need to do a WaitForSingle/MultipleObjects. If any other unexpected error occurs then a CSerialException will be thrown. See the implementation of the CSerialPort::DataWaiting which has been rewritten to use this new design pattern. Thanks to Serhiy Pavlov for spotting this inconsistency. PJN / 20-09-2002 1. Addition of an additional ASSERT in the internal _OnCompletion function. 2. Addition of an optional out parameter to the Write method which operates in overlapped mode. Thanks to Kevin Pinkerton for this addition. PJN / 10-04-2006 1. Updated copyright details. 2. Addition of a CSERIALPORT_EXT_CLASS and CSERIALPORT_EXT_API macros which makes the class easier to use in an extension dll. 3. Removed derivation of CSerialPort from CObject as it was not really needed. 4. Fixed a number of level 4 warnings in the sample app. 5. Reworked the overlapped IO methods to expose the LPOVERLAPPED structure to client code. 6. Updated the documentation to use the same style as the web site. 7. Did a spell check of the HTML documentation. 8. Updated the documentation on possible blocking in Read/Ex function. Thanks to D Kerrison for reporting this issue. 9. Fixed a minor issue in the sample app when the code is compiled using /Wp64 PJN / 02-06-2006 1. Removed the bOverlapped as a member variable from the class. There was no real need for this setting, since the SDK functions will perform their own checking of how overlapped operations should 2. Fixed a bug in GetOverlappedResult where the code incorrectly checking against the error ERROR_IO_PENDING instead of ERROR_IO_INCOMPLETE. Thanks to Sasho Darmonski for reporting this bug. 3. Reviewed all TRACE statements for correctness. PJN / 05-06-2006 1. Fixed an issue with the creation of the internal event object. It was incorrectly being created as an auto-reset event object instead of a manual reset event object. Thanks to Sasho Darmonski for reporting this issue. PJN / 24-06-2006 1. Fixed some typos in the history list. Thanks to Simon Wong for reporting this. 2. Made the class which handles the construction of function pointers at runtime a member variable of CSerialPort 3. Made AfxThrowSerialPortException part of the CSerialPort class. Thanks to Simon Wong for reporting this. 4. Removed the unnecessary CSerialException destructor. Thanks to Simon Wong for reporting this. 5. Fixed a minor error in the TRACE text in CSerialPort::SetDefaultConfig. Again thanks to Simon Wong for reporting this. 6. Code now uses new C++ style casts rather than old style C casts where necessary. Again thanks to Simon Wong for reporting this. 7. CSerialException::GetErrorMessage now uses the strsafe functions. This does mean that the code now requires the Platform SDK if compiled using VC 6. PJN / 25-06-2006 1. Combined the functionality of the CSerialPortData class into the main CSerialPort class. 2. Renamed AfxThrowSerialPortException to ThrowSerialPortException and made the method public. PJN / 05-11-2006 1. Minor update to stdafx.h of sample app to avoid compiler warnings in VC 2005. 2. Reverted the use of the strsafe.h header file. Instead now the code uses the VC 2005 Safe CRT and if this is not available, then we fail back to the standard CRT. PJN / 25-01-2007 1. Minor update to remove strsafe.h from stdafx.h of the sample app. 2. Updated copyright details. PJN / 24-12-2007 1. CSerialException::GetErrorMessage now uses the FORMAT_MESSAGE_IGNORE_INSERTS flag. For more information please see Raymond Chen's blog at http://blogs.msdn.com/oldnewthing/archive/2007/11/28/6564257.aspx. Thanks to Alexey Kuznetsov for reporting this issue. 2. Simplified the code in CSerialException::GetErrorMessage somewhat. 3. Optimized the CSerialException constructor code. 4. Code now uses newer C++ style casts instead of C style casts. 5. Reviewed and updated all the TRACE logging in the module 6. Replaced all calls to ZeroMemory with memset PJN / 30-12-2007 1. Updated the sample app to clean compile on VC 2008 2. CSerialException::GetErrorMessage now uses Checked::tcsncpy_s if compiled using VC 2005 or later. PJN / 18-05-2008 1. Updated copyright details. 2. Changed the actual values for Parity enum so that they are consistent with the Parity define values in the Windows SDK header file WinBase.h. This avoids the potential issue where you use the CSerialPort enum parity values in a call to the raw Win32 API calls. Thanks to Robert Krueger for reporting this issue. PJN / 21-06-2008 1. Code now compiles cleanly using Code Analysis (/analyze) 2. Updated code to compile correctly using _ATL_CSTRING_EXPLICIT_CONSTRUCTORS define 3. The code now only supports VC 2005 or later. 4. CSerialPort::Read, Write, GetOverlappedResult & WaitEvent now throw an exception irrespective of whether the last error is ERROR_IO_PENDING or not 5. Replaced all calls to ZeroMemory with memset PJN / 04-07-2008 1. Provided a version of the Open method which takes a string instead of a numeric port number value. This allows the code to support some virtual serial port packages which do not use device names of the form "COM%d". Thanks to David Balazic for suggesting this addition. PJN / 25-01-2012 1. Updated copyright details. 2. Updated sample app and class to compile cleanly on VC 2010 and later. PJN / 28-02-2015 1. Updated sample project settings to more modern default values. 2. Updated copyright details. 3. Reworked the CSerialPort and CSerialPortException classes to optionally compile without MFC. By default the classes now use STL classes and idioms but if you define CSERIALPORT_MFC_EXTENSTIONS the classes will revert back to the MFC behaviour. 4. Remove logic to use GetProcAddress to access CancelIO functionality. 5. Updated the code to clean compile on VC 2013 6. Added SAL annotations to all the code 7. Addition of a GetDefaultConfig method which takes a string 8. Addition of a SetDefaultConfig method which takes a string PJN / 26-04-2015 1. Removed unnecessary inclusion of WinError.h 2. Removed the CSerialPort::DataWaiting method as it depends on the port being open in overlapped mode. Instead client code can simply call CSerialPort::WaitEvent directly themselves. Removing this method also means that the CSerialPort::m_hEvent handle has not also been removed. 3. The CSerialPort::WriteEx method has been reworked to expose all the parameters of the underlying WriteFileEx API. This rework also fixes a memory leak in WriteEx which can sometimes occur. This reworks also means that the CSerialPort::_OnCompletion and CSerialPort::_OnCompletion methods have been removed. Thanks to Yufeng Huang for reporting this issue. 4. The CSerialPort::ReadEx method has been reworked to expose all the parameters of the underlying ReadFileEx API. This rework also fixes a memory leak in ReadEx which can sometimes occur. This reworks also means that the CSerialPort::_OnCompletion and CSerialPort::_OnCompletion methods have been removed. Thanks to Yufeng Huang for reporting this issue. Copyright (c) 1996 - 2015 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) All rights reserved. Copyright / Usage Details: You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) when your product is released in binary form. You are allowed to modify the source code in any way you want except you cannot modify the copyright details at the top of each module. If you want to distribute source code with your application, then you are only allowed to distribute versions released by the author. This is to maintain a single distribution point for the source code. */ // Includes #include "pch.h" #include "SerialPort.h" #ifndef __ATLBASE_H__ #pragma message("To avoid this message, please put atlbase.h in your pre compiled header (normally stdafx.h)") #include <atlbase.h> #endif //#ifndef __ATLBASE_H__ // Defines / #ifdef CSERIALPORT_MFC_EXTENSIONS #ifdef _DEBUG #define new DEBUG_NEW #endif //#ifdef _DEBUG #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS //Implementation /// #if _MSC_VER >= 1700 BOOL CSerialException::GetErrorMessage(_Out_z_cap_(nMaxError) LPTSTR lpszError, _In_ UINT nMaxError, _Out_opt_ PUINT pnHelpContext) #else BOOL CSerialException::GetErrorMessage(__out_ecount_z(nMaxError) LPTSTR lpszError, __in UINT nMaxError, __out_opt PUINT pnHelpContext) #endif { //Validate our parameters ATLASSERT(lpszError != NULL); if (pnHelpContext != NULL) *pnHelpContext = 0; //What will be the return value from this function (assume the worst) BOOL bSuccess = FALSE; LPTSTR lpBuffer; DWORD dwReturn = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, m_dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT), reinterpret_cast<LPTSTR>(&lpBuffer), 0, NULL); if (dwReturn == 0) *lpszError = _T('\0'); else { bSuccess = TRUE; Checked::tcsncpy_s(lpszError, nMaxError, lpBuffer, _TRUNCATE); LocalFree(lpBuffer); } return bSuccess; } #ifdef CSERIALPORT_MFC_EXTENSIONS CString CSerialException::GetErrorMessage() { CString rVal; LPTSTR pstrError = rVal.GetBuffer(4096); GetErrorMessage(pstrError, 4096, NULL); rVal.ReleaseBuffer(); return rVal; } #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS CSerialException::CSerialException(DWORD dwError) : m_dwError(dwError) { } #ifdef CSERIALPORT_MFC_EXTENSIONS #ifdef _DEBUG void CSerialException::Dump(_In_ CDumpContext& dc) const { CObject::Dump(dc); dc << _T("m_dwError = ") << m_dwError << _T("\n"); } #endif //#ifdef _DEBUG #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS CSerialPort::CSerialPort() : m_hComm(INVALID_HANDLE_VALUE) { } CSerialPort::~CSerialPort() { Close(); } void CSerialPort::ThrowSerialException(_In_ DWORD dwError) { if (dwError == 0) dwError = ::GetLastError(); ATLTRACE(_T("Warning: throwing CSerialException for error %d\n"), dwError); #ifdef CSERIALPORT_MFC_EXTENSIONS CSerialException* pException = new CSerialException(dwError); THROW(pException); #else CSerialException e(dwError); throw e; #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS } #ifdef CSERIALPORT_MFC_EXTENSIONS #ifdef _DEBUG void CSerialPort::Dump(CDumpContext& dc) const { dc << _T("m_hComm = ") << m_hComm << _T("\n"); } #endif //#ifdef _DEBUG #endif //#ifdef CSERIALPORT_MFC_EXTENSIONS void CSerialPort::Open(_In_z_ LPCTSTR pszPort, _In_ DWORD dwBaud, _In_ Parity parity, _In_ BYTE DataBits, _In_ StopBits stopBits, _In_ FlowControl fc, _In_ BOOL bOverlapped) { Close(); //In case we are already open //Call CreateFile to open the comms port m_hComm = CreateFile(pszPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, bOverlapped ? (FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED) : 0, NULL); if (m_hComm == INVALID_HANDLE_VALUE) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::Open, Failed to open the comms port, Error:%u\n"), dwLastError); //ThrowSerialException(dwLastError); return; } //Get the current state prior to changing it DCB dcb; dcb.DCBlength = sizeof(DCB); GetState(dcb); //Setup the baud rate dcb.BaudRate = dwBaud; //Setup the Parity switch (parity) { case EvenParity: { dcb.Parity = EVENPARITY; break; } case MarkParity: { dcb.Parity = MARKPARITY; break; } case NoParity: { dcb.Parity = NOPARITY; break; } case OddParity: { dcb.Parity = ODDPARITY; break; } case SpaceParity: { dcb.Parity = SPACEPARITY; break; } default: { ATLASSERT(FALSE); break; } } //Setup the data bits dcb.ByteSize = DataBits; //Setup the stop bits switch (stopBits) { case OneStopBit: { dcb.StopBits = ONESTOPBIT; break; } case OnePointFiveStopBits: { dcb.StopBits = ONE5STOPBITS; break; } case TwoStopBits: { dcb.StopBits = TWOSTOPBITS; break; } default: { ATLASSERT(FALSE); break; } } //Setup the flow control dcb.fDsrSensitivity = FALSE; switch (fc) { case NoFlowControl: { dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fOutX = FALSE; dcb.fInX = FALSE; break; } case CtsRtsFlowControl: { dcb.fOutxCtsFlow = TRUE; dcb.fOutxDsrFlow = FALSE; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; dcb.fOutX = FALSE; dcb.fInX = FALSE; break; } case CtsDtrFlowControl: { dcb.fOutxCtsFlow = TRUE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; dcb.fOutX = FALSE; dcb.fInX = FALSE; break; } case DsrRtsFlowControl: { dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = TRUE; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; dcb.fOutX = FALSE; dcb.fInX = FALSE; break; } case DsrDtrFlowControl: { dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = TRUE; dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; dcb.fOutX = FALSE; dcb.fInX = FALSE; break; } case XonXoffFlowControl: { dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fOutX = TRUE; dcb.fInX = TRUE; dcb.XonChar = 0x11; dcb.XoffChar = 0x13; dcb.XoffLim = 100; dcb.XonLim = 100; break; } default: { ATLASSERT(FALSE); break; } } //Now that we have all the settings in place, make the changes SetState(dcb); } void CSerialPort::Open(_In_ int nPort, _In_ DWORD dwBaud, _In_ Parity parity, _In_ BYTE DataBits, _In_ StopBits stopBits, _In_ FlowControl fc, _In_ BOOL bOverlapped) { //Form the string version of the port number TCHAR szPort[12]; _stprintf_s(szPort, sizeof(szPort) / sizeof(TCHAR), _T("\\\\.\\COM%d"), nPort); //Delegate the work to the other version of Open Open(szPort, dwBaud, parity, DataBits, stopBits, fc, bOverlapped); } void CSerialPort::Close() { if (IsOpen()) { //Close down the comms port CloseHandle(m_hComm); m_hComm = INVALID_HANDLE_VALUE; } } void CSerialPort::Attach(_In_ HANDLE hComm) { Close(); //Validate our parameters, now that the port has been closed ATLASSERT(m_hComm == INVALID_HANDLE_VALUE); m_hComm = hComm; } HANDLE CSerialPort::Detach() { //What will be the return value from this function HANDLE hComm = m_hComm; m_hComm = INVALID_HANDLE_VALUE; return hComm; } void CSerialPort::Read(_Out_writes_bytes_(dwNumberOfBytesToRead) __out_data_source(FILE) void* lpBuffer, _In_ DWORD dwNumberOfBytesToRead) { //Validate our parameters ATLASSERT(IsOpen()); DWORD dwBytesRead = 0; if (!ReadFile(m_hComm, lpBuffer, dwNumberOfBytesToRead, &dwBytesRead, NULL)) { DWORD dwLastError = GetLastError(); if (ERROR_IO_PENDING != dwLastError) ATLTRACE(_T("CSerialPort::Read, Failed in call to ReadFile, Error:%u\n"), dwLastError); // ThrowSerialException(dwLastError); } } void CSerialPort::Read(_Out_writes_bytes_to_opt_(dwNumberOfBytesToRead, *lpNumberOfBytesRead) __out_data_source(FILE) void* lpBuffer, _In_ DWORD dwNumberOfBytesToRead, _In_ OVERLAPPED& overlapped, _Inout_opt_ DWORD* lpNumberOfBytesRead) { //Validate our parameters ATLASSERT(IsOpen()); *lpNumberOfBytesRead = 0; if (overlapped.hEvent) ResetEvent(overlapped.hEvent); if (!ReadFile(m_hComm, lpBuffer, dwNumberOfBytesToRead, lpNumberOfBytesRead, &overlapped)) { DWORD dwLastError = GetLastError(); if (ERROR_IO_PENDING != dwLastError) { ATLTRACE(_T("CSerialPort::Read, Failed in call to ReadFile, Error:%u\n"), dwLastError); } // ThrowSerialException(dwLastError); } } void CSerialPort::ReadEx(_Out_writes_bytes_opt_(dwNumberOfBytesToRead) __out_data_source(FILE) LPVOID lpBuffer, _In_ DWORD dwNumberOfBytesToRead, _Inout_ LPOVERLAPPED lpOverlapped, _In_ LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) { //Validate our parameters ATLASSERT(IsOpen()); if (!ReadFileEx(m_hComm, lpBuffer, dwNumberOfBytesToRead, lpOverlapped, lpCompletionRoutine)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::ReadEx, Failed in call to ReadFileEx, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } DWORD CSerialPort::Write(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) const void* lpBuffer, _In_ DWORD dwNumberOfBytesToWrite) { //Validate our parameters ATLASSERT(IsOpen()); DWORD dwBytesWritten = 0; if (!WriteFile(m_hComm, lpBuffer, dwNumberOfBytesToWrite, &dwBytesWritten, NULL)) { DWORD dwLastError = GetLastError(); if (ERROR_IO_PENDING != dwLastError) ATLTRACE(_T("CSerialPort::Write, Failed in call to WriteFile, Error:%u\n"), dwLastError); //ThrowSerialException(dwLastError); } return dwBytesWritten; } void CSerialPort::Write(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) const void* lpBuffer, _In_ DWORD dwNumberOfBytesToWrite, _In_ OVERLAPPED& overlapped, _Out_opt_ DWORD* lpNumberOfBytesWritten) { //Validate our parameters ATLASSERT(IsOpen()); if (!WriteFile(m_hComm, lpBuffer, dwNumberOfBytesToWrite, lpNumberOfBytesWritten, &overlapped)) { DWORD dwLastError = GetLastError(); if (ERROR_IO_PENDING != dwLastError) { ATLTRACE(_T("CSerialPort::Write, Failed in call to WriteFile, Error:%u\n"), dwLastError); } // ThrowSerialException(dwLastError); } } void CSerialPort::WriteEx(_In_reads_bytes_opt_(dwNumberOfBytesToWrite) LPCVOID lpBuffer, _In_ DWORD dwNumberOfBytesToWrite, _Inout_ LPOVERLAPPED lpOverlapped, _In_ LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) { //Validate our parameters ATLASSERT(IsOpen()); if (!WriteFileEx(m_hComm, lpBuffer, dwNumberOfBytesToWrite, lpOverlapped, lpCompletionRoutine)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::WriteEx, Failed in call to WriteFileEx, Error:%u\n"), dwLastError); //ThrowSerialException(dwLastError); } } DWORD CSerialPort::GetOverlappedResult(_In_ OVERLAPPED& overlapped, _Out_ DWORD& dwBytesTransferred, _In_ BOOL bWait) { //Validate our parameters DWORD dwLastError = 0; ATLASSERT(IsOpen()); dwBytesTransferred = 0; if (!::GetOverlappedResult(m_hComm, &overlapped, &dwBytesTransferred, bWait)) { dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::GetOverlappedResult, Failed in call to GetOverlappedResult, Error:%u\n"), dwLastError); //ThrowSerialException(dwLastError); } return dwLastError; } void CSerialPort::CancelIo() { //Validate our parameters ATLASSERT(IsOpen()); if (!::CancelIo(m_hComm)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("Failed in call to CancelIO, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } DWORD CSerialPort::BytesWaiting() { //Validate our parameters //ATLASSERT(IsOpen()); if (!IsOpen()) return 0; //Check to see how many characters are unread COMSTAT stat; GetStatus(stat); return stat.cbInQue; } DWORD CSerialPort::BytesPending() { if (!IsOpen()) return 0; //Check to see how many characters are unwrite COMSTAT stat; GetStatus(stat); return stat.cbOutQue; } void CSerialPort::TransmitChar(_In_ char cChar) { //Validate our parameters ATLASSERT(IsOpen()); if (!TransmitCommChar(m_hComm, cChar)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::TransmitChar, Failed in call to TransmitCommChar, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::GetConfig(_In_ COMMCONFIG& config) { //Validate our parameters ATLASSERT(IsOpen()); DWORD dwSize = sizeof(COMMCONFIG); if (!GetCommConfig(m_hComm, &config, &dwSize)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::GetConfig, Failed in call to GetCommConfig, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::SetConfig(_In_ COMMCONFIG& config) { //Validate our parameters ATLASSERT(IsOpen()); DWORD dwSize = sizeof(COMMCONFIG); if (!SetCommConfig(m_hComm, &config, dwSize)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::SetConfig, Failed in call to SetCommConfig, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::SetBreak() { //Validate our parameters ATLASSERT(IsOpen()); if (!SetCommBreak(m_hComm)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::SetBreak, Failed in call to SetCommBreak, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::ClearBreak() { //Validate our parameters ATLASSERT(IsOpen()); if (!ClearCommBreak(m_hComm)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::ClearBreak, Failed in call to SetCommBreak, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::ClearError(_Out_ DWORD& dwErrors) { //Validate our parameters ATLASSERT(IsOpen()); if (!ClearCommError(m_hComm, &dwErrors, NULL)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::ClearError, Failed in call to ClearCommError, Error:%u\n"), dwLastError); //ThrowSerialException(dwLastError); } } void CSerialPort::GetDefaultConfig(_In_ int nPort, _Out_ COMMCONFIG& config) { //Create the device name as a string TCHAR szPort[12]; _stprintf_s(szPort, sizeof(szPort) / sizeof(TCHAR), _T("COM%d"), nPort); return GetDefaultConfig(szPort, config); } void CSerialPort::GetDefaultConfig(_In_z_ LPCTSTR pszPort, _Out_ COMMCONFIG& config) { DWORD dwSize = sizeof(COMMCONFIG); if (!GetDefaultCommConfig(pszPort, &config, &dwSize)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::GetDefaultConfig, Failed in call to GetDefaultCommConfig, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::SetDefaultConfig(_In_ int nPort, _In_ COMMCONFIG& config) { //Create the device name as a string TCHAR szPort[12]; _stprintf_s(szPort, sizeof(szPort) / sizeof(TCHAR), _T("COM%d"), nPort); return SetDefaultConfig(szPort, config); } void CSerialPort::SetDefaultConfig(_In_z_ LPCTSTR pszPort, _In_ COMMCONFIG& config) { DWORD dwSize = sizeof(COMMCONFIG); if (!SetDefaultCommConfig(pszPort, &config, dwSize)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::SetDefaultConfig, Failed in call to SetDefaultCommConfig, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::GetStatus(_Out_ COMSTAT& stat) { //Validate our parameters ATLASSERT(IsOpen()); DWORD dwErrors; if (!ClearCommError(m_hComm, &dwErrors, &stat)) { DWORD dwLastError = GetLastError(); stat.cbInQue = 0; ATLTRACE(_T("CSerialPort::GetStatus, Failed in call to ClearCommError, Error:%u\n"), dwLastError); // ThrowSerialException(dwLastError); } } void CSerialPort::GetState(_Out_ DCB& dcb) { //Validate our parameters ATLASSERT(IsOpen()); if (!GetCommState(m_hComm, &dcb)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::GetState, Failed in call to GetCommState, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::SetState(_In_ DCB& dcb) { //Validate our parameters ATLASSERT(IsOpen()); if (!SetCommState(m_hComm, &dcb)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::SetState, Failed in call to SetCommState, Error:%u\n"), dwLastError); // ThrowSerialException(dwLastError); } } void CSerialPort::Escape(_In_ DWORD dwFunc) { //Validate our parameters ATLASSERT(IsOpen()); if (!EscapeCommFunction(m_hComm, dwFunc)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::Escape, Failed in call to EscapeCommFunction, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::ClearDTR() { Escape(CLRDTR); } void CSerialPort::ClearRTS() { Escape(CLRRTS); } void CSerialPort::SetDTR() { Escape(SETDTR); } void CSerialPort::SetRTS() { Escape(SETRTS); } void CSerialPort::SetXOFF() { Escape(SETXOFF); } void CSerialPort::SetXON() { Escape(SETXON); } void CSerialPort::GetProperties(_Inout_ COMMPROP& properties) { //Validate our parameters ATLASSERT(IsOpen()); if (!GetCommProperties(m_hComm, &properties)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::GetProperties, Failed in call to GetCommProperties, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::GetModemStatus(_Out_ DWORD& dwModemStatus) { //Validate our parameters ATLASSERT(IsOpen()); if (!GetCommModemStatus(m_hComm, &dwModemStatus)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::GetModemStatus, Failed in call to GetCommModemStatus, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::SetMask(_In_ DWORD dwMask) { //Validate our parameters ATLASSERT(IsOpen()); if (!SetCommMask(m_hComm, dwMask)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::SetMask, Failed in call to SetCommMask, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::GetMask(_Out_ DWORD& dwMask) { //Validate our parameters ATLASSERT(IsOpen()); if (!GetCommMask(m_hComm, &dwMask)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::GetMask, Failed in call to GetCommMask, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::Flush() { //Validate our parameters ATLASSERT(IsOpen()); if (!FlushFileBuffers(m_hComm)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::Flush, Failed in call to FlushFileBuffers, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::Purge(_In_ DWORD dwFlags) { //Validate our parameters ATLASSERT(IsOpen()); if (!PurgeComm(m_hComm, dwFlags)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::Purge, Failed in call to PurgeComm, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::TerminateOutstandingWrites() { Purge(PURGE_TXABORT); } void CSerialPort::TerminateOutstandingReads() { Purge(PURGE_RXABORT); } void CSerialPort::ClearWriteBuffer() { Purge(PURGE_TXCLEAR); } void CSerialPort::ClearReadBuffer() { Purge(PURGE_RXCLEAR); } void CSerialPort::Setup(_In_ DWORD dwInQueue, _In_ DWORD dwOutQueue) { //Validate our parameters ATLASSERT(IsOpen()); if (!SetupComm(m_hComm, dwInQueue, dwOutQueue)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::Setup, Failed in call to SetupComm, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::SetTimeouts(_In_ COMMTIMEOUTS& timeouts) { //Validate our parameters ATLASSERT(IsOpen()); if (!SetCommTimeouts(m_hComm, &timeouts)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::SetTimeouts, Failed in call to SetCommTimeouts, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::GetTimeouts(_Out_ COMMTIMEOUTS& timeouts) { //Validate our parameters ATLASSERT(IsOpen()); if (!GetCommTimeouts(m_hComm, &timeouts)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::GetTimeouts, Failed in call to GetCommTimeouts, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } void CSerialPort::Set0Timeout() { COMMTIMEOUTS Timeouts; memset(&Timeouts, 0, sizeof(Timeouts)); Timeouts.ReadIntervalTimeout = MAXDWORD; SetTimeouts(Timeouts); } void CSerialPort::Set0WriteTimeout() { COMMTIMEOUTS Timeouts; GetTimeouts(Timeouts); Timeouts.WriteTotalTimeoutMultiplier = 0; Timeouts.WriteTotalTimeoutConstant = 0; SetTimeouts(Timeouts); } void CSerialPort::Set0ReadTimeout() { COMMTIMEOUTS Timeouts; GetTimeouts(Timeouts); Timeouts.ReadIntervalTimeout = MAXDWORD; Timeouts.ReadTotalTimeoutMultiplier = 0; Timeouts.ReadTotalTimeoutConstant = 0; SetTimeouts(Timeouts); } void CSerialPort::WaitEvent(_Inout_ DWORD& dwMask) { //Validate our parameters ATLASSERT(IsOpen()); if (!WaitCommEvent(m_hComm, &dwMask, NULL)) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::WaitEvent, Failed in call to WaitCommEvent, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } } BOOL CSerialPort::WaitEvent(_Inout_ DWORD& dwMask, _Inout_ OVERLAPPED& overlapped) { //Validate our parameters ATLASSERT(IsOpen()); ATLASSERT(overlapped.hEvent != NULL); BOOL bSuccess = WaitCommEvent(m_hComm, &dwMask, &overlapped); if (!bSuccess) { DWORD dwLastError = GetLastError(); ATLTRACE(_T("CSerialPort::WaitEvent, Failed in call to WaitCommEvent, Error:%u\n"), dwLastError); ThrowSerialException(dwLastError); } return bSuccess; } #pragma once #include "afxwin.h" // 自定义串口异常类 class CSerialException : public CException { public: DWORD m_dwError; CSerialException(DWORD dwError); }; // 串口类声明 class CSerialPort { public: enum Parity { None, Odd, Even }; enum StopBits { One = 1, OnePointFive = 2, Two = 3 }; CSerialPort(); virtual ~CSerialPort(); // 添加 virtual 关键字 BOOL Open(LPCTSTR lpszPort, DWORD dwBaudRate, Parity parity, BYTE byDataBits, StopBits stopBits); void Close(); BOOL IsOpen() const { return m_hComm != INVALID_HANDLE_VALUE; } DWORD Write(const void* lpBuf, DWORD dwCount); DWORD Read(void* lpBuf, DWORD dwCount); DWORD BytesWaiting(); void Set0Timeout(); private: HANDLE m_hComm; }; // CPCMFCDlg 对话框 class CPCMFCDlg : public CDialogEx { public: CPCMFCDlg(CWnd* pParent = nullptr); virtual ~CPCMFCDlg(); #ifdef AFX_DESIGN_TIME enum { IDD = IDD_PCMFC_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); virtual BOOL OnInitDialog(); protected: HICON m_hIcon; // 控件变量 CComboBox m_cbPort; CComboBox m_cbBaud; CComboBox m_cbParity; CComboBox m_cbDate; CComboBox m_cbStop; CListBox m_listStatus; // 数据变量 CString m_strTime1; CString m_strTime2; CString m_strTime3; // 状态变量 BOOL m_bConnected; BOOL m_bTimerActive; BOOL m_bThreadRunning; // 串口对象 CSerialPort m_SerialPort; HANDLE m_hThread; // 辅助函数 void UpdateControls(); UINT ReadThreadFunc(); static UINT ReadThread(LPVOID pParam); BOOL ValidateTimeFormat(const CString& strTime); // 消息处理 DECLARE_MESSAGE_MAP() afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnBnClickedBtnOpen(); afx_msg void OnBnClickedBtnClose(); afx_msg void OnBnClickedBtnFeedNow(); afx_msg void OnBnClickedBtnFeedTimer(); afx_msg LRESULT OnUpdateStatus(WPARAM wParam, LPARAM lParam); afx_msg void OnTimer(UINT_PTR nIDEvent); afx_msg void OnDestroy(); }; #include "pch.h" #include "PCMFC.h" #include "PCMFCDlg.h" #include "afxdialogex.h" #include <winbase.h> #include <tchar.h> #include <atlstr.h> #ifdef _DEBUG #define new DEBUG_NEW #endif #define FEED_COMMAND 0x01 #define COMPLETE_SIGNAL 0xFF #define WM_UPDATE_STATUS (WM_USER + 100) // CSerialException 实现 CSerialException::CSerialException(DWORD dwError) : m_dwError(dwError) {} // CSerialPort 成员函数实现 CSerialPort::CSerialPort() : m_hComm(INVALID_HANDLE_VALUE) {} CSerialPort::~CSerialPort() { if (IsOpen()) Close(); } BOOL CSerialPort::Open(LPCTSTR lpszPort, DWORD dwBaudRate, Parity parity, BYTE byDataBits, StopBits stopBits) { m_hComm = CreateFile(lpszPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (m_hComm == INVALID_HANDLE_VALUE) throw new CSerialException(GetLastError()); DCB dcb = { 0 }; dcb.DCBlength = sizeof(DCB); if (!GetCommState(m_hComm, &dcb)) throw new CSerialException(GetLastError()); dcb.BaudRate = dwBaudRate; dcb.ByteSize = byDataBits; switch (parity) { case None: dcb.Parity = NOPARITY; break; case Odd: dcb.Parity = ODDPARITY; break; case Even: dcb.Parity = EVENPARITY; break; } switch (stopBits) { case One: dcb.StopBits = ONESTOPBIT; break; case OnePointFive: dcb.StopBits = ONE5STOPBITS; break; case Two: dcb.StopBits = TWOSTOPBITS; break; } dcb.fBinary = TRUE; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fRtsControl = RTS_CONTROL_ENABLE; if (!SetCommState(m_hComm, &dcb)) throw new CSerialException(GetLastError()); // 设置超时 COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = 50; timeouts.ReadTotalTimeoutConstant = 50; timeouts.ReadTotalTimeoutMultiplier = 10; timeouts.WriteTotalTimeoutConstant = 50; timeouts.WriteTotalTimeoutMultiplier = 10; if (!SetCommTimeouts(m_hComm, &timeouts)) throw new CSerialException(GetLastError()); return TRUE; } void CSerialPort::Close() { if (m_hComm != INVALID_HANDLE_VALUE) { CloseHandle(m_hComm); m_hComm = INVALID_HANDLE_VALUE; } } DWORD CSerialPort::Write(const void* lpBuf, DWORD dwCount) { DWORD dwBytesWritten = 0; OVERLAPPED ov = { 0 }; ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!WriteFile(m_hComm, lpBuf, dwCount, &dwBytesWritten, &ov)) { if (GetLastError() == ERROR_IO_PENDING) { WaitForSingleObject(ov.hEvent, INFINITE); GetOverlappedResult(m_hComm, &ov, &dwBytesWritten, FALSE); } else { throw new CSerialException(GetLastError()); } } CloseHandle(ov.hEvent); return dwBytesWritten; } DWORD CSerialPort::Read(void* lpBuf, DWORD dwCount) { DWORD dwBytesRead = 0; OVERLAPPED ov = { 0 }; ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!ReadFile(m_hComm, lpBuf, dwCount, &dwBytesRead, &ov)) { if (GetLastError() == ERROR_IO_PENDING) { WaitForSingleObject(ov.hEvent, INFINITE); GetOverlappedResult(m_hComm, &ov, &dwBytesRead, FALSE); } else { throw new CSerialException(GetLastError()); } } CloseHandle(ov.hEvent); return dwBytesRead; } DWORD CSerialPort::BytesWaiting() { COMSTAT comStat; DWORD dwErrors; if (!ClearCommError(m_hComm, &dwErrors, &comStat)) throw new CSerialException(GetLastError()); return comStat.cbInQue; } void CSerialPort::Set0Timeout() { COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = MAXDWORD; timeouts.ReadTotalTimeoutConstant = 0; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; if (!SetCommTimeouts(m_hComm, &timeouts)) throw new CSerialException(GetLastError()); } // CPCMFCDlg 实现 CPCMFCDlg::CPCMFCDlg(CWnd* pParent) : CDialogEx(IDD_PCMFC_DIALOG, pParent) , m_strTime1(_T("08:00")) , m_strTime2(_T("12:00")) , m_strTime3(_T("18:00")) , m_bConnected(FALSE) , m_bTimerActive(FALSE) , m_bThreadRunning(FALSE) , m_hThread(NULL) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } CPCMFCDlg::~CPCMFCDlg() { if (m_hThread) { CloseHandle(m_hThread); } } void CPCMFCDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_COMBO_PORT, m_cbPort); DDX_Control(pDX, IDC_COMBO_BAUD, m_cbBaud); DDX_Control(pDX, IDC_COMBO_PARITY, m_cbParity); DDX_Control(pDX, IDC_COMBO_DATA, m_cbDate); DDX_Control(pDX, IDC_COMBO_STOP, m_cbStop); DDX_Control(pDX, IDC_LIST, m_listStatus); DDX_Text(pDX, IDC_EDIT_TIME1, m_strTime1); DDX_Text(pDX, IDC_EDIT_TIME2, m_strTime2); DDX_Text(pDX, IDC_EDIT_TIME3, m_strTime3); } BEGIN_MESSAGE_MAP(CPCMFCDlg, CDialogEx) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_OPEN, &CPCMFCDlg::OnBnClickedBtnOpen) ON_BN_CLICKED(IDC_BUTTON_CLOSE, &CPCMFCDlg::OnBnClickedBtnClose) ON_BN_CLICKED(IDC_BUTTON_NOWFEED, &CPCMFCDlg::OnBnClickedBtnFeedNow) ON_BN_CLICKED(IDC_BUTTON_TIMEFEED, &CPCMFCDlg::OnBnClickedBtnFeedTimer) ON_MESSAGE(WM_UPDATE_STATUS, &CPCMFCDlg::OnUpdateStatus) ON_WM_TIMER() ON_WM_DESTROY() END_MESSAGE_MAP() BOOL CPCMFCDlg::OnInitDialog() { CDialogEx::OnInitDialog(); SetIcon(m_hIcon, TRUE); SetIcon(m_hIcon, FALSE); // 初始化串口选择下拉框 for (int i = 1; i <= 16; i++) { CString port; port.Format(_T("COM%d"), i); m_cbPort.AddString(port); } m_cbPort.SetCurSel(0); // 初始化波特率下拉框 CString baudRates[] = { _T("9600"), _T("19200"), _T("38400"), _T("57600"), _T("115200") }; for (auto& baud : baudRates) { m_cbBaud.AddString(baud); } m_cbBaud.SetCurSel(0); // 初始化校验位下拉框 CString parityOptions[] = { _T("None"), _T("Odd"), _T("Even") }; for (auto& parity : parityOptions) { m_cbParity.AddString(parity); } m_cbParity.SetCurSel(0); // 初始化数据位下拉框 CString dataBits[] = { _T("5"), _T("6"), _T("7"), _T("8") }; for (auto& bits : dataBits) { m_cbDate.AddString(bits); } m_cbDate.SetCurSel(3); // 初始化停止位下拉框 CString stopBits[] = { _T("1"), _T("1.5"), _T("2") }; for (auto& stop : stopBits) { m_cbStop.AddString(stop); } m_cbStop.SetCurSel(0); // 初始禁用控件 UpdateControls(); return TRUE; } void CPCMFCDlg::UpdateControls() { BOOL bConnected = m_SerialPort.IsOpen(); GetDlgItem(IDC_BUTTON_OPEN)->EnableWindow(!bConnected); GetDlgItem(IDC_BUTTON_CLOSE)->EnableWindow(bConnected); GetDlgItem(IDC_BUTTON_NOWFEED)->EnableWindow(bConnected); GetDlgItem(IDC_BUTTON_TIMEFEED)->EnableWindow(bConnected); BOOL bTimerActive = m_bTimerActive; GetDlgItem(IDC_EDIT_TIME1)->EnableWindow(bConnected && !bTimerActive); GetDlgItem(IDC_EDIT_TIME2)->EnableWindow(bConnected && !bTimerActive); GetDlgItem(IDC_EDIT_TIME3)->EnableWindow(bConnected && !bTimerActive); } BOOL CPCMFCDlg::ValidateTimeFormat(const CString& strTime) { if (strTime.GetLength() != 5) return FALSE; if (strTime[2] != ':') return FALSE; int hour = _ttoi(strTime.Left(2)); int minute = _ttoi(strTime.Mid(3)); return (hour >= 0 && hour <= 23) && (minute >= 0 && minute <= 59); } UINT CPCMFCDlg::ReadThread(LPVOID pParam) { CPCMFCDlg* pDlg = (CPCMFCDlg*)pParam; return pDlg->ReadThreadFunc(); } UINT CPCMFCDlg::ReadThreadFunc() { BYTE buffer[1]; while (m_bThreadRunning) { try { DWORD dwBytes = m_SerialPort.BytesWaiting(); if (dwBytes > 0) { if (m_SerialPort.Read(buffer, 1) > 0) { if (buffer[0] == COMPLETE_SIGNAL) { CString* pMsg = new CString(_T("喂食操作完成")); PostMessage(WM_UPDATE_STATUS, (WPARAM)pMsg, 0); } } } Sleep(50); } catch (CSerialException* e) { CString* pMsg = new CString(); pMsg->Format(_T("串口读取错误: %d"), e->m_dwError); PostMessage(WM_UPDATE_STATUS, (WPARAM)pMsg, 0); delete e; break; } } return 0; } void CPCMFCDlg::OnBnClickedBtnOpen() { CString strPort; m_cbPort.GetWindowText(strPort); strPort = _T("\\\\.\\") + strPort; CString strBaud; m_cbBaud.GetLBText(m_cbBaud.GetCurSel(), strBaud); DWORD dwBaud = _ttoi(strBaud); int nParity = m_cbParity.GetCurSel(); CString strDataBits; m_cbDate.GetLBText(m_cbDate.GetCurSel(), strDataBits); BYTE byDataBits = (BYTE)_ttoi(strDataBits); int nStopBits = m_cbStop.GetCurSel(); try { CSerialPort::Parity parity = static_cast<CSerialPort::Parity>(nParity); CSerialPort::StopBits stopBits = static_cast<CSerialPort::StopBits>(nStopBits); m_SerialPort.Open(strPort, dwBaud, parity, byDataBits, stopBits); m_SerialPort.Set0Timeout(); m_bConnected = TRUE; m_bThreadRunning = TRUE; m_hThread = (HANDLE)_beginthreadex(NULL, 0, ReadThread, this, 0, NULL); m_listStatus.AddString(_T("串口打开成功")); } catch (CSerialException* e) { CString strError; strError.Format(_T("打开串口失败: 错误代码 %d"), e->m_dwError); m_listStatus.AddString(strError); delete e; m_bConnected = FALSE; } UpdateControls(); } void CPCMFCDlg::OnBnClickedBtnClose() { m_bThreadRunning = FALSE; if (m_hThread) { WaitForSingleObject(m_hThread, 1000); CloseHandle(m_hThread); m_hThread = NULL; } try { if (m_SerialPort.IsOpen()) { m_SerialPort.Close(); m_listStatus.AddString(_T("串口已关闭")); } } catch (CSerialException* e) { delete e; } m_bConnected = FALSE; UpdateControls(); } void CPCMFCDlg::OnBnClickedBtnFeedNow() { BYTE cmd = FEED_COMMAND; try { if (m_SerialPort.IsOpen()) { m_SerialPort.Write(&cmd, 1); m_listStatus.AddString(_T("喂食命令已发送")); } } catch (CSerialException* e) { CString strError; strError.Format(_T("发送失败: 错误代码 %d"), e->m_dwError); m_listStatus.AddString(strError); delete e; } } void CPCMFCDlg::OnBnClickedBtnFeedTimer() { if (m_bTimerActive) { KillTimer(1); m_bTimerActive = FALSE; GetDlgItem(IDC_BUTTON_TIMEFEED)->SetWindowText(_T("开始定时")); m_listStatus.AddString(_T("定时器已停止")); } else { UpdateData(TRUE); // 验证时间格式 if (!ValidateTimeFormat(m_strTime1) || !ValidateTimeFormat(m_strTime2) || !ValidateTimeFormat(m_strTime3)) { MessageBox(_T("时间格式无效! 请使用HH:MM格式"), _T("错误"), MB_ICONERROR); return; } m_bTimerActive = TRUE; SetTimer(1, 1000, NULL); // 每秒检查一次 GetDlgItem(IDC_BUTTON_TIMEFEED)->SetWindowText(_T("停止定时")); m_listStatus.AddString(_T("定时器已启动")); } UpdateControls(); } void CPCMFCDlg::OnTimer(UINT_PTR nIDEvent) { if (nIDEvent == 1) { CTime now = CTime::GetCurrentTime(); CString strNow = now.Format(_T("%H:%M")); if (strNow == m_strTime1 || strNow == m_strTime2 || strNow == m_strTime3) { OnBnClickedBtnFeedNow(); } } CDialogEx::OnTimer(nIDEvent); } LRESULT CPCMFCDlg::OnUpdateStatus(WPARAM wParam, LPARAM lParam) { CString* pStr = (CString*)wParam; if (pStr) { m_listStatus.AddString(*pStr); delete pStr; } return 0; } void CPCMFCDlg::OnDestroy() { CDialogEx::OnDestroy(); if (m_bTimerActive) { KillTimer(1); } m_bThreadRunning = FALSE; if (m_hThread) { WaitForSingleObject(m_hThread, 1000); CloseHandle(m_hThread); m_hThread = NULL; } if (m_SerialPort.IsOpen()) { m_SerialPort.Close(); } } void CPCMFCDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); 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; dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } HCURSOR CPCMFCDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } "public: void __cdecl CSerialPort::Set0Timeout(void)" (?Set0Timeout@CSerialPort@@QEAAXXZ) 已经在 PCMFCDlg.obj 中定义 "public: unsigned long __cdecl CSerialPort::BytesWaiting(void)" (?BytesWaiting@CSerialPort@@QEAAKXZ) 已经在 PCMFCDlg.obj 中定义 "public: unsigned long __cdecl CSerialPort::Write(void const *,unsigned long)" (?Write@CSerialPort@@QEAAKPEBXK@Z) 已经在 PCMFCDlg.obj 中定义 "public: void __cdecl CSerialPort::Close(void)" (?Close@CSerialPort@@QEAAXXZ) 已经在 PCMFCDlg.obj 中定义 "public: virtual __cdecl CSerialPort::~CSerialPort(void)" (??1CSerialPort@@UEAA@XZ) 已经在 PCMFCDlg.obj 中定义 "public: __cdecl CSerialPort::CSerialPort(void)" (??0CSerialPort@@QEAA@XZ) 已经在 PCMFCDlg.obj 中定义 "public: __cdecl CSerialException::CSerialException(unsigned long)" (??0CSerialException@@QEAA@K@Z) 已经在 PCMFCDlg.obj 中定义 找到一个或多个多重定义的符号 请你解决这些问题
06-04
#请优化下面程序,实现更超强更先进的功能 import tkinter as tk from tkinter import ttk, filedialog, messagebox, scrolledtext, simpledialog import ollama import os import time import threading import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import pandas as pd import seaborn as sns import PyPDF2 import docx import markdown from bs4 import BeautifulSoup import openpyxl from PIL import Image import pytesseract import io import psutil from ttkthemes import ThemedTk import pynvml import re # 初始化pynvml pynvml.nvmlInit() # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False class RAGApplication: def __init__(self, root): self.root = root self.root.title("✨智能RAG应用系统✨") self.root.geometry("1400x900") self.root.configure(bg="#f0f0f0") # 淡灰色背景#f0f0f0 # 使用现代主题 self.style = ttk.Style() self.style.theme_use('arc') # 现代主题 # 自定义样式 - 淡色调 self.style.configure('TFrame', background='#f0f0f0') self.style.configure('TLabel', background='#f0f0f0', foreground='#333333') self.style.configure('TLabelframe', background='#f0f0f0', foreground='#4dabf5', borderwidth=1) self.style.configure('TLabelframe.Label', background='#f0f0f0', foreground='#4dabf5') # 淡蓝色标题 self.style.configure('TButton', background='#4dabf5', foreground='#333333', borderwidth=1) # 深色文字按钮 self.style.map('TButton', background=[('active', '#3b99e0')]) self.style.configure('TNotebook', background='#f0f0f0', borderwidth=0) self.style.configure('TNotebook.Tab', background='#e6f0ff', foreground='#333333', padding=[10, 5]) # 淡蓝色标签 self.style.map('TNotebook.Tab', background=[('selected', '#4dabf5')]) # 初始化数据 self.documents = [] self.chunks = [] self.embeddings = [] self.qa_history = [] # 获取 Ollama 中已安装的模型列表 try: models_response = ollama.list() self.all_models = [model['model'] for model in models_response['models']] # 使用 'model' 字段 except Exception as e: print(f"获取 Ollama 模型列表失败: {e}") self.all_models = [] self.default_llm_model = "gemma3:12b" self.default_embedding_model = "bge-m3:latest" # 默认参数 self.params = { "temperature": 0.7, "top_p": 0.9, "max_length": 2048, "num_context_docs": 3, "chunk_size": 500, "chunk_overlap": 100, "chunk_strategy": "固定大小", "separators": "\n\n,。,!,?,\n, ", # 默认分隔符 "embed_batch_size": 1, "enable_stream": True, "show_progress": True, "show_visualization": True, "ocr_enabled": True } # 创建界面 self.create_ui() def create_ui(self): # 主框架 self.main_frame = ttk.Frame(self.root) self.main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20) # 标题 title_frame = ttk.Frame(self.main_frame) title_frame.pack(fill=tk.X, pady=(0, 20)) ttk.Label(title_frame, text="✨ 智能RAG应用系统 ✨", font=('Arial', 24, 'bold'), foreground="#4dabf5").pack(side=tk.LEFT) # 淡青色标题 # 状态指示器 status_frame = ttk.Frame(title_frame) status_frame.pack(side=tk.RIGHT) self.status_label = ttk.Label(status_frame, text="● 就绪", foreground="#28a745") # 绿色状态 self.status_label.pack(side=tk.RIGHT, padx=10) # 参数控制面板 self.create_sidebar() # 主内容区域 self.create_main_content() def create_sidebar(self): # 侧边栏框架 self.sidebar = ttk.LabelFrame(self.main_frame, text="⚙️ 参数控制面板", width=300) self.sidebar.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10) # 大模型参数 ttk.Label(self.sidebar, text="🔧 大模型参数", font=('Arial', 10, 'bold'), foreground="#333333").pack( pady=(15, 5)) self.temperature = tk.DoubleVar(value=self.params["temperature"]) ttk.Label(self.sidebar, text="温度(temperature)").pack(anchor=tk.W, padx=10) temp_frame = ttk.Frame(self.sidebar) temp_frame.pack(fill=tk.X, padx=10, pady=(0, 5)) ttk.Scale(temp_frame, from_=0.0, to=2.0, variable=self.temperature, length=180, command=lambda v: self.update_param("temperature", float(v))).pack(side=tk.LEFT) self.temp_label = ttk.Label(temp_frame, text=f"{self.temperature.get():.1f}", width=5) self.temp_label.pack(side=tk.RIGHT, padx=5) self.top_p = tk.DoubleVar(value=self.params["top_p"]) ttk.Label(self.sidebar, text="Top P").pack(anchor=tk.W, padx=10) top_p_frame = ttk.Frame(self.sidebar) top_p_frame.pack(fill=tk.X, padx=10, pady=(0, 5)) ttk.Scale(top_p_frame, from_=0.0, to=1.0, variable=self.top_p, length=180, command=lambda v: self.update_param("top_p", float(v))).pack(side=tk.LEFT) self.top_p_label = ttk.Label(top_p_frame, text=f"{self.top_p.get():.2f}", width=5) self.top_p_label.pack(side=tk.RIGHT, padx=5) # 添加大模型名称选择(来自 Ollama) ttk.Label(self.sidebar, text="大模型名称").pack(anchor=tk.W, padx=10) self.llm_model_var = tk.StringVar(value=self.default_llm_model) llm_combobox = ttk.Combobox(self.sidebar, textvariable=self.llm_model_var, values=self.all_models) llm_combobox.pack(padx=10, pady=5) # 嵌入模型选择(来自 Ollama) ttk.Label(self.sidebar, text="嵌入模型名称").pack(anchor=tk.W, padx=10) self.embedding_model_var = tk.StringVar(value=self.default_embedding_model) embed_combobox = ttk.Combobox(self.sidebar, textvariable=self.embedding_model_var, values=self.all_models) embed_combobox.pack(padx=10, pady=5) # RAG参数 ttk.Label(self.sidebar, text="🔧 RAG参数", font=('Arial', 10, 'bold'), foreground="#333333").pack(pady=(15, 5)) # 分块策略选择 ttk.Label(self.sidebar, text="分块策略").pack(anchor=tk.W, padx=10) self.chunk_strategy_var = tk.StringVar(value=self.params["chunk_strategy"]) strategy_combobox = ttk.Combobox(self.sidebar, textvariable=self.chunk_strategy_var, values=["固定大小", "按分隔符"]) strategy_combobox.pack(padx=10, pady=5) strategy_combobox.bind("<<ComboboxSelected>>", self.toggle_separators_visibility) # 分隔符配置(默认隐藏) self.separators_frame = ttk.Frame(self.sidebar) ttk.Label(self.separators_frame, text="分隔符配置:").pack(anchor=tk.W, padx=5) # 创建下拉列表框替代文本框 self.separators_var = tk.StringVar(value=self.params["separators"]) self.separator_options = ["换行符", "句号", "空格", "无", "换行符+句号", "换行符+空格", "句号+空格", "自定义"] separators_combobox = ttk.Combobox( self.separators_frame, textvariable=self.separators_var, values=self.separator_options, width=20, state="readonly" ) separators_combobox.pack(padx=5, pady=5, fill=tk.X) separators_combobox.bind("<<ComboboxSelected>>", self.on_separator_selected) # 初始状态:如果当前策略是"按分隔符"则显示 if self.params["chunk_strategy"] == "按分隔符": self.separators_frame.pack(fill=tk.X, padx=10, pady=5) else: self.separators_frame.pack_forget() # 分块大小配置 self.chunk_size = tk.IntVar(value=self.params["chunk_size"]) ttk.Label(self.sidebar, text="分块大小(字符)").pack(anchor=tk.W, padx=10) chunk_frame = ttk.Frame(self.sidebar) chunk_frame.pack(fill=tk.X, padx=10, pady=(0, 5)) ttk.Scale(chunk_frame, from_=100, to=2000, variable=self.chunk_size, length=180, command=lambda v: self.update_param("chunk_size", int(v))).pack(side=tk.LEFT) self.chunk_label = ttk.Label(chunk_frame, text=f"{self.chunk_size.get()}", width=5) self.chunk_label.pack(side=tk.RIGHT, padx=5) # OCR开关 self.ocr_var = tk.BooleanVar(value=self.params["ocr_enabled"]) ttk.Checkbutton(self.sidebar, text="启用OCR扫描", variable=self.ocr_var, command=lambda: self.update_param("ocr_enabled", self.ocr_var.get())).pack(pady=(15, 5), padx=10, anchor=tk.W) # 使用说明 ttk.Label(self.sidebar, text="📖 使用说明", font=('Arial', 10, 'bold'), foreground="#333333").pack(pady=(15, 5)) instructions = """1. 在"文档上传"页上传您的文档 2. 在"文档处理"页对文档进行分块和嵌入 3. 在"问答交互"页提问并获取答案 4. 在"系统监控"页查看系统状态""" ttk.Label(self.sidebar, text=instructions, justify=tk.LEFT, background="#e6f0ff", # 淡蓝色背景 foreground="#333333", padding=10).pack(fill=tk.X, padx=10, pady=5) def on_separator_selected(self, event): """处理分隔符选择事件""" selected = self.separators_var.get() # 映射选项到实际分隔符 separator_map = { "换行符": "\n", "句号": "。", "空格": " ", "无": "", "换行符+句号": "\n,。", "换行符+空格": "\n, ", "句号+空格": "。, " } if selected in separator_map: self.params["separators"] = separator_map[selected] elif selected == "自定义": # 弹出对话框让用户输入自定义分隔符 custom_sep = simpledialog.askstring("自定义分隔符", "请输入分隔符(多个用逗号分隔):", parent=self.root) if custom_sep: self.params["separators"] = custom_sep def toggle_separators_visibility(self, event=None): """根据分块策略显示或隐藏分隔符配置""" strategy = self.chunk_strategy_var.get() self.update_param("chunk_strategy", strategy) if strategy == "按分隔符": self.separators_frame.pack(fill=tk.X, padx=10, pady=5) else: self.separators_frame.pack_forget() def create_main_content(self): # 主内容框架 self.content_frame = ttk.Frame(self.main_frame) self.content_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True) # 创建选项卡 self.notebook = ttk.Notebook(self.content_frame) self.notebook.pack(fill=tk.BOTH, expand=True) # 文档上传页 self.create_upload_tab() # 文档处理页 self.create_process_tab() # 问答交互页 self.create_qa_tab() # 系统监控页 self.create_monitor_tab() def create_upload_tab(self): self.upload_tab = ttk.Frame(self.notebook) self.notebook.add(self.upload_tab, text="📤 文档上传") # 标题 title_frame = ttk.Frame(self.upload_tab) title_frame.pack(fill=tk.X, pady=(10, 20)) ttk.Label(title_frame, text="📤 文档上传与管理", font=('Arial', 14, 'bold'), foreground="#4dabf5").pack(side=tk.LEFT) # 淡青色标题 # 上传区域 upload_frame = ttk.Frame(self.upload_tab) # 修正:ttk.Frame 而不是 tttk.Frame upload_frame.pack(fill=tk.X, pady=10) # 上传按钮 upload_btn = ttk.Button(upload_frame, text="📁 上传文档", command=self.upload_files, style='Accent.TButton') upload_btn.pack(side=tk.LEFT, padx=10) # 清除按钮 clear_btn = ttk.Button(upload_frame, text="🗑️ 清除所有", command=self.clear_documents) clear_btn.pack(side=tk.RIGHT, padx=10) # 文档列表 self.doc_list_frame = ttk.LabelFrame(self.upload_tab, text="📋 已上传文档") self.doc_list_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # 创建带滚动条的树状视图 tree_frame = ttk.Frame(self.doc_list_frame) tree_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 创建滚动条 tree_scroll = ttk.Scrollbar(tree_frame) tree_scroll.pack(side=tk.RIGHT, fill=tk.Y) # 创建树状视图 columns = ("name", "size", "time", "type") self.doc_tree = ttk.Treeview(tree_frame, columns=columns, show="headings", yscrollcommand=tree_scroll.set, height=8) # 设置列标题 self.doc_tree.heading("name", text="文件名") self.doc_tree.heading("size", text="大小") self.doc_tree.heading("time", text="上传时间") self.doc_tree.heading("type", text="类型") # 设置列宽 self.doc_tree.column("name", width=250) self.doc_tree.column("size", width=80) self.doc_tree.column("time", width=150) self.doc_tree.column("type", width=80) self.doc_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) tree_scroll.config(command=self.doc_tree.yview) # 文档统计 self.doc_stats_frame = ttk.Frame(self.upload_tab) self.doc_stats_frame.pack(fill=tk.X, pady=10, padx=10) stats_style = ttk.Style() stats_style.configure('Stats.TLabel', background='#e6f0ff', foreground='#333333', padding=5) # 淡蓝色背景 ttk.Label(self.doc_stats_frame, text="📊 文档统计:", style='Stats.TLabel').pack(side=tk.LEFT, padx=5) self.doc_count_label = ttk.Label(self.doc_stats_frame, text="0", style='Stats.TLabel') self.doc_count_label.pack(side=tk.LEFT, padx=5) ttk.Label(self.doc_stats_frame, text="总字符数:", style='Stats.TLabel').pack(side=tk.LEFT, padx=5) self.char_count_label = ttk.Label(self.doc_stats_frame, text="0", style='Stats.TLabel') self.char_count_label.pack(side=tk.LEFT, padx=5) ttk.Label(self.doc_stats_frame, text="总页数:", style='Stats.TLabel').pack(side=tk.LEFT, padx=5) self.page_count_label = ttk.Label(self.doc_stats_frame, text="0", style='Stats.TLabel') self.page_count_label.pack(side=tk.LEFT, padx=5) def clear_documents(self): if not self.documents: return if messagebox.askyesno("确认", "确定要清除所有文档吗?"): self.documents = [] self.update_doc_list() # ================== 文件读取函数 ================== def read_pdf(self, filepath): """读取PDF文件内容,支持扫描版OCR""" content = "" pages = 0 try: with open(filepath, 'rb') as f: reader = PyPDF2.PdfReader(f) num_pages = len(reader.pages) pages = num_pages for page_num in range(num_pages): page = reader.pages[page_num] text = page.extract_text() # 如果是扫描版PDF,使用OCR识别 if not text.strip() and self.params["ocr_enabled"]: try: # 获取页面图像 images = page.images if images: for img in images: image_data = img.data image = Image.open(io.BytesIO(image_data)) text += pytesseract.image_to_string(image, lang='chi_sim+eng') except Exception as e: print(f"OCR处理失败: {str(e)}") content += text + "\n" except Exception as e: print(f"读取PDF失败: {str(e)}") return content, pages def read_docx(self, filepath): """读取Word文档内容""" content = "" pages = 0 try: doc = docx.Document(filepath) for para in doc.paragraphs: content += para.text + "\n" pages = len(doc.paragraphs) // 50 + 1 # 估算页数 except Exception as e: print(f"读取Word文档失败: {str(e)}") return content, pages def read_excel(self, filepath): """读取Excel文件内容,优化内存使用""" content = "" pages = 0 try: # 使用openpyxl优化大文件读取 wb = openpyxl.load_workbook(filepath, read_only=True) for sheet_name in wb.sheetnames: content += f"\n工作表: {sheet_name}\n" sheet = wb[sheet_name] for row in sheet.iter_rows(values_only=True): row_content = " | ".join([str(cell) if cell is not None else "" for cell in row]) content += row_content + "\n" pages = len(wb.sheetnames) except Exception as e: print(f"读取Excel文件失败: {str(e)}") return content, pages def read_md(self, filepath): """读取Markdown文件内容""" content = "" pages = 0 try: with open(filepath, 'r', encoding='utf-8') as f: html = markdown.markdown(f.read()) soup = BeautifulSoup(html, 'html.parser') content = soup.get_text() pages = len(content) // 2000 + 1 # 估算页数 except Exception as e: print(f"读取Markdown文件失败: {str(e)}") return content, pages def read_ppt(self, filepath): """读取PPT文件内容(简化版)""" content = "" pages = 0 try: # 实际应用中应使用python-pptx库 # 这里仅作演示 content = f"PPT文件内容提取: {os.path.basename(filepath)}" pages = 10 # 假设有10页 except Exception as e: print(f"读取PPT文件失败: {str(e)}") return content, pages # ...(前面的代码保持不变)... def upload_files(self): filetypes = [ ("文本文件", "*.txt"), ("PDF文件", "*.pdf"), ("Word文件", "*.docx *.doc"), ("Excel文件", "*.xlsx *.xls"), ("Markdown文件", "*.md"), ("PPT文件", "*.pptx *.ppt"), ("所有文件", "*.*") ] filenames = filedialog.askopenfilenames(title="选择文档", filetypes=filetypes) if filenames: self.status_label.config(text="● 正在上传文档...", foreground="#ffc107") total_pages = 0 for filename in filenames: try: ext = os.path.splitext(filename)[1].lower() if ext == '.txt': with open(filename, 'r', encoding='utf-8') as f: content = f.read() pages = len(content) // 2000 + 1 elif ext == '.pdf': content, pages = self.read_pdf(filename) elif ext in ('.docx', '.doc'): content, pages = self.read_docx(filename) elif ext in ('.xlsx', '.xls'): content, pages = self.read_excel(filename) elif ext == '.md': content, pages = self.read_md(filename) elif ext in ('.pptx', '.ppt'): content, pages = self.read_ppt(filename) else: messagebox.showwarning("警告", f"不支持的文件类型: {ext}") continue # 处理字符编码问题 if not isinstance(content, str): try: content = content.decode('utf-8') except: content = content.decode('latin-1', errors='ignore') self.documents.append({ "name": os.path.basename(filename), "content": content, "size": len(content), "upload_time": time.strftime("%Y-%m-%d %H:%M:%S"), "type": ext.upper().replace(".", ""), "pages": pages }) total_pages += pages # 更新文档列表 self.update_doc_list() except Exception as e: messagebox.showerror("错误", f"无法读取文件 {filename}: {str(e)}") # 更新检索文档数量 if hasattr(self, 'req_docs_entry'): self.req_docs_entry.delete(0, tk.END) self.req_docs_entry.insert(0, str(len(self.documents))) self.params["num_context_docs"] = len(self.documents) self.status_label.config(text=f"● 上传完成! 共{len(filenames)}个文档", foreground="#28a745") self.page_count_label.config(text=str(total_pages)) # ...(后面的代码保持不变)... def update_doc_list(self): # 清空现有列表 for item in self.doc_tree.get_children(): self.doc_tree.delete(item) # 添加新文档 for doc in self.documents: size_kb = doc["size"] / 1024 size_str = f"{size_kb:.1f} KB" if size_kb < 1024 else f"{size_kb / 1024:.1f} MB" self.doc_tree.insert("", tk.END, values=( doc["name"], size_str, doc["upload_time"], doc["type"] )) # 更新统计信息 self.doc_count_label.config(text=str(len(self.documents))) self.char_count_label.config(text=str(sum(d['size'] for d in self.documents))) def create_process_tab(self): self.process_tab = ttk.Frame(self.notebook) self.notebook.add(self.process_tab, text="🔧 文档处理") # 标题 title_frame = ttk.Frame(self.process_tab) title_frame.pack(fill=tk.X, pady=(10, 20)) ttk.Label(title_frame, text="🔧 文档处理与分块", font=('Arial', 14, 'bold'), foreground="#4dabf5").pack(side=tk.LEFT) # 淡青色标题 # 处理按钮 btn_frame = ttk.Frame(self.process_tab) btn_frame.pack(fill=tk.X, pady=10) process_btn = ttk.Button(btn_frame, text="🔄 处理文档", command=self.process_documents, style='Accent.TButton') process_btn.pack(side=tk.LEFT, padx=10) visualize_btn = ttk.Button(btn_frame, text="📊 更新可视化", command=self.show_visualizations) visualize_btn.pack(side=tk.LEFT, padx=10) # 主内容区域 content_frame = ttk.Frame(self.process_tab) # 修正:self.process_tab 而不是 self.process极ab content_frame.pack(fill=tk.BOTH, expand=True) # 左侧:可视化区域 self.visual_frame = ttk.LabelFrame(content_frame, text="📈 文档分析") self.visual_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=10) # 右侧:分块列表 self.chunk_frame = ttk.LabelFrame(content_frame, text="📋 分块结果") self.chunk_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10, pady=10) # 创建带滚动条的树状视图 tree_frame = ttk.Frame(self.chunk_frame) tree_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 创建滚动条 tree_scroll = ttk.Scrollbar(tree_frame) tree_scroll.pack(side=tk.RIGHT, fill=tk.Y) # 创建树状视图 columns = ("doc_name", "start", "end", "content") self.chunk_tree = ttk.Treeview( tree_frame, columns=columns, show="headings", yscrollcommand=tree_scroll.set, height=15 ) # 设置列标题 self.chunk_tree.heading("doc_name", text="来源文档") self.chunk_tree.heading("start", text="起始位置") self.chunk_tree.heading("end", text="结束位置") self.chunk_tree.heading("content", text="内容预览") # 设置列宽 self.chunk_tree.column("doc_name", width=150) self.chunk_tree.column("start", width=80) self.chunk_tree.column("end", width=80) self.chunk_tree.column("content", width=300) self.chunk_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) tree_scroll.config(command=self.chunk_tree.yview) # 初始显示占位图 self.show_placeholder() def show_placeholder(self): """显示可视化占位图""" for widget in self.visual_frame.winfo_children(): widget.destroy() placeholder = ttk.Label(self.visual_frame, text="文档处理后将显示分析图表", font=('Arial', 12), foreground="#7f8c8d") placeholder.pack(expand=True, pady=50) def process_documents(self): if not self.documents: messagebox.showwarning("警告", "请先上传文档") return # 在新线程中处理文档 threading.Thread(target=self._process_documents_thread, daemon=True).start() def _process_documents_thread(self): # 显示进度条 self.progress_window = tk.Toplevel(self.root) self.progress_window.title("处理进度") self.progress_window.geometry("400x150") self.progress_window.resizable(False, False) self.progress_window.transient(self.root) self.progress_window.grab_set() self.progress_window.configure(bg="#f0f0f0") # 淡灰色背景 # 设置窗口居中 x = self.root.winfo_x() + (self.root.winfo_width() - 400) // 2 y = self.root.winfo_y() + (self.root.winfo_height() - 150) // 2 self.progress_window.geometry(f"+{x}+{y}") # 进度窗口内容 ttk.Label(self.progress_window, text="正在处理文档...", font=('Arial', 11)).pack(pady=(20, 10)) progress_frame = ttk.Frame(self.progress_window) progress_frame.pack(fill=tk.X, padx=20, pady=10) self.progress_var = tk.DoubleVar() progress_bar = ttk.Progressbar(progress_frame, variable=self.progress_var, maximum=100, length=360) progress_bar.pack() self.progress_label = ttk.Label(progress_frame, text="0%") self.progress_label.pack(pady=5) self.status_label.config(text="● 正在处理文档...", foreground="#ffc107") # 黄色状态 self.progress_window.update() try: # 分块处理 self.chunks = self.chunk_documents( self.documents, self.params["chunk_strategy"], self.params["chunk_size"], self.params["chunk_overlap"], self.params["separators"] ) # 生成嵌入 self.embeddings = self.generate_embeddings(self.chunks) # 更新UI self.root.after(0, self.update_chunk_list) self.root.after(0, self.show_visualizations) self.root.after(0, lambda: messagebox.showinfo("完成", "文档处理完成!")) self.status_label.config(text="● 文档处理完成", foreground="#28a745") # 绿色状态 except Exception as e: self.root.after(0, lambda: messagebox.showerror("错误", f"处理文档时出错: {str(e)}")) self.status_label.config(text="● 处理出错", foreground="#dc3545") # 红色状态 finally: self.root.after(0, self.progress_window.destroy) def chunk_documents(self, documents, strategy, size, overlap, separators): chunks = [] total_docs = len(documents) for doc_idx, doc in enumerate(documents): content = doc['content'] if strategy == "固定大小": # 固定大小分块策略 for i in range(0, len(content), size - overlap): chunk = content[i:i + size] chunks.append({ "doc_name": doc['name'], "content": chunk, "start": i, "end": min(i + size, len(content)) }) elif strategy == "按分隔符": # 按分隔符分块策略 # 将分隔符字符串拆分成列表 separator_list = [sep.strip() for sep in separators.split(',') if sep.strip()] # 如果没有提供分隔符,使用默认分隔符 if not separator_list: separator_list = ['\n\n', '。', '!', '?', '\n', ' '] # 构建正则表达式模式 pattern = '|'.join([re.escape(sep) for sep in separator_list]) # 使用正则表达式分割文本 parts = re.split(f'({pattern})', content) # 合并片段和分隔符 fragments = [] for i in range(0, len(parts), 2): if i < len(parts) - 1: fragments.append(parts[i] + parts[i + 1]) else: fragments.append(parts[i]) # 合并片段直到达到块大小 current_chunk = "" start_index = 0 current_length = 0 for fragment in fragments: frag_len = len(fragment) # 如果当前块加上新片段不超过块大小 if current_length + frag_len <= size: current_chunk += fragment current_length += frag_len else: # 保存当前块 if current_chunk: chunks.append({ "doc_name": doc['name'], "content": current_chunk, "start": start_index, "end": start_index + current_length }) start_index += current_length - overlap if start_index < 0: start_index = 0 # 保留重叠部分作为下一块的开头 current_chunk = current_chunk[-overlap:] + fragment current_length = len(current_chunk) else: # 如果当前块为空(片段本身大于块大小) chunks.append({ "doc_name": doc['name'], "content": fragment, "start": start_index, "end": start_index + frag_len }) start_index += frag_len - overlap if start_index < 0: start_index = 0 current_chunk = "" current_length = 0 # 添加最后一个块 if current_chunk: chunks.append({ "doc_name": doc['name'], "content": current_chunk, "start": start_index, "end": start_index + len(current_chunk) }) # 更新进度 progress = (doc_idx + 1) / total_docs * 100 self.progress_var.set(progress) self.progress_label.config(text=f"{int(progress)}%") self.progress_window.update() return chunks def generate_embeddings(self, chunks): """单批次处理每个分块,避免API参数类型错误""" embeddings = [] total_chunks = len(chunks) for idx, chunk in enumerate(chunks): try: # 传递单个字符串而不是列表 response = ollama.embeddings( model=self.embedding_model_var.get(), prompt=chunk['content'] # 单个字符串 ) embeddings.append({ "chunk_id": idx, "embedding": response['embedding'], "doc_name": chunk['doc_name'] }) except Exception as e: print(f"生成嵌入时出错: {str(e)}") # 添加空嵌入占位符 embeddings.append({ "chunk_id": idx, "embedding": None, "doc_name": chunk['doc_name'] }) # 更新进度 progress = (idx + 1) / total_chunks * 100 self.progress_var.set(progress) self.progress_label.config(text=f"{int(progress)}%") self.progress_window.update() # 添加延迟避免请求过快 time.sleep(0.1) return embeddings def update_chunk_list(self): # 清空现有列表 for item in self.chunk_tree.get_children(): self.chunk_tree.delete(item) # 添加新分块 for chunk in self.chunks: preview = chunk['content'][:50] + "..." if len(chunk['content']) > 50 else chunk['content'] self.chunk_tree.insert("", tk.END, values=( chunk['doc_name'], chunk['start'], chunk['end'], preview )) def show_visualizations(self): # 清空可视化区域 for widget in self.visual_frame.winfo_children(): widget.destroy() if not self.params["show_visualization"] or not self.chunks: self.show_placeholder() return # 创建图表框架 fig = plt.Figure(figsize=(10, 8), dpi=100) fig.set_facecolor('#f0f0f0') # 淡灰色背景 # 分块大小分布 ax1 = fig.add_subplot(221) ax1.set_facecolor('#e6f0ff') # 淡蓝色背景 chunk_sizes = [len(c['content']) for c in self.chunks] sns.histplot(chunk_sizes, bins=20, ax=ax1, color='#4dabf5') # 淡青色 ax1.set_title("分块大小分布", color='#333333') ax1.set_xlabel("字符数", color='#333333') # 修正:正确的颜色代码 ax1.set_ylabel("数量", color='#333333') ax1.tick_params(axis='x', colors='#333333') ax1.tick_params(axis='y', colors='#333333') ax1.spines['bottom'].set_color('#333333') ax1.spines['left'].set_color('#333333') # 文档分块数量 ax2 = fig.add_subplot(222) ax2.set_facecolor('#e6f0ff') # 淡蓝色背景 doc_chunk_counts = {} for chunk in self.chunks: doc_chunk_counts[chunk['doc_name']] = doc_chunk_counts.get(chunk['doc_name'], 0) + 1 # 只显示前10个文档 doc_names = list(doc_chunk_counts.keys()) counts = list(doc_chunk_counts.values()) if len(doc_names) > 10: # 按分块数量排序,取前10 sorted_indices = np.argsort(counts)[::-1][:10] doc_names = [doc_names[i] for i in sorted_indices] counts = [counts[i] for i in sorted_indices] sns.barplot(x=counts, y=doc_names, hue=doc_names, ax=ax2, palette='Blues', orient='h', legend=False) ax2.set_title("各文档分块数量", color='#333333') ax2.set_xlabel("分块数", color='#333333') ax2.set_ylabel("") ax2.tick_params(axis='x', colors='#333333') ax2.tick_params(axis='y', colors='#333333') ax2.spines['bottom'].set_color('#333333') ax2.spines['left'].set_color('#333333') # 内容词云(模拟) ax3 = fig.add_subplot(223) ax3.set_facecolor('#e6f0ff') # 淡蓝色背景 ax3.set_title("内容关键词分布", color='#333333') ax3.text(0.5, 0.5, "关键词可视化区域", horizontalalignment='center', verticalalignment='center', color='#333333', fontsize=12) ax3.axis('off') # 处理进度 ax4 = fig.add_subplot(224) ax4.set_facecolor('#e6f0ff') # 淡蓝色背景 ax4.set_title("处理进度", color='#333333') # 模拟数据 stages = ['上传', '分块', '嵌入', '完成'] progress = [100, 100, 100, 100] # 假设都已完成 ax4.barh(stages, progress, color=['#4dabf5', '#20c997', '#9b59b6', '#ffc107']) # 淡色系 ax4.set_xlim(0, 100) ax4.set_xlabel("完成百分比", color='#333333') ax4.tick_params(axis='x', colors='#333333') ax4.tick_params(axis='y', colors='#333333') ax4.spines['bottom'].set_color('#333333') ax4.spines['left'].set_color('#333333') # 调整布局 fig.tight_layout(rect=[0, 0, 1, 0.95], pad=3.0) # 添加总标题 fig.suptitle("文档分析概览", fontsize=16, color='#333333') # 在Tkinter中显示图表 canvas = FigureCanvasTkAgg(fig, master=self.visual_frame) canvas.draw() canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True) def create_qa_tab(self): self.qa_tab = ttk.Frame(self.notebook) self.notebook.add(self.qa_tab, text="💬 问答交互") # 标题 title_frame = ttk.Frame(self.qa_tab) title_frame.pack(fill=tk.X, pady=(10, 20)) ttk.Label(title_frame, text="💬 问答交互", font=('Arial', 14, 'bold'), foreground="#4dabf5").pack(side=tk.LEFT) # 淡青色标题 # 主内容区域 main_frame = ttk.Frame(self.qa_tab) main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5) # 左侧:问答区域 left_frame = ttk.Frame(main_frame) left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5) # 问题输入 self.question_frame = ttk.LabelFrame(left_frame, text="❓ 输入问题") self.question_frame.pack(fill=tk.X, padx=5, pady=5) self.question_text = scrolledtext.ScrolledText(self.question_frame, height=8, wrap=tk.WORD, font=('Arial', 11)) self.question_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) self.question_text.focus_set() # 提交按钮 btn_frame = ttk.Frame(left_frame) btn_frame.pack(fill=tk.X, pady=10) submit_btn = ttk.Button(btn_frame, text="🚀 提交问题", command=self.submit_question, style='Accent.TButton') submit_btn.pack(side=tk.LEFT, padx=5) clear_btn = ttk.Button(btn_frame, text="🗑️ 清除问题", command=self.clear_question) clear_btn.pack(side=tk.LEFT, padx=5) # 检索文档数量控制 - 放到按钮下方 control_frame = ttk.LabelFrame(left_frame, text="⚙️ 检索设置") control_frame.pack(fill=tk.X, padx=5, pady=5) req_frame = ttk.Frame(control_frame) req_frame.pack(fill=tk.X, padx=5, pady=5) ttk.Label(req_frame, text="检索文档数量:").pack(side=tk.LEFT) self.req_docs_entry = ttk.Entry(req_frame, width=5) self.req_docs_entry.insert(0, str(len(self.documents))) # 默认为文档总数 self.req_docs_entry.pack(side=tk.LEFT, padx=5) ttk.Button(req_frame, text="更新", command=self.update_num_context_docs).pack(side=tk.LEFT, padx=5) ttk.Button(req_frame, text="全部", command=self.set_all_docs).pack(side=tk.LEFT) # 回答显示 self.answer_frame = ttk.LabelFrame(left_frame, text="💡 回答") self.answer_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) self.answer_text = scrolledtext.ScrolledText(self.answer_frame, state=tk.DISABLED, wrap=tk.WORD, font=('Arial', 11)) self.answer_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 右侧:问答历史 right_frame = ttk.Frame(main_frame, width=400) # 设置宽度 right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=False, padx=5, pady=5) self.history_frame = ttk.LabelFrame(right_frame, text="🕒 问答历史") self.history_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 创建带滚动条的树状视图 tree_frame = ttk.Frame(self.history_frame) tree_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 创建滚动条 tree_scroll = ttk.Scrollbar(tree_frame) tree_scroll.pack(side=tk.RIGHT, fill=tk.Y) # 创建树状视图 columns = ("question", "time") self.history_tree = ttk.Treeview( tree_frame, columns=columns, show="headings", yscrollcommand=tree_scroll.set, height=20 ) # 设置列标题 self.history_tree.heading("question", text="问题") self.history_tree.heading("time", text="时间") # 设置列宽 self.history_tree.column("question", width=250) self.history_tree.column("time", width=120) self.history_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) tree_scroll.config(command=self.history_tree.yview) # 历史操作按钮 history_btn_frame = ttk.Frame(right_frame) history_btn_frame.pack(fill=tk.X, pady=10) view_btn = ttk.Button(history_btn_frame, text="👁️ 查看详情", command=lambda: self.show_history_detail(None)) view_btn.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True) clear_history_btn = ttk.Button(history_btn_frame, text="🗑️ 清除历史", command=self.clear_history) clear_history_btn.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True) # 绑定双击事件查看历史详情 self.history_tree.bind("<Double-1>", self.show_history_detail) def update_num_context_docs(self): try: value = int(self.req_docs_entry.get()) if value > 0: self.params["num_context_docs"] = value messagebox.showinfo("提示", f"已更新检索文档数量为: {value}") else: raise ValueError except: messagebox.showerror("错误", "请输入有效的正整数") def set_all_docs(self): if self.documents: self.req_docs_entry.delete(0, tk.END) self.req_docs_entry.insert(0, str(len(self.documents))) self.params["num_context_docs"] = len(self.documents) messagebox.showinfo("提示", f"已更新检索文档数量为: {len(self.documents)}") else: messagebox.showwarning("警告", "请先上传文档") def clear_question(self): self.question_text.delete("1.0", tk.END) def clear_history(self): if not self.qa_history: return if messagebox.askyesno("确认", "确定要清除所有问答历史吗?"): self.qa_history = [] self.update_history_list() def submit_question(self): question = self.question_text.get("1.0", tk.END).strip() if not question: messagebox.showwarning("警告", "问题不能为空") return # 在新线程中处理问题 threading.Thread(target=self._submit_question_thread, args=(question,), daemon=True).start() def _submit_question_thread(self, question): try: # 显示进度窗口 self.progress_window = tk.Toplevel(self.root) self.progress_window.title("处理中...") self.progress_window.geometry("400x150") self.progress_window.resizable(False, False) self.progress_window.transient(self.root) self.progress_window.grab_set() self.progress_window.configure(bg="#f0f0f0") # 淡灰色背景 # 设置窗口居中 x = self.root.winfo_x() + (self.root.winfo_width() - 400) // 2 y = self.root.winfo_y() + (self.root.winfo_height() - 150) // 2 self.progress_window.geometry(f"+{x}+{y}") # 进度窗口内容 ttk.Label(self.progress_window, text="正在思考中...", font=('Arial', 11)).pack(pady=(20, 10)) progress_frame = ttk.Frame(self.progress_window) progress_frame.pack(fill=tk.X, padx=20, pady=10) self.progress_var = tk.DoubleVar() progress_bar = ttk.Progressbar(progress_frame, variable=self.progress_var, maximum=100, length=360) # 修正:100 而不是 极00 progress_bar.pack() self.progress_label = ttk.Label(progress_frame, text="0%") self.progress_label.pack(pady=5) self.status_label.config(text="● 正在处理问题...", foreground="#ffc107") # 黄色状态 self.progress_window.update() # 检索相关文档块 relevant_chunks = self.retrieve_relevant_chunks(question, self.params["num_context_docs"]) # 构建上下文 context = "\n\n".join([ f"文档: {c['doc_name']}\n内容: {c['content']}\n相关性: {c['similarity']:.4f}" for c in relevant_chunks ]) # 调用大模型生成回答 prompt = f"""基于以下上下文,回答问题。如果答案不在上下文中,请回答"我不知道"。 上下文: {context} 问题: {question} 回答:""" # 更新进度 self.progress_var.set(50) self.progress_label.config(text="50%") self.progress_window.update() # 流式输出或一次性输出 self.root.after(0, self.answer_text.config, {'state': tk.NORMAL}) self.root.after(0, self.answer_text.delete, "1.0", tk.END) if self.params["enable_stream"]: full_response = "" for chunk in ollama.generate( model=self.llm_model_var.get(), # 使用用户选择的模型 prompt=prompt, stream=True, options={ 'temperature': self.params["temperature"], 'top_p': self.params["top_p"], 'num_ctx': self.params["max_length"] } ): full_response += chunk['response'] self.root.after(0, self.answer_text.insert, tk.END, chunk['response']) self.root.after(0, self.answer_text.see, tk.END) self.root.after(0, self.answer_text.update) # 更新进度 if len(full_response) > 0: progress = min(50 + len(full_response) / 200, 99) self.progress_var.set(progress) self.progress_label.config(text=f"{int(progress)}%") self.progress_window.update() else: response = ollama.generate( model=self.llm_model_var.get(), # 使用用户选择的模型 prompt=prompt, options={ 'temperature': self.params["temperature"], 'top_p': self.params["top_p"], 'num_ctx': self.params["max_length"] } ) full_response = response['response'] self.root.after(0, self.answer_text.insert, tk.END, full_response) # 记录问答历史 self.qa_history.append({ "question": question, "answer": full_response, "context": context, "time": time.strftime("%Y-%m-%d %H:%M:%S") }) # 更新历史列表 self.root.after(0, self.update_history_list) # 完成 self.progress_var.set(100) self.progress_label.config(text="100%") self.status_label.config(text="● 问题处理完成", foreground="#28a745") # 绿色状态 self.root.after(1000, self.progress_window.destroy) except Exception as e: self.root.after(0, lambda: messagebox.showerror("错误", f"处理问题时出错: {str(e)}")) self.root.after(0, self.progress_window.destroy) self.status_label.config(text="● 处理出错", foreground="#dc3545") # 红色状态 def retrieve_relevant_chunks(self, query, k): """处理嵌入为None的情况""" # 生成查询的嵌入 query_embedding = ollama.embeddings( model=self.embedding_model_var.get(), # 使用用户选择的模型 prompt=query )['embedding'] # 注意:返回的是字典中的'embedding'字段 # 计算相似极 similarities = [] for emb in self.embeddings: # 跳过无效的嵌入 if emb['embedding'] is None: continue # 计算余弦相似度 similarity = np.dot(query_embedding, emb['embedding']) similarities.append({ 'chunk_id': emb['chunk_id'], 'similarity': similarity, 'doc_name': emb['doc_name'] }) # 按相似度排序并返回前k个 top_chunks = sorted(similarities, key=lambda x: x['similarity'], reverse=True)[:k] return [{ **self.chunks[c['chunk_id']], 'similarity': c['similarity'] } for c in top_chunks] def update_history_list(self): # 清空现有列表 for item in self.history_tree.get_children(): self.history_tree.delete(item) # 添加新历史记录 for i, qa in enumerate(reversed(self.qa_history)): # 截断长问题 question = qa["question"] if len(question) > 50: question = question[:47] + "..." self.history_tree.insert("", tk.END, values=(question, qa["time"])) def show_history_detail(self, event): selected_item = self.history_tree.selection() if not selected_item: return item = self.history_tree.item(selected_item) question = item['values'][0] # 查找对应的问答记录 for qa in reversed(self.qa_history): if qa["question"].startswith(question) or question.startswith(qa["question"][:50]): # 显示详情窗口 detail_window = tk.Toplevel(self.root) detail_window.title("问答详情") detail_window.geometry("900x700") detail_window.configure(bg='#f0f0f0') # 淡灰色背景 # 设置窗口居中 x = self.root.winfo_x() + (self.root.winfo_width() - 900) // 2 y = self.root.winfo_y() + (self.root.winfo_height() - 700) // 2 detail_window.geometry(f"+{x}+{y}") # 问题 ttk.Label(detail_window, text="问题:", font=('Arial', 12, 'bold'), foreground="#4dabf5").pack(pady=(15, 5), padx=20, anchor=tk.W) question_frame = ttk.Frame(detail_window) question_frame.pack(fill=tk.X, padx=20, pady=(0, 10)) question_text = scrolledtext.ScrolledText(question_frame, wrap=tk.WORD, height=3, font=('Arial', 11)) question_text.insert(tk.INSERT, qa["question"]) question_text.config(state=tk.DISABLED) question_text.pack(fill=tk.X) # 回答 ttk.Label(detail_window, text="回答:", font=('Arial', 12, 'bold'), foreground="#4dabf5").pack(pady=(15, 5), padx=20, anchor=tk.W) answer_frame = ttk.Frame(detail_window) answer_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=(0, 10)) answer_text = scrolledtext.ScrolledText(answer_frame, wrap=tk.WORD, font=('Arial', 11)) answer_text.insert(tk.INSERT, qa["answer"]) answer_text.config(state=tk.DISABLED) answer_text.pack(fill=tk.BOTH, expand=True) # 上下文 ttk.Label(detail_window, text="上下文:", font=('Arial', 12, 'bold'), foreground="#4dabf5").pack(pady=(15, 5), padx=20, anchor=tk.W) context_frame = ttk.Frame(detail_window) context_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=(0, 20)) context_text = scrolledtext.ScrolledText(context_frame, wrap=tk.WORD, font=('Arial', 10)) context_text.insert(tk.INSERT, qa["context"]) context_text.config(state=tk.DISABLED) context_text.pack(fill=tk.BOTH, expand=True) break def create_monitor_tab(self): self.monitor_tab = ttk.Frame(self.notebook) self.notebook.add(self.monitor_tab, text="📊 系统监控") # 标题 title_frame = ttk.Frame(self.monitor_tab) title_frame.pack(fill=tk.X, pady=(10, 20)) ttk.Label(title_frame, text="📊 系统监控", font=('Arial', 14, 'bold'), foreground="#4dabf5").pack(side=tk.LEFT) # 主内容区域 main_frame = ttk.Frame(self.monitor_tab) main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5) # 左侧:资源监控 left_frame = ttk.Frame(main_frame) left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5) # 资源使用 self.resource_frame = ttk.LabelFrame(left_frame, text="📈 资源使用") self.resource_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # CPU使用 cpu_frame = ttk.Frame(self.resource_frame) cpu_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Label(cpu_frame, text="CPU使用率:").pack(side=tk.LEFT) self.cpu_value = ttk.Label(cpu_frame, text="0%", width=5) self.cpu_value.pack(side=tk.RIGHT, padx=10) self.cpu_usage = ttk.Progressbar(self.resource_frame, length=400, mode='determinate') # 修正:正确的变量名 self.cpu_usage.pack(fill=tk.X, padx=10, pady=(0, 10)) # 内存使用 mem_frame = ttk.Frame(self.resource_frame) mem_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Label(mem_frame, text="内存使用率:").pack(side=tk.LEFT) self.mem_value = ttk.Label(mem_frame, text="0%", width=5) self.mem_value.pack(side=tk.RIGHT, padx=10) self.mem_usage = ttk.Progressbar(self.resource_frame, length=400, mode='determinate') self.mem_usage.pack(fill=tk.X, padx=10, pady=(0, 10)) # 磁盘使用 disk_frame = ttk.Frame(self.resource_frame) disk_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Label(disk_frame, text="磁盘使用率:").pack(side=tk.LEFT) self.disk_value = ttk.Label(disk_frame, text="0%", width=5) self.disk_value.pack(side=tk.RIGHT, padx=10) self.disk_usage = ttk.Progressbar(self.resource_frame, length=400, mode='determinate') self.disk_usage.pack(fill=tk.X, padx=10, pady=(0, 10)) # GPU 使用情况 gpu_frame = ttk.Frame(self.resource_frame) gpu_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Label(gpu_frame, text="GPU使用率:").pack(side=tk.LEFT) self.gpu_value = ttk.Label(gpu_frame, text="0%", width=5) self.gpu_value.pack(side=tk.RIGHT, padx=10) self.gpu_usage = ttk.Progressbar(self.resource_frame, length=400, mode='determinate') self.gpu_usage.pack(fill=tk.X, padx=10, pady=(0, 10)) # 右侧:模型状态 right_frame = ttk.Frame(main_frame) right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5) # 模型状态 self.model_frame = ttk.LabelFrame(right_frame, text="🤖 模型状态") self.model_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) btn_frame = ttk.Frame(self.model_frame) btn_frame.pack(fill=tk.X, padx=10, pady=10) ttk.Button(btn_frame, text="🔄 检查模型状态", command=self.check_model_status).pack() self.model_status_text = scrolledtext.ScrolledText(self.model_frame, height=15, state=tk.DISABLED, font=('Consolas', 10)) self.model_status_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10)) # 性能统计 self.perf_frame = ttk.LabelFrame(left_frame, text="⚡ 性能统计") self.perf_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 创建图表 fig = Figure(figsize=(8, 4), dpi=100) fig.set_facecolor('#f0f0f0') # 淡灰色背景 self.ax = fig.add_subplot(111) self.ax.set_facecolor('#e6f0ff') # 淡蓝色背景 self.ax.set_title("CPU使用率历史", color='#333333') self.ax.set_xlabel("时间", color='#333333') self.ax.set_ylabel("使用率(%)", color='#333333') self.ax.tick_params(axis='x', colors='#333333') self.ax.tick_params(axis='y', colors='#333333') self.ax.spines['bottom'].set_color('#333333') self.ax.spines['left'].set_color('#333333') self.cpu_history = [] self.line, = self.ax.plot([], [], color='#4dabf5', marker='o', markersize=4) # 淡青色线条 self.ax.set_ylim(0, 100) canvas = FigureCanvasTkAgg(fig, master=self.perf_frame) canvas.draw() canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # GPU 使用历史图表 self.gpu_fig = Figure(figsize=(8, 4), dpi=100) self.gpu_fig.set_facecolor('#f0f0f0') self.gpu_ax = self.gpu_fig.add_subplot(111) self.gpu_ax.set_facecolor('#e6f0ff') self.gpu_ax.set_title("GPU使用率历史", color='#333333') self.gpu_ax.set_xlabel("时间", color='#333333') self.gpu_ax.set_ylabel("使用率(%)", color='#333333') self.gpu_ax.tick_params(axis='x', colors='#333333') self.gpu_ax.tick_params(axis='y', colors='#333333') self.gpu_ax.spines['bottom'].set_color('#333333') self.gpu_ax.spines['left'].set_color('#333333') self.gpu_history = [] self.gpu_line, = self.gpu_ax.plot([], [], color='#9b59b6', marker='o', markersize=4) # 紫色线条 self.gpu_ax.set_ylim(0, 100) gpu_canvas = FigureCanvasTkAgg(self.gpu_fig, master=self.perf_frame) gpu_canvas.draw() gpu_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # 开始更新资源使用情况 self.update_resource_usage() def update_resource_usage(self): # 获取真实资源数据 cpu_percent = psutil.cpu_percent() mem_percent = psutil.virtual_memory().percent disk_percent = psutil.disk_usage('/').percent # 获取GPU使用情况 try: handle = pynvml.nvmlDeviceGetHandleByIndex(0) info = pynvml.nvmlDeviceGetUtilizationRates(handle) gpu_percent = info.gpu except: gpu_percent = 0 # 更新进度条 self.cpu_usage['value'] = cpu_percent self.mem_usage['value'] = mem_percent self.disk_usage['value'] = disk_percent self.gpu_usage['value'] = gpu_percent # 更新数值标签 self.cpu_value.config(text=f"{cpu_percent}%") self.mem_value.config(text=f"{mem_percent}%") self.disk_value.config(text=f"{disk_percent}%") self.gpu_value.config(text=f"{gpu_percent}%") # 更新CPU历史图表 self.cpu_history.append(cpu_percent) if len(self.cpu_history) > 20: self.cpu_history.pop(0) self.line.set_data(range(len(self.cpu_history)), self.cpu_history) self.ax.set_xlim(0, max(10, len(self.cpu_history))) self.ax.figure.canvas.draw() # 更新GPU历史图表 self.gpu_history.append(gpu_percent) if len(self.gpu_history) > 20: self.gpu_history.pop(0) self.gpu_line.set_data(range(len(self.gpu_history)), self.gpu_history) self.gpu_ax.set_xlim(0, max(10, len(self.gpu_history))) self.gpu_fig.canvas.draw() # 5秒后再次更新 self.root.after(5000, self.update_resource_usage) def check_model_status(self): try: self.model_status_text.config(state=tk.NORMAL) self.model_status_text.delete("1.0", tk.END) # 添加加载动画 self.model_status_text.insert(tk.INSERT, "正在检查模型状态...") self.model_status_text.update() # 模拟检查过程 time.sleep(1) # 清空并插入真实信息 self.model_status_text.delete("1.0", tk.END) llm_info = ollama.show(self.llm_model_var.get()) # 使用用户选择的模型 embed_info = ollama.show(self.embedding_model_var.get()) # 使用用户选择的模型 status_text = f"""✅ 大模型信息: 名称: {self.llm_model_var.get()} 参数大小: {llm_info.get('size', '未知')} 最后使用时间: {llm_info.get('modified_at', '未知')} 支持功能: {llm_info.get('capabilities', '未知')} ✅ 嵌入模型信息: 名称: {self.embedding_model_var.get()} 参数大小: {embed_info.get('size', '未知')} 最后使用时间: {embed_info.get('modified_at', '未知')} 支持功能: {embed_info.get('capabilities', '未知')} ⏱️ 最后检查时间: {time.strftime("%Y-%m-%d %H:%M:%S")} """ self.model_status_text.insert(tk.INSERT, status_text) self.model_status_text.config(state=tk.DISABLED) self.status_label.config(text="● 模型状态检查完成", foreground="#28a745") # 绿色状态 except Exception as e: self.model_status_text.config(state=tk.NORMAL) self.model_status_text.delete("1.0", tk.END) self.model_status_text.insert(tk.INSERT, f"❌ 检查模型状态时出错: {str(e)}") self.model_status_text.config(state=tk.DISABLED) self.status_label.config(text="● 模型检查出错", foreground="#dc3545") # 红色状态 def update_param(self, param, value): self.params[param] = value # 更新标签显示 if param == "temperature": self.temp_label.config(text=f"{value:.1f}") elif param == "top_p": self.top_p_label.config(text=f"{value:.2f}") elif param == "chunk_size": self.chunk_label.config(text=f"{value}") # 运行应用程序 if __name__ == "__main__": root = ThemedTk(theme="arc") # 使用现代主题 app = RAGApplication(root) root.mainloop()
最新发布
08-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值