‪Black Box
Program.cs
Go to the documentation of this file.
1 /*
2 * FILE : program.cs
3 * PROJECT : Black Box
4 * PROGRAMMER : BRIAN HINDS
5 * FIRST VERSION : 1.0.0.0
6 * DATE : March 20, 2019
7 * DESCRIPTION : This file is the main program for the BBPresenseSensor.
8 */
9 
13 using System;
14 using System.Collections.Generic;
15 using System.Configuration;
16 using System.Net.Sockets;
17 using System.Threading;
18 
19 /*
20  *
21  * Presence Sensor Architecture
22  *
23  *
24 Conestoga College
25 
26 Copyright (c) 2019, Brian Hinds
27 
28 Permission is hereby granted, free of charge, to any person obtaining a copy
29 of this software and associated documentation files (the "Software"), to deal
30 in the Software without restriction, including without limitation the rights
31 to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
32 copies of the Software, and to permit persons to whom the Software is
33 furnished to do so, subject to the following conditions:
34 
35 The above copyright notice and this permission notice shall be included in all
36 copies or substantial portions of the Software.
37 
38 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44 SOFTWARE.
45 */
46 
48 {
49  internal class ‪Program
50  {
51  #region Variables
52 
53  // Connection string needed for the connection library
54  private static readonly string ‪BBconection = ConfigurationManager.ConnectionStrings["BB_Sensor_CONNECTION"].ConnectionString;
55 
56  // Client Collection
57  private static List<BBSensorObjects> ‪_sensors;
58 
59  // Thread Signal
60  private static ManualResetEvent ‪_connected = new ManualResetEvent(false);
61 
62  //private static BBPresenceSensorStatus bbs;
63 
64  public static bool ‪isItRunning = false;
65 
66  // Server socket
67  private static Socket ‪_sensorServer = null;
68 
69  #endregion Variables
70 
71  #region Main
72 
73  private static void ‪Main(string[] args)
74  {
76  Console.Title = "BBPresenceSensor";
77 
78  ‪_sensors = new List<BBSensorObjects>();
80  Console.ReadLine();
82  }
83 
84  #endregion Main
85 
86  #region Listener
87 
91  private static void ‪StartListening()
92  {
93  try
94  {
96 
97  while (true)
98  {
99  // Set the event to non signaled state
100  ‪_connected.Reset();
101 
102  // Start an asynchronous socket to listen for connections
103  ‪_sensorServer.BeginAccept(new AsyncCallback(‪AcceptCallback), ‪_sensorServer);
104 
105  // Set operation status to true
107 
108  // Wait until a connection is made before continuing
109  ‪_connected.WaitOne();
110  }
111  }
112  catch (Exception ex)
113  {
114  ‪BBSensorErrorLog.‪SaveErrorData("PIR Sensor " + ex.Message.ToString());
115  }
116  }
117 
118  #endregion Listener
119 
120  #region AcceptCallback
121 
126  private static void ‪AcceptCallback(IAsyncResult ar)
127  {
128  // Signal the main thread to continue accepting new connections
129  ‪_connected.Set();
130 
131  // Accept new client socket connection
132  Socket socket = ‪_sensorServer.EndAccept(ar);
133 
134  // Create a new client connection object and store the socket
136  {
137  Socket = socket
138  };
139 
140  // Store all clients
141  ‪_sensors.Add(client);
142 
143  // Begin receiving messages from new connection
144  try
145  {
146  client.‪Socket.BeginReceive(client.‪Buffer, 0, client.‪BufferSize, SocketFlags.None, new AsyncCallback(‪ReceiveCallback), client);
147  }
148  catch (SocketException)
149  {
150  // Client was forcibly closed on the client side
151  ‪CloseClient(client);
152  }
153  catch (Exception ex)
154  {
155  // Set operation status to true
156 
157  ‪BBSensorErrorLog.‪SaveErrorData("PIR Sensor " + ex.Message.ToString());
158  }
159  }
160 
161  #endregion AcceptCallback
162 
163  #region ReceiveCallback
164 
169  private static void ‪ReceiveCallback(IAsyncResult ar)
170  {
171  int bytesRead;
172 
173  // Check for null values
174  if (!‪CheckState(ar, out string err, out ‪BBSensorObjects client))
175  {
177 
178  return;
179  }
180 
181  // Read message from the client socket
182  try
183  {
184  bytesRead = client.Socket.EndReceive(ar);
185  }
186  catch (SocketException)
187  {
188  // Client was forcedly closed on the client side
189  ‪CloseClient(client);
190 
191  return;
192  }
193  catch (Exception ex)
194  {
195  ‪BBSensorErrorLog.‪SaveErrorData("PIR Sensor " + ex.Message.ToString());
196 
197  return;
198  }
199 
200  // Check message
201  if (bytesRead > 0)
202  {
203  // Build message as it comes in
204  client.BuildIncomingMessage(bytesRead);
205 
206  // Print message to the console
207  client.PrintMessage();
208 
209  // Reset message
210  client.ClearIncomingMessage();
211  }
212 
213  // Listen for more incoming messages
214  try
215  {
216  client.Socket.BeginReceive(client.Buffer, 0, client.BufferSize, SocketFlags.None, new AsyncCallback(‪ReceiveCallback), client);
217  }
218  catch (SocketException)
219  {
220  // Client was forcedly closed on the client side
221  ‪CloseClient(client);
222  }
223  catch (Exception ex)
224  {
225  ‪BBSensorErrorLog.‪SaveErrorData("PIR Sensor " + ex.Message.ToString());
226  }
227  }
228 
229  #endregion ReceiveCallback
230 
231  #region CheckState
232 
240  private static bool ‪CheckState(IAsyncResult ar, out string err, out ‪BBSensorObjects client)
241  {
242  // Initialize
243  client = null;
244  err = "";
245 
246  // Check ar
247  if (ar == null)
248  {
249  err = "Async result null";
250 
251  return false;
252  }
253 
254  // Check client
255  client = (‪BBSensorObjects)ar.AsyncState;
256  if (client == null)
257  {
258  err = "Client null";
259 
260  return false;
261  }
262 
263  return true;
264  }
265 
266  #endregion CheckState
267 
268  #region CloseClient
269 
274  private static void ‪CloseClient(‪BBSensorObjects client)
275  {
276  ‪BBSensorErrorLog.‪SaveErrorData("Client disconnected");
277  client.‪Close();
278  if (‪_sensors.Contains(client))
279  {
280  ‪_sensors.Remove(client);
281  }
282 
283  //Console.WriteLine(_sensors.Count().ToString());
284 
285  foreach (‪BBSensorObjects sensor in ‪_sensors)
286  {
287  Console.WriteLine(sensor);
288  }
289  }
290 
291  #endregion CloseClient
292 
293  #region CloseAllSockets
294 
298  private static void ‪CloseAllSockets()
299  {
300  // Close all clients
301  foreach (‪BBSensorObjects connection in ‪_sensors)
302  {
303  connection.‪Close();
304  }
305 
306  // Close server
307  ‪_sensorServer.Close();
308  }
309 
310  #endregion CloseAllSockets
311  }
312 }
‪static Socket CreateListener()
‪Create the connection needed for the TCP connection
‪static void SaveErrorData(string error)
‪Log all the error that occurs in the program
‪static void Main(string[] args)
Definition: Program.cs:73
‪static void ReceiveCallback(IAsyncResult ar)
‪Handler for received messages
Definition: Program.cs:169
‪static void CloseClient(BBSensorObjects client)
‪Closes a client socket and removes it from the client list
Definition: Program.cs:274
‪static readonly string BBconection
Definition: Program.cs:54
‪void Close()
‪Closes the connection
‪static void StartListening()
‪Listen for client connections
Definition: Program.cs:91
‪static bool isItRunning
Definition: Program.cs:64
‪static void parseConnectionData(string connection)
‪Parse connection data
‪static Socket _sensorServer
Definition: Program.cs:67
‪static List< BBSensorObjects > _sensors
Definition: Program.cs:57
‪static ManualResetEvent _connected
Definition: Program.cs:60
‪static void AcceptCallback(IAsyncResult ar)
‪Handler for new connections
Definition: Program.cs:126
‪static bool CheckState(IAsyncResult ar, out string err, out BBSensorObjects client)
‪Checks IAsyncResult for null value
Definition: Program.cs:240
‪static void CloseAllSockets()
‪Closes all client and server connections
Definition: Program.cs:298