summaryrefslogtreecommitdiff
path: root/src/hal/classicladder/serial_linux.c
blob: 0e114a1f1d181f33285097dda4d77c263655a83c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/* Classic Ladder Project */
/* Copyright (C) 2001-2005 Marc Le Douarain */
/* http://www.multimania.com/mavati/classicladder */
/* http://www.sourceforge.net/projects/classicladder */
/* August 2005 */
/* ------------------------------------ */
/* Serial low-level functions for Linux */
/* ------------------------------------ */

/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */

/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU */
/* Lesser General Public License for more details. */

/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include <termios.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h> 
#include <sys/ioctl.h>
#include <errno.h>

#include "serial_common.h"
extern int ModbusSerialUseRtsToSend;
extern int ModbusDebugLevel;
extern int ModbusSerialDataBits;   // Number of data bits (7, 6, 7, 8)
extern int ModbusSerialStopBits;   // Number of stop bits (1 or 2)
extern int ModbusSerialParity;      // Parity (00 = NONE, 01 = Odd, 02 = Even, 03 = Mark, 04 = Space)

int SerialSpeed[ ] = { 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 0 };
int SerialCorres[ ] = { B300, B600, B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, 0 };

char PortIsOpened = 0;
int fd;
long DATABITS;
long STOPBITS;
long PARITYON;
long PARITY;

struct termios oldtio;
struct termios newtio;

char SerialOpen( char * SerialPortName, int Speed )
{
	/* if port already opened => close it before */
	if ( PortIsOpened )
		SerialClose( );

	/* open the device to be non-blocking (read will return immediatly) */
	fd = open( SerialPortName, O_RDWR | O_NOCTTY | O_NDELAY/*don't wait DTR*/ );
        //fd = open( SerialPortName, O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (fd >=0)
	{
		int BaudRate = -1;
		int ScanBaudRate = 0;
		fcntl(fd, F_SETFL, O_RDWR | O_NOCTTY ); /* perform blocking reads */
		for(ScanBaudRate = 0; SerialSpeed[ScanBaudRate]; ScanBaudRate++)
		{
			if ( SerialSpeed[ ScanBaudRate ]==Speed )
			{
				BaudRate = SerialCorres[ ScanBaudRate ];
				break;
			}
		}
switch (ModbusSerialDataBits)
      {
         case 8:
         default:
            DATABITS = CS8;
            break;
         case 7:
            DATABITS = CS7;
            break;
         case 6:
            DATABITS = CS6;
            break;
         case 5:
            DATABITS = CS5;
            break;
      }  //end of switch data_bits
      switch (ModbusSerialStopBits)
      {
         case 1:
         default:
            STOPBITS = 0;
            break;
         case 2:
            STOPBITS = CSTOPB;
            break;
      }  //end of switch stop bits
      switch (ModbusSerialParity)
      {
         case 0:
         default:                       //none
            PARITYON = 0;
            PARITY = 0;
            break;
         case 1:                        //odd
            PARITYON = PARENB;
            PARITY = PARODD;
            break;
         case 2:                        //even
            PARITYON = PARENB;
            PARITY = 0;
            break;
      }  //end of switch parity
		if ( BaudRate!=-1 )
		{        
			tcgetattr(fd,&oldtio); /* save current port settings */
			/* set new port settings */
			bzero(&newtio, sizeof(newtio));
			//newtio.c_cflag = BaudRate | /*CRTSCTS |*/ CS8 | CLOCAL | CREAD;
                        newtio.c_cflag = BaudRate | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
			//newtio.c_cflag |= PARENB
			newtio.c_iflag = IGNPAR    | IGNBRK; // | ICRNL;
			newtio.c_oflag = 0;
			newtio.c_lflag = 0;
			newtio.c_cc[VMIN]=0; //1;
			newtio.c_cc[VTIME]=0;
			tcsetattr(fd,TCSANOW,&newtio);
			PortIsOpened = 1;
		}
		else
		{
			printf("Speed value not found for serial\n");
		}
	}
	else
	{
		printf( "Failed to open serial port %s...\n", SerialPortName );
	}
	return PortIsOpened;
}

void SerialClose( )
{
	if ( PortIsOpened )
	{
		PortIsOpened = 0;
		/* restore old port settings */
		tcsetattr(fd,TCSANOW,&oldtio);
		close(fd);
	}
}

void SerialSetRTS( int State )
{
     int status;
	if ( PortIsOpened )
	{
		ioctl(fd, TIOCMGET, &status);
		if ( State )
			status |= TIOCM_RTS;
		else
			status &= ~TIOCM_RTS;
		if ( ModbusDebugLevel>=3 )
			printf( "Set RTS=%d\n", State );
		ioctl(fd, TIOCMSET, &status);
	}
}

void SerialSend( char *Buff, int BuffLength )
{
	if ( PortIsOpened )
	{
		if ( ModbusSerialUseRtsToSend )
		{
			SerialSetRTS( 1 );
		}
		if ( ModbusDebugLevel>=2 )
			printf("Serial writing...\n");
		while(BuffLength > 0) {
			int r = write(fd,Buff,BuffLength);
			if(r < 0) {
				if ( ModbusDebugLevel>=1 )
					printf("SerialSend failed: %s!\n", strerror(errno));
				break;
			}
			Buff += r;
			BuffLength -= r;
		}
		if ( ModbusDebugLevel>=2 )
			printf("Writing done!\n");
		// wait until everything has been transmitted
		tcdrain( fd );
		if ( ModbusSerialUseRtsToSend )
		{
			SerialSetRTS( 0 );
		}
	}
}

void SerialSetResponseSize( int Size, int TimeOutResp )
{
	if ( PortIsOpened )
	{
	        newtio.c_cc[VMIN] = Size; //Nbr chars we should receive;
		newtio.c_cc[VTIME] = 1;
//		tcflush(fd, TCIFLUSH);
		if ( ModbusDebugLevel>=2 )
			printf("Serial config...\n");
		tcsetattr(fd,TCSANOW,&newtio);
	}
}

int SerialReceive( char * Buff, int MaxBuffLength, int TimeOutResp )
{
	int NbrCarsReceived = 0;
	if ( PortIsOpened )
	{

// the select is used it no char at all is received (else read() block...)
int recep_descrip;
fd_set myset;
struct timeval tv;
FD_ZERO( &myset);
// add descrip to survey and set time-out wanted !
FD_SET( fd, &myset );
tv.tv_sec = TimeOutResp / 1000; //seconds
tv.tv_usec = (TimeOutResp % 1000) * 1000; //micro-seconds
if ( ModbusDebugLevel>=3 )
	printf("select() for serial reading...\n");
recep_descrip = select( 16, &myset, NULL, NULL, &tv );
if ( recep_descrip>0 )
{
		if ( ModbusDebugLevel>=2 )
			printf("Serial reading...\n");
			NbrCarsReceived = read(fd,Buff,MaxBuffLength);
		if ( ModbusDebugLevel>=2 )
			printf("%d chars found\n", NbrCarsReceived);
}
	}
	return NbrCarsReceived;
}

void SerialFlush( void )
{
	if ( PortIsOpened )
	{
		if ( ModbusDebugLevel>=2 )
			printf("Serial flush all!\n");
		tcflush( fd, TCIOFLUSH );
		usleep( 250*1000 );
		tcflush( fd, TCIOFLUSH );
	}
}