Send a backslash using C socket for iso8583 message - c

I am building a POS application verifone (C-language) which should communicate with m2m switch from Morocco but I'm stuck when sending initialization message which should have a backslash like this (08\00) but when sending this I'm having 08\5c00.
It converts backslash by its value in hex(5c). The tool I'm using is socket workbench to simulate the server.
How can I send a backslash without being converted into \5c?
It needs to be done in C Language.
EDIT
This is the data I want to send to the server with the header but when trying to print \00 I get \5C00
sprintf(data,"%s%s%s%s%s%s%s%s%s%s%s%s%s","\x30\x60\x60\x20\x15\x35\x35","\x08",‌"\\00","\x0x00","\x01\x30\x30\x30\x30\xC0\x30\x30\x30\x30","\x97","\\00","\x30\x30"‌,"\x00\x00\x01\x00","\x02",idTerminal,idCommercant,"\x20\x20\x20\xA4\xBC");

If I'm understanding correctly, the first part of your example:
sprintf(data,"%s%s",
"\x30\x60\x60\x20\x15\x35\x35",
"\x08");
is doing exactly what you want. The problem is that on the next %s, you are using "\\00" and you want to server to receive ASCII \00 (which would be 0x5c, 0x30, 0x30), but instead the server reports that it is receiving ASCII \5c00 (which would be 0x5c, 0x,35, 0x43, 0x30, 0x30).
I agree with Klas Lindbäck in that it sounds like the VeriFone terminal is doing the correct thing, but the server is displaying it wrong. There are 2 things I would consider doing in order to troubleshoot this in order to prove that this is correct (and you can do just one or the other or you can do both together).
First: You can use LOG_PRINTF (or print to paper or the screen if you prefer) to print the values of each byte just before you send it off. Below is a quick-and-dirty function I wrote to do just that when I was troubleshooting a similar sort of problem once. Note that I only cared about the beginning of the string (as is the case with you, it seems) so I don't print the end if I run out of buffer space.
void LogDump(unsigned char* input, int expectedLength)
{
#ifdef LOGSYS_FLAG
char buffer[100];
int idx, bfdx;
memset(buffer, 0, sizeof(buffer));
bfdx = 0;
for (idx = 0; idx < expectedLength && bfdx < sizeof(buffer); idx++)
{
//if it is a printable character, print as is
if (input[idx] > 31 && input[idx] < 127)
{
buffer[bfdx++] = (char) input[idx];
continue;
}
//if we are almost out of buffer space, show that we are truncating
// the results with a ~ character and break. Note we are leaving 5 bytes
// because we expand non-printable characters like "<121>"
if (bfdx + 5 > sizeof(buffer))
{
buffer[bfdx++] = '~';
break;
}
//if we make it here, then we have a non-printable character, so we'll show
// the value inside of "<>" to visually denote it is a numeric representation
sprintf(&buffer[bfdx], "<%d>", (int) input[idx]);
//advance bfdx to the next 0 in buffer. It will be at least 3...
bfdx += 3;
//... but for 2 and 3 digit numbers, it will be more.
while (buffer[bfdx] > 0)
bfdx++;
}
//I like to surround my LOG_PRINTF statements with short waits because if there
// is a crash in the program directly after this call, the LOG_PRINTF will not
// finish writing to the serial port and that can make it look like this LOG_PRINTF
// never executed which can make it look like the problem is elsewhere
SVC_WAIT(5);
LOG_PRINTF(("%s", buffer));
SVC_WAIT(5);
#endif
}
Second: try assigning each position in your char array an explicit value. If you already used my LOG_PRINTF suggestion above and found it was not sending what you thought it should be, this would be one way to fix it so that it DOES send EXACTLY what you want. This method is a bit more tedious, but since you are spelling it out each value, anyway, it shouldn't be too much more overhead:
data[0] = 0x30;
//actually, I'd probably use either the decimal value: data[0] = 48;
// or I'd use the ASCII value: data[0] = '0';
// depending on what this data actually represents, either of those is
// likely to be more clear to whomever has to read the code later.
// However, that's your call to make.
data[1] = 0x60;
data[2] = 0x60;
data[3] = 0x20;
data[4] = 0x15;
data[5] = 0x35;
data[6] = 0x35;
data[7] = 0x08;
data[8] = 0x5C; // This is the '\'
data[9] = 0x48; // The first '0'
data[10]= 0x48; // The second '0'
data[11]= 0;
//for starters, you may want to stop here and see what you get on the other side
After you have proven to yourself that it IS or IS NOT the VeriFone code causing the problem, you will know whether you need to focus on the terminal or on the server side.

Related

Enabling Newline or Carriage return

I am reading some robotic code and i came across something like Newline and Carriage. What are those two things? I could not find any useful usage related the code itself.
Here is the code
// !! make sure you have enabled Newline or Carriage return
#define _mode 0 // (0) used for calibration and testing, (1) uses serial as input
void handle_serial() {
//: reads and stores the serial data
int i = 0; float buff[3] = {0, 0, 0};
String s_buff = "";
while (Serial.available()) {
char c = Serial.read();
if (c == 13 || c == 32 || c == '\n') {
buff[i] = s_buff.toFloat();
s_buff = "";
i++;
} else
s_buff += c;
}
if (_mode == 0)
commands_exe(buff[0], buff[1], buff[2]);
else if (_mode == 1)
if (state == 4) {
_direction = {buff[0], buff[1]};
turn = buff[2];
}
}
Newline and Carriage. What are those two things?
That's two control characters. Usually expressed as the escape sequence "\n" (new line) and "\r" (carriage return)
https://en.wikipedia.org/wiki/Carriage_return
https://en.wikipedia.org/wiki/Newline
Both have historic reasons. Carriage return moved the printhead back to the beginning of the line. New line moved to the next line.
This is still used in computers to move the cursor around or to make linebreaks when reading text files.
The idea of it in this code is to read bytes until newline, space or carriage return are received. then the bytes received till then is converted to a float.
But as the comments suggest this implementation is bad for many reasons. mainly it is very error prone.
For example you risk to exceeed the boudnaries of your buffer if you don't receive space, newline or carriage return in time.
It is also often used to terminate serial commands so the computer knows when he received a full command, which at the same time allows to display them nicely in a terminal. It is up to the sender to make sure the correct data is sent which in gerneral is a very bad idea.
The only thing you can learn from this snippet is how not do to do it.

AVR gcc, weird array behaviour

it's the first time I see something like this. I'm starting to suspect it's a hardware fault.
whenever I try to send the contents of array "test" and that array is larger than 4 elements or I initialize all elements in the declaration it contains 0xff instead of values I try to initialise with.
this works fine. when I read values from the array in while(sending them to the lcd and uart) both readouts are consistent with test values:
uint8_t i=0;
uint8_t test[4] = {1,2,3,4};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
this doesn't, it returns 0xff instead of test[i] value:
uint8_t i=0;
uint8_t test[5] = {1,2,3,4,5};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
but this works! it returns proper values
uint8_t i=0;
uint8_t test[6] = {1,2,3,4,5};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
this also works:
uint8_t i=0;
uint8_t test[5];
test[0]=1;
test[1]=2;
test[2]=3;
test[3]=4;
test[4]=5;
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
it works fine when compiled on linux
I swapped out an mcu for a different one and it works the way it should. must be an hardware problem
In first example you are going out of bounds of array test[4]. You are running while 5 times, when array has only 4 items length.
I think your problem is that you're overloading the USART. I assume that GLCD_WriteData() is VERY quick, and that USART_Transmit() buffers the character for transmission and then quickly returns. I don't know your hardware, so I can't tell - but a four-character buffer for a USART sounds reasonable.
Your five-character examples don't work because the actual character that you're trying to transmit is lost - so it puts an 0xFF in instead. You need to check the state of the USART buffer and wait for it to show that space is available (note NOT empty - that'd be inefficient!).
In the 8250 and 16450 UART chips there are two status bits:
TSRE says that the Transmit Shift Register is Empty;
THRE says that the Transmit Holding Register is Empty.
THRE can be set even when TSRE isn't - it's busy. I'd test TSRE and not send the next character until there's room - or set up a buffer and an interrupt handler.
If it's not the I/O hardware, then the only other thing that I can think of is the compiler is producing incorrect code. What is the exact declaration of USART_Transmit()? Does it expect a uint8_t? Or something else, like an int (for some reason)?
If it's something else, like int, please try the following code:
while(i<5){
int c = test[i]; // Whatever USART_Transmit wants
GLCD_WriteData(test[i]);
USART_Transmit(c);
i++;
} // while
If that always works, then you've got a compiler problem, not a hardware problem.
EDIT: Code for USART_Transmit() provided:
void USART_Transmit( uint8_t data ) {
//Wait for empty transmit buffer
while( !( UCSR0A & (1<<UDRE0)) );
//Put data into buffer, sends the data
UDR0 = data;
}
You've got something better than JTAG - you've got an LCD display! Although I don't know how many characters it has, or how long it takes to transmit a character...
You could try something like:
char Hex(uint8_t nibble) {
return nibble<10 ?
'0'+nibble :
'A'+nibble-10;
} // Hex
...
void Send(uint8_t c) {
uint8_t s;
UDR0 = c; // Send character NOW: don't wait!
do {
s = UCSR0A; // Get current USART state
//s = UCSR0A & (1<<UDRE0); // Or this: isolate ready bit...
GLCD_WriteData('x');
GLCD_WriteData(Hex(s >> 4)); // Write state-hi hex
GLCD_WriteData(Hex(s & 0xF)); // Write state-lo hex
} while (!(s & (1<<UDRE0))); // Until is actually ready
} // Send(c)
...
Send('A');
Send('B');
Send('C');
Assuming that UDRE0 is 3, then that code will result in a sequence like x00x00x00x00x00x08x00x00x00x00x08x00x00x00x08 if it is working. If it produces x08x08x08 then you've got a stuck UCSR0A bit, and it's hardware.
Old question, but giving my feedback since this is the first place I got sent while searching solution for same issue, getting even exact same results with the code samples in original question.
For me it was a bad Makefile that caused some sections to be left out by avr-objcopy as far as I know.
For example in my case, the original parameters for building my sample hex that were causing this issue:
${OBJCOPY} -j .text -O ihex led.elf led.hex
What worked a bit better:
${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

Reading serial port faster

I have a computer software that sends RGB color codes to Arduino using USB. It works fine when they are sent slowly but when tens of them are sent every second it freaks out. What I think happens is that the Arduino serial buffer fills out so quickly that the processor can't handle it the way I'm reading it.
#define INPUT_SIZE 11
void loop() {
if(Serial.available()) {
char input[INPUT_SIZE + 1];
byte size = Serial.readBytes(input, INPUT_SIZE);
input[size] = 0;
int channelNumber = 0;
char* channel = strtok(input, " ");
while(channel != 0) {
color[channelNumber] = atoi(channel);
channel = strtok(0, " ");
channelNumber++;
}
setColor(color);
}
}
For example the computer might send 255 0 123 where the numbers are separated by space. This works fine when the sending interval is slow enough or the buffer is always filled with only one color code, for example 255 255 255 which is 11 bytes (INPUT_SIZE). However if a color code is not 11 bytes long and a second code is sent immediately, the code still reads 11 bytes from the serial buffer and starts combining the colors and messes them up. How do I avoid this but keep it as efficient as possible?
It is not a matter of reading the serial port faster, it is a matter of not reading a fixed block of 11 characters when the input data has variable length.
You are telling it to read until 11 characters are received or the timeout occurs, but if the first group is fewer than 11 characters, and a second group follows immediately there will be no timeout, and you will partially read the second group. You seem to understand that, so I am not sure how you conclude that "reading faster" will help.
Using your existing data encoding of ASCII decimal space delimited triplets, one solution would be to read the input one character at a time until the entire triplet were read, however you could more simply use the Arduino ReadBytesUntil() function:
#define INPUT_SIZE 3
void loop()
{
if (Serial.available())
{
char rgb_str[3][INPUT_SIZE+1] = {{0},{0},{0}};
Serial.readBytesUntil( " ", rgb_str[0], INPUT_SIZE );
Serial.readBytesUntil( " ", rgb_str[1], INPUT_SIZE );
Serial.readBytesUntil( " ", rgb_str[2], INPUT_SIZE );
for( int channelNumber = 0; channelNumber < 3; channelNumber++)
{
color[channelNumber] = atoi(channel);
}
setColor(color);
}
}
Note that this solution does not require the somewhat heavyweight strtok() processing since the Stream class has done the delimiting work for you.
However there is a simpler and even more efficient solution. In your solution you are sending ASCII decimal strings then requiring the Arduino to spend CPU cycles needlessly extracting the fields and converting to integer values, when you could simply send the byte values directly - leaving if necessary the vastly more powerful PC to do any necessary processing to pack the data thus. Then the code might be simply:
void loop()
{
if( Serial.available() )
{
for( int channelNumber = 0; channelNumber < 3; channelNumber++)
{
color[channelNumber] = Serial.Read() ;
}
setColor(color);
}
}
Note that I have not tested any of above code, and the Arduino documentation is lacking in some cases with respect to descriptions of return values for example. You may need to tweak the code somewhat.
Neither of the above solve the synchronisation problem - i.e. when the colour values are streaming, how do you know which is the start of an RGB triplet? You have to rely on getting the first field value and maintaining count and sync thereafter - which is fine until perhaps the Arduino is started after data stream starts, or is reset, or the PC process is terminated and restarted asynchronously. However that was a problem too with your original implementation, so perhaps a problem to be dealt with elsewhere.
First of all, I agree with #Thomas Padron-McCarthy. Sending character string instead of a byte array(11 bytes instead of 3 bytes, and the parsing process) is wouldsimply be waste of resources. On the other hand, the approach you should follow depends on your sender:
Is it periodic or not
Is is fixed size or not
If it's periodic you can check in the time period of the messages. If not, you need to check the messages before the buffer is full.
If you think printable encoding is not suitable for you somehow; In any case i would add an checksum to the message. Let's say you have fixed size message structure:
typedef struct MyMessage
{
// unsigned char id; // id of a message maybe?
unsigned char colors[3]; // or unsigned char r,g,b; //maybe
unsigned char checksum; // more than one byte could be a more powerful checksum
};
unsigned char calcCheckSum(struct MyMessage msg)
{
//...
}
unsigned int validateCheckSum(struct MyMessage msg)
{
//...
if(valid)
return 1;
else
return 0;
}
Now, you should check every 4 byte (the size of MyMessage) in a sliding window fashion if it is valid or not:
void findMessages( )
{
struct MyMessage* msg;
byte size = Serial.readBytes(input, INPUT_SIZE);
byte msgSize = sizeof(struct MyMessage);
for(int i = 0; i+msgSize <= size; i++)
{
msg = (struct MyMessage*) input[i];
if(validateCheckSum(msg))
{// found a message
processMessage(msg);
}
else
{
//discard this byte, it's a part of a corrupted msg (you are too late to process this one maybe)
}
}
}
If It's not a fixed size, it gets complicated. But i'm guessing you don't need to hear that for this case.
EDIT (2)
I've striked out this edit upon comments.
One last thing, i would use a circular buffer. First add the received bytes into the buffer, then check the bytes in that buffer.
EDIT (3)
I gave thought on comments. I see the point of printable encoded messages. I guess my problem is working in a military company. We don't have printable encoded "fire" arguments here :) There are a lot of messages come and go all the time and decoding/encoding printable encoded messages would be waste of time. Also we use hardwares which usually has very small messages with bitfields. I accept that it could be more easy to examine/understand a printable message.
Hope it helps,
Gokhan.
If faster is really what you want....this is little far fetched.
The fastest way I can think of to meet your needs and provide synchronization is by sending a byte for each color and changing the parity bit in a defined way assuming you can read the parity and bytes value of the character with wrong parity.
You will have to deal with the changing parity and most of the characters will not be human readable, but it's gotta be one of the fastest ways to send three bytes of data.

How to optimize C for loop for font rendering on oled display

I need to optimize this function: Any strange way to optimize the for loop? (early break i think can't be possible)
void SeeedGrayOLED::putChar(unsigned char C)
{
if(C < 32 || C > 127) //Ignore non-printable ASCII characters. This can be modified for multilingual font.
{
C=' '; //Space
}
uint8_t k,offset = 0;
char bit1,bit2,c = 0;
for(char i=0;i<16;i++)
{
for(char j=0;j<32;j+=2)
{
if(i>8){
k=i-8;
offset = 1;
}else{
k=i;
}
// Character is constructed two pixel at a time using vertical mode from the default 8x8 font
c=0x00;
bit1=(pgm_read_byte(&hallfetica_normal[C-32][j+offset]) >> (8-k)) & 0x01;
bit2=(pgm_read_byte(&hallfetica_normal[C-32][j+offset]) >> ((8-k)-1)) & 0x01;
// Each bit is changed to a nibble
c|=(bit1)?grayH:0x00;
c|=(bit2)?grayL:0x00;
sendData(c);
}
}
}
I've got a font in the array hallfetica_normal, is an array of array of uint8_t, that maybe compressed or something like that?
This code run on a arduino, ad i've to run a countdown from 500 to 0 with one unit down every 10/20ms.
EDIT
This is the new code after yours indication, thanks all:
I'm looking to organise the font differently to permit less call to pgm_read_byte.. (something like changing the orientation... i wonder)
void SeeedGrayOLED::putChar(unsigned char C)
{
if(C < 32 || C > 127) //Ignore non-printable ASCII characters. This can be modified for multilingual font.
{
C=' '; //Space
}
char c,byte = 0x00;
unsigned char nibble_lookup[] = { 0, grayL, grayH, grayH | grayL };
for(int ii=0;ii<2;ii++){
for(int i=0;i<8;i++)
{
for(int j=0;j<32;j+=2)
{
byte = pgm_read_byte(&hallfetica_normal[C-32][j+ii]);
c = nibble_lookup[(byte >> (8-i)) & 3];
sendData(c);
}
}
}
}
Well, you seem to be reading the same byte twice in a row unnecessarily via pgm_read_byte(&hallfetica_normal[C-32][j+offset]). You could load that once into a local variable.
Additionally, you could avoid the if(i>8){ check per iteration by breaking up the code into two loops; one where i goes from 0 to 8 and another where it goes from 9 to 15. (Although I suspect you really intended >= here, making the loop boundaries 0-7 then 8-15.) That also means things like offset become constant values, which will help.
In an effort to make the inner loop as fast as possible, I'd try to get rid of all branching with a lookup table and see whether that helped.
First, I'd define the lookup table outside the loop:
/* outside the loop */
unsigned char h_lookup[] = { 0, grayH };
unsigned char l_lookup[] = { 0, grayL };
Then inside the loop, since you're testing the least-significant bit, you can use that as an index into the lookup table. If it's clear, then the lookup index will be 0. If it's set, then the lookup index will be 1:
/* inside the loop */
byte = pgm_read_byte(&hallfetica_normal[C-32][j+offset]);
c = h_lookup[((byte >> (8-k)) & 0x01)] |
l_lookup[((byte >> (8-k-1)) & 0x01)]
sendData(c);
Since you're masking and testing 2 adjacent bits, 8-k and 8-k-1, you could list all 4 possibilities in a single lookup table:
/* Outside loop */
unsigned char nibble_lookup[] = { 0, grayL, grayH, grayH | grayL };
And then the lookup becomes dramatically simplified.
/* loop */
byte = pgm_read_byte(&hallfetica_normal[C-32][j+offset]);
c = nibble_lookup[(byte >> (8-k)) & 3];
sendData(c);
The other answer has addressed what to do about the branches in the top part of your inner loop.

Dice Simulator with C Programming

I am trying to write a code for a basic dice simulator program. When a switch is pressed the two seven segment displays will rapidly change between 1-6. When the button is released the random number will display on the two seven segment display.
This code will be connected to a pic16F877 in ISIS and I'm using MPLAB for the C Programming.
I'm really new to this programming stuff so its hard for me to get my head around it.
#include <pic.h>
const char patterns[]={0X3F, 0X06, 0X5B, 0x4F, 0X66, 0X6D, 0X7D}
char rand_num1=0;
char rand_num2=0;
void main(void)
{
TRISB=0x00;
TRISC=0x01;
TRISD=0x00;
for(;;)
{
if(RCO==0)
{
rand_num1=rand()%6+1;
rand_num2=rand()%6+1;
}
if (RC0==1)
{
const char patterns[];
}
}
}
Let me clarify my comments above a bit:
First, you don't need to call rand(). The user will be pressing the button for some interval (in a precision of 10 or 20 nanoseconds, which is a reasonable clock for a microcontroller). This interval, and given the precision will probably be more random than calling rand(). Therefore, you can have a single counter (i.e. up to 256) and grab two random numbers from this counter. In code, this would be something like:
int counter = 0;
int lo_chunk, hi_chunk;
if(RCO == 0) { // assuming that RCO == 0 means the button is pressed
counter = (counter + 1) % 256; // keep one byte out of the int
// we'll use that byte two get 2 4-bit
// chunks that we'll use as our randoms
lo_chunk = (counter & 0xF) % 6; // keep 4 LSBits and mod them by 6
hi_chunk = ((counter >> 4) & 0xF) % 6; // shift to get next 4 bits and mod them by 6
// Now this part is tricky.
// since you want to display the numbers in the 7seg display, I am assuming
// that you will need to write the respective patterns "somewhere"
// (either a memory address or output pins). You'll need to check the
// documentation of your board on this. I'll just outline them as
// "existing functions"
write_first_7segment(patterns[lo_chunk]);
write_second_7segment(patterns[hi_chunk]);
} else if(RCO == 1) { // assuming that this means "key released"
rand_num1 = lo_chunk;
rand_num2 = hi_chunk;
// probably you'll also need to display the numbers.
}
I hope that what I wrote in the comments above makes more sense now.
Keep in mind, that by not knowing the exact details of your board, I cannot
tell you how to actually write the patterns to the 7segment display, but I
assume that there will be a function of some sort.
Let's start by breaking this down into pieces, and address them individually. This is good practise anyway, and you should end up with lots of small problems that are individually easy to solve.
We can start with pseudocode for the main loop:
for ever {
while button is pushed {
roll the dice
update the displays
}
/* this ^ loop ends when the button is released
and is never entered until the button is pushed
*/
}
which translates to something like:
int main(void)
{
/* somewhere to keep the current value of each die,
initialized to zero */
char dice[2] = {0,0};
for (;;) {
while (button_pushed()) {
roll(dice);
display(dice);
}
}
}
so now we need to write button_pushed:
/* return true (non-zero) if RC0 is zero/one (delete as appropriate) */
int button_pushed(void)
{
return RC0 == 0;
}
... and roll, and display. Does that get you started?

Resources