Subversion Repositories HomeAutomation

Rev

Details | Last modification | View Log | SVN | RSS feed

Rev Author Line No. Line
434 arune 1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.IO.Ports;
5
using System.Net;
6
using System.Net.Sockets;
7
 
8
public class SerialConnection {
9
	const byte DEBUG_LEVEL = 3;	//0, 1, 2, 3
10
 
11
	public const byte UART_START_BYTE = 253;
12
	public const byte UART_END_BYTE = 250;
13
	public const int PACKET_LENGTH = 17;
14
	private const int readBufferSize = 8192;
15
	public const byte UART_CONN_BYTE = 252;
16
 
17
	private Socket udpserver = null;
18
	private IPEndPoint iep = null;
19
	private string remoteIP = null;
20
	private int remotePort = 1100;
21
 
22
	private SerialPort serial_conn = null;
23
	private byte[] iBuff = new byte[8192];
24
	private int iBuffPointer = 0;
25
 
26
	public SerialConnection() {  }
27
 
28
	public bool open() { 
29
		if (serial_conn != null) {
30
			if (!serial_conn.IsOpen) serial_conn.Open();
31
			return true; 
32
		} else if (udpserver != null) {
33
			return true;
34
		} else {
35
			return false;
36
		}
37
	}
38
 
39
	public bool close() {
40
		if (serial_conn != null) {
41
			if (serial_conn.IsOpen) serial_conn.Close();
42
			return true; 
43
		} else if (udpserver != null) {
44
			udpserver.Close();
45
			return true;
46
		} else {
47
			return false;
48
		}
49
 
50
	}
51
 
52
	public bool isOpen() { 
53
		if (serial_conn != null) {
54
			return serial_conn.IsOpen; 
55
		} else if (udpserver != null) {
56
			return true;
57
		} else {
58
			return false;
59
		}
60
	}
61
 
62
	public void setConfiguration(int baudRate, Parity parity, string portName, StopBits stopbits, int databits, bool rtsEnable) {
63
		if (DEBUG_LEVEL>1) { Console.WriteLine("Connecting to target..."); }
64
 
65
		if (!portName.Contains("/udp")) {
66
			try {
67
				serial_conn = new SerialPort();
68
				serial_conn.ReadBufferSize = readBufferSize;
69
				serial_conn.BaudRate = baudRate;
70
				serial_conn.Parity = parity;
71
				serial_conn.PortName = portName;
72
				serial_conn.StopBits = stopbits;
73
				serial_conn.DataBits = databits;
74
				serial_conn.RtsEnable = rtsEnable;
75
				if (DEBUG_LEVEL>1) { Console.WriteLine("Serial port opened to target"); }
76
				if (DEBUG_LEVEL>1) { Console.WriteLine("Establishing serial connection to target"); }
77
				byte[] bytes = new byte[1];
78
				bytes[0] = UART_CONN_BYTE;
79
				//... ...
80
 
81
 
82
			}
83
			catch (Exception e) {
84
				throw e;
85
			}
86
		} else {
87
			try {
88
				string[] splitted = portName.Split('/');
89
				if (splitted.Length == 4) {
90
					if (splitted[0] == "" && splitted[1] == "udp") {
91
						remoteIP = splitted[2];
92
						remotePort = Int32.Parse(splitted[3]);
93
						iep = new IPEndPoint(IPAddress.Any, remotePort);
94
						udpserver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
95
						udpserver.Bind(iep);
96
 
97
						if (DEBUG_LEVEL>1) { Console.WriteLine("Establishing UDP connection to target"); }
98
						byte[] bytes = new byte[1];
99
						bytes[0] = UART_CONN_BYTE;
100
						udpserver.SendTo(bytes, bytes.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(remoteIP), remotePort));
101
 
102
						//... här ska man vänta på svar från servern ...
103
 
104
						if (DEBUG_LEVEL>1) { Console.WriteLine("UDP connection established to target"); }
105
					}
106
				}
107
 
108
			} catch (Exception e) {
109
				throw e;
110
			}
111
		}
112
	}
113
 
114
	public bool writePacket(CanPacket cp) {
115
		if (serial_conn != null) {
116
			if (serial_conn.IsOpen) {
117
				byte[] bytes = new byte[PACKET_LENGTH];
118
				Array.Copy(cp.getBytes(), 0, bytes, 1, PACKET_LENGTH - 2);
119
				bytes[0] = UART_START_BYTE;
120
				bytes[PACKET_LENGTH - 1] = UART_END_BYTE;
121
				serial_conn.Write(bytes, 0, PACKET_LENGTH);
122
				return true;
123
			}
124
			return false;
125
		} else if (udpserver != null) {
126
			byte[] bytes = new byte[PACKET_LENGTH];
127
			Array.Copy(cp.getBytes(), 0, bytes, 1, PACKET_LENGTH - 2);
128
			bytes[0] = UART_START_BYTE;
129
			bytes[PACKET_LENGTH - 1] = UART_END_BYTE;
130
 
131
			udpserver.SendTo(bytes, bytes.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(remoteIP), remotePort));
132
 
133
			return true;
134
		} else {
135
			return false;
136
		}
137
	}
138
 
139
	public bool getPacket(out CanPacket cp) {
140
		cp = null;
141
		if ((serial_conn != null) || (udpserver != null)) {
142
 
143
			if (serial_conn != null) {
144
			   	int bytesToRead = serial_conn.BytesToRead;
145
				if (bytesToRead > 0) {
146
					byte[] data = new byte[bytesToRead];
147
 
148
					try {
149
						serial_conn.Read(data, 0, data.Length);
150
					} catch (Exception e) {
151
						Console.WriteLine("Exception " + e + " occured\n");
152
					}
153
 
154
					Array.Copy(data, 0, iBuff, iBuffPointer, data.Length);
155
					iBuffPointer += bytesToRead;
156
				}
157
			} else if (udpserver != null) {
158
			   	int bytesToRead = udpserver.Available;
159
				if (udpserver.Available > 0) {
160
					byte[] data = new byte[bytesToRead];
161
					try {
162
						EndPoint tmpRemote = (EndPoint)iep;
163
						udpserver.ReceiveFrom(data, ref tmpRemote);
164
					} catch (Exception e) {
165
						Console.WriteLine("Exception " + e + " occured\n");
166
					}
167
 
168
					int bytestomove = data.Length;
169
					if (bytestomove ==18) {
170
						bytestomove = data.Length -1;
171
					}
172
					Array.Copy(data, 0, iBuff, iBuffPointer, bytestomove);
173
					iBuffPointer += bytestomove;
174
				}
175
 
176
			}
177
 
178
			// N�r array st�rre eller lika med PACKET_LENGTH...
179
			while (iBuffPointer >= PACKET_LENGTH) {
180
				int startIndex = 0;
181
 
182
				// S�k igenom efter start byte fr�n b�rjan.
183
				for (int i = 0; i < iBuffPointer; i++) {
184
					// Poppa alla bytes som inte �r startbyte.
185
					if (iBuff[i] != UART_START_BYTE) startIndex++;
186
					else {
187
						// N�r startbyte hittas, kolla om �terst�ende l�ngd �r st�rre eller lika med PACKET_LENGTH (inkl startbyte)
188
						if ((iBuffPointer - startIndex) >= PACKET_LENGTH) {
189
							//om s�, kolla PACKET_LENGTH-1 byte fram.
190
							if (iBuff[startIndex + PACKET_LENGTH - 1] == UART_END_BYTE) {
191
								// Om byte PACKET_LENGTH-1 �r slutbyte s� extraktas startIndex till slutbyteindex.
192
								CanPacket cm = new CanPacket(iBuff, (uint)startIndex + 1);
193
								// S�tt ny startindex och avsluta loop.
194
								startIndex += PACKET_LENGTH;
195
								cp = cm;
196
								// och i slutet g�ra en array copy.
197
								// Flytta ner allt efter slutbyte till index 0 i array.
198
								Array.Copy(iBuff, startIndex, iBuff, 0, iBuffPointer - PACKET_LENGTH);
199
								iBuffPointer -= startIndex;
200
 
201
								return true;
202
							}
203
						}
204
					}
205
				}
206
				// och i slutet g�ra en array copy.
207
				// Flytta ner allt efter slutbyte till index 0 i array.
208
				Array.Copy(iBuff, startIndex, iBuff, 0, iBuffPointer - PACKET_LENGTH);
209
				iBuffPointer -= startIndex;
210
			}
211
			return false;
212
 
213
		} else {
214
			return false;
215
		}
216
	}
217
 
218
}