private void _DiscoverNetwork(object obj, EventArgs eventArgs) { Console.WriteLine("Sending broadcast..."); try { string[] ep = _mNetworkDiscoveryClient.Client.LocalEndPoint.ToString().Split(':'); var data = new NetworkData { Message = ep[0], MessageType = MessageTypes.ReceiveClient }; var stream = new MemoryStream(); var serializer = new DataContractJsonSerializer(typeof(NetworkData)); serializer.WriteObject(stream, data); _mNetworkDiscoveryClient.Send(stream.GetBuffer(), (int)stream.Length); } catch (Exception e) { Console.WriteLine(e); throw; } }
public void Handle() { if (_mTcpServer.Pending()) { var connectedClient = _mTcpServer.AcceptTcpClient(); _clients.Add(connectedClient); Console.WriteLine($"Connected: {connectedClient.Client.RemoteEndPoint}"); } var disconnectedClients = new List <TcpClient>(); foreach (var client in _clients) { if (!client.Connected) { disconnectedClients.Add(client); continue; } if (client.Available <= 0) { continue; } var bytes = new byte[client.Available]; client.Client.Receive(bytes); var stream = new MemoryStream(); stream.Write(bytes, 0, bytes.Length); var serializer = new DataContractJsonSerializer(typeof(NetworkData)); NetworkData data = null; stream.Position = 0; try { data = (NetworkData)serializer.ReadObject(stream); } catch (Exception e) { Console.WriteLine(e); } if (data == null) { continue; } switch (data.ClientType) { case ClientTypes.Mcu: if (data.Message == "activate alarm" && !isAlarmActive) { WiringPi.GPIO.digitalWrite(buzzerPin, 1); isAlarmActive = true; Console.WriteLine("Alarma activada!"); try { SmtpClient smtpServer = new SmtpClient { Host = "smtp.gmail.com", UseDefaultCredentials = false, Credentials = new System.Net.NetworkCredential("*****@*****.**", "Alan23253"), DeliveryMethod = SmtpDeliveryMethod.Network, EnableSsl = true, Port = 587 }; var mail = new MailMessage { From = new MailAddress("*****@*****.**"), Subject = "Aviso!", Body = $"¡La alarma ha sido activada a las {DateTime.Now}!" }; ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; mail.To.Add("*****@*****.**"); // mail.To.Add("*****@*****.**"); smtpServer.Send(mail); } catch (Exception e) { Console.WriteLine(e); } } break; case ClientTypes.Phone: case ClientTypes.Pc: if (data.Message == "deactivate" && isAlarmActive) { WiringPi.GPIO.digitalWrite(buzzerPin, 0); isAlarmActive = false; } break; default: Console.WriteLine("Unknown client"); break; } } foreach (var disconnectedClient in disconnectedClients) { _clients.Remove(disconnectedClient); } }