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
            return true;
133
        } else {
134
            return false;
135
        }
136
    }
137
 
138
    public bool getPacket(out CanPacket cp) {
139
        cp = null;
140
        if ((serial_conn != null) || (udpserver != null)) {
141
 
142
            if (serial_conn != null) {
143
                int bytesToRead = serial_conn.BytesToRead;
144
                if (bytesToRead > 0) {
145
                    byte[] data = new byte[bytesToRead];
146
 
147
                    try {
148
                        serial_conn.Read(data, 0, data.Length);
149
                    } catch (Exception e) {
150
                        Console.WriteLine("Exception " + e + " occured\n");
151
                    }
152
 
153
                    Array.Copy(data, 0, iBuff, iBuffPointer, data.Length);
154
                    iBuffPointer += bytesToRead;
155
                }
156
            } else if (udpserver != null) {
157
                int bytesToRead = udpserver.Available;
158
                if (udpserver.Available > 0) {
159
                    byte[] data = new byte[bytesToRead];
160
                    try {
161
                        EndPoint tmpRemote = (EndPoint)iep;
162
                        udpserver.ReceiveFrom(data, ref tmpRemote);
163
                    } catch (Exception e) {
164
                        Console.WriteLine("Exception " + e + " occured\n");
165
                    }
166
 
167
                    int bytestomove = data.Length;
168
                    if (bytestomove ==18) {
169
                        bytestomove = data.Length -1;
170
                    }
171
                    Array.Copy(data, 0, iBuff, iBuffPointer, bytestomove);
172
                    iBuffPointer += bytestomove;
173
                }
174
 
175
            }
176
 
177
            // N�r array st�rre eller lika med PACKET_LENGTH...
178
            while (iBuffPointer >= PACKET_LENGTH) {
179
                int startIndex = 0;
180
 
181
                // S�k igenom efter start byte fr�n b�rjan.
182
                for (int i = 0; i < iBuffPointer; i++) {
183
                    // Poppa alla bytes som inte �r startbyte.
184
                    if (iBuff[i] != UART_START_BYTE) startIndex++;
185
                    else {
186
                        // N�r startbyte hittas, kolla om �terst�ende l�ngd �r st�rre eller lika med PACKET_LENGTH (inkl startbyte)
187
                        if ((iBuffPointer - startIndex) >= PACKET_LENGTH) {
188
                            //om s�, kolla PACKET_LENGTH-1 byte fram.
189
                            if (iBuff[startIndex + PACKET_LENGTH - 1] == UART_END_BYTE) {
190
                                // Om byte PACKET_LENGTH-1 �r slutbyte s� extraktas startIndex till slutbyteindex.
191
                                CanPacket cm = new CanPacket(iBuff, (uint)startIndex + 1);
192
                                // S�tt ny startindex och avsluta loop.
193
                                startIndex += PACKET_LENGTH;
194
                                cp = cm;
195
                                // och i slutet g�ra en array copy.
196
                                // Flytta ner allt efter slutbyte till index 0 i array.
197
                                Array.Copy(iBuff, startIndex, iBuff, 0, iBuffPointer - PACKET_LENGTH);
198
                                iBuffPointer -= startIndex;
199
 
200
                                return true;
201
                            }
202
                        }
203
                    }
204
                }
205
                // och i slutet g�ra en array copy.
206
                // Flytta ner allt efter slutbyte till index 0 i array.
207
                Array.Copy(iBuff, startIndex, iBuff, 0, iBuffPointer - PACKET_LENGTH);
208
                iBuffPointer -= startIndex;
209
            }
210
            return false;
211
 
212
        } else {
213
            return false;
214
        }
215
    }
216
 
217
}