Getting error with sending SMS with AT Commands? - c++

Please have a look at the following code:
#pragma once
using namespace System::IO::Ports;
using namespace System::Text::RegularExpressions;
using namespace System::Collections::Generic;
ref class SMS
{
public:
SMS(void);
void sendMessage();
private:
System::IO::Ports::SerialPort ^port;
};
And the cpp file
#include "StdAfx.h"
#include "SMS.h"
SMS::SMS(void)
{
//Initialize the Serial Port
port = gcnew System::IO::Ports::SerialPort();
port->PortName = "COM12";
port->BaudRate = 9600;
port->Parity = Parity::None;
port->DataBits = 8;
port->StopBits = StopBits::One;
port->Handshake = Handshake::RequestToSend;
port->DtrEnable = true;
port->RtsEnable = true;
port->NewLine = System::Environment::NewLine;
if(!port->IsOpen)
{
port->Open();
}
//Set message format
port->WriteLine("AT+CMGF=1");
//Turn off echo
port->WriteLine("ATE0");
//Set memory configurations
port->WriteLine("AT+CPMS=\"ME\",\"ME\",\"ME\"");
}
//This method will send the SMS
void SMS::sendMessage()
{
if(!port->IsOpen)
{
port->Open();
}
port->WriteLine("AT+CMGS=\"012121212\"");
port->WriteLine("Test Message From C#");
port->WriteLine(System::Convert::ToString((char)(26)));
port->Close();
}
I am trying to send SMS by accessing the dongle. The port is correct and the dongle also fine because it responded to my friend's code few hours back. What am I doing wrong here? Have I done anything incorrect with C++/CLI ? AT Commands?

try adding "CR" "LF" (Carriage Return and Line Feed characters) after each AT command, some GSM dongles (like SIM900) needem in order to work. I hope this helps
Regards

if for win32,..
prefer using
HFILE OpenFile(
LPCSTR lpFileName, // pointer to filename
LPOFSTRUCT lpReOpenBuff, // pointer to buffer for file information
UINT uStyle // action and attributes
);
with other events,...
if using SMS gateway with modem AT command capability, that's fine for direct read and write to COM port
if U using cell phone, many of this will not work. example nokia 6070, 3100 model group
best test it using hyperterminal.
I used CBuildre6 for
https://sites.google.com/site/xpressdms/rosegarden
cheer.

Related

Nucleo F401RE - can’t receive a data from rx pin (response from ESP32 WiFi module)

I have a problem with the UART communication from Nucleo f401re to ESP-Wroom-32 (WiFi BLE Click wifi module mikroe). I’m able to send an AT command but not to receive. I’m using the latest mbed-os verion, also I’m sending the at command via the ATCmdParser Api that it’s included on the “mbed.h” file. I had tried to receive with the the recv() function but it returns False. I tried also with the BufferedSerial.h with the read() but nothinguuu. I’m positive that i’m sending the command because i tried to receive the response from the esp32 module with the samd21 dev board and i’m receiving it fine.
Here is the code:
#include “mbed.h”
#include
#define ESP32_DEFAULT_BAUD_RATE 115200
BufferedSerial _serial;
ATCmdParser _parser;
/////~ set the debug parameter as a true of the ATCmdParser ~////
using namespace std;
char bufRead[100], buffWrite[50];
int main()
{
_serial = new BufferedSerial(D8, D2, ESP32_DEFAULT_BAUD_RATE);
_serial->set_format(
/* bits / 8,
/ parity / BufferedSerial::None,
/ stop bit */ 1
);
_parser = new ATCmdParser(_serial);
_parser->debug_on( 1 );
_parser->set_delimiter( “\r\n” );
bool result = false;
while(1){
_parser->send("AT");
int x = _serial->read(bufRead, 40);
printf("Response %s\n", bufRead);
printf("-> %d\n", x);
thread_sleep_for(2000);
}
}

writing and reading to/from a serial port with a timeout in c++ and Linux

I'm trying to send some hex string to a serial port, and directly read its answer in c++. If there is no answer it should timeout after a given period of time.
What is the simplest implementation of such a task?
Do i need to use stuff like boost?
To be clear: I'm searching for the most simple way to achieve this.
Sorry if my question is dumb, but im new to this topic, thanks in advance!
EDIT: Sorry that I forgot to mention, it should run on Linux.
this should be similar to your declaration:
Setup(CSerial::EBaud9600,CSerial::EData8,CSerial::EParNone,CSerial::EStop1);
Setup(CSerial::EBaudrate(9600),
CSerial::EDataBits(8),
CSerial::EParity(NOPARITY),
CSerial::EStopBits(ONESTOPBIT));
Reading data:
// Read data, until there is nothing left
DWORD dwBytesRead = 0;
BYTE abBuffer[100];
do
{
// Read data from the COM-port
serial.Read(abBuffer,sizeof(abBuffer),&dwBytesRead);
if (dwBytesRead > 0)
{
// TODO: Process the data
}
}
while (dwBytesRead == sizeof(abBuffer));
More details can be found here on code project: http://www.codeproject.com/Articles/992/Serial-library-for-C
Please note: I am used to programming serial ports in c#, and so (to the best of my knowledge) believe this would work for you. (I would also like to point outall serial port communication is send actually through as hex, but may be read via the buffer as a decimal value ( please refer to http://www.asciitable.com/ for converstion, or use something similar to UTF8 encoding)
EDIT - As per comment;
Please refer to : http://msdn.microsoft.com/en-gb/library/windows/hardware/hh439614(v=vs.85).aspx for details on serial port read/write timeouts
Write timeout will be similar to;
[BrowsableAttribute(true)]
public:
property int WriteTimeout {
int get ();
void set (int value);
}
Which allows you to get or set the timeout attribute
Full Program
public:
static void Main()
{
String^ name;
String^ message;
StringComparer^ stringComparer = StringComparer::OrdinalIgnoreCase;
Thread^ readThread = gcnew Thread(gcnew ThreadStart(PortChat::Read));
// Create a new SerialPort object with default settings.
_serialPort = gcnew SerialPort();
// Allow the user to set the appropriate properties.
_serialPort->PortName = SetPortName(_serialPort->PortName);
_serialPort->BaudRate = SetPortBaudRate(_serialPort->BaudRate);
_serialPort->Parity = SetPortParity(_serialPort->Parity);
_serialPort->DataBits = SetPortDataBits(_serialPort->DataBits);
_serialPort->StopBits = SetPortStopBits(_serialPort->StopBits);
_serialPort->Handshake = SetPortHandshake(_serialPort->Handshake);
// Set the read/write timeouts
_serialPort->ReadTimeout = 500;
_serialPort->WriteTimeout = 500;
_serialPort->Open();
_continue = true;
readThread->Start();
Console::Write("Name: ");
name = Console::ReadLine();
Console::WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console::ReadLine();
if (stringComparer->Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort->WriteLine(
String::Format("<{0}>: {1}", name, message) );
}
}
readThread->Join();
_serialPort->Close();
}
static void Read()
{
while (_continue)
{
try
{
String^ message = _serialPort->ReadLine();
Console::WriteLine(message);
}
catch (TimeoutException ^) { }
}
}
EDIT 2
Please refer to Linux Serial Port: Blocking Read with Timeout where this has been declared in the question and some of the answers may prove useful to you as well! :)
I recently came for the same issue and I found a good solution using select()
Read the documentation here: manpages.courirer-mta.org/htmlman2/select2.html
In your case you need to setup the timeout, which is the 5th argument of select:
struct timeval timeout;
timeout.tv_sec = 0 ; // seconds
timeout.tv_usec = 1000 ; // microseconds
Hope this helps.

sending emails from gmail with c++ code

I'm interested in sending emails with c++ code.
So far I've tried using the jwsmtp library at jwsmtplib and I haven't had any real success. Any suggestions? Below is my code:
//code:
#include <iostream>
#include <jwsmtp/jwsmtp.h>
using std::cout;
using std::endl;
int main( ) {
std::vector<char> vec;
std::string mess("Foo\nBar");
for(std::string::size_type i = 0; i < mess.length( ); ++i)
vec.push_back(mess[i]);
jwsmtp::mailer mail("me#gmail.com", // who the mail is too
"sme#gmail.com", // who the mail is from
"There is always room for FooBar", // subject for the email
vec, // content of the message
"smtp.gmail.com", // the smtp server to mail to
465, //jwsmtp::mailer::SMTP_PORT, // default smtp port (25)
false); // do not query MX records
mail.username("me#gmail.com");
mail.password("mepassword");
//mail.authtype(jwsmtp::mailer::PLAIN);
mail.send();
return 0;
}
I'm definitely open to other libraries or classes, but I'm constraint with OS X.
I've also download the POCO library as I've seen it mentioned in other threads, but I would prefer to have a flatter learning curve. If anyone has example code with POCO I would appreciate getting a look.
Thanks
Check out the VMime library!

Serial communication timeout in C++ with Arduino

The code below is what I am using to send and receive information from my Arduino. My problem is when the Arduino is first plugged in. Reading from it hangs because the command doesn't return anything because there is nothing there yet so my whole program crashes. How can I add a time-out to the read function, which is arduino->ReadLine();, that causes the issue? That way will it keep going after a second?
#include "stdafx.h"
#include <iostream>
using namespace System;
using namespace System::IO::Ports;
int main(int argc, char* argv[])
{
using namespace std;
String^ portName;
int baudRate=9600;
portName="COM4";
// Arduino settings.
SerialPort^ arduino;
arduino = gcnew SerialPort(portName, baudRate);
// Open port.
try
{
arduino->Open();
{
if (strcmp(argv[1],"-send")==0) {
String^ command = gcnew String(reinterpret_cast<const char*>(argv[2]));
if (String::Compare(command,"int6")==0) {
arduino->Write("^");
}
else
arduino->Write(command);
}
if(strcmp(argv[1],"-get")==0) {
String^ command = gcnew String(reinterpret_cast<const char*>(argv[2]));
arduino->WriteLine(command);
String^ result = arduino->ReadLine();
Console::Write(result);
}
}
Set arduino->ReadTimeout = duration_in_ms and then catch TimeoutException.
In addition to the timeout your code should loop until the BytesToRead property of the SerialPort is greater than zero
while (arduino->BytesToRead==0) {}
You could keep track of how long you have looped and exit gracefully with a user message if there is nothing received from the arduino within the expected time frame.

Command Line C++ Program to Send an EMail

I'm using VS2008 & C++ and I'm trying to create a command line program that sends an email.
I've looked on line and found some sample programs but none will compile for me.
Does anyone have an example program for me?
Thanks
This code compiles & runs for me - after figuring out the right headers etc. Still needs command line handling, and the use of the MAPI libraries is deprecated, but what do you want for free? Original code from codeproject.com
#include "windows.h"
#include "tchar.h"
#include "mapi.h"
#include "assert.h"
#define ASSERT assert
#define VERIFY assert
BOOL SendMail(CHAR *lpszFrom, CHAR *lpszTo, CHAR *lpszSubject, CHAR *lpszMessage)
{
BOOL bSent = FALSE;
HINSTANCE hMAPI = ::LoadLibrary(_T("mapi32.dll"));
if(0==hMAPI) return bSent;
typedef ULONG (FAR PASCAL *PFN_MAPILogon)(ULONG,LPTSTR,LPTSTR,FLAGS,ULONG,LPLHANDLE);
typedef ULONG (FAR PASCAL *PFN_MAPISendMail)(LHANDLE,ULONG,lpMapiMessage,FLAGS,ULONG);
typedef ULONG (FAR PASCAL *PFN_MAPILogoff)(LHANDLE,ULONG,FLAGS,ULONG);
PFN_MAPILogon MAPILogon = (PFN_MAPILogon)::GetProcAddress(hMAPI,"MAPILogon");
PFN_MAPISendMail MAPISendMail = (PFN_MAPISendMail)::GetProcAddress(hMAPI,"MAPISendMail");
PFN_MAPILogoff MAPILogoff = (PFN_MAPILogoff)::GetProcAddress(hMAPI,"MAPILogoff");
const BOOL bFunctionsLoaded = (0!=MAPILogon)&&(0!=MAPISendMail)&&(0!=MAPILogoff);
ASSERT(bFunctionsLoaded);
if(bFunctionsLoaded)
{
LHANDLE session = 0;
VERIFY(SUCCESS_SUCCESS==MAPILogon(0,0,0,MAPI_NEW_SESSION,0,&session));
ASSERT(0!=session);
MapiRecipDesc recipient;
::ZeroMemory(&recipient,sizeof(recipient));
recipient.ulRecipClass = MAPI_TO;
recipient.lpszName = lpszTo;
MapiMessage message;
::ZeroMemory(&message,sizeof(message));
message.lpszSubject = lpszSubject;
message.lpszNoteText = lpszMessage;
message.nRecipCount = 1;
message.lpRecips = &recipient;
bSent = SUCCESS_SUCCESS == MAPISendMail(session,0,&message,0,0);
VERIFY(SUCCESS_SUCCESS==MAPILogoff(session,0,0,0));
}
::FreeLibrary(hMAPI);
return bSent;
}
int _tmain(int argc, _TCHAR* argv[])
{
SendMail("from_you#go_daddy.com","to.someone#gmail.com","Test subject","New Message");
return 0;
}
Take a look at this: http://sourceforge.net/projects/blat/files/
Since your server is Exchange, your most convenient method to write a program to send email will be using C# and System.Net.Mail as demonstrated here. Here is the C++/CLI code:
static void CreateTestMessage2( String^ server )
{
String^ to = L"jane#contoso.com";
String^ from = L"ben#contoso.com";
MailMessage^ message = gcnew MailMessage( from,to );
message->Subject = L"Using the new SMTP client.";
message->Body = L"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient^ client = gcnew SmtpClient( server );
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client->UseDefaultCredentials = true;
client->Send( message );
client->~SmtpClient();
}
If you really want to use native C++ (ie. not access System.Net.Mail via C++/CLI) then you are stuck with one of the native APIs described here.
However you could use MapiSend or blat as described here.