/// <summary> /// Associate a station, if its config exists, or open the config procedure /// </summary> public Station tryAddStation(String NameMAC, StationHandler _handler, bool AllowAsynchronous) //Replace Object with the relevant type { //check if not attempting reconnection locker.EnterReadLock(); //lock to avoid removal if reconnecting Station s = getStation(NameMAC); if (s != null) // s is reconnecting after losing contact { s.handler.socket.Close(); s.handler = _handler; //updating handler s.hearbeat(); locker.ExitReadLock(); return(s); } locker.ExitReadLock(); s = loadStation(NameMAC, _handler); //search Station in DB if (s == null && AllowAsynchronous) //this is already the check if a configuration for the station exists or not { int?wId = FindWindowByMAC(_handler.macAddress); if (wId != null) { int id = wId ?? 0; Application.Current.Windows[id].Close(); } StationAdder sa1 = new StationAdder(this, _handler); sa1.Show(); return(null); } return(s); }
/// <summary> /// Try to load the configs of a station from persistent storage /// </summary> public Station loadStation(String NameMAC, StationHandler handler) { DatabaseInterface.StationInfo?si = databaseInt.loadStationInfo(NameMAC); if (si == null) { return(null); } Station s = new Station(); s.hearbeat(); s.NameMAC = NameMAC; s.handler = handler; String roomName = si.Value.RoomName; double x = si.Value.X; double y = si.Value.Y; Room room = getRoom(roomName); if (room == null) // The room to which it was attached does not exist anymore. Reconfig { deleteStation(NameMAC); return(null); } s.location = new PositionTools.Position(x, y, room); locker.EnterWriteLock(); room.addStation(s); stations[s.NameMAC] = s; locker.ExitWriteLock(); foreach (Publisher pb in publishers) { if (pb.supportsOperation(Publisher.DisplayableType.StationUpdate)) { pb.publishStationUpdate(room, s, Publisher.EventType.Appear); } } return(s); }
/// <summary> /// Interprets the command received through the socket /// </summary> public int Command(string text, Socket socket, int received) { int x; int toReceive = 0; int fileSize = 0; int timestamp = 0; DateTime timestampDT = new DateTime(); bool ignoring = false; //true if there's any reason to ignore the file received if (text.IndexOf("REGISTER(") > -1) //-----------------------REGISTER------------------------ { int offset = text.IndexOf("REGISTER("); string macAddress = text.Substring(offset + 9, 17); macAddresses.Add(socket, macAddress.Replace(@":", string.Empty)); Console.WriteLine("An ESP board with MAC: " + macAddress + " has requested access"); //apro finestra configurazione nuova scheda var d = new SafeNewStation(ctx.guiPub.linkedwindow.NewStation); Application.Current.Dispatcher.Invoke(d, macAddress.Replace(@":", string.Empty), socket); byte[] data = Encoding.UTF8.GetBytes("ACCEPT\r\n"); try { socket.Send(data); //blocking method } catch (Exception) { macAddresses.Remove(socket); socket.Close(); return(-1); } int result = ESP_SyncClock(socket); if (result == -1) { return(-1); } } else if ((x = text.IndexOf("FILE")) > -1) //-------------------FILE---------------------------- { //FILE\r\n BBBB TTTT 010101010101010101010... byte[] buffer = Encoding.UTF8.GetBytes(text); byte[] data = new byte[BUFFER_SIZE]; //copio l'array "data" nel buffer di ricezione for (int i = 0; i < received; i++) { data[i] = buffer[i]; } try { while (received < 14) { //ricevo di nuovo, finché non ricevo tutti i metadati int receivedBytesLen = socket.Receive(data, received, BUFFER_SIZE - received, SocketFlags.None); received += receivedBytesLen; } //ora ho ricevuto i metadati if (received > 14) { //leggere quanti byte si devono ricevere e timestamp byte[] fileSizeBytes = new byte[4]; byte[] timestampBytes = new byte[4]; byte[] timestampBytesReversed = new byte[4]; for (int i = 0; i < 4; i++) { fileSizeBytes[3 - i] = data[i + 6]; } for (int i = 0; i < 4; i++) { timestampBytes[3 - i] = data[i + 10]; } fileSize = BitConverter.ToInt32(fileSizeBytes, 0); timestamp = BitConverter.ToInt32(timestampBytes, 0); timestampDT = FileParser.TimeFromUnixTimestamp(timestamp); toReceive = fileSize - received + 14; //bytes che devo ancora ricevere } string toAnalyze = Encoding.UTF8.GetString(data, 14, data.Length - 14); string chunk = Chunker(toAnalyze, out toAnalyze); Station station = ctx.getStation(macAddresses[socket]); //dal socket trovo la station if (station == null) //probably, the station isn't configured yet { ignoring = true; //received file will be ignored } else { station.hearbeat(); } if (!ignoring) { fileParser.ParseOnTheFly(chunk, station); } while (toReceive > 0) { Array.Clear(data, 0, BUFFER_SIZE); //svuoto buffer ricezione var ttt = Encoding.UTF8.GetBytes(toAnalyze); ttt.CopyTo(data, 0); //ripristino data con il residuo della vecchia ricezione //ricevo ancora int receivedBytesLen = socket.Receive(data, toAnalyze.Length, BUFFER_SIZE - toAnalyze.Length, SocketFlags.None); received += receivedBytesLen; toReceive = toReceive - receivedBytesLen; toAnalyze = Encoding.UTF8.GetString(data); chunk = Chunker(toAnalyze, out toAnalyze); if (!ignoring) { fileParser.ParseOnTheFly(chunk, station); } } } catch (Exception) { macAddresses.Remove(socket); socket.Close(); return(-1); } Console.WriteLine("{1} Client:{0} data received.", socket.RemoteEndPoint, DateTime.Now.ToString()); } else if (text.IndexOf("SYNC") > -1) //----------------------SYNC---------------------------- { int result = ESP_SyncClock(socket); if (result == -1) { return(-1); } } else { return(-1); } return(0); //if here, all fine }