not receiving '>' after using at+cmgs - avr

I am using SIM900 GSM module connect to my AVR microcontroller.My compiler is Code Vision AVR.
I want to send a message and I don’t want to use delay.I use an usart rx interrupt. I want to receive '>' in rx interrupt after sending number.Then send my meessage.
But '>' charachter wasn’t received. I am checking this process with a 'a' variable. First of all 'a' variable is equal to zero and after 1 minute is equal to 2. But it is never equal to 3. As a result my message haven't been sent. I can't find my problem!
interrupt [USART_RXC] void usart_rx_isr(void)
{
char status,data;
status=UCSRA;
data=UDR;
if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
{
rx_buffer[rx_wr_index++]=data;
if(a==2)
{
if(data=='>')
a=3;
}
#if RX_BUFFER_SIZE == 256
// special case for receiver buffer size=256
if (++rx_counter == 0)
{
#else
if (rx_wr_index == RX_BUFFER_SIZE) rx_wr_index=0;
if (++rx_counter == RX_BUFFER_SIZE)
{
rx_counter=0;
#endif
rx_buffer_overflow=1;
}
}
}
void main()
{
//...rest of code
printf("at+cmgf=1%1c",enter);
printf("at+cmgda=%1c%s%1c%1c",q,del,q,enter);
while (1)
{
//...rest of code
RTC();
if(minute!=1*count)
flag1=0;
if(minute==1*count && flag1!=1)
{
flag1=1;
count++;
a=1;
}
if(a==1)
{
printf("at+cmgs=%1c%s%1c%1c",q,tel,q,enter);
a=2;
}
if(a==3)
{
printf("Ba salam\rTemperature=%d\rHumidity=%d\rWind Direction=%s\rWind Speed=%d%1c%1c",temperature(),humidity(),direct1,anemometer(),cz,enter);
a=0;
}
}
}

You are not doing proper parsing of the responses from the modem.
First of all, never, ever, ever use time as a separator for command and response. You MUST read and parse everything received from the modem until you get a final response. Absolutely nothing else will work reliably. See this answer for some hints on how to fix.
And secondly, for AT+CMGS you MUST wait for a sequence of four characters, \r\n>, before sending data. There is also hints about this in the above linked answer.

You appear to be sending commands using lower case letters. The user manual specifies capital letters, that is, AT not at.
There is also something wrong with the minute-count code at the top of the loop. The flag1 will be set back to 0, which will eventually change a to 1 again, which will cause the message to be sent again. I don't think this is your immediate problem but it should be corrected.
We also don't know if the message is getting through to the SIM900. Maybe trying testing this by sending the AT commands over a terminal and checking the return values. (Your code doesn't check if the first two commands are acknowledged by the SIM900, for example.)
EDIT:
Looking more closely, I see that your code is not following the protocol set out in the manual for sending a text. This may be because the manual has a typographical error. It has two sections labelled "Sending a Text", but one of them is actually for reading a text.
You don't need to include the AT+CMGDA=”DEL ALL” part. This is in the section for reading a text. Also, you have misspelled ”DEL ALL” as "DElALL".
The bigger problem is that sending the two commands so close together is clobbering the return codes.

Related

How to insert an "on key" Replay block in CAPL

I'm wondering if it is possible to create a CAPL code in which, by using "on key" feature, the user may:
- activate a replay mode (.asc file)
- activate a filter on it
- activate additionally a specific signal (not present in asc files)
- deactivate the replay mode
- deactivate the specific signal
- activate or deactivate alternatively specific messages and/or trace
In detail, for the moment I am using this one:
/*#!Encoding:1252*/
variables // declaration of the specific messages I need
{
message MESSAGE01 msg_MESSAGE01 ;
message MESSAGE02 msg_MESSAGE02 ;
}
on key 't' // here I'd need the activation of a replay block in .asc format with a filter on a specific message
{
// Really don't know how to insert here
}
on key 'd' // here I'd need the deactivation of a replay block in .asc format
{
// Really don't know how to insert here
}
on key 'p' // specific signals deactivation
{
msg_MESSAGE01.SIGNAL01= 0; // assign the value to the message
msg_MESSAGE02.SIGNAL02 = 1; // assign the value to the message
output(msg_MESSAGE01); //send the message to the CAN bus
output(msg_MESSAGE02); //send the message to the CAN bus
// output(output of the asc file); // if activated, I'd like to see in output all the messages of the .asc; if not, I'd like to see just those specific signals.
}
on key 'u' // specific signals deactivation
{
// msg_MESSAGE01.SIGNAL01 = none; // here, I'd like to "unset" the value
msg_MESSAGE02.SIGNAL02= 0;
output(msg_MESSAGE01);
output (msg_MESSAGE02);
// output(output of the asc file); // if activated, I'd like to see in output all the messages of the .asc; if not, I'd like to see just those specific signals.
}
If not clear, I'm available to explain better my request :)
Thank you in advance ^^
Cheers
Welcome to StackOverflow!
You can actually activate a replay block (at least on CANoe, please have a look for compatibility on CANalyzer).
I'd need the activation/deactivation of a replay block in .asc format
variables
{
char replayName[32] = "ibus_data";
}
on key 'b'
{
replayStart( replayName);
}
on key 'e'
{
replayStop( replayName);
}
on key 's'
{
replaySuspend( replayName);
}
on key 'r'
{
replayResume( replayName);
}
on key 'w'
{
writeReplayState( replayName);
}
void writeReplayState( char name[])
{
switch ( replayState( name))
{
case 0:
write( "Replay Block %s is stopped", replayName);
break;
case 1:
write( "Replay Block %s is running", replayName);
break;
case 2:
write( "Replay Block %s is suspended", replayName);
break;
default:
write( "Error: Replay Block %s has an unknown state!", replayName);
break;
};
}
You'll have to configure the replay file beforehands, and the filter part requires a different solution. For more information, check the reference and this example: ReplayStart, ReplayStop, ReplaySuspend, ReplayResume, ReplayState
From: CAPL Function Overview » General » Example: ReplayStart, ReplayStop, ReplaySuspend, ReplayResume, ReplayState
specific signals activation/deactivation
One "hacky" solution that pops into my mind, it to have a flag system in place. Of course, ugly solution, probably there is something better at hand. Try something like:
on message myMessage
{
if (flag)
output(myMessage)
}
on key 'u'
{
flag ? 0 : 1 // short for: toggle the status of the flag
}
Please let me know if this helped.
Regarding this piece of code:
on key 'p' // specific signals deactivation
{
msg_MESSAGE01.SIGNAL01= 0; // assign the value to the message
msg_MESSAGE02.SIGNAL02 = 1; // assign the value to the message
output(msg_MESSAGE01); //send the message to the CAN bus
output(msg_MESSAGE02); //send the message to the CAN bus
}
Please note that it won't do what you expect. You are asking to send the message on user keyboard action. If the message was already set for cyclic output, it will continue to go with the clock and an extra publish will be made on keyboard. Otherwise, message will only be published once.
The proposed solution works with a flag in the on message *, that, in turn, works as a filter, blocking the message and repeating it only if the flag is set.
You can just add Replay Block to the bus, and in configuration type specified start/stop key. Specified signals activation/deactivation can stay as you wrote it.

How can flex return multiple terminals at one time

In order to make my question easy to understand I want to use the following example:
The following code is called nonblock do-loop in fortran language
DO 20 I=1, N ! line 1
DO 20 J=1, N ! line 2
! more codes
20 CONTINUE ! line 4
Pay attention that the label 20 at line 4 means the end of both the inner do-loop and the outer do-loop.
I want my flex program to parse the feature correctly: when flex reads the label 20, it will return ENDDO terminal twice.
Firstly, because I also use bison, so every time bison calls yylex() to get one terminal. If I can ask bison to get terminals from yylex() in some cases, and from another function in other cases, maybe I could solve this problem, however, I got no idea here then.
Of course there are some workarounds, for eample, I can use flex's start condition but I don't think it is a good solution. So I ask if there's any way to solve my question without a workaround?
It is easy enough to modify the lexical scanner produced by (f)lex to implement a token queue, but that is not necessarily the optimal solution. (See below for a better solution.) (Also, it is really not clear to me that for your particular problem, fabricating the extra token in the lexer is truly appropriate.)
The general approach is to insert code at the top of the yylex function, which you can do by placing the code immediately after the %% line and before the first rule. (The code must be indented so that it is not interpreted as a rule.) For non-reentrant scanners, this will typically involve the use of a local static variable to hold the queue. For a simple but dumb example, using the C API but compiling with C++ so as to have access to the C++ standard library:
%%
/* This code will be executed each time `yylex` is called, before
* any generated code. It may include declarations, even if compiled
* with C89.
*/
static std::deque<int> tokenq;
if (!tokenq.empty()) {
int token = tokenq.front();
tokenq.pop_front();
return token;
}
[[:digit:]]+ { /* match a number and return that many HELLO tokens */
int n = atoi(yytext);
for (int i = 0; i < n; ++i)
tokenq.push_back(HELLO);
}
The above code makes no attempt to provide a semantic value for the queued tokens; you could achieve that using something like a std::queue<std::pair<int, YYSTYPE>> for the token queue, but the fact that YYSTYPE is typically a union will make for some complications. Also, if that were the only reason to use the token queue, it is obvious that it could be replaced with a simple counter, which would be much more efficient. See, for example, this answer which does something vaguely similar to your question (and take note of the suggestions in Note 1 of that answer).
Better alternative: Use a push parser
Although the token queue solution is attractive and simple, it is rarely the best solution. In most cases, code will be clearer and easier to write if you request bison to produce a "push parser". With a push parser, the parser is called by the lexer every time a token is available. This makes it trivial to return multiple tokens from a lexer action; you just call the parser for each token. Similarly, if a rule doesn't produce any tokens, it simply fails to call the parser. In this model, the only lexer action which actually returns is the <<EOF>> rule, and it only does so after calling the parser with the END token to indicate that parsing is complete.
Unfortunately, the interface for push parsers is not only subject to change, as that manual link indicates; it is also very badly documented. So here is a simple but complete example which shows how it is done.
The push parser keeps its state in a yypstate structure, which needs to be passed to the parser on each call. Since the lexer is called only once for each input file, it is reasonable for the lexer to own that structure, which can be done as above with a local static variable [Note 1]: the parser state is initialized when yylex is called, and the EOF rule deletes the parser state in order to reclaim whatever memory it is using.
It is usually most convenient to build a reentrant push parser, which means that the parser does not rely on the global yylval variable [Note 2]. Instead, a pointer to the semantic value must be provided as an additional argument to yypush_parse. If your parser doesn't refer to the semantic value for the particular token type, you can provide NULL for this argument. Or, as in the code below, you can use a local semantic value variable in the lexer. It is not necessary that every call to the push parser provide the same pointer. In all, the changes to the scanner definition are minimal:
%%
/* Initialize a parser state object */
yypstate* pstate = yypstate_new();
/* A semantic value which can be sent to the parser on each call */
YYSTYPE yylval;
/* Some example scanner actions */
"keyword" { /* Simple keyword which just sends a value-less token */
yypush_parse(pstate, TK_KEYWORD, NULL); /* See Note 3 */
}
[[:digit:]]+ { /* Token with a semantic value */
yylval.num = atoi(yytext);
yypush_parse(pstate, TK_NUMBER, &yylval);
}
"dice-roll" { /* sends three random numbers */
for (int i = 0; i < 2; ++i) {
yylval.num = rand() % 6;
yypush_parse(pstate, TK_NUMBER, &yylval);
}
<<EOF>> { /* Obligatory EOF rule */
/* Send the parser the end token (0) */
int status = yypush_parse(pstate, 0, NULL);
/* Free the pstate */
yypstate_delete(pstate);
/* return the parser status; 0 is success */
return status;
}
In the parser, not much needs to be changed at all, other than adding the necessary declarations: [Note 4]
%define api.pure full
%define api.push-pull push
Notes
If you were building a reentrant lexer as well, you would use the extra data section of the lexer state object instead of static variables.
If you are using location objects in your parser to track source code locations, this also applies to yylloc.
The example code does not do a good job of detecting errors, since it doesn't check return codes from the calls to yypush_parse. One solution I commonly use is some variant on the macro SEND:
#define SEND(token) do { \
int status = yypush_parse(pstate, token, &yylval); \
if (status != YYPUSH_MORE) { \
yypstate_delete(pstate); \
return status; \
} \
} while (0)
It's also possible to use a goto to avoid the multiple instances of the yypstate_delete and return. YMMV.
You may have to modify the prototype of yyerror. If you are using locations and/or providing extra parameters to the push_parser, the location object and/or the extra parameters will also be present in the yyerror call. (The error string is always the last parameter.) For whatever reason, the parser state object is not provided to yyerror, which means that the yyerror function no longer has access to variables such as yych, which are now members of the yypstate structure rather than being global variables, so if you use these variables in your error reporting (which is not really recommended practice), then you will have to find an alternative solution.
Thanks to one of my friends, he provide a way to achieve
If I can ask bison to get terminals from yylex() in some cases, and from another function in other cases
In flex generated flex.cpp code, there is a macro
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
so I can "rename" flex's yylex() function to another function like pure_yylex().
So my problem is solved by:
push all terminals I want to give bison to a global vector<int>
implement a yylex() function by myself, when bison call yylex(), this function will firstly try to get terminals from a that global vector<int>
if vector<int> is empty, yylex() calls pure_yylex(), and flex starts to work

How can I safely append data to a sk_buff for IPTables target

I am working on a Linux kernel module that needs to modify network packets and append an extra header. I already implemented the modification part, recomputed the check-sums and it worked nice. But I don't know how to safely append an extra header. If my input packet is something like:
ip-header / tcp-header / data
I would like to have an output packet like:
ip-header / tcp-header / my-header / data
For what I read, I think I need something like the following code. I wrote my specific questions on the code as comments. My general concern is if the code I am writing here is memory-safe or what should I do to have a memory-safe way to append the new header. Also, if I am doing something wrong or there is a better way to do it I will also appreciate the comment. I have tried to find examples but no luck so far. Here is the code:
static unsigned int my_iptables_target(struct sk_buff *skb, const struct xt_action_param *par) {
const struct xt_mytarget_info *info = par->targinfo;
/* Some code ... */
if (!skb_make_writable(skb, skb->len)) {
//Drop the packet
return NF_DROP;
}
struct newheader* myheader;
// Check if there is enough space and do something about it
if (skb_headroom(skb) < sizeof(struct newheader)) {
// So there is no enugh space.
/* I don't know well what to put here. I read that a function called pskb_expand_head might
* do the job. I do not understand very well how it works, or why it might fail (return value
* different from zero). Does this code work:
*/
if (pskb_expand_head(skb, sizeof(struct newheader) - skb_headroom(skb), 0, GPF_ATOMIC) != 0) {
// What does it mean if the code reaches this point?
return NF_DROP;
}
}
// At this point, there should be enough space
skb_push(skb, sizeof(struct newheader));
/* I also think that skb_push() creates space at the beggining, to open space between the header and
* the body I guess I must move the network/transport headers up. Perhaps something like this:
*/
memcpy(skb->data, skb->data + sizeof(struct newheader), size_of_all_headers - sizeof(struct newheader));
// Then set myheader address and fill data.
myheader = skb->data + size_of_all_headers;
//Then just set the new header, and recompute checksums.
return XT_CONTINUE;
}
I assumed that the variable size_of_all_headers contains the size in bytes of the network and transport headers. I also think that memcpy copies bytes in increasing order, so that call shouldn't be a problem. So does the above code works? It is all memory-safe? Are there better ways to do it? Are there examples (or can you provide one) that does something like this?
I used a code similar to the one in the question and so far it has worked very well for all the test I have done. To answer some of the specific questions, I used something like:
if (skb_headroom(skb) < sizeof(struct newheader)) {
printk("I got here!\n");
if (pskb_expand_head(skb, sizeof(struct newheader) - skb_headroom(skb), 0, GPF_ATOMIC) != 0) {
printk("And also here\n");
return NF_DROP;
}
}
But none of the print statements ever executed. I suppose that happens because the OS reserves enough space in memory such that there can be no problems given the limits of the IP header. But I think it is better to leave that if statement to grow the packet if necessary.
The other difference of the code that I tested and worked is that instead of moving all the other headers up to create a space for my header, I chose to move the body of the packet down.

How to get single keypress in D with getc()?

I need to get user input (y/n) keypress in console.
How I can do it? I know that I can use readln, but is there any other way? I am trying to use getc()
import std.stdio;
import std.string;
import std.stream;
void main()
{
while (getc() != 'y')
{
writeln("try again");
}
}
but I am getting error:
source\app.d(6): Error: function core.stdc.stdio.getc (shared(_iobuf)* stream) is not callable using argument types (File)
next attempt:
char [] checkYesNo() #property
{
char [] key;
while(readln(key) != 'y')
{
}
return key;
}
This code compile, but failure at execution time with strange error "Error executing command run"
One library that does the single press is my terminal.d
https://github.com/adamdruppe/arsd/blob/master/terminal.d
It looks more complex than it is. Here's an example to get a single key:
import terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
auto input = RealTimeConsoleInput(&terminal, ConsoleInputFlags.raw);
terminal.writeln("Press any key to exit");
auto ch = input.getch();
terminal.writeln("Bye!");
}
To build, put terminal.d in your folder and then compile them together: dmd yourfile.d terminal.d.
First, you construct a terminal. The two types are linear or cellular. Linear outputs one line at a time, cellular goes "full screen" in the console.
Then, you make an input struct based on that terminal. The ConsoleInputFlags says what you want: do you want echo? Mouse input? etc. raw is the simplest one: it will send you plain keyboard input as they happen with relatively little else.
Then you can write to the terminal and get characters from the input. The input.getch() line fetches a single character, returning immediately when something is available without buffering. Other functions available on input include kbhit, which returns true if a key was hit so input is available, false if it isn't - useful for a real time game, being checked on a timer, or nextEvent, which gives full input support, including mouse events. The Demo in the terminal.d source code shows something with full support:
https://github.com/adamdruppe/arsd/blob/master/terminal.d#L2265
Another useful convenience function on terminal itself btw is getline, which grabs a full line at a time, but also lets the user edit it and offers history and autocomplete. terminal also offers a function called color to do colored output, and moveTo, useful in cellular mode, to move the cursor around the screen. Browse the code to learn more, if you're interested.
The error is because phobos is conflicting with the runtime.
std.stdio publicly imports core.stdc.stdio, and they both define stdin, but as different types. getc() really just calls fgetc( stdin ), so when the runtime tries calling getc(), it passes in the stdin from std.stdio instead of the correct one from core.stdc.stdio, resulting in the error.
The best way to get around the conflict is just to alias core.stdc.stdio as something else and then use the fully qualified name.
import std.stdio;
void main()
{
while (getc() != 'y')
{
writeln("try again");
}
}
auto getc()
{
import stdc = core.stdc.stdio;
return stdc.getc( stdc.stdin );
}
But beware that getc() uses a buffer internally, and won't return until the user presses the enter key, at which point it reads the first char from the buffer and returns that, and will continue to read the next char from the buffer for subsequent calls until it reaches the end. So entering nnn<enter> in the terminal window results in try again being printed 3 times. If you want a method that returns a single char without the need for the enter key, you'll need to look for a library solution, no standard functions for that exist in either C or D.
If you're not concerned with a cross-platform solution, there's a Windows-specific header that defines a getch() function which doesn't use a buffer and returns on every keystroke, rather than on enter. Just add this to your code and replace the call to getc() with a call to getch().
extern( C ) int getch();
How about:
import std.stdio;
void main(){
writefln("Enter something: ");
char entered;
do{
readf(" %c\n", &entered);
writefln("Entered: %s", entered);
}while(entered != 'y');
}
The important bit is the " %c\n".
%c tells readf to match a char rather than a string.

some content of function 'send' is missing

I used the tcp protocol to deal the request the client, I found a phenomenon which is some of the content is missing while using the function of 'send'. the code is as fellow:
_stprintf(cData,"[%s]",send_back);
memset(send_back,0,sizeof(cData));
int send_count;
if((send_count=send(service_sock,cData,_tcslen(cData),0))!=SOCKET_ERROR){
fwrite(cData,sizeof(char),_tcslen(cData),hFile);
fflush(hFile);
g_log->print_log("%c%c%c%c",cData[0],cData[1],cData[2],cData[send_count-1]);
g_log->print_log("buffer len is :%d , send %d bytes",_tcslen(cData),send_count);
fclose(hFile);
memset(cData,0,sizeof(cData));
return true;
}
the send function is always successful, and the value of _tcslen(cData) is equal to send_count and the cData[send_count-1] is ']'.
But when I use the wireshark(a capture tool) to capture the packet which is send out by the socket, I found some content is always missing including the Character of ']'. the content is encapsulated by JSON protocol, so the ']' is important. the total size of every time send out is 8900 bytes. But when I change the request item one time (before is 100) to 50, there is nothing missed, the size of send back is about 4000 bytes.
I do not know why this happened.
from my log file, I am sure the array named 'cData' contain the total content, But why the the content from the packets captured by the wireshark is not complete?
Seeing that you're using TCP, it already looks wrong.
First off, TCP is stream protocol which is not suited for one time packets ( especially small ) but the benefits are far more greater than just use UDP instead.
Keep in mind that in case of TPC you are not in control you can only make sure that your requests are handled correctly, the actual communication is done by the Winsock library.
Always remember that the send functions len parameter is NOT a requirement it's a hint on how big is your buffer and how much you can send in one go, it may return less than you want to send, and this may depend on lot of factors how often it happens, lets say you use the loopback device it would probably never ever do this, meaning that send will actually send what you requested. In a real network it may send it on one go in about 90% or with even less probability.
You have to make sure you send as much as you want, i.e. check for the return value and call send again if it didn't send as much as you wanted and do the same on the other side with recv, call recv until you get as much data as you wanted. This method only works if you know exactly how much data you want to send over the network.
As for the loss off data, TCP, I would say almost always sends data, assuming that you checked the return value of send. If there is a network problem, like loss of data you would see the TCP retransmit packet.
For your way of sending data this is more suitable, this is to make sure you really send the amount of data you want :
xint xsend(SOCKET s,const char* buf,xint len)
{
xint lastSize;
xint result;
if (len==0 || s==(SOCKET)NULL || buf==(const char*)NULL)
return SOCKET_ERROR;
lastSize=0;
result=0;
do
{
result=send(s,buf+lastSize,len-lastSize,0);
if (result==0)
return 0;
if (result==SOCKET_ERROR)
return SOCKET_ERROR;
if (result==len)
return len;
if (result>len)
{
xlog(1,"xsend : socket sent too much data [ %i of %i ]",result,len);
return SOCKET_ERROR;
}
lastSize+=result;
if (lastSize>len)
{
xlog(1,"xsend : socket sent too much data ( overall ) [ %i of %i ]",result,len);
return SOCKET_ERROR;
}
if (lastSize==len)
return len;
}
while (1);
xlog(2,"failed to do xsend");
return SOCKET_ERROR;
}
This code is just a copy paste from one of my projects, xlog is simple logging function, you can figure it out.

Resources