DWORD转换为格式时出错 time_t注意!

本文解决了一个程序从VS2003移植到VS2008后出现的问题,在调用localtime_s时因time_t类型从32位变更为64位导致的错误。通过调整类型转换方式修复了此问题。

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

本文转载自http://bluezealot.spaces.live.com/blog/cns!A07F3383AB036B6A!392.entry

原文如下:

注意VC9中的time_t

最近碰到了一个问题,原先用VS2003编译的非托管C程序,移植到VS2008上编译出来的程序不能用了,执行到localtime_s这个语句的时候出错了。

原先的程序是这样的:

struct tm gtime;

DOWRD dwordTime = xxxxxx;//此处数据随便所以用xxxxxx代替

localtime_s(&gtime, (time_t*)&dwordTime);//此处出错

 

经过调查如果将程序修改成下面这样执行就OK:

struct tm gtime;

DOWRD dwordTime = xxxxxx;

time_t time = (time_t)dwordTime;

localtime_s(&gtime,&time);

从上面这段程序来看,很难看出看出来问题出在哪儿。但是如果我们看一下VC9中关于time_t的定义就可以找到前面那段代码的问题所在了。

#ifdef _USE_32BIT_TIME_T

typedef __time32_t time_t;      /* time value */

#else

typedef __time64_t time_t;      /* time value */

#endif

可以看出time_t的默认类型是__time64_t也就是int64,现在明白之前的程序为什么出错了,因为在没有宏定义_USE_32BIT_TIME_T的情况下,localtime_s的第二个参数要求是指向int64位的指针,但是原先的定义DWORD类型的所以出错了。如果使用EVENTLOGRECORD结构体的关于时间的成员转换成tm的话要小心,因为EVENTLOGRECORD结构体重的时间成员全部是DWORD类型的。

那么我们在编译的preprossesor中定义_USE_32BIT_TIME_T可不可以呢,当然是可以的,我们可以不修改程序,但是如果碰到2038年以后的时间的话localtime_s会出错,所以还是用int64型的time_t好一些。

那么之后的修改中强制类型转换time_t time = (time_t)dwordTime; 为什么没问题呢,这应该是强制类型转换的基础知识,对指针做强制类型转换的时候,并没有重新申请空间而只是转换结果的指针指向了转换目标的指针指向的地址,如果转换前后的类型所使用的内存空间不一样,结果是不可预知的,所以指针的强制类型转换一定要小心,而值类型的强制类型转换会申请新的空间并且有一定的转换规则(拷贝高位之类的),相对要安全一些,不过也要了解转换规则才可以使用。
================================
正好我在写一个相关的程序的时候,同样被那个定义搞伤了,单步跟踪到系统函数里面发现有段代码不执行~~~上网查到了这篇文章,问题解决了~~
记录以备忘。
我做了一个宠物智能投喂系统,现在我有一个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
/*************************************************************************** * @file power_data.c * @brief * **************************************************************************** * @attention * * Created on: 2025-05-12 * Author: YL Monitor Software group * **************************************************************************** * @description * 功率部件的数据缓存处理模块 * * ****************************************************************************/ /************************ Includes *************************/ /************************ 宏指令 *************************/ #include "power_data.h" /************************ Private types *************************/ /************************ Private constants *************************/ /************************ 功能结构体 *************************/ typedef enum{ CACHE_L1_LOADING = 0xA1,/*正在加载数据*/ CACHE_L1_READY = 0xA2,/*数据就绪*/ CACHE_L1_SENT = 0xA2,/*数据已上传至LEVEL2*/ }ENUM_CACHE_L1_STATUS; typedef enum{ CACHE_L2_SENDING = 0x55,/*数据待上传*/ CACHE_L2_SENT = 0xAA,/*数据已上传*/ }ENUM_CACHE_L2_STATUS; /************************ Private macros *************************/ /************************ Private variables *************************/ /************************ 私有变量 *************************/ #if !SERIAL1_DMARx_ENABLE //禁用DMA1读取 0 /* 一级数据缓存:用于功率部件接收数据的实缓存 */ uint8_t power1_data_cache_L1[POWER_DEVICE_DATA_SIZE] = {0}; static SemaphoreHandle_t mutex_RW_Power1_L1 = NULL; /* 一级缓存当前数据写入位置 */ static uint16_t power1_L1_wPos = 0; /* 一级数据缓存状态 */ static uint16_t power1_L1_status = CACHE_L1_LOADING; #endif #if !SERIAL2_DMARx_ENABLE //禁用DMA2读取 0 /* 一级数据缓存:用于功率部件接收数据的实缓存 */ uint8_t power2_data_cache_L1[POWER_DEVICE_DATA_SIZE] = {0}; static SemaphoreHandle_t mutex_RW_Power2_L1 = NULL; /* 一级缓存当前数据写入位置 */ static uint16_t power2_L1_wPos = 0; /* 一级数据缓存状态 */ static uint16_t power2_L1_status = CACHE_L1_LOADING; #endif /* 二级数据缓存:用于系统状态监控 */ static uint8_t power1_data_cache_L2[POWER_DEVICE_DATA_SIZE] = {0}; static uint8_t power2_data_cache_L2[POWER_DEVICE_DATA_SIZE] = {0}; static SemaphoreHandle_t mutex_RW_Power1_L2 = NULL; static SemaphoreHandle_t mutex_RW_Power2_L2 = NULL; /* 二级数据缓存状态 */ static uint8_t power1_L2_status = CACHE_L2_SENDING; static uint8_t power2_L2_status = CACHE_L2_SENDING; /************************ Functions *************************/ /************************ 功能函数 *************************/ /************************************************************ * @funName : MD_SwInitPowerData * @Input : NULL * * @Output : ***************** * @Description : 数据缓存模块软件资源初始化 * * ***************** * @Athor : YL Software Group * @Version : V0.0.0 * @Data : 2025/5/12 * *************************************************************/ void MD_SwInitPowerData(void) { #if !SERIAL1_DMARx_ENABLE if(NULL == mutex_RW_Power1_L1) { mutex_RW_Power1_L1 = xSemaphoreCreateBinary(); /* 数据读写互斥量创建失败 */ if(NULL == mutex_RW_Power1_L1) { } else { /* 释放数据读写互斥量 */ xSemaphoreGive(mutex_RW_Power1_L1); } } #endif #if SERIAL2_DMARx_ENABLE #else if(NULL == mutex_RW_Power2_L1) { mutex_RW_Power2_L1 = xSemaphoreCreateBinary(); /* 数据读写互斥量创建失败 */ if(NULL == mutex_RW_Power2_L1) { } else { /* 释放数据读写互斥量 */ xSemaphoreGive(mutex_RW_Power2_L1); } } #endif if(NULL == mutex_RW_Power1_L2) { mutex_RW_Power1_L2 = xSemaphoreCreateBinary(); /* 数据读写互斥量创建失败 */ if(NULL == mutex_RW_Power1_L2) { } else { /* 释放数据读写互斥量 */ xSemaphoreGive(mutex_RW_Power1_L2); } } if(NULL == mutex_RW_Power2_L2) { mutex_RW_Power2_L2 = xSemaphoreCreateBinary(); /* 数据读写互斥量创建失败 */ if(NULL == mutex_RW_Power2_L2) { } else { /* 释放数据读写互斥量 */ xSemaphoreGive(mutex_RW_Power2_L2); } } } /************************************************************ * @funName : MD_UpdatePowerL2 * @Input : device-功率部件序号 * * @Output : ***************** * @Description : 更新功率部件二级缓存数据 * * ***************** * @Athor : YL Software Group * @Version : V0.0.0 * @Data : 2025/5/12 * *************************************************************/ void MD_UpdatePowerL2(const uint8_t device) { switch(device) { case POWER_DEVICE_1: { #if SERIAL1_DMARx_ENABLE if(BSP_GetRecvSize4Serial1() >= POWER_DEVICE_DATA_SIZE) { uint8_t rbuf[POWER_DEVICE_DATA_SIZE] = {0}; uint16_t rlen = 0; BSP_Recv4Serial1(rbuf, &rlen); if(rlen >= POWER_DEVICE_DATA_SIZE){ portBASE_TYPE xRecvWoken = pdFALSE; xSemaphoreTakeFromISR(mutex_RW_Power1_L2, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); memcpy((uint8_t*)power1_data_cache_L2, (uint8_t*)rbuf, POWER_DEVICE_DATA_SIZE); power1_L2_status = CACHE_L2_SENDING;/* 待发送 */ xRecvWoken = pdFALSE; xSemaphoreGiveFromISR(mutex_RW_Power1_L2, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); } } #else if(CACHE_L1_READY == power1_L1_status) { portBASE_TYPE xRecvWoken = pdFALSE; xSemaphoreTakeFromISR(mutex_RW_Power1_L2, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); memcpy((uint8_t*)power1_data_cache_L2, (uint8_t*)power1_data_cache_L1, POWER_DEVICE_DATA_SIZE); power1_L1_status = CACHE_L1_SENT; power1_L2_status = CACHE_L2_SENDING;/* 待发送 */ xRecvWoken = pdFALSE; xSemaphoreGiveFromISR(mutex_RW_Power1_L2, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); } #endif }break; case POWER_DEVICE_2: { #if SERIAL2_DMARx_ENABLE if(BSP_GetRecvSize4Serial2() >= POWER_DEVICE_DATA_SIZE) { uint8_t rbuf[POWER_DEVICE_DATA_SIZE] = {0}; uint16_t rlen = 0; BSP_Recv4Serial2(rbuf, &rlen); if(rlen >= POWER_DEVICE_DATA_SIZE){ portBASE_TYPE xRecvWoken = pdFALSE; xSemaphoreTakeFromISR(mutex_RW_Power2_L2, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); memcpy((uint8_t*)power2_data_cache_L2, (uint8_t*)rbuf, POWER_DEVICE_DATA_SIZE); power2_L2_status = CACHE_L2_SENDING;/* 待发送 */ xRecvWoken = pdFALSE; xSemaphoreGiveFromISR(mutex_RW_Power2_L2, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); } } #else if(CACHE_L1_READY == power2_L1_status) { portBASE_TYPE xRecvWoken = pdFALSE; xSemaphoreTakeFromISR(mutex_RW_Power2_L2, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); memcpy((uint8_t*)power2_data_cache_L2, (uint8_t*)power2_data_cache_L1, POWER_DEVICE_DATA_SIZE); power1_L1_status = CACHE_L1_SENT; power2_L2_status = CACHE_L2_SENDING;/* 待发送 */ xRecvWoken = pdFALSE; xSemaphoreGiveFromISR(mutex_RW_Power2_L2, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); } #endif }break; } } /************************************************************ * @funName : MD_UpdatePowerL1 * @Input : device-功率部件序号 * bFirst-是否为第一个数据 * wbuf-数据 * wlen-数据长度 * * @Output : ***************** * @Description : 更新功率部件一级缓存数据 * * ***************** * @Athor : YL Software Group * @Version : V0.0.0 * @Data : 2025/5/12 * *************************************************************/ //static uint8_t byte = 0; void MD_UpdatePowerL1(const uint8_t device, const bool bFirst, const uint8_t* wbuf, const uint16_t wlen) { uint16_t len = wlen; if(wlen <= 0) { return; } switch(device) { case POWER_DEVICE_1: { #if SERIAL1_DMARx_ENABLE #else if(bFirst) { power1_L1_status = CACHE_L1_LOADING; power1_L1_wPos = 0; memset((uint8_t*)power1_data_cache_L1, 0, POWER_DEVICE_DATA_SIZE); } if(len > POWER_DEVICE_DATA_SIZE - power1_L1_wPos) { len = POWER_DEVICE_DATA_SIZE - power1_L1_wPos; } portBASE_TYPE xRecvWoken = pdFALSE; xSemaphoreTakeFromISR(mutex_RW_Power1_L1, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); memcpy((uint8_t*)&power1_data_cache_L1[power1_L1_wPos], wbuf, len); power1_L1_wPos += len; xRecvWoken = pdFALSE; xSemaphoreGiveFromISR(mutex_RW_Power1_L1, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); if(POWER_DEVICE_DATA_SIZE <= power1_L1_wPos) { power1_L1_status = CACHE_L1_READY; } #endif }break; case POWER_DEVICE_2: { #if SERIAL2_DMARx_ENABLE #else if(bFirst) { power2_L1_status = CACHE_L1_LOADING; power2_L1_wPos = 0; memset((uint8_t*)power2_data_cache_L1, 0, POWER_DEVICE_DATA_SIZE); } if(len > POWER_DEVICE_DATA_SIZE - power2_L1_wPos) { len = POWER_DEVICE_DATA_SIZE - power2_L1_wPos; } portBASE_TYPE xRecvWoken = pdFALSE; xSemaphoreTakeFromISR(mutex_RW_Power2_L1, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); memcpy((uint8_t*)&power2_data_cache_L1[power2_L1_wPos], wbuf, len); power2_L1_wPos += len; xRecvWoken = pdFALSE; xSemaphoreGiveFromISR(mutex_RW_Power2_L1, &xRecvWoken); portYIELD_FROM_ISR(xRecvWoken); if(POWER_DEVICE_DATA_SIZE <= power2_L1_wPos) { power2_L1_status = CACHE_L1_READY; } #endif }break; } } /********************功率部件一级缓存数据********************/ /************************************************************ * @funName : MD_ReadPowerL2 * @Input : device-功率部件序号 * rbuf-数据输出缓存 * pos-数据读取位置 * rlen-数据读取长度 * * @Output : ***************** * @Description : 获取功率部件二级缓存数据 * * ***************** * @Athor : YL Software Group * @Version : V0.0.0 * @Data : 2025/5/13 * *************************************************************/ bool MD_ReadPowerL2(const uint8_t device, uint8_t *rbuf, const uint16_t pos, const uint16_t rlen) { if(rlen > POWER_DEVICE_DATA_SIZE || pos >= POWER_DEVICE_DATA_SIZE || POWER_DEVICE_DATA_SIZE - pos < rlen) { return false; } switch(device) { case POWER_DEVICE_1: { xSemaphoreTake(mutex_RW_Power1_L2, portMAX_DELAY); memcpy(rbuf, (uint8_t*)&power1_data_cache_L2[pos], rlen); xSemaphoreGive(mutex_RW_Power1_L2); }break; case POWER_DEVICE_2: { xSemaphoreTake(mutex_RW_Power2_L2, portMAX_DELAY); memcpy(rbuf, (uint8_t*)&power2_data_cache_L2[pos], rlen); xSemaphoreGive(mutex_RW_Power2_L2); }break; } return true; } /************************************************************ * @funName : MD_GetPowerL2 * @Input : device-功率部件序号 * rbuf-数据缓存地址 * * @Output : ***************** * @Description : 获取功率部件二级缓存地址 * * ***************** * @Athor : YL Software Group * @Version : V0.0.0 * @Data : 2025/5/13 * *************************************************************/ uint8_t* MD_GetPowerL2(const uint8_t device) { uint8_t* addr = NULL; switch(device) { case POWER_DEVICE_1: { xSemaphoreTake(mutex_RW_Power1_L2, portMAX_DELAY); if(CACHE_L2_SENDING != power1_L2_status) { addr = NULL; } else { power1_L2_status = CACHE_L2_SENT; addr = power1_data_cache_L2; } xSemaphoreGive(mutex_RW_Power1_L2); }break; case POWER_DEVICE_2: { xSemaphoreTake(mutex_RW_Power2_L2, portMAX_DELAY); if(CACHE_L2_SENDING != power2_L2_status) { addr = NULL; } else{ power2_L2_status = CACHE_L2_SENT; addr = power2_data_cache_L2; } xSemaphoreGive(mutex_RW_Power1_L2); }break; } return addr; } /************************ End of file *************************/ /*************************************************************************** * @file fw_data.h * @brief This file contains the macros & function about real data for framework & App. * **************************************************************************** * @attention * * Created on: 2025-05-30 * Author: YL Monitor Software group * **************************************************************************** * @description * * * ****************************************************************************/ #ifndef __FW_DATA_H_ #define __FW_DATA_H_ #ifdef __cplusplus extern "C" { #endif /************************ Includes *************************/ #include "main.h" /************************ Exportd types ********************/ typedef struct{ uint8_t byte_H; uint8_t byte_L; }Power_Bits16; typedef struct{ uint8_t byte0; uint8_t byte1; uint8_t byte2; uint8_t byte3; }Power_Bits32; /* 功率部件系统参数 */ typedef struct{ /* word 0 */ Power_Bits16 Reserved0; //0-预留 /* word 1 */ Power_Bits16 SYSCTRL; //1-系统控制 /* word 2 */ Power_Bits16 Flag; //2-系统状态标志 /* word 3 */ Power_Bits16 ProtectHard_PROHARD; //3-硬件保护标志 /* word 4 */ Power_Bits16 ProtectSoft_PROSOFT; //4-软件保护标志 /* word 5 */ Power_Bits16 ProtectDrive_PRODRIVE; //5-驱动保护标志 /* word 6 */ Power_Bits16 ProtectComm_PROCOMM; //6-通信保护标志 /* word 7 */ Power_Bits16 INVCTRL; //7-逆变器控制 /* word 8 */ Power_Bits16 Reserved8; //预留 /* word 9 */ Power_Bits16 Reserved9; //预留 /* word 10 */ Power_Bits16 Reserved10; //预留 /* word 11 */ Power_Bits32 GPADAT_H; //GPIO0~31状态 /* word 12 */ Power_Bits32 GPADAT_L; //GPIO0~31状态 /* word 13*/ Power_Bits32 GPBDAT_H; //GPIO32~63状态 /* word 14 */ Power_Bits32 GPBDAT_L; //GPIO32~63状态 /* word 15 */ Power_Bits32 GPCDAT_H; //GPIO64~87状态 /* word 16 */ Power_Bits32 GPCDAT_L; //GPIO64~87状态 /* word 17 */ Power_Bits16 Reserved17; //预留 /* word 18 */ Power_Bits16 Reserved18; //预留 /* word 19 */ Power_Bits16 Reserved19; //预留 /* word 20 */ Power_Bits16 OSC_CLK_FRQ; //外部晶振频率 /* word 21 */ Power_Bits16 SYS_CLK_FRQ; //系统钟频率 /* word 22 */ Power_Bits16 SYS_TICK; //定钟基准 /* word 23 */ Power_Bits16 SET_F_PWM; //开关频率 /* word 24 */ Power_Bits16 Reserved24; //预留 /* word 25 */ Power_Bits16 SysMode; //工作模式 /* word 26 */ Power_Bits16 SysState; //工作状态 /* word 27 */ Power_Bits16 SysStartMode; //启动方式 /* word 28*/ Power_Bits16 SysStartStopControl; //启停控制指令来源 /* word 29*/ Power_Bits16 SysCommandSource; //系统频率指令来源 /* word 30*/ Power_Bits16 ModID; //模块编号 /* word 31*/ Power_Bits16 SETUP_UOUT; //电压设定值 /* word 32*/ Power_Bits16 SETUP_IOUT; //电流设定值 /* word 33*/ Power_Bits16 SETUP_FREQ; //频率设定值 /* word 34*/ Power_Bits16 SOFTSTART_TIME; //软件起动间 /* word 35*/ Power_Bits16 STEP_UOUT; //电压步长 /* word 36*/ Power_Bits16 STEP_IOUT; //电流步长 /* word 37*/ Power_Bits16 STEP_FREQ; //频率步长 /* word 38 */ Power_Bits16 STEP_ANGLE; //相角步长 /* word 39 */ Power_Bits16 POINTCYCLE; //周波点数 /* word 40 */ Power_Bits16 REF_UOUT; //电压给定值 /* word 41 */ Power_Bits16 REF_IOUT; //电流给定值 /* word 42 */ Power_Bits16 REF_FREQ; //频率给定值 /* word 43 */ Power_Bits16 REF_ANGLE; //实相角 /* word 44 */ Power_Bits16 KPWMA; //A相调制系数 /* word 45 */ Power_Bits16 KPWMB; //B相调制系数 /* word 46 */ Power_Bits16 KPWMC; //C相调制系数 /* word 47 */ Power_Bits16 Effective_Uin; //输入电压有效值 /* word 48 */ Power_Bits16 Effective_Iin; //输入电流有效值 /* word 49 */ Power_Bits16 Effective_Udc; //直流母线电压有效值 /* word 50 */ Power_Bits16 Effective_Uout1; //A相输出电压有效值 /* word 51 */ Power_Bits16 Effective_Uout2; //B相输出电压有效值 /* word 52 */ Power_Bits16 Effective_Uout3; //C相输出电压有效值 /* word 53 */ Power_Bits16 Effective_Iout1; //A相输出电流有效值 /* word 54 */ Power_Bits16 Effective_Iout2; //B相输出电流有效值 /* word 55 */ Power_Bits16 Effective_Iout3; //C相输出电流有效值 /* word 56 */ Power_Bits16 Effective_IL1; //A相电感电流有效值 /* word 57 */ Power_Bits16 Effective_IL2; //B相电感电流有效值 /* word 58 */ Power_Bits16 Effective_IL3; //C相电感电流有效值 /* word 59 */ Power_Bits16 Effective_UinC; //备用电源电压有效值 /* word 60 */ Power_Bits16 Effective_UoutSet; //输出电压设定值(模拟) /* word 61 */ Power_Bits16 Effective_IoutSet; //输出电流设定值(模拟) /* word 62 */ Power_Bits16 Reserved62; //预留 /* word 63 */ Power_Bits16 Effective_FreqSet; //输出电压频率设定值(模拟) /* word 64 */ Power_Bits16 PIDU1_hReference; //PIDU1给定值 /* word 65 */ Power_Bits16 PIDI1_hPresentFeedback; //PIDI1反馈值 /* word 66 */ Power_Bits16 PIDI1_hReference; //PIDI1输出值 /* word 67 */ Power_Bits16 PIDU1_hKp_Gain; //PIDU1参数kp /* word 68*/ Power_Bits16 PIDU1_hKi_Gain; //PIDU1参数ki /* word 69*/ Power_Bits16 PIDU1_hKd_Gain; //PIDU1参数kd /* word 70*/ Power_Bits32 PIDU1_wLower_Limit_Integral; //PIDU1积分下限值 /* word 71*/ Power_Bits32 PIDU1_wUpper_Limit_Integral; //PIDU1积分上限值 /* word 72*/ Power_Bits16 PIDU1_hLower_Limit_Output; //PIDU1输出下限值 /* word 73*/ Power_Bits16 PIDU1_hUpper_Limit_Output; //PIDU1输出上限值 /* word 74*/ Power_Bits16 PIDU2_hReference; //PIDU2给定值 /* word 75*/ Power_Bits16 PIDU2_hPresentFeedback; //PIDU2反馈值 /* word 76*/ Power_Bits16 PIDI2_hReference; //PIDI2输出值 /* word 77*/ Power_Bits16 PIDU2_hKp_Gain; //PIDU2参数kp /* word 78*/ Power_Bits16 PIDU2_hKi_Gain; //PIDU2参数ki /* word 79*/ Power_Bits16 PIDU2_hKd_Gain; //PIDU2参数kd /* word 80*/ Power_Bits32 PIDU2_wLower_Limit_Integral; //PIDU2积分下限值 /* word 81*/ Power_Bits32 PIDU2_wUpper_Limit_Integral; //PIDU2积分上限值 /* word 82*/ Power_Bits16 PIDU2_hLower_Limit_Output; //PIDU2输出下限值 /* word 83*/ Power_Bits16 PIDU2_hUpper_Limit_Output; //PIDU2输出上限值 /* word 84 */ Power_Bits16 PIDI1hReference; //PIDI1给定值 /* word 85 */ Power_Bits16 PIDI1hPresentFeedback; //PIDI1反馈值 /* word 86 */ Power_Bits16 iParkUref_Ds; //PIDI1输出值 /* word 87 */ Power_Bits16 PIDI1_hKp_Gain; //PIDI1参数kp /* word 88*/ Power_Bits16 PIDI1_hKi_Gain; //PIDI1参数ki /* word 89*/ Power_Bits16 PIDI1_hKd_Gain; //PIDI1参数kd /* word 90*/ Power_Bits32 PIDI1_wLower_Limit_Integral; //PIDI1积分下限值 /* word 91*/ Power_Bits32 PIDI1_wUpper_Limit_Integral; //PIDI1积分上限值 /* word 92*/ Power_Bits16 PIDI1_hLower_Limit_Output; //PIDI1输出下限值 /* word 93*/ Power_Bits16 PIDI1_hUpper_Limit_Output; //PIDI1输出上限值 /* word 94 */ Power_Bits16 PIDI2hReference; //PIDI2给定值 /* word 95 */ Power_Bits16 PIDI2_hPresentFeedback; //PIDI2反馈值 /* word 96 */ Power_Bits16 iParkUref_Qs; //输出值 /* word 97 */ Power_Bits16 PIDI2_hKp_Gain; //PIDI2参数kp /* word 98*/ Power_Bits16 PIDI2_hKi_Gain; //PIDI2参数ki /* word 99*/ Power_Bits16 PIDI2_hKd_Gain; //PIDI2参数kd /* word 100*/ Power_Bits32 PIDI2_wLower_Limit_Integral; //PIDI2积分下限值 /* word 101*/ Power_Bits32 PIDI2_wUpper_Limit_Integral; //PIDI2积分上限值 /* word 102*/ Power_Bits16 PIDI2_hLower_Limit_Output; //PIDI2输出下限值 /* word 103*/ Power_Bits16 PIDI2_hUpper_Limit_Output; //PIDI2输出上限值 /* word 104 */ Power_Bits16 PIDPARA_hReference; //PIDPARA给定值 /* word 105 */ Power_Bits16 PIDPARA_hPresentFeedback; //PIDPARA反馈值 /* word 106 */ Power_Bits16 Reserved106; //PIDPARA输出值 /* word 107 */ Power_Bits16 PIDPARA_hKp_Gain; //PIDPARA参数kp /* word 108*/ Power_Bits16 PIDPARA_hKi_Gain; //PIDPARA参数ki /* word 109*/ Power_Bits16 PIDPARA_hKd_Gain; //PIDPARA参数kd /* word 110*/ Power_Bits32 PIDPARA_wLower_Limit_Integral;//PIDPARA积分下限值 /* word 111*/ Power_Bits32 PIDPARA_wUpper_Limit_Integral;//PIDPARA积分上限值 /* word 112*/ Power_Bits16 PIDPARA_hLower_Limit_Output; //PIDPARA输出下限值 /* word 113*/ Power_Bits16 PIDPARA_hUpper_Limit_Output; //PIDPARA输出上限值 /* word 114 */ Power_Bits16 PIDPLL_hReference; //PIDPLL给定值 /* word 115 */ Power_Bits16 PIDPLL_hPresentFeedback; //PIDPLL反馈值 /* word 116 */ Power_Bits16 Reserved116; //PIDPLL输出值 /* word 117 */ Power_Bits16 PIDPLL_hKp_Gain; //PIDPLL参数kp /* word 118*/ Power_Bits16 PIDPLL_hKi_Gain; //PIDPLL参数ki /* word 119*/ Power_Bits16 PIDPLL_hKd_Gain; //PIDPLL参数kd /* word 120*/ Power_Bits32 PIDPLL_wLower_Limit_Integral; //PIDPLL积分下限值 /* word 121*/ Power_Bits32 PIDPLL_wUpper_Limit_Integral; //PIDPLL积分上限值 /* word 122*/ Power_Bits16 PIDPLL_hLower_Limit_Output; //PIDPLL输出下限值 /* word 123*/ Power_Bits16 PIDPLL_hUpper_Limit_Output; //PIDPLL输出上限值 /* word 124 */ Power_Bits16 Reserved124; //输出变压器变比 /* word 125 */ Power_Bits16 Reserved125; //变压器等效电抗 /* word 126 */ Power_Bits16 Reserved126; //变压器等效电阻 /* word 127 */ Power_Bits16 Reserved127; //预留 /* word 128 */ Power_Bits16 FdOverUin_ValLimitHi; //输入过压保护值 /* word 129 */ Power_Bits16 FdUnderUin_ValLimitHi; //输入欠压保护值 /* word 130 */ Power_Bits16 FdOverIin_ValLimitHi; //输入过流保护值 /* word 131 */ Power_Bits16 FdOverUo1_ValLimitHi; //输出过压保护值 /* word 132 */ Power_Bits16 FdOverIo1_ValLimitHi; //输出过流保护值 /* word 133 */ Power_Bits16 FdOverIL1_ValLimitHi; //电感过流保护值 /* word 134 */ Power_Bits16 Reserved134; //短路保护电压动作值 /* word 135 */ Power_Bits16 Reserved135; //短路保护电流动作值 /* word 136 */ Power_Bits16 Reserved136; //短路保护电压返回值 /* word 137 */ Power_Bits16 Reserved137; //短路保护电流返回值 /* word 138 */ Power_Bits16 Reserved138; //短路运行间 /* word 139 */ Power_Bits16 Reserved139; //110%过载保护限值 /* word 140 */ Power_Bits16 Reserved140; //110%过载保护间 /* word 141 */ Power_Bits16 Reserved141; //110%过载保护倒计 /* word 142 */ Power_Bits16 Reserved142; //120%过载保护限值 /* word 143 */ Power_Bits16 Reserved143; //120%过载保护间 /* word 144 */ Power_Bits16 Reserved144; //120%过载保护倒计 /* word 145 预留*/ Power_Bits16 Reserved145; /* word 146 AD结果寄存器数据(CH0)*/ Power_Bits16 AdcRegs_ADCRESULT0; /* word 147 */ Power_Bits16 AdcRegs_ADCRESULT1; //AD结果寄存器数据(CH1) /* word 148 */ Power_Bits16 AdcRegs_ADCRESULT2; //AD结果寄存器数据(CH2) /* word 149 */ Power_Bits16 AdcRegs_ADCRESULT3; //AD结果寄存器数据(CH3) /* word 150 */ Power_Bits16 AdcRegs_ADCRESULT4; //AD结果寄存器数据(CH4) /* word 151 */ Power_Bits16 AdcRegs_ADCRESULT5; //AD结果寄存器数据(CH5) /* word 152 */ Power_Bits16 AdcRegs_ADCRESULT6; //AD结果寄存器数据(CH6) /* word 153 */ Power_Bits16 AdcRegs_ADCRESULT7; //AD结果寄存器数据(CH7) /* word 154 */ Power_Bits16 AdcRegs_ADCRESULT8; //AD结果寄存器数据(CH8) /* word 155 */ Power_Bits16 AdcRegs_ADCRESULT9; //AD结果寄存器数据(CH9) /* word 156 */ Power_Bits16 AdcRegs_ADCRESULT10; //AD结果寄存器数据(CH10) /* word 157 */ Power_Bits16 AdcRegs_ADCRESULT11; //AD结果寄存器数据(CH11) /* word 158 */ Power_Bits16 AdcRegs_ADCRESULT12; //AD结果寄存器数据(CH12) /* word 159 */ Power_Bits16 AdcRegs_ADCRESULT13; //AD结果寄存器数据(CH13) /* word 160 */ Power_Bits16 AdcRegs_ADCRESULT14; //AD结果寄存器数据(CH14) /* word 161 */ Power_Bits16 AdcRegs_ADCRESULT15; //AD结果寄存器数据(CH15) /* word 162 预留*/ Power_Bits16 Reserved162; /* word 163 预留*/ Power_Bits16 Reserved163; /* word 164 预留*/ Power_Bits16 Reserved164; /* word 165 预留*/ Power_Bits16 Reserved165; /* word 166 预留*/ Power_Bits16 Reserved166; /* word 167 预留*/ Power_Bits16 Reserved167; /* word 168 预留*/ Power_Bits16 Reserved168; /* word 169预留 */ Power_Bits16 Reserved169; /* word 170 预留*/ Power_Bits16 Reserved170; /* word 171 预留*/ Power_Bits16 Reserved171; /* word 172 预留*/ Power_Bits16 Reserved172; /* word 173 预留*/ Power_Bits16 Reserved173; /* word 174 预留*/ Power_Bits16 Reserved174; /* word 175 预留*/ Power_Bits16 Reserved175; /* word 176 预留*/ Power_Bits16 Reserved176; /* word 177 预留*/ Power_Bits16 Reserved177; /* word 178 预留*/ Power_Bits16 Reserved178; /* word 179 预留*/ Power_Bits16 Reserved179; /* word 180 输入电压传感器采样范围*/ Power_Bits16 PEAK_UIN_SENSOR; /* word 181 输入电流传感器采样范围*/ Power_Bits16 PEAK_IIN_SENSOR; /* word 182 输出电压传感器采样范围*/ Power_Bits16 PEAK_UO_SENSOR; /* word 183 输出电流传感器采样范围*/ Power_Bits16 PEAK_IO_SENSOR; /* word 184 电感电流传感器采样范围*/ Power_Bits16 PEAK_IL_SENSOR; /* word 185 预留*/ Power_Bits16 Reserved185; /* word 186 预留*/ Power_Bits16 Reserved186; /* word 187 预留*/ Power_Bits16 Reserved187; /* word 188 预留*/ Power_Bits16 Reserved188; /* word 189 预留*/ Power_Bits16 Reserved189; /* word 190 通道选择*/ Power_Bits16 ChannelSelect; /* word 191 预留*/ Power_Bits16 Reserved191; /* word 192 预留*/ Power_Bits16 Reserved192; /* word 193 地址偏移量*/ Power_Bits16 AddressOffset; /* word 194 预留*/ Power_Bits16 Reserved194; /* word 195 预留*/ Power_Bits16 Reserved195; /* word 196 预留*/ Power_Bits16 Reserved196; /* word 197 预留*/ Power_Bits16 Reserved197; /* word 198 预留*/ Power_Bits16 Reserved198; /* word 199 网络通讯协议控制*/ Power_Bits16 Modbus_Control_ModbusCtrl; }Power_System_Type; STM32F105 power_data.c程序的二级缓存的400字节的数据准确的映射给fw_data.h程序中的Power_System_Type结构体中,然后去调用结构体的某一个数据,需要频繁访问结构体中的某个字段,可以将其缓存到局部变量中,减少多次访问互斥锁的开销,用标准库写出详细代码和注释,优化的建议也写入代码中,别单独提出来
最新发布
06-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值