public bool AnalyzeCommand(RS485Packet packet) { VooProtocol protocol = new VooProtocol(packet.current, packet.source, packet.destination, packet.RawData); if (protocol.isFound) { switch (protocol.CurrentPacket.Key) { case VooProtocol.Commands.SERVER_HELP: RS485VooEvents.Instance.OutputData(VooConfiguration.Help); break; case VooProtocol.Commands.SERVER_EXIT: RS485VooEvents.Instance.TerminateMachine(RS485Constants.Machine.ServerAndClient); break; case VooProtocol.Commands.SERVER_ADD_AUTH: RS485VooEvents.Instance.RegisterUser(protocol); break; case VooProtocol.Commands.SERVER_REMOVE_AUTH: RS485VooEvents.Instance.UnRegisterUser(protocol); break; case VooProtocol.Commands.SERVER_CREATE_APPLICATION: RS485VooEvents.Instance.CreateApplication(protocol); break; case VooProtocol.Commands.SERVER_REMOVE_APPLICATION: RS485VooEvents.Instance.RemoveApplication(protocol); break; case VooProtocol.Commands.CLIENT_BEGIN_SESSION: RS485VooEvents.Instance.BeginSession(protocol); break; case VooProtocol.Commands.CLIENT_END_SESSION: RS485VooEvents.Instance.EndSession(protocol); break; case VooProtocol.Commands.CLIENT_CD: RS485VooEvents.Instance.ExecuteCommand(protocol); break; case VooProtocol.Commands.CLIENT_DIR: RS485VooEvents.Instance.ExecuteCommand(protocol); break; case VooProtocol.Commands.CLIENT_FETCH: RS485VooEvents.Instance.Fetch(protocol); break; case VooProtocol.Commands.CLIENT_PUSH: RS485VooEvents.Instance.Push(protocol); break; case VooProtocol.Commands.CLIENT_AUTH: RS485VooEvents.Instance.LoginUser(protocol); break; case VooProtocol.Commands.CLIENT_PUSH_DATA: break; default: // TODO: Output information about error of protocol data. // RS485VooEvents.Instance.Error("You have error in protocol parser."); // It's for other messages not for implementation protocol. RS485VooEvents.Instance.ReceiveData(protocol); break; } } else { RS485VooEvents.Instance.ReceiveData(protocol); } return true; }
public static void AnalysePacket(RS485Packet packet) { AnalysePacketDelegate local = AnalysePacketEvent; if (local != null) { local(packet); } }
public virtual void Send(RS485Packet packet) { RS485Events.SetIgnorePacket(true); lock (RS485Events.synchronized) { rs.Port.RtsEnable = true; foreach (byte b in packet) { Send(b); } Thread.Sleep(400); rs.Port.RtsEnable = false; // events.Output(this, new RS485Events.OutputEventArg(packet.Data, RS485Events.OutputType.Common, RS485Events.DestinationType.ClientPacket)); } }
protected override bool AnalyzeCommand(RS485Packet packet) { return VooServer.Instance.AnalyzeCommand(packet); }
public static List<RS485Packet> ProcessInputData(RS485_dll.Voodoo.Libraries.RS485Library.RS485Terminal.InputData input, int size) { List<RS485Packet> result = new List<RS485Packet>(); while (input.Data.Length != 0) { if (size > input.Data.Length) { size = input.Data.Length; } String packetData = input.Data.Substring(0, size); input.Data = input.Data.Substring(size); RS485Packet packet = new RS485Packet(input.Source, input.Current, input.Destination, input.Priority, RS485Packet.CommandEnum.Data, packetData); result.Add(packet); } return result; }
protected void Fetch(VooProtocol protocol) { Console.WriteLine("Application: Fetch(VooProtocol protocol)"); Console.WriteLine("Application: Fetch -> from = '{0}', to = '{1}'", protocol.Get("from"), protocol.Get("to")); VooFile file = new VooFile(protocol.Source, protocol.Destination, protocol.Get("from"), protocol.Get("to")); fetches.Add(file); Console.WriteLine("Application: Fetch -> read data"); file.ReadToEnd(); RS485PacketManager manager = new RS485PacketManager(new RS485_dll.Voodoo.Libraries.RS485Library.RS485Terminal.InputData(RS485Packet.PriorityEnum.Highest, file.Data, protocol.Destination, protocol.Source, protocol.Destination), 32); RS485Packet packet = new RS485Packet(protocol.Destination, protocol.Destination, protocol.Source, RS485Packet.PriorityEnum.Highest, RS485Packet.CommandEnum.Data, protocol.CreatePushCommand()); manager.Packets.Insert(0, packet); Console.WriteLine("Application: Call send packets."); RS485VooEvents.Instance.SendPackets(manager); }
private void Events_RemovePacketAfterSuccessed(RS485Packet packet) { for (int i = 0; i < managers.Count; i++) { try { for (int j = 0; j < managers[i].Packets.Count; j++) { RS485Packet localpacket = managers[i].Packets[j]; if (localpacket == packet) { managers[i].Packets.Remove(packet); if (!managers[i].HasPackets()) { managers.Remove(managers[i]); } } } } catch { } } }
private void StartSend(Object sender, System.Timers.ElapsedEventArgs arg) { // lock (RS485Events.synchronized) { if (managers.Count > 0) { for (int i = 0; i < managers.Count; i++) { RS485PacketManager manager = managers[i]; if (manager.HasPackets()) { client.Send(manager.FirstPacket); lastSend = manager.FirstPacket; break; } } } else { RS485Packet packet = new RS485Packet(source, source, NextDestination(source), RS485Packet.PriorityEnum.Lowest, RS485Packet.CommandEnum.AllowTransmit, "x"); client.Send(packet); lastSend = packet; } // packetsTimer.Start(); } }
private void AddUserAction() { if (session != null) { Console.WriteLine("username: "******"password: "******"Please input session information."); } }
public static void SendNext(RS485Packet packet) { SendNextDelegate local = SendNextEvent; if (local != null) { local(packet); } }
protected void Events_AllowNextEvent(object sender, RS485Events.ReceivedPacketsArg arg) { // lock (RS485Events.synchronized) { RS485Packet packet = new RS485Packet(source, source, NextDestination(source), RS485Packet.PriorityEnum.Highest, RS485Packet.CommandEnum.AllowTransmit, "x"); lastSend = packet; client.Send(packet); } }
public static void RemovePacketAfterSuccessed(RS485Packet packet) { RemovePacketAfterSuccessedDelegate local = RemovePacketAfterSuccessedEvent; if (local != null) { local(packet); } }
protected virtual bool AnalyzeCommand(RS485Packet packet) { return true; }
/// <summary> /// Buffer: FEND,CMD,N,DATA /// </summary> protected override void Port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { base.Port_DataReceived(sender, e); foreach (byte b in buffer) { if (b == Convert.ToByte((char) RS485Packet.TokenBusEnum.FSTART) && !startPacket) { startPacket = true; } else if (startPacket && command == RS485Packet.CommandEnum.nil) { command = b; } else if (command != RS485Packet.CommandEnum.nil && priority == RS485Packet.PriorityEnum.nil) { priority = b; } else if (priority != RS485Packet.PriorityEnum.nil && String.IsNullOrEmpty(destination)) { destination = Convert.ToString((char)b); } else if (!String.IsNullOrEmpty(destination) && String.IsNullOrEmpty(source)) { source = Convert.ToString((char)b); } else if (!String.IsNullOrEmpty(source) && String.IsNullOrEmpty(current)) { current = Convert.ToString((char)b); } else if (!String.IsNullOrEmpty(current) && length == -1) { try { length = b; } catch { } } else if (length != -1) { --length; data += Convert.ToString((char) b); if (length == 0) { RS485Packet packet = new RS485Packet(source, current, destination, priority, command, data); RS485Terminal.StopTimer(); Thread.Sleep(500); if (!IsEcho(packet)) { AnalysePacket(packet); } Reset(); rs.Port.BaseStream.Flush(); } } }// end for }
private bool IsEcho(RS485Packet packet) { RS485Packet p = RS485Terminal.LastSend; if (p != null) { return p.Equals(packet); } return false; }
private void AnalysePacket(RS485Packet packet) { // Так как у нас сеть передаёт во всех направлениях одновременно, то для // реализации кольца, нам нужно как фильтровать пакеты. // Ввели в кажлый пакет дополнительное поле current, которое говорит // админу компа может ли он принять данный пакет, если может, то тогда // можно начать анализировать пакет, если же нет, то хз. if (RS485Terminal.NextDestination(packet.current) == name) { // Получили наш пакет packet = new RS485Packet(packet.source, RS485Terminal.NextDestination(packet.current), packet.destination, packet.priority, packet.command, packet.RawData); if (name == packet.destination) { if (packet.command != RS485Packet.CommandEnum.Successed && packet.command != RS485Packet.CommandEnum.AllowTransmit) { // сразу же отправляем пакет дальше с Successed RS485Events.ReceivedPackets(this, new RS485Events.ReceivedPacketsArg(packet)); // Console.WriteLine("send successed packet."); if (packet.command == RS485Packet.CommandEnum.Data) { // В этой области нам не нужно ничего сразу отправлять // сначала мы анализируем пакет, далее если всё - таки нам нужно // отправить результат выполненной команды, мы должны дождаться // когда к нам придёт маркер и дальше перенаправить нужную информацию. AnalyzeCommand(packet); } } else if (packet.command == RS485Packet.CommandEnum.Successed) { // Если нам пришёл ответ на пакет, что был удачно доставлен. // то нам можно просто пропустить и продолжить дальше работать. RS485Events.AllowNext(this, new RS485Events.ReceivedPacketsArg(packet)); // GET AllowTransmit RS485PacketManager manager = RS485Terminal.GetFirstManager(); if (manager != null) { RS485Events.RemovePacketAfterSuccessed(manager.FirstPacket); } // Console.WriteLine("packet successed received."); } } else { // Successed пакет ходит с наивысшим приоритетом. if (packet.command == RS485Packet.CommandEnum.Successed) { // передать управление следующему в сети хосту. // Console.WriteLine("We are received packets and now we have to send forward order of pointers."); RS485Events.SendNext(packet); } else { // Пакет не нам. Смотрим приоритеты. RS485PacketManager manager = RS485Terminal.GetFirstManager(); if (manager != null && manager.HasPackets()) { RS485Packet clientPacket = manager.FirstPacket; if (clientPacket.priority > packet.priority) { packet = clientPacket; } } if (packet.command == RS485Packet.CommandEnum.Data) { RS485Events.SendNext(packet); } } } if (packet.command == RS485Packet.CommandEnum.AllowTransmit) { // получил разрешение на отправление пакета. RS485Events.EnableMarker(); } } else if (packet.current == name) { RS485Events.EnableMarker(); } }
public static void CheckLastPacket(RS485Packet packet) { CheckLastPacketDelegate local = CheckLastPacketEvent; if (local != null) { local(packet); } }
private void SendFileAction() { if (session != null) { // TODO: Create custom packets for sending files. Console.Write("Push: "); String from = Console.ReadLine(); Console.Write("To: "); String to = Console.ReadLine(); if (File.Exists(from)) { VooFile file = new VooFile(session.Source, session.Destination, from, to); Console.WriteLine("Application: SendFileAction() -> read file('{0}')", from); file.ReadToEnd(); // lock (RS485Events.synchronized) { RS485PacketManager manager = new RS485PacketManager( new RS485_dll.Voodoo.Libraries.RS485Library.RS485Terminal.InputData( RS485Packet.PriorityEnum.High, file.Data, session.Source, session.Destination, session.Source), 32); RS485Packet packet = new RS485Packet(session.Source, session.Source, session.Destination, RS485Packet.PriorityEnum.High, RS485Packet.CommandEnum.Data, VooProtocol.CreatePushCommand(session.ToString(), from, to, Convert.ToString(file.Data.Length))); manager.Packets.Insert(0, packet); Managers.Add(manager); } } else { Console.WriteLine("File doesn't exist."); } } else { Console.WriteLine("Please input session information."); } }
protected void Events_SendNext(RS485Packet packet) { // lock (RS485Events.synchronized) { RS485Packet newPacket = new RS485Packet(packet.source, packet.current, packet.destination, packet.priority, packet.command, packet.RawData); lastSend = newPacket; client.Send(newPacket); } }
private void SetSessionAction() { RS485PacketManager manager; if (session != null) { // Send request to remove new session. manager = new RS485PacketManager( new InputData(RS485Packet.PriorityEnum.High, VooProtocol.CreateEndSessionCommand(session), session.Source, session.Destination, session.Source), 32); lock (RS485Events.synchronized) { Managers.Add(manager); } } Console.Write("Destination = "); String destination = Console.ReadLine().Trim(); // Console.Write("Entry application = "); // application = Console.ReadLine().Trim(); application = @"C:\"; session = new Session(source, destination); // Send request to begin new session. manager = new RS485PacketManager( new InputData(RS485Packet.PriorityEnum.High, VooProtocol.CreateBeginSessionCommand(session), session.Source, session.Destination, session.Source), 32); RS485Packet packet = new RS485Packet(session.Source, session.Source, session.Destination, RS485Packet.PriorityEnum.High, RS485Packet.CommandEnum.Data, VooProtocol.CreateCApplicationCommand(application)); manager.Packets.Add(packet); // lock (RS485Events.synchronized) { Managers.Add(manager); } }
private void Events_CheckLastPacket(RS485Packet packet) { }
protected void Events_ReceivedPackets(Object sender, RS485Events.ReceivedPacketsArg arg) { // lock (RS485Events.synchronized) { RS485Packet packet = new RS485Packet(source, source, arg.Packet.source, RS485Packet.PriorityEnum.Highest, RS485Packet.CommandEnum.Successed, "*"); lastSend = packet; client.Send(packet); } }
public ReceivedPacketsArg(RS485Packet packet) { this.packet = packet; }