Exemple #1
0
 private void tcpServerHandle(bool isOpen, CommunicationMode comMode)
 {
     if (tcpHandle != null)
     {
         tcpHandle(isOpen, comMode);
     }
 }
Exemple #2
0
        public void commOver3CallBack(string msg, CommunicationMode comMode)
        {
            addFromBaseModel(fromMainModel);
            timer1.Interval = 500;
            timer1.Start();

            if (button1.Tag.Equals("green") && getcdInterface3Open() && PeoplePowerModel.getPeoplePowerModel().IsConnect)
            {
                panel6.BackgroundImage  = Resources.tag_2;
                panel7.BackgroundImage  = Resources.pc_2;
                button1.BackgroundImage = Resources.start_3;
                button1.Tag             = "yellow";
                button1.Text            = "關閉連接";
                fromMainModel.setListViewCanInfos();
                fromMainModel.sendConjiReveLocaData();
                new Thread(tongBuAllData).Start();
                if (!timer3.Enabled)
                {
                    timer3.Start();
                }
                fromMainModel.OpenUDPtime = XwDataUtils.GetTimeStamp();
                //    timer2.Interval = 1000;
                //    if (!timer2.Enabled) timer2.Start();
            }
            else if (button1.Tag.Equals("yellow") && getcdInterface3Open() && !PeoplePowerModel.getPeoplePowerModel().IsConnect)
            {
                panel6.BackgroundImage     = Resources.tag_1;
                panel7.BackgroundImage     = Resources.pc_1;
                button1.BackgroundImage    = Resources.start_1;
                button1.Tag                = "green";
                button1.Text               = "開始連接監控";
                fromMainModel.CloseUDPtime = XwDataUtils.GetTimeStamp();
            }
        }
Exemple #3
0
 private void reDate(byte[] buf, string ipInfo, CommunicationMode comMode)
 {
     if (crdInter != null)
     {
         crdInter.revePortsData(buf, ipInfo, comMode);
     }
 }
        public void SaveUserData()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.AppSettings.Settings["CommunicationMode"].Value = CommunicationMode.ToString();
            config.AppSettings.Settings["IPAddress"].Value         = IPAddress.ToString();
            config.AppSettings.Settings["TCPPort"].Value           = TCPPort.ToString();
            config.AppSettings.Settings["PortName"].Value          = PortName.ToString();
            config.AppSettings.Settings["Baud"].Value     = Baud.ToString();
            config.AppSettings.Settings["Parity"].Value   = Parity.ToString();
            config.AppSettings.Settings["SlaveId"].Value  = SlaveId.ToString();
            config.AppSettings.Settings["DataBits"].Value = DataBits.ToString();
            config.AppSettings.Settings["StopBits"].Value = StopBits.ToString();
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");


            //Properties.Settings.Default.CommunicationMode = CommunicationMode.ToString();
            //Properties.Settings.Default.IPAddress = IPAddress.ToString();
            //Properties.Settings.Default.DisplayFormat = DisplayFormat.ToString();
            //Properties.Settings.Default.TCPPort = TCPPort;
            //Properties.Settings.Default.PortName = PortName;
            //Properties.Settings.Default.Baud = Baud;
            //Properties.Settings.Default.Parity = Parity;
            //Properties.Settings.Default.StartAddress = StartAddress;
            //Properties.Settings.Default.DataLength = DataLength;
            //Properties.Settings.Default.SlaveId = SlaveId;
            //Properties.Settings.Default.SlaveDelay = SlaveDelay;
            //Properties.Settings.Default.DataBits = DataBits;
            //Properties.Settings.Default.StopBits = StopBits;
            //Properties.Settings.Default.Save();
        }
Exemple #5
0
        /// <summary>
        /// Try to obtain user input on the communication mode and encryption passphrase.
        /// </summary>
        /// <param name="mode">When successful, contains the user's selected communication mode. Otherwise, unspecified.</param>
        /// <param name="passphrase">When successful, contains the SecureString passphrase for encryption.</param>
        /// <param name="file">When successful, contains the path to a file for processing.</param>
        /// <returns>The return value indicates whether the input was successfully completed.</returns>
        public static bool TryInput(out CommunicationMode mode, out SecureString passphrase, out FileInfo file)
        {
            // Assign default values
            file = null;

            // Obtain input values from other TryInput methods
            bool result = TryInput(out mode, out passphrase);

            if (!result)
            {
                return(false);
            }

            // Input the filename
            do
            {
                Console.Write("Enter the file name: ");
                string path = Console.ReadLine();
                if (File.Exists(path))
                {
                    file = new FileInfo(path);
                    break;
                }

                Console.WriteLine("File not found.");
            }while (true);

            Console.WriteLine();
            return(result);
        }
Exemple #6
0
 public SendDataType(byte[] buf, string ip, CommunicationMode comMode, SendMode sendMode)
 {
     this.buf      = buf;
     this.ip       = ip;
     this.comMode  = comMode;
     this.sendMode = sendMode;
 }
Exemple #7
0
 public void tcpServerHandle(bool isOpen, CommunicationMode comMode)
 {
     if (comMode == CommunicationMode.TCPServer)
     {
         if (isOpen)
         {
             button19.Text = "關閉";
         }
         else
         {
             button19.Text = "打開TCPServer";
         }
     }
     else if (comMode == CommunicationMode.TCPClien)
     {
         if (isOpen)
         {
             button24.Text = "關閉";
         }
         else
         {
             button24.Text = "連接TCPServer";
         }
     }
     else if (comMode == CommunicationMode.TCPClien_File)
     {
         if (PeoplePowerModel.getPeoplePowerModel().Jurisdiction == PeoplePowerModel.getPeoplePowerModel().CongjiValue)
         {
             button25.Visible = isOpen;
         }
     }
 }
Exemple #8
0
        /// <summary>
        /// Try to obtain user input on the communication mode and encryption passphrase.
        /// </summary>
        /// <param name="mode">When successful, contains the user's selected communication mode. Otherwise, unspecified.</param>
        /// <param name="passphrase">When successful, contains the SecureString passphrase for encryption.</param>
        /// <param name="remoteAddress">When successful, contains an IP address bound on the remote computer.</param>
        /// <returns>The return value indicates whether the input was successfully completed.</returns>
        public static bool TryInput(out CommunicationMode mode, out SecureString passphrase, out System.Net.IPAddress remoteAddress)
        {
            // Assign default values
            remoteAddress = System.Net.IPAddress.Parse("127.0.0.1");

            // Obtain input values from other TryInput methods
            bool result = TryInput(out mode, out passphrase);

            if (!result)
            {
                return(false);
            }

            // Input the remote IP address
            do
            {
                // Prompt the user
                Console.Write("Please enter the remote IP address: ");
                string line = Console.ReadLine();

                // Assess the input and exit the loop if the address is valid
                result = System.Net.IPAddress.TryParse(line, out remoteAddress);
                if (result)
                {
                    break;
                }

                // Try again
                Console.WriteLine("Invalid IP address entered.");
            }while (true);

            Console.WriteLine();
            return(result);
        }
Exemple #9
0
 public void sendData(byte[] buf, int index, int Length, string ipInfo)
 {
     if (formClose)
     {
         return;
     }
     if (socketclient != null && buf != null)
     {
         editBuf(ref buf, ref index, ref Length, ipInfo);
         if (ipInfo.Equals("255.255.255.255"))
         {
             comm = CommunicationMode.TCPClien;
         }
         else if (ipInfo.Equals("255.255.255.0"))
         {
             comm = CommunicationMode.UDP;
         }
         else if (ipInfo.Equals("255.255.255.254"))
         {
             comm = CommunicationMode.TCPClien_loca;
         }
         try
         {
             socketclient.Send(buf, index, Length, SocketFlags.None);
         }
         catch (Exception e)
         {
             FileModel.getFlModel().setErrorData("TCPClien.sendData");
             closeTcpClien(e.ToString());
         }
     }
     //将发送的信息追加到聊天内容文本框中
 }
        /// <summary>
        /// Конструктор коммуникатора
        /// </summary>
        public Communicator()
        {
            // TO DO Переделать под конфигуратор
            localIP               = IPAddress.Parse(Settings.Default.localIP);
            remoteIP              = IPAddress.Parse(Settings.Default.remoteIP);
            localReceivingPort    = Convert.ToInt16(Settings.Default.localReceivingPort);
            remoteReceivingPort   = Convert.ToInt16(Settings.Default.remoteReceivingPort);;
            localSendingPort      = Convert.ToInt16(Settings.Default.localSendingPort);
            remoteSendingPort     = Convert.ToInt16(Settings.Default.remoteSendingPort);
            hostType              = (HostType)Enum.Parse(typeof(HostType), Settings.Default.hostType);
            ExchangePeriod        = Convert.ToInt16(Settings.Default.netExchangePeriod);
            communicationMode     = (CommunicationMode)Enum.Parse(typeof(CommunicationMode), Settings.Default.communicationMode);
            localApplicationName  = "Source";
            remoteApplicationName = "Target";
            state = CommunicatorState.stoped;

            transceiver = new UDPTransceiver(localIP, localReceivingPort, localSendingPort, remoteIP, remoteSendingPort, remoteSendingPort);

            // Создаем пустой список параметров.
            Parameters = new List <Parameter>();
            // Создаем поток для работы обменника
            if (hostType == HostType.Slave)
            {
                NetworkThread = new Thread(ListenNetworkSlave);
            }
            else
            {
                NetworkThread = new Thread(ListenNetworkMaster);
            }
            InputParameterChanged += (s, e) => hasInputParameterChanged = true;
        }
Exemple #11
0
 /// <summary>
 /// TCPServer数据格式专属协议,专属神器
 /// </summary>
 private void reveTCPServerOutDate(byte[] buf, string ipInfo, CommunicationMode comMode)
 {
     if (buf[0] == 0XFE && buf[buf.Length - 1] == 0xFC) //为了将TCP数据放进来
     {
         checkPacket(buf, ipInfo);
         return;
     }
 }
Exemple #12
0
 private void GetTags(CommunicationMode mode)
 {
     comm.Mode = mode;
     comm.GetTags(tags =>
     {
         Log.Info("Tags", tags);
     });
 }
Exemple #13
0
        private void sendPortsData(byte[] buf, string ip, CommunicationMode comMode, SendMode sendMode)
        {
            SendDataType sType = new SendDataType(buf, ip, comMode, sendMode);

            if (cdInterface != null)
            {
                new Thread(sendPortsDataThread).Start(sType);                     // serPort.commWriteByte(buf, 0, buf.Length);
            }
        }
Exemple #14
0
        public static void Initialize(CommunicationMode mode)
        {
            if (Instance != null)
            {
                throw new InvalidOperationException("SerialPortManager already initialized!");
            }

            Instance = new SerialPortManager(mode);
        }
Exemple #15
0
 /// <summary>
 /// 接收数据开始处
 /// </summary>
 /// <param name="buf"></param>
 public void revePortsData(byte[] buf, string ipInfo, CommunicationMode comMode)
 {
     if (comMode == CommunicationMode.TCPServer_OUT)
     {
         reveTCPServerOutDate(buf, ipInfo, comMode);
     }
     else
     {
         reveData(buf, ipInfo, comMode);
     }
 }
        private void DataSender(string cmd, CommunicationMode mode, Tuple <string, CommunicationMode, string> CommandToSend)
        {
            try
            {
                _sending = true;
                if (string.IsNullOrEmpty(cmd) || string.IsNullOrWhiteSpace(cmd))
                {
                    return;
                }
                else
                {
                    cmd = cmd.Trim();
                }

                switch (CommandToSend.Item2)
                {
                case CommunicationMode.TEXT:
                    GPSSerialPort.Write(CommandToSend.Item1);
                    CmdSentTime = DateTime.Now;
                    CommandSent = true;
                    SentQueue.Enqueue(CommandToSend);
                    UpdateLogWindow("GPS Data Sent: " + CommandToSend.Item1 + " , " + CommandToSend.Item3);
                    break;

                case CommunicationMode.HEXA:
                    try
                    {
                        byte[] buffer = HexToByte(CommandToSend.Item1);
                        GPSSerialPort.Write(buffer, 0, buffer.Length);
                        CmdSentTime = DateTime.Now;
                        CommandSent = true;
                        SentQueue.Enqueue(CommandToSend);
                        UpdateLogWindow("GPS Data Sent: " + CommandToSend.Item1 + " , " + CommandToSend.Item3);
                    }
                    catch (Exception ex)
                    {
                        UpdateLogWindow("GPS DataSender failed:" + ex.Message);
                        CommandSent = false;
                        Logger.Log("GPS DataSender: Failed.", ex);
                        throw;
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                UpdateLogWindow("GPS DataSender Err" + ex.Message + " Data: " + (string.IsNullOrEmpty(cmd) ? " " : cmd));
            }
            finally
            {
                //FormRef.timer1.Enabled = true;
                _sending = false;
            }
        }
        public Guid SendSetCommunicationModeRequest(Guid resourceId, CommunicationMode mode)
        {
            GatewaySocketClient client = null;
            Guid requestGuid           = Guid.Empty;

            if (m_gatewayClients.TryGetValue(GetResourceUri(resourceId), out client))
            {
                requestGuid = client.SendSetCommunicationMode(resourceId, mode);
            }

            return(requestGuid);
        }
        public AlarmSystem()
        {
            serialPort = new SerialPort();
            serialPort.BaudRate = 38400;
            serialPort.PortName = "COM3";
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;

            communicationMode = CommunicationMode.ASCII;

            serialPort.DataReceived += serialPort_DataReceived;
            serialPort.Open();
        }
        public Guid SendSetCommunicationMode(Guid resourceId, CommunicationMode mode)
        {
            var requestGuid = Guid.NewGuid();
            var request     = new ResourceMessage()
            {
                Command     = "mode",
                Data        = mode.ToString().ToLower(),
                TargetGuid  = resourceId.ToString(),
                SenderGuid  = m_clientId.ToString(),
                RequestGuid = requestGuid.ToString()
            };

            SendRequest(request);
            return(requestGuid);
        }
Exemple #20
0
 private void createSerPortUtil(CommunicationMode comMode)
 {
     if (cdInterface != null)
     {
         return;
     }
     if (comMode == CommunicationMode.SERIALPORT)
     {
         cdInterface = new SerialPortUtils(this);
     }
     else if (comMode == CommunicationMode.UDP)
     {
         cdInterface = new UDPUtils(this);
     }
 }
Exemple #21
0
        public void SetMode()
        {
            if (radioButtonTCP.Checked)
            {
                _communicationMode  = CommunicationMode.TCP;
                groupBoxTCP.Enabled = true;
                groupBoxRTU.Enabled = false;
            }

            if (radioButtonRTU.Checked)
            {
                _communicationMode  = CommunicationMode.RTU;
                groupBoxTCP.Enabled = false;
                groupBoxRTU.Enabled = true;
            }
        }
 public void SendNextCommand(string cmd, CommunicationMode mode)
 {
     try
     {
         _mode = mode;
         DataSender(cmd, mode,
                    new Tuple <string, CommunicationMode, string>(cmd, mode, "GPS," + Metadata.InputDictionaryCollection["GPS"].FirstOrDefault(x => x.Hexa == cmd).Name)
                    );
         CurrentCmd            = new Tuple <string, CommunicationMode, string>(cmd, mode, "GPS," + Metadata.InputDictionaryCollection["GPS"].FirstOrDefault(x => x.Hexa == cmd).Name);
         GotResponseForPrevCmd = false;
     }
     catch (Exception ex)
     {
         UpdateLogWindow("SendNextCommand Err. " + ex.Message);
     }
 }
Exemple #23
0
        public override void commOverCallBack(string msg, CommunicationMode comMode)
        {
            if (comMode == CommunicationMode.TCPServer)
            {
                tcpServerHandle(getcdInterface2Open(), comMode);
            }
            else if (comMode == CommunicationMode.TCPClien)
            {
                tcpServerHandle(getcdInterface3Open(), comMode);
            }

            if (!msg.Equals("%!%"))
            {
                timer1.Stop();
                if (comMode == CommunicationMode.UDP)
                {
                    MessageBox.Show(msg);
                }
                else if (comMode == CommunicationMode.TCPServer)
                {
                    return;
                }
                else if (comMode == CommunicationMode.TCPClien)
                {
                    return;
                }
            }
            addFromBaseModel(fromMainModel);

            if (comMode == CommunicationMode.TCPServer)
            {
                return;
            }

            timer1.Interval = 500;
            timer1.Start();
            if (button1.Tag.Equals("green") && getcdInterfaceOpen())
            {
                btnChangeGreen();
                fromMainModel.setListViewCanInfos();
                fromMainModel.OpenUDPtime = XwDataUtils.GetTimeStamp();
            }
            else if (button1.Tag.Equals("yellow") && !getcdInterfaceOpen())
            {
                btnChangeYellow();
            }
        }
Exemple #24
0
 private void SaveUserData()
 {
     Properties.Settings.Default.CommunicationMode = CommunicationMode.ToString();
     Properties.Settings.Default.IPAddress         = IPAddress.ToString();
     Properties.Settings.Default.DisplayFormat     = DisplayFormat.ToString();
     Properties.Settings.Default.TCPPort           = TCPPort;
     Properties.Settings.Default.PortName          = PortName;
     Properties.Settings.Default.Baud         = Baud;
     Properties.Settings.Default.Parity       = Parity;
     Properties.Settings.Default.StartAddress = StartAddress;
     Properties.Settings.Default.DataLength   = DataLength;
     Properties.Settings.Default.SlaveId      = SlaveId;
     Properties.Settings.Default.SlaveDelay   = SlaveDelay;
     Properties.Settings.Default.DataBits     = DataBits;
     Properties.Settings.Default.StopBits     = StopBits;
     Properties.Settings.Default.Save();
 }
Exemple #25
0
        /// <summary>
        /// Start listening
        /// </summary>
        /// <param name="currentHostIP">Current Host IP (Listener Host)</param>
        /// <param name="currentHostPort">Current Host Port (Listener Host)</param>
        public async void StartListeninigAsyn(string currentHostIP, int currentHostPort,CommunicationMode mode=CommunicationMode.StreamFile)
        {
            socket.ReciveByteIntterupt += socket_ReciveByteIntterupt;
            switch (mode)
            {
                case CommunicationMode.StreamFile:
                    await Task.Factory.StartNew(() => { socket.StartListeninig(currentHostIP, currentHostPort, APSocket.Net.Server.CommunicationMode.StreamFile); });
                    break;
                case CommunicationMode.LengthFirst:
                    await Task.Factory.StartNew(() => { socket.StartListeninig(currentHostIP, currentHostPort, APSocket.Net.Server.CommunicationMode.LengthFirst); });
                    break;

                default:
                    await Task.Factory.StartNew(() => { socket.StartListeninig(currentHostIP, currentHostPort, APSocket.Net.Server.CommunicationMode.StreamFile); });
                    break;
            }
        }
        public string GetApdu(byte fileNumber, CommunicationMode communicationMode, string accessRights,
                              string fileSize)
        {
            ValidateInput(accessRights, fileSize);

            _accessRights = BinaryHelper.ConvertOctetStringToBytes(accessRights);
            _fileSize     = BinaryHelper.ConvertOctetStringToBytes(fileSize);

            byte[] data;
            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    WritePrefix(writer);

                    writer.Write(SeProcessorCommandTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(ProcessCardAPITag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(CardAPIDESFireTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(DESFireCreateStandardDataFileTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(FileNumberTag);
                    writer.Write(FileNumberValLength);
                    writer.Write(fileNumber);
                    writer.Write(CommunicationSettingsTag);
                    writer.Write(CommunicationSettingsValLength);
                    writer.Write((byte)communicationMode);
                    writer.Write(AccessRightsTag);
                    writer.Write((byte)_accessRights.Length);
                    writer.Write(_accessRights);
                    writer.Write(FileSizeTag);
                    writer.Write((byte)_fileSize.Length);
                    writer.Write(_fileSize);

                    WritePostfix(writer);
                }

                data = stream.ToArray();
            }

            return(BinaryHelper.ConvertBytesToOctetString(data));
        }
        public string GetApdu(byte fileNumber, string offset, byte numberOfBytesToBeRead,
                              CommunicationMode communicationMode)
        {
            ValidateInput(offset);

            _offset = BinaryHelper.ConvertOctetStringToBytes(offset);

            byte[] data;
            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                {
                    WritePrefix(writer);

                    writer.Write(SeProcessorCommandTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(ProcessCardAPITag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(CardAPIDESFireTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(DESFireReadDataTag);
                    writer.Write(GetLengthToEnd(writer));
                    writer.Write(FileNumberTag);
                    writer.Write(FileNumberValLength);
                    writer.Write(fileNumber);
                    writer.Write(OffsetTag);
                    writer.Write((byte)_offset.Length);
                    writer.Write(_offset);
                    writer.Write(DataTag);
                    writer.Write(DataValLenght);
                    writer.Write(numberOfBytesToBeRead);
                    writer.Write(ModeTag);
                    writer.Write(ModeValLength);
                    writer.Write((byte)communicationMode);

                    WritePostfix(writer);
                }

                data = stream.ToArray();
            }

            return(BinaryHelper.ConvertBytesToOctetString(data));
        }
Exemple #28
0
 protected void SetMode()
 {
     if (this.radioButtonTCP.Checked)
     {
         this._communicationMode  = CommunicationMode.TCP;
         this.groupBoxTCP.Enabled = true;
         this.groupBoxRTU.Enabled = false;
     }
     if (this.radioButtonRTU.Checked)
     {
         this._communicationMode  = CommunicationMode.RTU;
         this.groupBoxTCP.Enabled = false;
         this.groupBoxRTU.Enabled = true;
     }
     if (!this.radioButtonUDP.Checked)
     {
         return;
     }
     this._communicationMode  = CommunicationMode.UDP;
     this.groupBoxTCP.Enabled = true;
     this.groupBoxRTU.Enabled = false;
 }
Exemple #29
0
        public SqlSession(Mode mode)
        {
            this.mode = mode;
            commitMode = (mode == Mode.AUTO_COMMIT || mode == Mode.READ_ONLY ? Mode.AUTO_COMMIT : Mode.TRANSACTIONAL);
            //commitMode = (mode == Mode.TRANSACTIONAL ? mode : Mode.AUTO_COMMIT);
            commsMode = (mode == Mode.BATCH ? CommunicationMode.SQL : globalCommsMode);

            if (mode == Mode.BATCH && batch == null)
            {
                batch = new List<DataRow>();
            }

            BatchTable = new Dictionary<String, DataTable>(8);

            // if there is an existing session, then make it our parent
            parent = current.Value;

            //session = new SqlSession(mode);
            current.Value = this;
            sessions.TryAdd(this, Thread.CurrentThread.Name);

            //return session;
        }
Exemple #30
0
        /// <summary>
        /// Start Listening On Specified IP And Port For Accespting Connections
        /// </summary>
        /// <param name="serverIP">Current Host IP (Listener)</param>
        /// <param name="port">Current Host Port (Listener)</param>
        /// <param name="communicationMode">Type Of Ccommunicatio
        ///Messaging: For Transfer Message. End Of Each Message Is 'EOF'/'FOF'.
        ///StreamFile: For Transfer File (In This Case Your BufferSize Must Be Larger Than File Size) </param>
        public async void StartListeninig(string serverIP, int port, CommunicationMode communicationMode)
        {
            await Task.Factory.StartNew(() =>
            {
                selectedMode = communicationMode;

                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(serverIP), port);
                Socket server = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                server.Bind(ep);
                server.Listen(BackLog);

                while (true)
                {
                    DoWork.Reset();
                    server.BeginAccept(new AsyncCallback(Accepting), server);
                    DoWork.WaitOne();
                }
            });
        }
        private void DataSender(string cmd, CommunicationMode mode, Tuple <string, CommunicationMode, bool, string> CommandToSend)
        {
            try
            {
                //FormRef.timer1.Enabled = false;
                _sending = true;
                if (string.IsNullOrEmpty(cmd) || string.IsNullOrWhiteSpace(cmd))
                {
                    return;
                }
                else
                {
                    cmd = cmd.Trim();
                }

                /* //LR
                 * if (Metadata.InputDictionaryCollection[Metadata.ActiveHexaSet].Count(X => X.Hexa == cmd) > 0)
                 *  Logger.Log("sending cmd:" + Metadata.InputDictionaryCollection[Metadata.ActiveHexaSet].FirstOrDefault(x => x.Hexa == cmd).Name + " : " + cmd);
                 * else
                 *  Logger.Log("sending cmd:" + cmd);
                 *///LR

                // Logger.Log("Serial Receiver Monitor:S1: ReadBufferSize: " + serialPort.ReadBufferSize);
                // Logger.Log("Serial Receiver Monitor:S1: BytesToRead: " + serialPort.BytesToRead);

                switch (CommandToSend.Item2)
                {
                case CommunicationMode.TEXT:
                    serialPort.Write(CommandToSend.Item1);
                    CmdSentTime = DateTime.Now;
                    CommandSent = true;
                    SentQueue.Enqueue(CommandToSend);
                    Logger.Log("Data Sent:T: " + CommandToSend.Item1 + " , " + CommandToSend.Item4);
                    break;

                case CommunicationMode.HEXA:
                    try
                    {
                        byte[] buffer = HexToByte(CommandToSend.Item1);
                        serialPort.Write(buffer, 0, buffer.Length);
                        CmdSentTime = DateTime.Now;
                        CommandSent = true;
                        SentQueue.Enqueue(CommandToSend);
                        Logger.Log("Data Sent:H: " + CommandToSend.Item1 + " , " + CommandToSend.Item4);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log("DataSender failed:" + ex.Message);
                        CommandSent = false;
                        Logger.Log("DataSender: Failed.", ex);
                        throw;
                    }
                    break;
                }

                // Logger.Log("Serial Receiver Monitor:S1: ReadBufferSize: " + serialPort.ReadBufferSize);
                // Logger.Log("Serial Receiver Monitor:S1: BytesToRead: " + serialPort.BytesToRead);

                //DataReceiver(null, null);
            }
            catch (Exception ex)
            {
                Logger.Log("DataSender Err" + ex.Message + " Data: " + (string.IsNullOrEmpty(cmd) ? " " : cmd));
            }
            finally
            {
                //FormRef.timer1.Enabled = true;
                _sending = false;
            }
        }
        public void SendNextCommand(string cmd, CommunicationMode mode, bool IsManulalCmd = false)
        {
            try
            {
                //_mode = mode;
                if (IsManulalCmd)
                {
                    ManualCmdQueue.Enqueue(cmd);
                }
                //if (!GotResponseForPrevCmd)
                //{
                //    Logger.Log("waiting for sending cmd:" + CurrentCmd.Item4 + "\n");
                //    waitCounter++;
                //    if (waitCounter > int.Parse(ConfigurationManager.AppSettings["WaitCounter"]))
                //    {

                //        CommandSent = false;
                //        waitCounter = 0;
                //        GotResponseForPrevCmd = true;
                //        Logger.Log("Command Timed Out for the command:" + CurrentCmd.Item4 + " . Wait: " + waitCounter);
                //        Logger.Log("Command Timed Out for the command:" + CurrentCmd.Item4, new Exception("TimedOut Exception"));
                //        if (ManualCmdQueue.Count > 0 && CurrentCmd.Item3)
                //        {
                //            SaveResponse(cmd + "," + "Command Timed Out, No response from the device", CurrentCmd.Item3);
                //            SendNextCommand(ManualCmdQueue.Dequeue(), CommunicationMode.HEXA, true);
                //        }
                //        else
                //        {
                //            Main.cmdCounter++;

                //        }
                //    }
                //    return;
                //}
                //else
                //{
                if (ManualCmdQueue.Count > 0)
                {
                    string mCmd = ManualCmdQueue.Dequeue();
                    Logger.Log("Received Manual CMD:" + mCmd + "    *****");

                    DataSender(mCmd, CommunicationMode.HEXA,
                               new Tuple <string, CommunicationMode, bool, string>(mCmd, CommunicationMode.HEXA, true, "Manual," +
                                                                                   ((Metadata.InputDictionaryCollection[Metadata.ActiveHexaSet].Count(x => x.Hexa == mCmd) > 0) ? Metadata.InputDictionaryCollection[Metadata.ActiveHexaSet].FirstOrDefault(x => x.Hexa == mCmd).Name : mCmd))
                               );

                    CurrentCmd = new Tuple <string, CommunicationMode, bool, string>(mCmd, CommunicationMode.HEXA, true, "Manual," +
                                                                                     ((Metadata.InputDictionaryCollection[Metadata.ActiveHexaSet].Count(x => x.Hexa == mCmd) > 0) ? Metadata.InputDictionaryCollection[Metadata.ActiveHexaSet].FirstOrDefault(x => x.Hexa == mCmd).Name : mCmd));
                    //to write logic to find names in alll list
                }
                else
                {
                    //LR Logger.Log("Auto cmd:\n");
                    _isManualCmd = IsManulalCmd;
                    _mode        = mode;
                    DataSender(cmd, mode,
                               new Tuple <string, CommunicationMode, bool, string>(cmd, mode, IsManulalCmd, Metadata.ActiveHexaSet + "," + Metadata.InputDictionaryCollection[Metadata.ActiveHexaSet].FirstOrDefault(x => x.Hexa == cmd).Name)
                               );
                    CurrentCmd = new Tuple <string, CommunicationMode, bool, string>(cmd, mode, IsManulalCmd, Metadata.ActiveHexaSet + "," + Metadata.InputDictionaryCollection[Metadata.ActiveHexaSet].FirstOrDefault(x => x.Hexa == cmd).Name);
                }
                GotResponseForPrevCmd = false;

                //}
            }
            catch (Exception ex)
            {
                Logger.Log("SendNextCommand Err. " + ex.Message);
            }
        }
Exemple #33
0
 public extern static bool  GISetCommunicationMode(CommunicationMode mode);
Exemple #34
0
        /// <summary>
        /// Try to obtain user input on the communication mode and encryption passphrase.
        /// </summary>
        /// <param name="mode">When successful, contains the user's selected communication mode. Otherwise, unspecified.</param>
        /// <param name="passphrase">When successful, contains the SecureString passphrase for encryption.</param>
        /// <param name="remoteAddress">When successful, contains an IP address bound on the remote computer.</param>
        /// <param name="localAddress">When successful, contains an IP address bound on the local computer.</param>
        /// <returns>The return value indicates whether the input was successfully completed.</returns>
        public static bool TryInput(out CommunicationMode mode, out SecureString passphrase, out System.Net.IPAddress remoteAddress, out System.Net.IPAddress localAddress)
        {
            // Assign default values
            localAddress = System.Net.IPAddress.Parse("127.0.0.1");

            // Obtain input values from other TryInput methods
            bool result = TryInput(out mode, out passphrase, out remoteAddress);
            if (!result) return false;

            // Display available IP addresses on the local computer
            string line = "Available IP addresses:";
            Console.WriteLine(line);
            Console.WriteLine(HorizontalLine(line.Length));

            System.Net.IPAddress[] addressList =
                System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;

            for (int i = 0; i < addressList.Length; i++)
            {
                // Display only the valid IPv4 and IPv6 addresses
                if (addressList[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork || addressList[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                {
                    Console.WriteLine(" {0} = {1}", i.ToString(), addressList[i].ToString());
                }
            }

            // Input the local IP Address
            do
            {
                Console.Write("Please enter the number of the IP address: ");
                string input = Console.ReadLine();
                ushort selection = ushort.MaxValue;
                result = ushort.TryParse(input, out selection);

                if (result && selection < addressList.Length)
                {
                    // Set the local address to the value selected
                    localAddress = addressList[selection];

                    // Verify the local and remote addresses are in the same family
                    if (remoteAddress.AddressFamily == localAddress.AddressFamily)
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("Both addresses must be in the same IP address family (IPv4, IPv6).");
                    }
                }

                Console.WriteLine("Invalid IP address selected.");
                Console.WriteLine();
            }
            while (true);

            Console.WriteLine();
            return result;
        }
Exemple #35
0
        /// <summary>
        /// Try to obtain user input on the communication mode and encryption passphrase.
        /// </summary>
        /// <param name="mode">When successful, contains the user's selected communication mode. Otherwise, unspecified.</param>
        /// <param name="passphrase">When successful, contains the SecureString passphrase for encryption.</param>
        /// <param name="remoteAddress">When successful, contains an IP address bound on the remote computer.</param>
        /// <returns>The return value indicates whether the input was successfully completed.</returns>
        public static bool TryInput(out CommunicationMode mode, out SecureString passphrase, out System.Net.IPAddress remoteAddress)
        {
            // Assign default values
            remoteAddress = System.Net.IPAddress.Parse("127.0.0.1");

            // Obtain input values from other TryInput methods
            bool result = TryInput(out mode, out passphrase);
            if (!result) return false;

            // Input the remote IP address
            do
            {
                // Prompt the user
                Console.Write("Please enter the remote IP address: ");
                string line = Console.ReadLine();

                // Assess the input and exit the loop if the address is valid
                result = System.Net.IPAddress.TryParse(line, out remoteAddress);
                if (result) break;

                // Try again
                Console.WriteLine("Invalid IP address entered.");
            }
            while (true);

            Console.WriteLine();
            return result;
        }
Exemple #36
0
        /// <summary>
        /// Try to obtain user input on the communication mode and encryption passphrase.
        /// </summary>
        /// <param name="mode">When successful, contains the user's selected communication mode. Otherwise, unspecified.</param>
        /// <param name="passphrase">When successful, contains the SecureString passphrase for encryption.</param>
        /// <param name="file">When successful, contains the path to a file for processing.</param>
        /// <returns>The return value indicates whether the input was successfully completed.</returns>
        public static bool TryInput(out CommunicationMode mode, out SecureString passphrase, out FileInfo file)
        {
            // Assign default values
            file = null;

            // Obtain input values from other TryInput methods
            bool result = TryInput(out mode, out passphrase);
            if (!result) return false;

            // Input the filename
            do
            {
                Console.Write("Enter the file name: ");
                string path = Console.ReadLine();
                if (File.Exists(path))
                {
                    file = new FileInfo(path);
                    break;
                }

                Console.WriteLine("File not found.");
            }
            while (true);

            Console.WriteLine();
            return result;
        }
Exemple #37
0
        /// <summary>
        /// Try to obtain user input on the communication mode and encryption passphrase.
        /// </summary>
        /// <param name="mode">When successful, contains the user's selected communication mode. Otherwise, unspecified.</param>
        /// <param name="passphrase">When successful, contains the SecureString passphrase for encryption.</param>
        /// <returns>The return value indicates whether the input was successfully completed.</returns>
        public static bool TryInput(out CommunicationMode mode, out SecureString passphrase)
        {
            // Assign default values
            mode = CommunicationMode.Unspecified;
            passphrase = new SecureString();

            // Input the communications mode
            do
            {
                Console.Write("Enter A to send messages, B to receive messages, or Q to quit: ");
                ConsoleKeyInfo k = Console.ReadKey(false);
                Console.WriteLine();

                switch (k.Key.ToString().ToUpper())
                {
                    case "A":
                        mode = CommunicationMode.Alice;
                        break;
                    case "B":
                        mode = CommunicationMode.Bob;
                        break;
                    case "Q":
                        mode = CommunicationMode.Quit;
                        break;
                    default:
                        Console.WriteLine("Invalid selection: {0}", k.Key.ToString());
                        break;
                }
            }
            while (mode == CommunicationMode.Unspecified);

            if (mode == CommunicationMode.Quit)
            {
                return false;
            }

            // Input the passphrase
            Console.WriteLine();
            Console.Write("Enter a 16-character or 32-character passphrase: ");

            do
            {
                // Read the next key without displaying it on the console, and exit if Enter is pressed
                ConsoleKeyInfo k = Console.ReadKey(true);
                if (k.Key == ConsoleKey.Enter) break;

                // Display a *, append the character to the passphrase, and exit if the passphrase is 32-characters long
                Console.Write("*");
                passphrase.AppendChar(k.KeyChar);
                if (passphrase.Length == 32) break;
            }
            while (true);

            Console.WriteLine();
            Console.WriteLine();
            return true;
        }
Exemple #38
0
 public SerialPortManager(CommunicationMode mode)
 {
     //this.receiveBuffer = new List<byte>();
     this.Mode = mode;
 }
Exemple #39
0
 protected void SetMode()
 {
     if (radioButtonTCP.Checked)
     {
         _communicationMode = CommunicationMode.TCP;
         groupBoxTCP.Enabled = true;
         groupBoxRTU.Enabled = false;
     }
     if (radioButtonRTU.Checked)
     {
         _communicationMode = CommunicationMode.RTU;
         groupBoxTCP.Enabled = false;
         groupBoxRTU.Enabled = true;
     }
     if (radioButtonUDP.Checked)
     {
         _communicationMode = CommunicationMode.UDP;
         groupBoxTCP.Enabled = true;
         groupBoxRTU.Enabled = false;
     }
 }