//#define CUSTOM_UUID

using ATK;

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.IO;

using System.Threading.Tasks;

using Windows.Devices.Bluetooth;

using Windows.Devices.Bluetooth.Rfcomm; // bluetooth RFCMM reference

using Windows.Devices.Enumeration;

using Windows.Networking.Proximity;

using Windows.Networking.Sockets;

using Windows.Storage.Streams;

using Windows.UI.Popups;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Media.Imaging;

using Windows.Foundation;

using Windows.UI.Core;

using System.Collections.ObjectModel;



namespace Zebra_RFID_Mobile

{

    public class readerinfo : INotifyPropertyChanged

    {

        public string DisplayName { get; set; }

        public string DisplayBTMacName { get; set; }

        public string _SerialDisplayName;

        public string _ModelDisplayName;

        public string _ReaderConnectionStateVisible = "Collapsed";

        public string ID { get; set; }

        public string ServiceName { get; set; }

        private bool _ConnectionState;

        internal RfcommDeviceService RFIDService;

        public bool ReaderConnectionState

        {

            get { return _ConnectionState; }

            set

            {

                _ConnectionState = value;

                onPropertyChanged(this, "ReaderConnectionState");

            }

        }



        public event PropertyChangedEventHandler PropertyChanged;



        private void onPropertyChanged(object sender, string propertyName)

        {

            if (this.PropertyChanged != null)

            {

                PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));

            }

        }



        public string SerialDisplayName

        {

            get { return _SerialDisplayName; }

            set

            {

                _SerialDisplayName = value;

                onPropertyChanged(this, "SerialDisplayName");

            }

        }

        public string ModelDisplayName

        {

            get { return _ModelDisplayName; }

            set

            {

                _ModelDisplayName = value;

                ReaderConnectionStateVisible = "Visible";

                onPropertyChanged(this, "ModelDisplayName");

            }

        }



        public string ReaderConnectionStateVisible

        {

            get { return _ReaderConnectionStateVisible; }

            set

            {

                _ReaderConnectionStateVisible = value;

                onPropertyChanged(this, "ReaderConnectionStateVisible");

            }

        }

    }



    public class ReaderConnect // class for bluetooth services

    {

        GenericReader genericReader;

        public readonly Guid RFIDUuidCustom = Guid.Parse("2ad8a392-0e49-e52c-a6d2-60834c012263");

        public readonly Guid RFIDUuid = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");

        public DeviceInformationCollection RFIDServiceInfoCollection;

        public RfcommDeviceService RFIDService;

        public StreamSocket RFIDSocket;

        public DataWriter RFIDWriter;

        public Stream strRFID;

        public StreamReader RFIDReader;

        public bool readerSelected;

        //public List<readerinfo> items;

        public ObservableCollection<readerinfo> items

        {

            get;

            private set;

        }

        private bool bDisconnectCompleted = false;

        private bool bReceiveLoopExit = false;

        public int reConnectionRetries = 0;



        private ReaderConnect()

        {

            RFIDSocket = null;

            RFIDWriter = null;

            RFIDService = null;

            RFIDServiceInfoCollection = null;

            genericReader = GenericReader.getInstance();

            items = new ObservableCollection<readerinfo>();

        }



        //create an object of SingleObject

        private static ReaderConnect instance = new ReaderConnect();



        //Get the only object available

        public static ReaderConnect getInstance()

        {

            if (instance == null)

            {

                instance = new ReaderConnect();

            }

            return instance;

        }



        public async Task findpaireddevicesnew() // finds the instance of all paired devices

        {

            // Platform : PC or Phone

            var platformFamily = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily;

            try

            {

                //PeerFinder.Start();

                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = ""; // only to test if Bluetooth is turned off

                if (!platformFamily.Contains("Desktop"))

                {

                    var peers = await PeerFinder.FindAllPeersAsync();

                }

            }

            catch (Exception e)

            {

                if ((uint)e.HResult == 0x8007048F)

                {

                    showStatus("Bluetooth", "Bluetooth is Off");

                    return;

                }

                else

                {

                    string str = e.Message;

                    showStatus("Bluetooth", str);

                    return;

                }

            }

#if CUSTOM_UUID

            RFIDServiceInfoCollection = await DeviceInformation.FindAllAsync(

                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RFIDUuidCustom)));



            if (RFIDServiceInfoCollection.Count > 0)

            {

                foreach (var RFIDServiceInfo in RFIDServiceInfoCollection)

                {

                    readerinfo oneitem = new readerinfo();

                    oneitem.ServiceName = RFIDServiceInfo.Properties.ToString();

                    RFIDService = await RfcommDeviceService.FromIdAsync(RFIDServiceInfo.Id);

                    oneitem.DisplayBTMacName = RFIDService.ConnectionHostName.DisplayName;

                    oneitem.DisplayName = RFIDServiceInfo.Name.ToString() + "\n" + oneitem.DisplayBTMacName;

                    oneitem.ReaderConnectionState = false;

                    oneitem.RFIDService = RFIDService;

                    items.Add(oneitem);

                }

            }

#else

            DeviceInformationCollection DeviceCollection = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(true));

            foreach (var Device in DeviceCollection)

            {

                await AddReader(Device);

            }

#endif

            if (items.Count == 0)

            {

                showStatus("Bluetooth", "No devices found!");

            }

            MainPage.Current.readerWatcher.StartWatcher();

        }



        public async Task AddReader(DeviceInformation Device)

        {

            // Platform : PC or Phone

            var platformFamily = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily;



            BluetoothDevice bluetoothDevice = await BluetoothDevice.FromIdAsync(Device.Id);

            IReadOnlyList<RfcommDeviceService> rfcommServices;

            if (platformFamily.Contains("Desktop"))

            {

                var rfcomServicesget = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RFIDUuid));//, BluetoothCacheMode.Uncached);

                rfcommServices = rfcomServicesget.Services;

            }

            else

            {

                // GetRfcommServicesForIdAsync generates exception on Phone so using directly

                // Unable to cast object of type 'Windows.Devices.Bluetooth.BluetoothDevice' to type 'Windows.Devices.Bluetooth.IBluetoothDevice3'

                // possibly because of win10 build version

                rfcommServices = bluetoothDevice.RfcommServices;

            }

            // last service/port is RFID Serial Port

            int lastRFComm = rfcommServices.Count - 1;

            if (bluetoothDevice.Name.Contains("RFD8500") && rfcommServices.Count > 1 && rfcommServices[lastRFComm].ServiceId.Uuid == RFIDUuid)

            {

                readerinfo oneitem = new readerinfo();

                RFIDService = rfcommServices[lastRFComm];// await RfcommDeviceService.FromIdAsync(rfcommServices[lastRFComm].ConnectionServiceName);

                oneitem.DisplayBTMacName = RFIDService.ConnectionHostName.DisplayName;

                oneitem.DisplayName = RFIDService.Device.Name + "\n" + oneitem.DisplayBTMacName;

                oneitem.ReaderConnectionState = false;

                oneitem.RFIDService = RFIDService;

                oneitem.ID = Device.Id;

                items.Add(oneitem);

            }

        }



        public async Task<int> connectToDevice(readerinfo readerConnect) // connects to a SPP profile and creates a I/O streams

        {

            int readerindex = items.IndexOf(readerConnect);

            RFIDService = items[readerindex].RFIDService;

            ReaderConfig.connectedReaderIndex = readerindex;

            ReaderConfig.isInitialSettingsRecieved = false;

            try

            {

                RFIDService = await RfcommDeviceService.FromIdAsync(RFIDService.ConnectionServiceName);

                //create a socket

                RFIDSocket = new StreamSocket();

                //connect to socket

                await RFIDSocket.ConnectAsync(RFIDService.ConnectionHostName, RFIDService.ConnectionServiceName);



            }

            catch (Exception e)

            {

                if ((uint)e.HResult == 0x8007048F || (uint)e.HResult == 0x800710DF)

                {

                    showStatus("Bluetooth", "Bluetooth is Off");

                    return 2;

                }

                items[readerindex].ReaderConnectionState = false;

                ReaderConfig.connectedReaderIndex = -1;

                ReaderConfig.isReaderConnected = false;

                return 0;

            }



            //update the connection state in UI checkbox

            items[readerindex].ReaderConnectionState = true;



            RFIDService.Device.ConnectionStatusChanged += new TypedEventHandler<BluetoothDevice, object>(Device_ConnectionStatusChanged);



            //create a data writer

            RFIDWriter = new DataWriter(RFIDSocket.OutputStream);

            //create the data reader

            strRFID = RFIDSocket.InputStream.AsStreamForRead();

            RFIDReader = new StreamReader(strRFID, System.Text.Encoding.ASCII, false, 1048560);



            //function that loop on the input stream

            bReceiveLoopExit = false;

            ReceiveStringLoop(RFIDReader);



            ConnectCommand();

            ReaderConfig.isReaderConnected = true;

            bDisconnectCompleted = false;

            return 1;

        }



        private async void Device_ConnectionStatusChanged(BluetoothDevice reader, object args) // gives immidiate disconnection event... crash issues

        {

            if (reader.ConnectionStatus == BluetoothConnectionStatus.Disconnected)

            {

                try

                {

                    RFIDService.Device.ConnectionStatusChanged -= Device_ConnectionStatusChanged;

                    bDisconnectCompleted = true;

                    //if (!MainPage.isApplicationWindowActive && ReaderConfig.connectionConfig.readerConnection)

                    //    ToastHelper.PopToast(reader.Name, "Disconnected");

                    if (MainPage.isApplicationWindowActive && ReaderConfig.connectionConfig.readerConnection)

                        showStatus(reader.Name, "Disconnected");

                    // if abrupt disconnection

                    if (ReaderConfig.isReaderConnected)

                    {

                        if (RFIDWriter != null)

                        {

                            RFIDWriter.DetachStream();

                            RFIDWriter.Dispose();

                            RFIDWriter = null;

                        }

                        if (RFIDReader != null)

                        {

                            RFIDReader.Dispose();

                            RFIDReader = null;

                        }

                        if (RFIDSocket != null)

                        {

                            RFIDSocket.Dispose();

                            RFIDSocket = null;

                        }

                        await MainPage.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async () =>

                        {

                            try

                            {

                                int rdrIndex = ReaderConfig.connectedReaderIndex;

                                await disconnect();

                                if (ReaderConfig.connectionConfig.autoReconnect)

                                {

                                    Reconnect(rdrIndex);

                                }

                            }

                            catch (UnauthorizedAccessException)

                            {

                            }

                        });

                    }

                }

                catch (Exception exp)

                {

                    showStatus("Bluetooth", "Disconnected!" + exp.HResult + " " + exp.Message);

                    return;

                }

            }

        }



        public async Task<bool> disconnect() //disconnects to the connected socket

        {

            ReaderConfig.isReaderConnected = false;

            readerSelected = false;

            bReceiveLoopExit = true;

            if (RFIDWriter != null)

            {

                RFIDWriter.DetachStream();

                RFIDWriter.Dispose();

                RFIDWriter = null;

            }

            if (RFIDReader != null)

            {

                RFIDReader.Dispose();

                RFIDReader = null;

            }

            if (RFIDSocket != null)

            {

                RFIDSocket.Dispose();

                RFIDSocket = null;

            }



            //reset the connection variable            

            ReaderConfig.isInventoryRunning = false;

            ReaderConfig.isCommandComplete = false;

            ReaderConfig.BatchMode.isEnabled = false;

            ReaderConfig.isRegionSet = false;

            ReaderConfig.isInitialSettingsRecieved = false;

            ReaderConfig.isBatchModeEventRecieved = false;

            ReaderConfig.isGetAllRegionsComplete = false;

            ReaderConfig.isTagReportSetComplete = false;

            ReaderConfig.isStartStopSetComplete = false;

            ReaderConfig.isSingulationSetComplete = false;

            ReaderConfig.isDPOSetComplete = false;

            ReaderConfig.isAntennaSetComplete = false;

            ReaderConfig.regionList.Clear();

            ReaderConfig.moveToRegioScreen = false;

            ReaderConfig.isPreFilterSetComplete = false;

            ReaderConfig.regionsChannelsAll.Clear();

            ReaderConfig.linkProfiles.Clear();

            ReaderConfig.linkProfilesWithIndex.Clear();

            ReaderConfig.frequencyChannelsAll.Clear();

            ReaderConfig.frequencyChannelsSelected.Clear();

            ReaderConfig.isGetAllRegionsInfoComplete = false;

            ReaderConfig.batteryLevel.BatteryLevel = "0%";

            ReaderConfig.StartStopButtonStatus.STARTSTATUS = "START";

            ReaderConfig.StartStopButtonStatus.isBankListEnabled = true;

            ReaderConfig.locateData.LocateStartStop = "START";

            ReaderConfig.locateData.LocateData = "0";

            ReaderConfig.locateData.LocateTagID_ON = true;

            ReaderConfig.batteryLevel.BatteryStatus = "Status: No active connection";

            Uri imageURI = new Uri("ms-appx:///Assets/title_dpo_disabled.png", UriKind.Absolute);

            BitmapImage dpoImage = new BitmapImage(imageURI);

            ReaderConfig.DPOImage.DPOImage = dpoImage;

            imageURI = new Uri("ms-appx:///Assets/ic_battery_0.png", UriKind.Absolute);

            ReaderConfig.batteryDPO.BatteryDPOImage = new BitmapImage(imageURI); ;

            ReaderConfig.lastRegion = "";

            ReaderConfig.lastMetadataResponse = null;

            genericReader.stopInventoryTimer();

            StartBattery_timer(false);



            await isDisconnectComplete();



            //update the connection state in UI checkbox

            items[ReaderConfig.connectedReaderIndex].ReaderConnectionState = false;

            items[ReaderConfig.connectedReaderIndex].ReaderConnectionStateVisible = "Collapsed";





            return true;

        }



        public async Task<bool> isDisconnectComplete()

        {

            int Count = 10;

            while (bDisconnectCompleted == false && Count > 0)

            {

                await Task.Delay(1000);

                Count--;

            }

            return bDisconnectCompleted;

        }



        public async void ReceiveStringLoop(StreamReader RFIDReader) // infinte stream to accept the input stream 

        {

            while (!bReceiveLoopExit)

            {

                string str = null;



                try

                {

                    str = await RFIDReader.ReadLineAsync();

                }

                catch (ObjectDisposedException e)

                {

                    //await disconnect();

                    break;

                }

                catch (Exception e)

                {

                    if (e.HResult == -2146232800) //8001010E: interface marshalled error //800703E3: thread exit or application request                                                                                   

                    {

                        //bReceivedLoopExited = true;

                        break;

                    }

                    else

                    {

                        showStatus("Bluetooth", e.HResult + e.Message);

                        await disconnect();

                        break;

                    }

                }

                if (str != null)

                {

                    this.genericReader.returnCommandObject(str);

                }

            }

        }



        private async void Reconnect(int rdrIndex)

        {

            BaseReciever baseRecieverObj;

            baseRecieverObj = BaseReciever.getInstance();



            await Task.Delay(1000);

            if (readerSelected != true)

            {

                reConnectionRetries++;

                int reconnected = await connectToDevice(items[rdrIndex]);

                while (reconnected == 0 && reConnectionRetries < 5 && readerSelected != true)

                {

                    await Task.Delay(5000);

                    reconnected = await connectToDevice(items[rdrIndex]);

                    reConnectionRetries++;

                }

                if (reconnected == 1)

                {

                    await baseRecieverObj.isConnectComplete();

                    await GetInitialConfiguration();

                    showStatus(items[rdrIndex].DisplayName, "Connected");

                }

                else

                    showStatus(items[rdrIndex].DisplayName, "Connection Error!");

            }

            reConnectionRetries = 0;

        }



        public void ConnectCommand()

        {

            //send a connect command

            Command_Connect connectObject = new Command_Connect();

            if (ReaderConfig.connectionPassword != "")

                connectObject.password = ReaderConfig.connectionPassword;

            writeData(connectObject.ToString());

            ReaderConfig.isConnectComplete = false;

        }



        public async Task GetInitialConfiguration()

        {

            BaseReciever baseRecieverObj;

            baseRecieverObj = BaseReciever.getInstance();

            if (ReaderConfig.isBatchModeEventRecieved == false)

            {

                await isRegionSet();

                if (ReaderConfig.moveToRegioScreen == true)

                {

                    await baseRecieverObj.isGetAllRegionInfoComplete();

                    ReaderConfig.isGetAllRegionsInfoComplete = false;

                    MainPage.Current.Frame.Navigate(typeof(PageRegulatory));

                }

                else

                {

                    getInitialConfig(true);

                    await baseRecieverObj.isInitialSettingsRecievedComplete();

                }

            }

        }



        /* Summary for: isRegionSet

          1) checks if isRegionSet response was recieved from the reader

         Input : none

         Output : none            

       */

        public async Task<bool> isRegionSet()

        {

            Command_ProtocolConfig protocolConfigObj = new Command_ProtocolConfig();

            protocolConfigObj.EchoOff = true;

            protocolConfigObj.EchoOn = false;

            writeData(protocolConfigObj.ToString());

            await Task.Delay(10);

            Command_SetRegulatory regulatoryObj = new Command_SetRegulatory();

            writeData(ASCIIProcessor.getCommandConfig(regulatoryObj.getCommandType(), CONFIG_TYPE.CURRENT));

            ReaderConfig.isRegionGetComplete = false;

            await isRegionSetComplete();

            if (ReaderConfig.isRegionSet == false)

            {

                getRegionConfig();

                ReaderConfig.moveToRegioScreen = true;

            }

            return true;

        }



        /* Summary for: isRegionSetComplete

         1) checks if isRegionSetComplete response was completed on the reader

        Input : none

        Output : none            

      */

        public async Task<bool> isRegionSetComplete()

        {

            while (ReaderConfig.isRegionGetComplete == false)

            {

                await Task.Delay(1000);

            }

            return true;

        }



        /* Summary for: getRegionConfig

         1) sends the commands to get the region settings from the reader

        Input : none

        Output : none            

      */

        public async Task getRegionConfig()

        {

            BaseReciever baserecieverobj;

            baserecieverobj = BaseReciever.getInstance();

            ReaderConfig.isGetAllRegionsComplete = false;

            Command_GetAllSupportedRegions supportedRegionobj = new Command_GetAllSupportedRegions();

            writeData(supportedRegionobj.ToString());

            await baserecieverobj.isGetAllRegionsComplete();

            if(ReaderConfig.regionList.Count > 0)

                await getRegionDetails();

        }



        public async Task getRegionDetails()

        {

            BaseReciever baserecieverobj;

            baserecieverobj = BaseReciever.getInstance();

            ReaderConfig.isGetAllRegionsInfoComplete = false;

            ReaderConfig.lastRegion = ReaderConfig.regionList[ReaderConfig.regionList.Count - 1].RegionCode;

            // change here to get for all regions

            Command_GetRegion getregionObj = new Command_GetRegion();

            foreach (var region in ReaderConfig.regionList)

            {

                getregionObj.region = region.RegionCode.ToString();

                writeData(getregionObj.ToString());

                await Task.Delay(10);

            }

            await baserecieverobj.isGetAllRegionInfoComplete();

        }



        /* Summary for: getInitialConfig

        1) sends the commands to get the noexec settings from the reader

       Input : none

       Output : none            

      */

        public async void getInitialConfig(bool getregion)

        {

            ReaderConfig.moveToRegioScreen = false;

            ReaderConfig.StartStopButtonStatus.STARTSTATUS = "START";



            await Task.Delay(100);



            Command_ProtocolConfig protocolConfigObj = new Command_ProtocolConfig();

            protocolConfigObj.EchoOff = true;

            protocolConfigObj.EchoOn = false;

            protocolConfigObj.Exctriggereventnotify = false;

            protocolConfigObj.Inctriggereventnotify = true;

            protocolConfigObj.ExcStartOperationNotify = false;

            protocolConfigObj.IncStartOperationNotify = true;

            protocolConfigObj.ExcStopoperationNotify = false;

            protocolConfigObj.IncStopOperationNotify = true;

            writeData(protocolConfigObj.ToString());

            await Task.Delay(10);



            if (getregion == true)

            {

                await getRegionConfig();

                await Task.Delay(10);

            }



            Command_GetSupportedLinkprofiles supporetdLinkProfilesObj = new Command_GetSupportedLinkprofiles();

            writeData(supporetdLinkProfilesObj.ToString());

            await Task.Delay(10);



            Command_GetCapabilities command_capabilities = new Command_GetCapabilities();

            writeData(command_capabilities.ToString());

            await Task.Delay(10);



            Command_SetDynamicPower dynamicPowerObj = new Command_SetDynamicPower();

            writeData(ASCIIProcessor.getCommandConfig(dynamicPowerObj.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_SetQueryParams queryParamsObj = new Command_SetQueryParams();

            writeData(ASCIIProcessor.getCommandConfig(queryParamsObj.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_SetAntennaConfiguration antennaConfigObj = new Command_SetAntennaConfiguration();

            writeData(ASCIIProcessor.getCommandConfig(antennaConfigObj.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_SetReportConfig reportconfigObj = new Command_SetReportConfig();

            writeData(ASCIIProcessor.getCommandConfig(reportconfigObj.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_SetUniqueReport setUniqueReport = new Command_SetUniqueReport();

            writeData(ASCIIProcessor.getCommandConfig(setUniqueReport.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_SetRegulatory regulatoryObj = new Command_SetRegulatory();

            writeData(ASCIIProcessor.getCommandConfig(regulatoryObj.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_GetAttrInfo beerperGetObj = new Command_GetAttrInfo();

            beerperGetObj.attnum = 140;  // attribute number for Beeper

            writeData(beerperGetObj.ToString());

            await Task.Delay(10);



            Command_SetStartTrigger startTriggerConfig = new Command_SetStartTrigger();

            writeData(ASCIIProcessor.getCommandConfig(startTriggerConfig.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_SetStopTrigger stopTriggerConfig = new Command_SetStopTrigger();

            writeData(ASCIIProcessor.getCommandConfig(stopTriggerConfig.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_SetAccessCriteria accessCriteriaObj = new Command_SetAccessCriteria();

            writeData(ASCIIProcessor.getCommandConfig(accessCriteriaObj.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_SetSelectRecords selectRecordsObj = new Command_SetSelectRecords();

            writeData(ASCIIProcessor.getCommandConfig(selectRecordsObj.getCommandType(), CONFIG_TYPE.CURRENT));

            await Task.Delay(10);



            Command_GetAttrInfo batchGetObj = new Command_GetAttrInfo();

            batchGetObj.attnum = 1500;  // attribute number for Batchmode

            writeData(batchGetObj.ToString());

            await Task.Delay(10);



            Command_GetVersion getVersion = new Command_GetVersion();

            writeData(getVersion.ToString());

            await Task.Delay(10);



            Command_GetDeviceInfo deviceinfo = new Command_GetDeviceInfo();

            deviceinfo.battery = true;

            writeData(deviceinfo.ToString());

            StartBattery_timer(true);// start battery timer for battery info

        }



        DispatcherTimer batterytimer = new DispatcherTimer();

        public void StartBattery_timer(bool start)

        {

            if (start)

            {

                batterytimer.Tick += timer_Tick;

                batterytimer.Interval = new TimeSpan(0, 0, 60);

                batterytimer.Start();

                ReaderConfig.isBatteryTimerStopped = false;

            }

            else

            {

                if (ReaderConfig.isBatteryTimerStopped == false)

                {

                    batterytimer.Stop();

                    ReaderConfig.isBatteryTimerStopped = true;

                    batterytimer.Tick -= timer_Tick;

                }

            }

        }



        void timer_Tick(object sender, object e)

        {

            Command_GetDeviceInfo deviceinfo = new Command_GetDeviceInfo();

            deviceinfo.battery = true;

            writeData(deviceinfo.ToString());

        }



        public void showStatus(string Title, string Status)

        {

            MainPage rootPage = MainPage.Current;

            rootPage.ShowStatus(Title, Status);

        }



        public async void writeData(string data) // writes data to the output stream

        {

            data = data + "\r\n";

            System.Diagnostics.Debug.WriteLine(">>" + data);

            if (RFIDWriter != null)

            {

                RFIDWriter.WriteString(data);

                try

                {

                    await RFIDWriter.StoreAsync();

                    await RFIDWriter.FlushAsync();

                }

                catch (Exception)

                {

                    //showStatus("Writer Error"+e .HResult+ e.Message);

                    return;

                }

            }

        }



        public string getDeviceName(int index)

        {

            return items[index].DisplayName.ToString();

        }

    }

}