如何实现手机与PC之间的通信
本文介绍如何建立手机与电脑之间的通信链路,以及如何从电脑上执行手机解释器中的命令。
引言
本文提供了一个逐步教程,介绍如何使用串行通信将手机连接到电脑,并描述了通过电脑执行手机特定命令的方法。
可以通过三种方式建立电脑和手机之间的通信:
- 串行端口(需要数据线)。
- 红外端口(需要在手机和电脑上都有红外端口)。
- 蓝牙(需要蓝牙无线连接器)。
(注意:我只使用过串行端口和红外端口。)
解释
初始化并打开端口
/* portNm =COM1,COM2 etc which ever COM port your phone is connected */ bool OpenPort( char *portNm ) { if( portNm != NULL ) // check to if port exists { /* hComm is handle that makes a buffer file pointin to your COM port for read and write of port data */ hComm = CreateFile( portNm,GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, NULL, 0); if (hComm == INVALID_HANDLE_VALUE) { //error occured alert user about error return false; } else // port opened successfully alert user return true; } else { // specified port missing alert user return false; } }
向端口写入
BOOL WriteABuffer(char * lpBuf, DWORD dwToWrite) { OVERLAPPED osWrite = {0}; DWORD dwWritten; BOOL fRes; // Issue write. if (!WriteFile(hComm, lpBuf, dwToWrite, &dwWritten, NULL)) { if (GetLastError() != ERROR_IO_PENDING) { // WriteFile failed, but it isn't delayed. Report error and abort. fRes = FALSE; } else { // Write is pending. if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, TRUE)) { fRes = FALSE;} else { // Write operation completed successfully. fRes = TRUE;} } } else // WriteFile completed immediately. fRes = TRUE; return fRes; }
从端口读取
void ReadPort() { DWORD dwRead; char chRead[250]; // remember to adjust 250 according to the total data read char *count = NULL; /* flush the old values and fill with some arbitary symbol thats most unlikely to appear in your data to know the end point after reading */ memset(chRead,'\x91',250); Sleep( 5L); ReadFile(hComm, chRead, 250, &dwRead, NULL); /* now chRead contains data . you can manipulate it accoring to your needs now. */ }
特殊设置
在调用 OpenPort
后,必须将 DCB 和连接超时时间分配给端口。DCB 用于调整端口的通信设置。您必须根据您的通信需求设置您的端口。
连接超时用于分配端口强制停止从手机读取数据的时长,以防止数据过长时出现异常。
if(OpenPort("COM4")) // opens COM4 port { DCB dcb dcb.fOutxCtsFlow = false; // Disable CTS monitoring dcb.fOutxDsrFlow = false; // Disable DSR monitoring dcb.fDtrControl = DTR_CONTROL_DISABLE; // Disable DTR monitoring dcb.fOutX = false; // Disable XON/XOFF for transmission dcb.fInX = false; // Disable XON/XOFF for receiving dcb.fRtsControl = RTS_CONTROL_DISABLE; // Disable RTS (Ready To Send) COMMTIMEOUTS timeouts; timeouts.ReadIntervalTimeout = 20; timeouts.ReadTotalTimeoutMultiplier = 10; timeouts.ReadTotalTimeoutConstant = 100; timeouts.WriteTotalTimeoutMultiplier = 10; timeouts.WriteTotalTimeoutConstant = 100; if (!SetCommTimeouts(hComm, &timeouts)) { // error with time outs .alert user and exit } }
上述代码片段可用于建立电脑和手机之间的有效通信。
您可以向手机解释器发出手机特定命令,它将进行处理并在处理后通过同一端口返回数据。大多数手机可以使用 Hayes AT 命令(这些命令是手机特定的,请检查这些命令与您的手机的兼容性)。Nokia AT 命令集可在 Nokia 官方网站上找到。
AT 命令可用于执行各种功能,例如将短信发送/接收到连接到手机的电脑,同步手机通讯录,更改手机设置等等。
希望本文对您有所帮助,如有任何其他问题,请随时通过 nitzbajaj@yahoo.com 与我联系。