#include <native/mutex.h>
#include <native/timer.h>
static struct termios oldterminfo;
tcsetattr(fd, TCSANOW, &oldterminfo);
/*------------------------- GPIO -------------------------------------*/
/* from armadeus/target/packages/as_devices/c/as_gpio* */
# define ERROR(fmt, ...) printf(fmt, ##__VA_ARGS__)
//# define ERROR(fmt, ...) /*fmt, ##__VA_ARGS__*/
int pin_file; /* pin file for 2.6.29 interface*/
struct gpio_device *RS485_GPIO_dev;
static int write_file_bool(int fd, int value)
ret = write(fd, value?"1":"0", 1);
if (lseek(fd, 0, SEEK_SET) < 0) {
static struct gpio_device *gpio_open(int aGpioNum)
export_file = open("/sys/class/gpio/export", O_WRONLY);
ERROR("Can't open /sys/class/gpio/export\nBe sure that gpiolib is under your kernel\n");
snprintf(buf, BUFF_SIZE, "%%d", aGpioNum);
retval = write(export_file, buf, strlen(buf));
ERROR("/sys/class/gpio/export can't be written\n");
snprintf(buf, BUFF_SIZE, "/sys/class/gpio/gpio%%d/direction", aGpioNum);
gpio_dir_fd = open(buf, O_WRONLY);
ERROR("Can't open gpio%%d direction\n", aGpioNum);
ret = write(gpio_dir_fd, "out", 3);
ERROR("Error writing direction\n");
snprintf(buf, BUFF_SIZE, "/sys/class/gpio/gpio%%d/value", aGpioNum);
pin_file = open(buf, O_RDWR);
ERROR("Can't export gpio number %%d\n", aGpioNum);
dev = malloc(sizeof(struct gpio_device));
ERROR("Can't allocate gpio_device structure\n");
dev->port_num = aGpioNum;
dev->pin_file = pin_file;
static int gpio_close(struct gpio_device *aDev)
ERROR("device is NULL\n");
unexport_file = open("/sys/class/gpio/unexport", O_WRONLY);
ERROR("Can't open /sys/class/gpio/unexport\nBe sure that gpiolib is under your kernel\n");
snprintf(buf, BUFF_SIZE, "%%d", aDev->port_num);
retval = write(unexport_file, buf, strlen(buf));
ERROR("/sys/class/gpio/unexport can't be written\n");
static int gpio_set_pin_value(struct gpio_device *aDev, int aValue)
int pin_file = aDev->pin_file;
retval = write_file_bool(pin_file, aValue);
ERROR("Can't write value\n");
#define TransmitMode() gpio_set_pin_value(RS485_GPIO_dev, 1)
#define RecieveMode() gpio_set_pin_value(RS485_GPIO_dev, 0)
/*--------------------------- Serial Port handling ---------------------------*/
int openserial(char *devicename, unsigned long baudrate)
speed_t baud = B115200; /* baud rate */
if ((fd = open(devicename, O_RDWR)) == -1) {
perror("openserial(): open()");
if (tcgetattr(fd, &oldterminfo) == -1) {
perror("openserial(): tcgetattr()");
attr.c_cflag |= CS8 ; /* 8 bits */
/* no parity, 1 stop bit */
cfsetspeed(&attr, baud); /* baud rate */
if (tcflush(fd, TCIOFLUSH) == -1) {
perror("openserial(): tcflush()");
if (tcsetattr(fd, TCSANOW, &attr) == -1) {
perror("initserial(): tcsetattr()");
#define MAX_UART_DEVICES 32
#define UART_BUFSIZE_SHORT 26 /* UART bus read & write buffer size - short buffer for LPC-2 */
#define UART_BUFSIZE_LONG 48 /* UART bus read & write buffer size - long buffer for LHC-2 */
char uartBufSize = UART_BUFSIZE_SHORT; /* Smarteh uart bus: buffer size */
unsigned long uartBaudrate = 19200; /* Smarteh uart bus: baudrate */
struct timeval uartTimeout = {0,40000}; /* Smarteh uart bus: timeout */
/* Tables containing information about connected devices on UART port
(initialized by Composer) */
unsigned char uartDev[MAX_UART_DEVICES][2];
unsigned char uartDevNum = MAX_UART_DEVICES;
/* Buffers for reading data from UART port devices */
typedef char uartDevReadBuf_t[MAX_UART_DEVICES][UART_BUFSIZE_LONG];
uartDevReadBuf_t uartDevReadBufA;
uartDevReadBuf_t uartDevReadBufB;
uartDevReadBuf_t *uartDevReadBuf_drv;
uartDevReadBuf_t *uartDevReadBuf_plc;
uartDevReadBuf_t uartDevReadBuf;
/* Buffers for writing data to UART port devices */
typedef char uartDevWriteBuf_t[MAX_UART_DEVICES][UART_BUFSIZE_LONG];
uartDevWriteBuf_t uartDevWriteBufA;
uartDevWriteBuf_t uartDevWriteBufB;
uartDevWriteBuf_t *uartDevWriteBuf_drv;
uartDevWriteBuf_t *uartDevWriteBuf_plc;
#define uartDevWriteBuf (*uartDevWriteBuf_drv)
int uartDevWriteBuf_plc_state;
int uartDevReadBuf_plc_state;
/* Buffers for communication statuses with UART port devices */
/* 2D arrays due to compatibility with Composer (LpcSmartehIDE) */
char uartCommErrCntBuf [MAX_UART_DEVICES][1];
char uartCommStatusBuf[MAX_UART_DEVICES][1];
/* Function interface definition for modules on UART (RS485) bus */
typedef unsigned char (*uartPortFunct)(char*, char*, char);
/* Table describing module positions on UART (RS485) bus (parsed from Composer data) */
uartPortFunct uartPortDevices[MAX_UART_DEVICES] = {NULL};
/* Table of timers (one for each position) */
static commTimer uartPortTim[MAX_UART_DEVICES];
static RT_TASK UART_task;
static RT_MUTEX UART_WriteMutex;
static RT_MUTEX UART_ReadMutex;
void UART_task_proc(void *arg)
static unsigned char i=0;
static uint64_t lastCommTime=0;
while (rt_task_sleep_until(TM_INFINITE) == -EINTR){
// Communicate only with initialised UART devices
if(uartPortDevices[i] != NULL)
// Timers for UART port modules
if(uartPortTim[i].status != TIM_DISABLED)
actTime = (uint64_t)rt_timer_read();
uartPortTim[i].actValue = actTime - uartPortTim[i].oldTime;
if((uartPortTim[i].actValue < uartPortTim[i].toValue)
|| (actTime - lastCommTime < 50000000))
uartPortTim[i].status = TIM_EN_RUNNING;
uartPortTim[i].status = TIM_EN_EXPIRED;
uartPortTim[i].oldTime = actTime;
if((uartPortTim[i].status == TIM_DISABLED)
|| (uartPortTim[i].status == TIM_EN_EXPIRED))
if(!rt_mutex_acquire(&UART_WriteMutex, TM_INFINITE )){
if(uartDevWriteBuf_plc_state == FULL){
uartDevWriteBuf_t *uartDevWriteBuf_tmp;
uartDevWriteBuf_tmp = uartDevWriteBuf_plc;
uartDevWriteBuf_plc = uartDevWriteBuf_drv;
uartDevWriteBuf_drv = uartDevWriteBuf_tmp;
uartDevWriteBuf_plc_state = EMPTY;
rt_mutex_release(&UART_WriteMutex);
// Communicate with device
commStat = (*uartPortDevices[i])(
memcpy(uartDevReadBuf_drv, &uartDevReadBuf, sizeof(uartDevReadBuf_t));
if(!rt_mutex_acquire(&UART_ReadMutex, TM_INFINITE )){
if(uartDevReadBuf_plc_state == EMPTY){
uartDevReadBuf_t *uartDevReadBuf_tmp;
uartDevReadBuf_tmp = uartDevReadBuf_plc;
uartDevReadBuf_plc = uartDevReadBuf_drv;
uartDevReadBuf_drv = uartDevReadBuf_tmp;
uartDevReadBuf_plc_state = FULL;
rt_mutex_release(&UART_ReadMutex);
// Check communication status:
uartCommStatusBuf[i][0] = TRUE;
uartCommErrCntBuf[i][0] = 0;
if(uartCommErrCntBuf[i][0] < UART_RETRY_NUM)
uartCommErrCntBuf[i][0]++;
uartCommStatusBuf[i][0] = FALSE;
// If timer is enabled, reset it's value,
// otherwise keep it disabled
if(uartPortTim[i].status != TIM_DISABLED)
uartPortTim[i].actValue = 0;
uartPortTim[i].status = TIM_EN_RUNNING;
else /* Keep timer disabled */
uartPortTim[i].status = TIM_DISABLED;
// Procede with next UART device only after
// communication with the current one is done
else /* Go back to the first UART device */
#define TAIL_LEN 3 /* Length of data tail in bytes */
/**************************************************************************//**
* Calculate checksum of a buffer
* @param [in] buffer Pointer to buffer
* @param [in] bufLen Buffer length
* @return Checksum values on buffer locations bufLen-TAIL_LEN &
******************************************************************************/
void Checksum(unsigned char *buffer, unsigned char bufLen)
unsigned char checksum1=0, checksum2=0;
unsigned char checksum1Temp=0;
for(i=0;i<bufLen-TAIL_LEN;i++)
for(j=0;j<8;j++) /* Compute number of '1' of whole buff. */
if((checksum1Temp & 0x01)>0)
checksum1Temp = checksum1Temp >> 1;
checksum2 = checksum2 ^ buffer[i]; /* Compute XOR of whole buffer */
buffer[bufLen-TAIL_LEN] = checksum2; /* Write number of '1' to buffer */
buffer[bufLen-TAIL_LEN+1] = checksum1; /* Write XOR to buffer */
/**************************************************************************//**
* Check if checksum values of received buffer are valid
* @param [in] buffer Pointer to buffer
* @param [in] bufLen Buffer length
* @return TRUE if valid, otherwise FALSE
******************************************************************************/
unsigned char ChecksumValid(unsigned char *buffer, unsigned char bufLen)
unsigned char checksum1=0, checksum2=0;
unsigned char checksum1Temp=0;
for(i=0;i<bufLen-TAIL_LEN;i++)
checksum1Temp = buffer[i];
for(j=0;j<8;j++) /* Compute number of '1' of whole buff. */
if((checksum1Temp & 0x01)>0)
checksum1Temp = checksum1Temp >> 1; /* Compute XOR of whole buffer */
checksum2 = checksum2 ^ buffer[i];
/* Check if computed checksums are the same as those in buffer (=> no error) */
if((checksum2==buffer[bufLen-TAIL_LEN]) && (checksum1==buffer[bufLen-TAIL_LEN+1]))
/*************************************************************************//**
* Support for UART modules
* @param [in] readBuf Pointer to read buffer (for previously polled UART device!)
* @param [out] writeBuf Pointer to write buffer (for current device)
* @param [in] address UART device address
* @return TRUE if communication was successful, otherwise FALSE
*****************************************************************************/
unsigned char UARTDevice(char* readBuf, char* writeBuf, char address)
/* Prepare transmit buffer */
memcpy(tmp+1,writeBuf,uartBufSize-TAIL_LEN-1);
tmp[uartBufSize-TAIL_LEN] = address;
Checksum((unsigned char*)tmp+1, uartBufSize);
tcflush(UART_fd, TCIOFLUSH);
if(write(UART_fd, tmp, uartBufSize) != uartBufSize){
/* Sleep until transmission completes + 0.5ms safety */
while(rt_task_sleep_until(
1000000000LL * uartBufSize * 10 / uartBaudrate
FD_ZERO(&set); /* clear the set */
FD_SET(UART_fd, &set); /* add our file descriptor to the set */
timeout.tv_sec = uartTimeout.tv_sec;
timeout.tv_usec = uartTimeout.tv_usec;
while(count < uartBufSize){
rv = select(UART_fd + 1, &set, NULL, NULL, &timeout);
printf("RS485 select error\n");
int rr = read(UART_fd, tmp + count, uartBufSize - count);
printf("RS485 read error %%d\n",rr);
/* Turn to transmit mode*/
/* Copy received buffer */
if((count == uartBufSize) && (tmp[uartBufSize-TAIL_LEN] == address)){
if(ChecksumValid((unsigned char*)tmp+1, uartBufSize)){
memcpy(readBuf,tmp+1,uartBufSize-TAIL_LEN-1);
tcflush(UART_fd, TCIOFLUSH);
/* Macro to transform milliseconds to ns */
#define msTOns(ms) (1000000L*ms)
void InitUartPortDevices_longBuffer(void)
uartTimeout.tv_usec = 20000; /* 20 ms timeout */
for(i=0;i<MAX_UART_DEVICES;i++)
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOns(50); /* 50ms */
uartPortTim[i].status = TIM_EN_RUNNING;
case(240): /* 240-254 are reserved for EEPROM settings */
uartPortDevices[i] = NULL; /* "Empty" or unknown module */
uartPortTim[i].status = TIM_DISABLED;
uartDevNum--; /* Substract unused devices from MAX_UART_DEVICES */
void InitUartPortDevices_shortBuffer(void)
uartTimeout.tv_usec = 40000; /* 40 ms timeout */
for(i=0;i<MAX_UART_DEVICES;i++)
case(130): /* P01, P02, P01V, P02V */
case(178): /* AQ1, SM1, SM5, SM6, SM7 */
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOns(250); /* 250ms */
uartPortTim[i].status = TIM_EN_RUNNING;
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOns(650); /* 650ms */
uartPortTim[i].status = TIM_EN_RUNNING;
case(170): /* ID1, ID2, ID3 */
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOns(450); /* 450ms */
uartPortTim[i].status = TIM_EN_RUNNING;
uartPortDevices[i] = NULL; /* "Empty" or unknown module */
uartPortTim[i].status = TIM_DISABLED;