【问题标题】:how to read AT commands with c++ code in linux如何在linux中用c++代码读取AT命令
【发布时间】:2013-05-23 07:34:43
【问题描述】:

我编写了以下代码,试图从 SM5100b GSM(连接到 Rasberry Pi)向我的手机发送消息。它正在工作,但我可以检查 AT 命令的结果,例如 Ok、Ok、+CME ERROR: 4,只有在我打开 Cutecom 模拟器时才可以。如何在此代码中编写“读取”函数以在逐行编译期间为我提供这些结果?我尝试了类似 out = read(fd, n, sizeof(n)) 的方法,但没有结果。我正在使用 Raspian 一个 Debian 操作系统和代码块。

#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */


int open_port(void)
{
 int fd; /* File descriptor for the port */
 int n,d,e,f,o,out;
 fd = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
 if (fd == -1)
  {
  /* Could not open the port. */
   perror("open_port: Unable to open /dev/ttyAMA0");
  }
 else
  fcntl(fd, F_SETFL, 0);
  sleep(2);
  n = write(fd, "AT\r\n", 4);
  if (n < 0)
  fputs("write() of 4 bytes failed!\n", stderr);
  sleep(2);

  d = write(fd, "AT+CMGF=1\r", 10);
  if (d < 0)
  fputs("write() of 10 bytes failed!\n", stderr);
  sleep(2);

  e = write(fd, "AT+CMGS=\"6034****\"\r", 20);
  if (e < 0)
  fputs("write() of 20 bytes failed!\n", stderr);
  sleep(2);

  f = write(fd, "hello\r\x1A", 10);
  if (f < 0)
  fputs("write() of 10 bytes failed!\n", stderr);
  sleep(2);

  return (fd);
  }

  int main(void)
  {
  open_port();
  }

【问题讨论】:

  • “编译期间” - 您打算如何在编译时检查运行时信息?
  • 否则在编译结束时给我上面提到的结果 Ok,Ok,Ok,Ok 等。

标签: c++ linux at-command


【解决方案1】:

您可以创建一个类似于 sendAT 的函数,它会执行以下操作:

int sendAT(char* command,int fd) {
  size_t cmdlen = strlen(command);

  int n = write(fd,command, cmdlen);
  if (n != cmdlen)
      return -1
  char reply[40];
  n = read(fd,reply,sizeof(reply));
  reply[n] = 0; //Terminate the string
  if (strcmp(reply, "OK")==0) 
      return 0; //All went well
  else
      return -1; //Some error occurred
}

目前,您有很多重复的代码,它们对您发送到手机的每个命令执行相同的操作。

【讨论】:

  • 非常感谢。我会用你的代码来测试它。还有一个问题,这段代码有什么办法不仅可以向我发送 0 或 -1,而且可以向我发送结果 OK、CME 错误等?我的意思是把我可能会遇到的错误准确地发送给我。
  • 你应该传递一个缓冲区作为参数并在读取中使用它,所以调用函数可以看到最后一个命令的结果,但我会保留整数返回代码,因为执行 strcmp(buf "OK") 在每个命令中都会再次重复代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-25
相关资源
最近更新 更多