Ejemplo n.º 1
0
        private void toolStripButtonExit_Click(object sender, EventArgs e)
        {
            if (_badgeReader != null)
            {
                _badgeReader.closePort();
            }

            if (!_bSaved)
            {
                MessageBox.Show(ResStrings.str_DATA_NOT_SAVED, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            //this.BeginInvoke((MethodInvoker)delegate { this.Close(); });
            {
                DeviceInfo[] di = _db.RecoverAllDevice();
                if (di != null)
                {
                    foreach (DeviceInfo dev in di)
                    {
                        if (!string.IsNullOrEmpty(dev.IP_Server))
                        {
                            if (CheckIpAddr(dev.IP_Server))
                            {
                                TcpIpClient tcp = new TcpIpClient();
                                tcp.setUserRefresh(dev.IP_Server, dev.Port_Server);
                            }
                        }
                    }
                }

                _myFinger.ReleaseFingerprint();
                _db.CloseDB();
                Close();
            }
        }
        public static void LedOnAll(DeviceInfo ethernetDevice, TcpIpClient tcpClient, List <string> tagsList)
        {
            if (ethernetDevice == null)
            {
                return;
            }

            int nbTagToLight = tagsList.Count; // initial number of tags

            TcpIpClient.RetCode ret;
            ret = tcpClient.RequestStartLighting(ethernetDevice.IP_Server, ethernetDevice.Port_Server, tagsList);
            if (ret != TcpIpClient.RetCode.RC_Succeed)
            {
                MessageBox.Show("An unexpected error occurred during communication with device : " + ret.ToString());
                tcpClient.RequestStopLighting(ethernetDevice.IP_Server, ethernetDevice.Port_Server);
                return;
            }

            StringBuilder resultMessage = new StringBuilder(String.Format("{0} tags to find : {1} have been found.", nbTagToLight,
                                                                          nbTagToLight - tagsList.Count));

            if (tagsList.Count > 0) // some tag UIDs are still in the list : they've not been found
            {
                resultMessage.AppendLine("Missing tags ID :");

                foreach (string missingTag in tagsList)
                {
                    resultMessage.AppendLine(missingTag);
                }
            }

            MessageBox.Show(resultMessage.ToString());

            tcpClient.RequestStopLighting(ethernetDevice.IP_Server, ethernetDevice.Port_Server);
        }
Ejemplo n.º 3
0
        protected override void OnDestroy()
        {
            if (onProxyConnected != null)
            {
                onProxyConnected.Dispose();
                onProxyConnected = null;
            }
            if (onProxyRecv != null)
            {
                onProxyRecv.Dispose();
                onProxyRecv = null;
            }
            if (proxyClient != null)
            {
                proxyClient.Close();
                proxyClient = null;
            }
            if (onConnected != null)
            {
                onConnected.Dispose();
                onConnected = null;
            }
            if (onRecv != null)
            {
                onRecv.Dispose();
                onRecv = null;
            }
            TcpIpServer.Shutdown();

            base.OnDestroy();
        }
Ejemplo n.º 4
0
 public void ConnectProxy(string addr, int port, LuaFunction onConnected, LuaFunction onRecv)
 {
     proxyClient      = new TcpIpClient();
     onProxyConnected = onConnected.Retain();
     onProxyRecv      = onRecv.Retain();
     proxyClient.Connect(addr, port, OnProxyConnected);
 }
Ejemplo n.º 5
0
 public void Connect(string addr, int port, LuaFunction onConnected, LuaFunction onRecv)
 {
     client           = new TcpIpClient();
     this.onConnected = onConnected.Retain();
     this.onRecv      = onRecv.Retain();
     client.Connect(addr, port, OnConnected);
 }
Ejemplo n.º 6
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(comboBoxRemoteReader.Text))
     {
         DeviceInfo[] tmpDeviceArray = _db.RecoverDevice(false);
         if (tmpDeviceArray != null)
         {
             foreach (DeviceInfo dev in tmpDeviceArray)
             {
                 if (dev.DeviceName == comboBoxRemoteReader.Text)
                 {
                     string              badge;
                     TcpIpClient         tcp = new TcpIpClient();
                     TcpIpClient.RetCode ret = tcp.getLastBadge(dev.IP_Server, dev.Port_Server, out badge);
                     if (ret == TcpIpClient.RetCode.RC_Succeed)
                     {
                         Invoke((MethodInvoker) delegate { textBoxReaderCard.Text = badge; });
                     }
                     else
                     {
                         MessageBox.Show(string.Format(ResStrings.str_Unable_to_get_Badge_from__0, dev.DeviceName), ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Information);
                     }
                     break;
                 }
             }
         }
     }
 }
Ejemplo n.º 7
0
        private void BtConnectToClient_Click(object sender, EventArgs e)
        {
            if (TbRemotePort.IsMatch)
            {
                if (int.TryParse(TbRemotePort.Text, out int port))
                {
                    string      hostName = TbRemoteHost.Text;
                    TcpIpClient client   = new TcpIpClient();

                    if (client.Connect(hostName, port))
                    {
                        client.ResiveMessage += Client_ResiveMessage;
                    }
                    else
                    {
                        MessageBox.Show("Unable to reach the host");
                    }
                }
                else
                {
                    MessageBox.Show("Some error is thrown");
                }
            }
            else
            {
                MessageBox.Show("Invalide port binding");
            }
        }
        public static WriteCode WriteNewUID(DeviceInfo ethernetDevice, TcpIpClient tcpClient, string oldUID, string newUID, int writeMode)
        {
            WriteCode result;

            tcpClient.RequestWriteBlock(ethernetDevice.IP_Server, ethernetDevice.Port_Server, oldUID, newUID, out result, writeMode);
            return(result);
        }
 public static TcpIpClient.RetCode StopScan(DeviceInfo ethernetDevice, TcpIpClient tcpClient)
 {
     if (ethernetDevice == null)
     {
         return(TcpIpClient.RetCode.RC_FailedToConnect);
     }
     return(tcpClient.requestStopScan(ethernetDevice.IP_Server, ethernetDevice.Port_Server, ethernetDevice.SerialRFID));
 }
Ejemplo n.º 10
0
 public override void ClienMessageResieve(TcpIpClient client, string message)
 {
     switch (message)
     {
     default:
         break;
     }
 }
 public static void Initialize()
 {
     RobotOUT     = new bool[32];
     RobotIN      = new bool[32];
     IOReceiveNet = new TcpIpClient();
     checkIOReceiveNet();
     IORevAnalysis();
 }
Ejemplo n.º 12
0
 private void Server_ClientConnected(TcpIpClient arg1)
 {
     if (MessageBox.Show("Accept Client?", "RemoteConnection", MessageBoxButtons.YesNo) == DialogResult.No)
     {
         arg1.Disconnect();
     }
     else
     {
         arg1.SendMessage(ALLOW_CONNECTION);
     }
 }
        public static TcpIpClient.RetCode StartScan(DeviceInfo ethernetDevice, TcpIpClient tcpClient, out InventoryData lastInventoryData)
        {
            lastInventoryData = null; // used to store inventory (once the scan is over)

            if (ethernetDevice == null)
            {
                return(TcpIpClient.RetCode.RC_FailedToConnect);
            }

            string status;

            // try to get device's status
            if (tcpClient.getStatus(ethernetDevice.IP_Server, ethernetDevice.Port_Server,
                                    ethernetDevice.SerialRFID, out status) != TcpIpClient.RetCode.RC_Succeed)
            {
                return(TcpIpClient.RetCode.RC_FailedToConnect);
            }

            DeviceStatus currentStatus = (DeviceStatus)Enum.Parse(typeof(DeviceStatus), status);

            // check that device is in ready state
            if (currentStatus != DeviceStatus.DS_Ready)
            {
                return(TcpIpClient.RetCode.RC_Device_Not_In_Ready_State);
            }

            if (tcpClient.requestScan(ethernetDevice.IP_Server, ethernetDevice.Port_Server, ethernetDevice.SerialRFID) != TcpIpClient.RetCode.RC_Succeed) // scan starting has failed
            {
                return(TcpIpClient.RetCode.RC_Failed);
            }

            do                     // will loop until Device doesn't leave "InScan" state
            {
                Thread.Sleep(500); // wait 500ms before polling device (to get scan result, if scan is over)

                // try to get device's status
                if (tcpClient.getStatus(ethernetDevice.IP_Server, ethernetDevice.Port_Server,
                                        ethernetDevice.SerialRFID, out status) != TcpIpClient.RetCode.RC_Succeed)
                {
                    return(TcpIpClient.RetCode.RC_FailedToConnect);
                }

                currentStatus = (DeviceStatus)Enum.Parse(typeof(DeviceStatus), status);
            } while (currentStatus == DeviceStatus.DS_InScan);

            if (tcpClient.requestGetLastScan(ethernetDevice.IP_Server,
                                             ethernetDevice.Port_Server,
                                             ethernetDevice.SerialRFID, out lastInventoryData) != TcpIpClient.RetCode.RC_Succeed) // failed to get last inventorydata
            {
                return(TcpIpClient.RetCode.RC_FailedToConnect);
            }

            return(lastInventoryData == null ? TcpIpClient.RetCode.RC_UnknownError : TcpIpClient.RetCode.RC_Succeed);
        }
Ejemplo n.º 14
0
        private void Client_ResiveMessage(TcpIpClient arg1, string arg2)
        {
            switch (arg2)
            {
            case ALLOW_CONNECTION:
                RemoteView view = new RemoteView(arg1);
                view.Show();
                break;

            default:
                break;
            }
        }
Ejemplo n.º 15
0
        public override void Process(string connection, IEnumerable <ScanMemberBase> members, IEnumerable <EstimatorBase> estimators)
        {
            _connection  = connection;
            _members     = members.ToList();
            _estimators  = estimators.ToList();
            _service     = new RocService();
            _dataService = new RocDataService(_connection);

            _members.ForEach(m =>
            {
                var member = m as RocScanMember;
                if (member == null)
                {
                    return;
                }
                var roc = _estimators.SingleOrDefault(e => e.Id == member.EstimatorId) as Roc809;
                if (roc == null)
                {
                    return;
                }

                if (!(member.ScanAlarmData || member.ScanDailyData || member.ScanEventData ||
                      member.ScanMinuteData || member.ScanPeriodicData))
                {
                    return;
                }

                IClient _client;

                if (!roc.IsScannedViaGPRS)
                {
                    _client = new TcpIpClient();
                }
                else
                {
                    _client = _gprsClient;
                }

                ProcessRoc(member, roc, _client);

                roc.MeasurePoints.Where(p => p.IsActive).ToList().ForEach(p =>
                {
                    var point = p as Roc809MeasurePoint;
                    if (point == null)
                    {
                        return;
                    }
                    ProcessPoint(member, roc, point, _client);
                });
            });
        }
Ejemplo n.º 16
0
        public Task RequestAsync(String requestString, IPEndPoint remoteEndPoint)
        {
            return(Task.Run(() =>
            {
                StateReporter statusReporter = new StateReporter(++CLIENT_ID, this);

                try
                {
                    using (TcpIpClient client = new TcpIpClient(remoteEndPoint.AddressFamily, Preferences.ClientStringEncoding, Preferences.ReceiveTimeout, Preferences.SendTimeout, TcpIpClient.DEF_RECEIVE_BUFFER_SIZE))
                    {
                        statusReporter.Report("Connecting to " + remoteEndPoint + "...");
                        client.Connect(remoteEndPoint);

                        if (Preferences.ReplaceHex)
                        {
                            requestString = Utilities.ConvertAllHex(requestString, Preferences.ClientStringEncoding);
                        }

                        statusReporter.Report("Connected to " + client.RemoteEndPoint + ".");

                        client.Send(requestString);
                        statusReporter.Report("Request sent to " + client.RemoteEndPoint + ":", requestString, true);

                        string respsonseString;

                        while (true)
                        {
                            respsonseString = client.Receive();

                            if (respsonseString == null)
                            {
                                statusReporter.Report("The socket at " + client.RemoteEndPoint + " was shut down.");
                                break;
                            }
                            else
                            {
                                statusReporter.Report("Response received from " + client.RemoteEndPoint + ":", respsonseString, true);
                            }
                        }
                    }
                }
                catch (SocketException ex)
                {
                    statusReporter.Report("Socket Error " + ex.ErrorCode + ":\n" + ex.Message);
                }

                statusReporter.Report("Client stopped.");
            }));
        }
        private void UpdateListBoxUser()
        {
            _userArrayAllowed = null;

            listBoxUser.Items.Clear();
            _tcp = new TcpIpClient();
            _tcp.getUserList(_dc.infoDev.IP_Server, _dc.infoDev.Port_Server, _dc.infoDev.SerialRFID, out _userArrayAllowed);

            if (_userArrayAllowed != null)
            {
                foreach (UserClassTemplate us in _userArrayAllowed)
                {
                    string strUser = string.Format("{0} {1}", us.firstName, us.lastName);
                    listBoxUser.Items.Add(strUser);
                }
            }
        }
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            int nbLocalDevices = (_arrayOfPluggedDevice == null) ? 0 : _arrayOfPluggedDevice.Length;

            if (_selectedDeviceIndex <= nbLocalDevices - 1) // Ethernet devices are added (in comboBox) after USB devices. Their index is greater than _arrayOfPluggedDevice length
            {
                MessageBox.Show(ResStrings.str_devicenotexist);
                return;
            }

            string selectedEthernetDeviceName = comboBoxDevice.Items[_selectedDeviceIndex].ToString();

            if (!_ethernetDevices.ContainsKey(selectedEthernetDeviceName))
            {
                MessageBox.Show(String.Format(ResStrings.strDeviceNotKnown, selectedEthernetDeviceName));
                return;
            }

            DeviceInfo deviceInfo = _ethernetDevices[selectedEthernetDeviceName];

            TcpIpClient tcpClient = new TcpIpClient();

            if (tcpClient.pingDevice(deviceInfo.IP_Server, deviceInfo.Port_Server, deviceInfo.SerialRFID) != TcpIpClient.RetCode.RC_Succeed)
            {
                MessageBox.Show(String.Format(ResStrings.strDeviceNotResponding, deviceInfo.SerialRFID, deviceInfo.IP_Server, deviceInfo.Port_Server));
                return;
            }

            bool spce2Available;

            if (tcpClient.RequestIsSPCE2Available(deviceInfo.IP_Server, deviceInfo.Port_Server, out spce2Available) != TcpIpClient.RetCode.RC_Succeed)
            {
                MessageBox.Show(String.Format(ResStrings.strDeviceNotResponding, deviceInfo.SerialRFID, deviceInfo.IP_Server, deviceInfo.Port_Server));
                return;
            }

            toolStripStatusLabelInfo.Text = String.Format(ResStrings.strDeviceNetworkError, deviceInfo.SerialRFID);

            //cbxAutoWrite.Visible = spce2Available;
            double fv = 0.0;

            tcpClient.RequestFirmwareVersion(deviceInfo.IP_Server, deviceInfo.Port_Server, out fv);
            cbxAutoWrite.Visible = fv > 2.54;

            _currentEthernetDevice = deviceInfo;
        }
Ejemplo n.º 19
0
 protected override void OnDestroy()
 {
     if (onConnected != null)
     {
         onConnected.Dispose();
         onConnected = null;
     }
     if (onRecv != null)
     {
         onRecv.Dispose();
         onRecv = null;
     }
     if (client != null)
     {
         client.Close();
         client = null;
     }
     base.OnDestroy();
 }
Ejemplo n.º 20
0
        public void UpdateFanem()
        {
            if (Lvd.SelectedNetworkDevice.infoDev.fridgeType != FridgeType.FT_FANEM)
            {
                return;
            }
            DataFanemInfo dfi = null;
            TcpIpClient   tcp = new TcpIpClient();

            tcp.getFridgeFanemInfo(Lvd.SelectedNetworkDevice.infoDev.IP_Server,
                                   Lvd.SelectedNetworkDevice.infoDev.Port_Server, Lvd.SelectedNetworkDevice.infoDev.SerialRFID, out dfi);
            if (dfi != null)
            {
                labelCurrentTemp.Text = string.Format(ResStrings.FridgeTempFrm_UpdateChart_currenttemp, DateTime.Now.ToLongTimeString(), Lvd.SelectedNetworkDevice.infoDev.DeviceName, dfi.GetT0.ToString("##.0 °C"));


                lblInfo.Items.Clear();
                lblInfo.Items.Add("Model : \t" + dfi.GetModel);
                lblInfo.Items.Add("Serial : \t" + dfi.GetSerial);
                lblInfo.Items.Add("Date : \t" + dfi.GetDateTime.ToString("dd/MM/yyyy - hh:mm:ss"));
                lblInfo.Items.Add("T0 : \t" + dfi.GetT0.ToString("##.0"));
                lblInfo.Items.Add("T1 : \t" + dfi.GetT1.ToString("##.0"));
                lblInfo.Items.Add("T2 : \t" + dfi.GetT2.ToString("##.0"));

                lblInfo.Items.Add("Set Temperature  : \t" + dfi.GetTconsigne.ToString("##.0"));
                lblInfo.Items.Add("Alarm High : \t" + dfi.GetAlarmHigh.ToString("##.0"));
                lblInfo.Items.Add("Alarm Low : \t" + dfi.GetAlarmLow.ToString("##.0"));
                lblInfo.Items.Add("Max Temperature  : " + dfi.GetMaxT.ToString("##.0"));
                lblInfo.Items.Add("Min Temperature : \t" + dfi.GetMinT.ToString("##.0"));

                lblInfo.Items.Add("Door : \t\t" + dfi.GetDoor);
                lblInfo.Items.Add("AC power : \t" + dfi.GetAcPower);
                lblInfo.Items.Add("Refrigeration: \t" + dfi.GetRefrigeration);
                lblInfo.Items.Add("Flash drive  : \t" + dfi.GetFlashDrive);
                lblInfo.Items.Add("Defrost  : \t" + dfi.GetDefrost);
            }
        }
Ejemplo n.º 21
0
        public TcpIpAgent(int num, string name, string loacl_ip, int local_port, string remote_ip, int remote_port, TCPIP_AGENT_COMM_MODE mode,
                          int recv_timeout, int send_timeout, int max_readsize, int reconnection_interval, int retry_count)
        {
            Num               = num;
            Name              = name;
            LocalIPAddress    = loacl_ip;
            LocalIPPort       = local_port;
            RemoteIPAddress   = remote_ip;
            RemoteIPPort      = remote_port;
            ConnectMode       = mode;
            RecvTimeout       = recv_timeout;
            SendTimeout       = send_timeout;
            MaxReadSize       = max_readsize;
            ReconnectInterval = reconnection_interval;
            RetryCount        = retry_count;

            if (ConnectMode == TCPIP_AGENT_COMM_MODE.CLINET_MODE)
            {
                tcpipClient = new TcpIpClient(remote_ip, remote_port, loacl_ip, local_port, this);
            }

            ImsgStateMachine = new StateMachineStateless <E_Msg_STS, E_Msg_EVENT>
                                   (name, StateMachineFactory.creatVHStateMachine(() => MessageState, (state) => MessageState = state));
        }
Ejemplo n.º 22
0
 public override void ClientDisconnected(TcpIpClient client)
 {
 }
Ejemplo n.º 23
0
 public RemoteView(TcpIpClient client)
 {
     InitializeComponent();
     _client = client;
     _client.ClientDisconnected += Client_ClientDisconnected;
 }
Ejemplo n.º 24
0
 public override bool AccessRequest(TcpIpClient client)
 {
     return(true);
 }
Ejemplo n.º 25
0
        private void CreateGrantTable()
        {
            _dt = new DataTable("TableGrant");
            _dt.Columns.Add("Device Serial", typeof(string));
            _dt.Columns.Add(ResStrings.str_Device_Name, typeof(string));
            _dt.Columns.Add(ResStrings.str_Device_Type, typeof(string));



            DeviceInfo[] di = _db.RecoverAllDevice();
            if (di != null)
            {
                foreach (DeviceInfo dev in di)
                {
                    //dt.Rows.Add(dev.SerialRFID,dev.DeviceName,dev.deviceType.ToString());
                    _dt.Rows.Add(dev.SerialRFID, dev.DeviceName, getEnumDesc.GetEnumDescription(dev.deviceType));
                }
            }

            dataGridViewGrant.DataSource = null;
            dataGridViewGrant.DataSource = _dt;

            for (int i = 0; i < dataGridViewGrant.RowCount; i++)
            {
                //dataGridViewGrant.Rows[i].Cells["Master"].Value = true;
                dataGridViewGrant.Rows[i].Cells["DoorGranted"].Value = 3;
            }
            comboBoxRemoteReader.Items.Clear();
            cbArmReader.Items.Clear();
            _tcpArmClients.Clear();
            DeviceInfo[] tmpDeviceArray = _db.RecoverDevice(false);
            if (tmpDeviceArray != null)
            {
                foreach (DeviceInfo dev in tmpDeviceArray)
                {
                    comboBoxRemoteReader.Items.Add(dev.DeviceName);

                    //Add remote enroll
                    TcpIpClient tmpTcp = new TcpIpClient();
                    try
                    {
                        tmpTcp._tcpArmDevice              = new TcpArmDevice(dev.IP_Server, dev.Port_Server);
                        tmpTcp._tcpArmDevice.DeviceEvent += _tcpArmDevice_DeviceEvent;
                        _tcpArmClients.Add(tmpTcp);
                        cbArmReader.Items.Add(dev.DeviceName + " (" + dev.IP_Server + ")");
                    }
                    catch (Exception)
                    {
                        if (tmpTcp._tcpArmDevice != null)
                        {
                            tmpTcp._tcpArmDevice.Release();
                        }
                    }
                }
            }
            if (comboBoxRemoteReader.Items.Count > 0)
            {
                comboBoxRemoteReader.Enabled       = true;
                comboBoxRemoteReader.SelectedIndex = 0;
                buttonBadge.Enabled = true;
            }
            if (cbArmReader.Items.Count > 0)
            {
                cbArmReader.SelectedIndex = 0;
            }

            cbxFinger.DataSource    = Enum.GetValues(typeof(FingerIndexValue));
            cbxFinger.SelectedIndex = 10;
        }
Ejemplo n.º 26
0
 private void Client_ClientDisconnected(TcpIpClient arg1)
 {
     MessageBox.Show("Connection lost or the host closed the connection");
     Close();
 }
        private bool WriteLotId(string tagId, string lotId)
        {
            lotId = lotId.Trim().ToUpper();

            if ((tagId.Length == 10) && (tagId.StartsWith("30")) && (_myRegexUid.IsMatch(tagId)))
            {
                MessageBox.Show(ResStrings.str_Tag_not_compatible_for_writing, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            if (!SDK_SC_RfidReader.DeviceBase.SerialRFID.isStringValidToWrite(lotId))
            {
                MessageBox.Show(ResStrings.str_Tag_Invalid_Tag_ID, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            WriteCode codeResult = WriteCode.WC_Error;

            if (_currentEthernetDevice == null) // (USB) local reader
            {
                if ((_device.ConnectionStatus == ConnectionStatus.CS_Connected) && (_device.DeviceStatus == DeviceStatus.DS_Ready))
                {
                    codeResult = _device.WriteNewUID(tagId, lotId);
                }

                else
                {
                    MessageBox.Show(ResStrings.str_device_not_ready, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            else
            {
                TcpIpClient tcpClient = new TcpIpClient();
                tcpClient.RequestWriteBlock(_currentEthernetDevice.IP_Server, _currentEthernetDevice.Port_Server, tagId, lotId, out codeResult);
            }


            switch (codeResult)
            {
            case WriteCode.WC_Error:
                MessageBox.Show(ResStrings.strWriteStatusUnexpectedError);
                break;

            case WriteCode.WC_TagNotDetected:
                MessageBox.Show(ResStrings.strWriteStatusOperation_failed);
                break;

            case WriteCode.WC_TagNotConfirmed:
                MessageBox.Show(ResStrings.strWriteStatus_Tag_not_confirmed);
                break;

            case WriteCode.WC_TagBlockedOrNotSupplied:
                MessageBox.Show(ResStrings.strWriteStatus_Tag_blocked_or_not_well_supplied);
                break;

            case WriteCode.WC_TagBlocked:
                MessageBox.Show(ResStrings.strWriteStatus_Tag_blocked);
                break;

            case WriteCode.WC_TagNotSupplied:
                MessageBox.Show(ResStrings.strWriteStatus_Tag_not_well_supplied);
                break;

            case WriteCode.WC_ConfirmationFailed:
                MessageBox.Show(ResStrings.strWriteStatus_Updated_tag_confirmation_has_failed);
                return(true);

            case WriteCode.WC_Success:
            {
                string initialUid = _db.GetInitialUID(tagId);
                _db.AddUidHistory(string.IsNullOrEmpty(initialUid) ? tagId : initialUid, lotId);
            }
                return(true);
            }

            return(false);
        }
        private void ScanDevice()
        {
            if (_currentEthernetDevice != null) // ethernet device : scan request, polling, tag blocks writing (if enabled by user)
            {
                TcpIpClient tcpClient = new TcpIpClient();
                string      status;

                if (tcpClient.getStatus(_currentEthernetDevice.IP_Server, _currentEthernetDevice.Port_Server,
                                        _currentEthernetDevice.SerialRFID, out status) != TcpIpClient.RetCode.RC_Succeed)
                {
                    MessageBox.Show(ResStrings.strErrorDevice, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                DeviceStatus currentStatus = (DeviceStatus)Enum.Parse(typeof(DeviceStatus), status);

                if (currentStatus != DeviceStatus.DS_Ready)
                {
                    MessageBox.Show(ResStrings.strDeviceEthernet_device_is_not_ready, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }


                InventoryData lastInventoryData;

                do // loop while we don't get a successful scan with ONE tag scanned
                {
                    if (tcpClient.requestScan(_currentEthernetDevice.IP_Server, _currentEthernetDevice.Port_Server,
                                              _currentEthernetDevice.SerialRFID) != TcpIpClient.RetCode.RC_Succeed) // scan starting has failed
                    {
                        MessageBox.Show(ResStrings.strdevice_Unable_to_start_scan);
                        return;
                    }

                    int tryIteration = 0;

                    do // loop while scan is not over (or if time limit excedeed [see Thread Sleep])
                    {
                        if (tryIteration > 4)
                        {
                            MessageBox.Show(ResStrings.strDevice_Scan_unexpectedly_long__please_retry, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        ++tryIteration;
                        Thread.Sleep(600);

                        if (tcpClient.getStatus(_currentEthernetDevice.IP_Server, _currentEthernetDevice.Port_Server,
                                                _currentEthernetDevice.SerialRFID, out status) != TcpIpClient.RetCode.RC_Succeed)
                        {
                            MessageBox.Show(ResStrings.strErrorDevice, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        currentStatus = (DeviceStatus)Enum.Parse(typeof(DeviceStatus), status);
                    } while (currentStatus == DeviceStatus.DS_InScan);

                    // scan terminated, now check if correct number of tag scanned (one)

                    if (tcpClient.requestGetLastScan(_currentEthernetDevice.IP_Server,
                                                     _currentEthernetDevice.Port_Server,
                                                     _currentEthernetDevice.SerialRFID, out lastInventoryData) != TcpIpClient.RetCode.RC_Succeed) // failed to get last inventorydata
                    {
                        MessageBox.Show(ResStrings.strDevice_Unable_to_get_last_scan_result, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    if (lastInventoryData == null) // failed to get last inventorydata
                    {
                        MessageBox.Show(ResStrings.strDevice_Unable_to_get_last_scan_result, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                } while (lastInventoryData.nbTagAll != 1);

                // we now have completed a scan with ONE tag
                string tagUid = lastInventoryData.listTagAll[0].ToString().Trim();
                toolStripStatusLabelInfo.Text = ResStrings.strScan_Completed_Tag_Scanned + tagUid;
                Invoke((MethodInvoker) delegate { textBoxTagID.Text = tagUid; });

                if (cbxAutoWrite.Checked)
                {
                    if (WriteLotId(tagUid, textBoxLotID.Text.Trim()))
                    {
                        Invoke((MethodInvoker) delegate { textBoxTagID.Text = textBoxLotID.Text; });
                        Invoke((MethodInvoker)ProcessTag);
                    }

                    else
                    {
                        Invoke((MethodInvoker) delegate { toolStripStatusLabelInfo.Text = ResStrings.ErrorWriting_new_tag_UID_failed; });
                    }
                }

                else
                {
                    Invoke((MethodInvoker)ProcessTag);
                }
            }

            else // (USB) local reader scan : requests a scan and everything is processed in RFID events
            {
                if (_device == null)
                {
                    return;
                }
                if ((_device.ConnectionStatus == ConnectionStatus.CS_Connected) &&
                    (_device.DeviceStatus == DeviceStatus.DS_Ready))
                {
                    _device.ScanDevice();
                }

                else
                {
                    MessageBox.Show(ResStrings.StrDeviceNotReadyOrNotConnected, ResStrings.strInfo, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        private void buttonUpdateUID_Click(object sender, EventArgs e)
        {
            if (listBoxTag.SelectedItems.Count > 1)
            {
                MessageBox.Show("Please update only one tag at a time.");
                return;
            }
            if (tabControl.SelectedIndex == 0) // (USB) local device
            {
                double fv = 0.0;
                double.TryParse(_currentUSBDevice.get_RFID_Device.FirmwareVersion.Replace(",", "."), NumberStyles.Number, CultureInfo.InvariantCulture, out fv);

                if (fv <= 2.54)
                {
                    MessageBox.Show("Please update device firmware with 2.55 or above version");
                    return;
                }
            }
            else
            {
                double      fv  = 0.0;
                TcpIpClient tcp = new TcpIpClient();
                tcp.RequestFirmwareVersion(_currentEthernetDevice.IP_Server, _currentEthernetDevice.Port_Server,
                                           out fv);
                if (fv <= 3.54)
                {
                    MessageBox.Show("Please update device firmware with 3.55 or above version");
                    return;
                }
            }


            string oldUID = listBoxTag.SelectedItem.ToString();

            using (NewUIDPrompt newUIDPrompt = new NewUIDPrompt(oldUID))
            {
                if (newUIDPrompt.ShowDialog(this) == DialogResult.OK)
                {
                    WriteCode writingResult;

                    string newUID    = newUIDPrompt.NewUID;
                    int    writeMode = newUIDPrompt.modeWrite;

                    if (tabControl.SelectedIndex == 0) // (USB) local device
                    {
                        if ((_currentUSBDevice.ConnectionStatus == ConnectionStatus.CS_Connected) &&
                            (_currentUSBDevice.DeviceStatus == DeviceStatus.DS_Ready))
                        {
                            writingResult = USBFeatures.WriteNewUID(_currentUSBDevice, oldUID, newUID, writeMode);
                        }

                        else
                        {
                            MessageBox.Show("RFID device not ready");
                            return;
                        }
                    }

                    else // (Ethernet) Remote device
                    {
                        writingResult = TCPFeatures.WriteNewUID(_currentEthernetDevice, tcpClient, oldUID, newUID, writeMode);
                    }

                    switch (writingResult)
                    {
                    case WriteCode.WC_Error:
                        MessageBox.Show("An unexpected error occurred. Operation failed !");
                        break;

                    case WriteCode.WC_TagNotDetected:
                        MessageBox.Show("Tag not detected. Operation failed !");
                        break;

                    case WriteCode.WC_TagNotConfirmed:
                        MessageBox.Show("Tag not confirmed. Operation failed !");
                        break;

                    case WriteCode.WC_TagBlockedOrNotSupplied:
                        MessageBox.Show("Tag blocked or not well supplied. Operation failed !");
                        break;

                    case WriteCode.WC_TagBlocked:
                        MessageBox.Show("Tag blocked. Operation failed !");
                        break;

                    case WriteCode.WC_TagNotSupplied:
                        MessageBox.Show("Tag not well supplied. Operation failed !");
                        break;

                    case WriteCode.WC_ConfirmationFailed:
                        MessageBox.Show("Updated tag confirmation has failed.");
                        break;

                    case WriteCode.WC_Success:
                        MessageBox.Show("Tag UID succesfully updated.");
                        break;
                    }
                }
            }
        }