bus_template_code = {"MC8":"""
/* Code generated by LPCBus confnode */
/* LPCBus confnode includes */
/* LPCBus confnode user variables definition */
/* LPCBus confnode functions */
int __init_%(location_str)s(int argc,char **argv)
void __cleanup_%(location_str)s(void)
void __retrieve_%(location_str)s(void)
void __publish_%(location_str)s(void)
#############################
/* Code generated by LPCBus confnode */
static inline int16_t getWord(char *buffer)
return *((int16_t*)buffer);
static inline void setWord(char *buffer, int16_t word)
*((int16_t*)buffer) = word;
static inline int8_t getBit(char *buffer, unsigned char bitOffset)
return (*buffer & (0x01 << bitOffset)) && 1;
static inline void setBit(char *buffer, unsigned char bitOffset, int8_t bit)
unsigned char msk = (0x01 << bitOffset);
/* LPCBus confnode user variables definition */
/* LPCBus confnode functions */
int __init_%(location_str)s(int argc,char **argv)
void __cleanup_%(location_str)s(void)
void __retrieve_%(location_str)s(void)
void __publish_%(location_str)s(void)
/* LPCBus confnode includes */
#define RIGHT_READ_BUFSIZE 30 /**< Right bus read buffer size */
#define RIGHT_WRITE_BUFSIZE 30 /**< Right bus write buffer size */
#define MAX_RIGHT_MODULES 8
/**< Buffers for reading data from right bus modules */
typedef char rightReadBuf_t[MAX_RIGHT_MODULES][RIGHT_READ_BUFSIZE];
/**< Buffers for writing data to right bus modules */
typedef char rightWriteBuf_t[MAX_RIGHT_MODULES][RIGHT_WRITE_BUFSIZE];
/**< Tables containing information about connected modules
on right bus (initialized by Composer) */
typedef char rightI2CMod_t[MAX_RIGHT_MODULES][2];
#define RTIOC_TYPE_SMT RTDM_CLASS_EXPERIMENTAL
#define RTSMT_RTIOC_INIT _IOR(RTIOC_TYPE_SMT, 0x00, rightI2CMod_t)
//#define RTSMT_RTIOC_CLEAN _IOR(RTIOC_TYPE_SMT, 0x01, int)
#define RTSMT_RTIOC_READ _IOR(RTIOC_TYPE_SMT, 0x02, rightReadBuf_t)
#define RTSMT_RTIOC_WRITE _IOR(RTIOC_TYPE_SMT, 0x03, rightWriteBuf_t)
static rightReadBuf_t rightReadBuf;
static rightWriteBuf_t rightWriteBuf;
static rightI2CMod_t rightI2CMod;
static int rightbusfd = -1;
/* XXX TODO #include "smarteh.h" */
#define DEVICEFILENAME "rightbus"
bzero(&rightReadBuf, sizeof(rightReadBuf_t));
bzero(&rightWriteBuf, sizeof(rightWriteBuf_t));
bzero(&rightI2CMod, sizeof(rightI2CMod_t));
rightbusfd = rt_dev_open( DEVICEFILENAME, 0);
printf("can't open %%s rtdm device, %%s\\n", DEVICEFILENAME,
err = rt_dev_ioctl(rightbusfd, RTSMT_RTIOC_INIT, &rightI2CMod);
printf("error while RTSMT_RTIOC_INIT, %%s\\n",
rt_dev_close(rightbusfd);
rt_dev_ioctl(rightbusfd, RTSMT_RTIOC_READ, &rightReadBuf);
rt_dev_ioctl(rightbusfd, RTSMT_RTIOC_WRITE, &rightWriteBuf);
rt_dev_close(rightbusfd);
#define MAX_ONBOARD_DEVICES 2
/* Tables containing information about enabled on-board devices
(initialized by Composer) */
unsigned char onBoardDev[MAX_ONBOARD_DEVICES][2];
bzero(&onBoardDev, sizeof(onBoardDev));
"retrieve":"%(retrieve_code)s",
"publish":"%(publish_code)s",
#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;
int write_file_bool(int fd, int value)
ret = write(fd, value?"1":"0", 1);
if (lseek(fd, 0, SEEK_SET) < 0) {
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;
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");
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");
return gpio_set_pin_value(RS485_GPIO_dev, 1);
return gpio_set_pin_value(RS485_GPIO_dev, 0);
/*------------------------------------------------------------------------------*/
int openserial(char *devicename)
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()");
typedef struct /* Type definition for timers for right modules */
unsigned char status; /* Current status of timer - running / expired */
RTIME actValue; /* Actual timer value */
RTIME toValue; /* Timeout value - initialized at startup */
#define MAX_UART_DEVICES 52
/* UART bus read and write buffer size */
/* Tables containing information about connected devices on UART port
(initialized by Composer) */
unsigned char uartDev[MAX_UART_DEVICES][2];
/* Buffers for reading data from UART port devices */
typedef char uartDevReadBuf_t[MAX_UART_DEVICES][UART_BUFSIZE];
uartDevReadBuf_t uartDevReadBufA;
uartDevReadBuf_t uartDevReadBufB;
uartDevReadBuf_t *uartDevReadBuf_drv;
uartDevReadBuf_t *uartDevReadBuf_plc;
#define uartDevReadBuf (*uartDevReadBuf_drv)
/* Buffers for writing data to UART port devices */
typedef char uartDevWriteBuf_t[MAX_UART_DEVICES][UART_BUFSIZE];
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;
/* Function interface definition for modules on UART (RS485) bus */
typedef void (*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)
while (rt_task_sleep_until(TM_INFINITE) == -EINTR){
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);
/* Scan all positions for attached UART port modules */
for(i=0;i<MAX_UART_DEVICES;i++)
RTIME now = rt_timer_read();
/* Timers for right modules */
if(uartPortTim[i].status != TIM_DISABLED)
if(now - uartPortTim[i].actValue < uartPortTim[i].toValue)
uartPortTim[i].status = TIM_EN_RUNNING;
uartPortTim[i].status = TIM_EN_EXPIRED;
if(uartPortDevices[i] != NULL)
if((uartPortTim[i].status == TIM_DISABLED)
|| (uartPortTim[i].status == TIM_EN_EXPIRED))
// Communicate with device
// If timer is enabled, reset it's value,
// otherwise keep it disabled
if(uartPortTim[i].status != TIM_DISABLED)
uartPortTim[i].actValue = now;
uartPortTim[i].status = TIM_EN_RUNNING;
else /* Keep timer disabled */
uartPortTim[i].status = TIM_DISABLED;
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);
/**************************************************************************//**
* Calculate checksum of a buffer
* @param [in] buffer Pointer to buffer
* @return Checksum values on buffer locations 23 & 24
******************************************************************************/
void Checksum(unsigned char *buffer)
unsigned char checksum1=0, checksum2=0;
unsigned char checksum1Temp=0;
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[45] = checksum2; // Write number of '1' to buffer
buffer[46] = checksum1; // Write XOR to buffer
/**************************************************************************//**
* Check if checksum values of received buffer are valid
* @param [in] buffer Pointer to buffer
* @return TRUE if valid, otherwise FALSE
******************************************************************************/
unsigned char ChecksumValid(unsigned char *buffer)
unsigned char checksum1=0, checksum2=0;
unsigned char checksum1Temp=0;
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];
if((checksum2==buffer[45]) && (checksum1==buffer[46])) // Check if computed checksums are the same as those in buffer (=> no error)
/*************************************************************************//**
* 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
*****************************************************************************/
void UARTDevice(char* readBuf, char* writeBuf, char address)
// writeBuf[45] = address;
Checksum((unsigned char*)writeBuf+1);
tcflush(UART_fd, TCIOFLUSH);
if(write(UART_fd, writeBuf, UART_BUFSIZE) != UART_BUFSIZE){
/* Sleep until transmission completes + 0.5ms safety */
1000000000LL * UART_BUFSIZE * 10 / 115200
while(count < UART_BUFSIZE){
FD_ZERO(&set); /* clear the set */
FD_SET(UART_fd, &set); /* add our file descriptor to the set */
rv = select(UART_fd + 1, &set, NULL, NULL, &timeout);
printf("select error\\n");
int rr = read(UART_fd, tmp + count, UART_BUFSIZE - count);
printf("read error %%d\\n",rr);
// for (i=0; i<UART_BUFSIZE; i++){
// printf("|%%c:%%d", tmp[i], tmp[i]);
/* Turn to transmit mode*/
if(count == UART_BUFSIZE){
memcpy(readBuf,tmp+1,UART_BUFSIZE-1);
tcflush(UART_fd, TCIOFLUSH);
/* Macro to transform milliseconds to xenomai ticks */
#define msTOxn(ms) rt_timer_ns2ticks(1000000L*ms)
void InitUartPortDevices(void)
for(i=0;i<MAX_UART_DEVICES;i++)
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOxn(50); /* 50ms */
uartPortTim[i].status = TIM_EN_RUNNING;
case(130): /* P01, P02, P01V, P02V */
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOxn(200); /* 200ms */
uartPortTim[i].status = TIM_EN_RUNNING;
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOxn(600); /* 600ms */
uartPortTim[i].status = TIM_EN_RUNNING;
case(170): /* ID1, ID2, ID3 */
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOxn(400); /* 400ms */
uartPortTim[i].status = TIM_EN_RUNNING;
uartPortDevices[i] = &UARTDevice;
uartPortTim[i].toValue = msTOxn(400); /* 400ms */
uartPortTim[i].status = TIM_EN_RUNNING;
uartPortDevices[i] = NULL; /* "Empty" or unknown module */
uartPortTim[i].status = TIM_DISABLED;
char *serialdev = "/dev/ttyAPP1";
int RS485_GPIO_NUM = 103;
uartDevWriteBuf_plc_state = EMPTY;
uartDevReadBuf_plc_state = EMPTY;
bzero(&uartDev, sizeof(uartDev));
bzero(&uartDevReadBufA, sizeof(uartDevReadBuf_t));
bzero(&uartDevReadBufB, sizeof(uartDevReadBuf_t));
uartDevReadBuf_drv = &uartDevReadBufA;
uartDevReadBuf_plc = &uartDevReadBufB;
bzero(&uartDevWriteBufA, sizeof(uartDevWriteBuf_t));
bzero(&uartDevWriteBufB, sizeof(uartDevWriteBuf_t));
uartDevWriteBuf_drv = &uartDevWriteBufA;
uartDevWriteBuf_plc = &uartDevWriteBufB;
if((err = rt_mutex_create (&UART_WriteMutex, "UART_WriteMutex")))
if((err = rt_mutex_create (&UART_ReadMutex, "UART_ReadMutex")))
RS485_GPIO_dev = gpio_open(RS485_GPIO_NUM);
fprintf(stderr, "Error while initializing RS485 GPIO.\\n");
UART_fd = openserial(serialdev);
fprintf(stderr, "Error while initializing %%s.\\n", serialdev);
if((err = rt_task_create(&UART_task, "UART_task", 0, 50, T_JOINABLE)))
if(rt_task_start(&UART_task, &UART_task_proc, NULL))
if(!rt_mutex_acquire(&UART_ReadMutex, TM_INFINITE )){
if((prevstate=uartDevReadBuf_plc_state) == FULL){
uartDevReadBuf_plc_state = LOCKED;
rt_mutex_release(&UART_ReadMutex);
uartDevReadBuf_plc_state = EMPTY;
/* No new data -> no update */
if(!rt_mutex_acquire(&UART_WriteMutex, TM_INFINITE )){
prevstate=uartDevWriteBuf_plc_state;
uartDevWriteBuf_plc_state = LOCKED;
rt_mutex_release(&UART_WriteMutex);
uartDevWriteBuf_plc_state = FULL;
rt_task_unblock(&UART_task);
rt_task_delete(&UART_task);
rt_task_join(&UART_task);
gpio_close(RS485_GPIO_dev);
rt_mutex_delete(&UART_WriteMutex);
rt_mutex_delete(&UART_ReadMutex);
# to be overloaded at import
from plcopen.structures import LOCATIONDATATYPES
from PLCControler import LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP,\
LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY
LOCATION_TYPES = {"I": LOCATION_VAR_INPUT,
"Q": LOCATION_VAR_OUTPUT,
"M": LOCATION_VAR_MEMORY}
LOCATION_DIRS = dict([(dir, size) for size, dir in LOCATION_TYPES.iteritems()])
for size, types in LOCATIONDATATYPES.iteritems():
LOCATION_SIZES[_type] = size
def GetModuleChildren(module):
for child in module["children"]:
if child["type"] == LOCATION_GROUP:
children.extend(child["children"])
def _GetVariables(module):
for child in module["children"]:
if child["type"] in [LOCATION_GROUP, LOCATION_MODULE]:
variables.extend(_GetVariables(child))
def GetLastModuleGroup(module):
for child in module["children"]:
if child["type"] == LOCATION_GROUP:
def GetModuleBySomething(module, something, toks):
for child in GetModuleChildren(module):
if child.get(something) == toks[0]:
return GetModuleBySomething(child, something, toks[1:])
def GetModuleVariable(module, location, direction):
for child in GetModuleChildren(module):
if child["location"] == location and child["type"] == LOCATION_TYPES[direction]:
def RemoveModuleChild(module, child):
if child in module["children"]:
module["children"].remove(child)
for group in module["children"]:
if group["type"] == LOCATION_GROUP and child in group["children"]:
group["children"].remove(child)
self.VariableLocationTree = []
self.ResetUsedLocations()
def __getitem__(self, key):
return self.VariableLocationTree
raise KeyError, "Only 'children' key is available"
def _GetChildBySomething(self, something, toks):
return GetModuleBySomething({"children" : self.VariableLocationTree}, something, toks)
return self.GetCTRoot().GetBaseTypes()
def GetSizeOfType(self, type):
return LOCATION_SIZES[self.GetCTRoot().GetBaseType(type)]
def _GetVariableLocationTree(self, current_location, infos):
if infos["type"] == LOCATION_MODULE:
location = current_location + (infos["IEC_Channel"],)
return {"name": infos["name"],
"location": ".".join(map(str, location + ("x",))),
"children": [self._GetVariableLocationTree(location, child) for child in infos["children"]]}
elif infos["type"] == LOCATION_GROUP:
return {"name": infos["name"],
"children": [self._GetVariableLocationTree(current_location, child) for child in infos["children"]]}
size = self.GetSizeOfType(infos["IEC_type"])
location = "%" + LOCATION_DIRS[infos["type"]] + size + ".".join(map(str, current_location + infos["location"]))
return {"name": infos["name"],
"IEC_type": infos["IEC_type"],
"var_name": infos["name"],
"description": infos["description"],
def GetVariableLocationTree(self):
return {"name": self.BaseParams.getName(),
"type": LOCATION_CONFNODE,
"location": self.GetFullIEC_Channel(),
"children": [self._GetVariableLocationTree(self.GetCurrentLocation(), child)
for child in self.VariableLocationTree]}
def CTNTestModified(self):
def CTNRequestSave(self, from_project_path=None):
def ResetUsedLocations(self):
def _AddUsedLocation(self, parent, location):
if not parent.has_key(num):
parent[num] = {"used": False, "children": {}}
self._AddUsedLocation(parent[num]["children"], location)
parent[num]["used"] = True
def AddUsedLocation(self, location):
self._AddUsedLocation(self.UsedLocations, list(location))
def _CheckLocationConflicts(self, parent, location):
if not parent.has_key(num):
return self._CheckLocationConflicts(parent[num]["children"], location)
elif len(parent[num]["children"]) > 0:
def CheckLocationConflicts(self, location):
return self._CheckLocationConflicts(self.UsedLocations, list(location))
def CTNGenerate_C(self, buildpath, locations):
@param current_location: Tupple containing confnode IEC location : %I0.0.4.5 => (0,0,4,5)
@param locations: List of complete variables locations \
[{"IEC_TYPE" : the IEC type (i.e. "INT", "STRING", ...)
"NAME" : name of the variable (generally "__IW0_1_2" style)
"DIR" : direction "Q","I" or "M"
"SIZE" : size "X", "B", "W", "D", "L"
"LOC" : tuple of interger for IEC location (0,1,2,...)
@return: [(C_file_name, CFLAGS),...] , LDFLAGS_TO_APPEND
current_location = self.GetCurrentLocation()
# define a unique name for the generated C file
location_str = "_".join(map(str, current_location))
code_str = {"location_str": location_str,
for module in GetModuleChildren(self):
code_str["init_code"] += " %s\n" % module["init"]
self.ResetUsedLocations()
for location in locations:
loc = location["LOC"][len(current_location):]
while next is not None and i < len(loc):
next = self._GetChildBySomething("IEC_Channel", loc[:i + 1])
for variable in GetModuleChildren(group):
if variable["location"] == var_loc and location["DIR"] == LOCATION_DIRS[variable["type"]]:
# if location["DIR"] != LOCATION_DIRS[variable["type"]]:
# raise Exception, "Direction conflict in variable definition"
# if location["IEC_TYPE"] != variable["IEC_type"]:
# raise Exception, "Type conflict in variable definition"
if location["DIR"] == "Q":
if self.CheckLocationConflicts(location["LOC"]):
raise Exception, "BYTE and BIT from the same BYTE can't be used together"
self.AddUsedLocation(location["LOC"])
vars.append({"location": location["NAME"],
"Type": variable["IEC_type"],
"Retrieve": variable["retrieve"],
"Publish": variable["publish"],
base_types = self.GetCTRoot().GetBaseTypes()
if var["Type"] in base_types:
code_str["var_decl"] += "%s%s beremiz%s;\n"%(prefix, var["Type"], var["location"])
code_str["var_decl"] += "%s%s *%s = &beremiz%s;\n"%(prefix, var["Type"], var["location"], var["location"])
if var["Retrieve"] != "":
code_str["retrieve_code"] += " " + var["Retrieve"] % ("*" + var["location"]) + "\n"
code_str["publish_code"] += " " + var["Publish"] % ("*" + var["location"]) + "\n"
BusName = LPCarch + ":" + self.BaseParams.getName()
return bus_code.get(BusName,{"decl":"",
"retrieve":"%(retrieve_code)s",
"publish":"%(publish_code)s",
"bus_decl":bcode("decl"),
"bus_init_code": bcode("init"),
"bus_cleanup_code": bcode("cleanup"),
"bus_retrieve_code": bcode("retrieve"),
"bus_publish_code": bcode("publish"),
if LPCarch not in bus_template_code:
raise Exception, "Unknown arch %s. Please use %s"%(
LPCarch,repr(bus_template_code.keys()))
Gen_Module_path = os.path.join(buildpath, "Bus_%s.c"%location_str)
module = open(Gen_Module_path,'w')
module.write(bus_template_code[LPCarch] % code_str)
matiec_flags = '"-I%s" -Wno-unused-function'%os.path.abspath(self.GetCTRoot().GetIECLibPath())
return [(Gen_Module_path, matiec_flags)],"",True