コード例 #1
0
        /// <summary>
        /// Task for starting the R2 and receiving meters over the COM Port.
        /// </summary>
        /// <returns></returns>
        private async Task R2Listen()
        {
            //Gets any devices associated with the R2 port
            var aqsFilter = SerialDevice.GetDeviceSelector(R2Device.PortName);
            var devices   = await DeviceInformation.FindAllAsync(aqsFilter);

            if (devices.Any())
            {
                var deviceId = devices.First().Id;

                //This redundancy ensures the device is supplies a valid datareader object
                using (SerialDevice device = await SerialDevice.FromIdAsync(deviceId))
                {
                    if (device != null)
                    {
                        var readCancellationTokenSource = new CancellationTokenSource();
                        //DataReader dataReaderObject = new DataReader(device.InputStream);

                        //Reading variables
                        R2PacketModel R2Model;
                        int           lineCount = 0;
                        StringBuilder OutputBuilder = new StringBuilder();
                        bool          packetStart = false, packetEnd = false;
                        string        endpointId = "", reading = "", flag = "", rssi = "";
                        DateTime      date = new DateTime();
                        TimeSpan      time = new TimeSpan();

                        //GetLog tests
                        //R2I8 r = new R2I8();
                        //await r.ExecuteGetLog(device, "7072600", 11520);
                        //var resp = await R2.Listen(device, readCancellationTokenSource, R2PacketHeader.I8LogDetails, R2PacketHeader.I8LogStart, R2PacketHeader.I8LogCompleted, 30, 1);

                        Stream str = device.InputStream.AsStreamForRead(0);
                        IsR2Listening = true;

                        while (IsR2Initialized && IsR2Listening)
                        {
                            byte[] buffer   = new byte[1];
                            string response = "";

                            while (!packetStart || !packetEnd)
                            {
                                int readCount = await str.ReadAsync(buffer, 0, 1, readCancellationTokenSource.Token);//.ConfigureAwait(false);

                                string temp = Encoding.UTF8.GetString(buffer);

                                //temp.AddRange(Regex.Split(resp, @"(?<=[$&])"));

                                //string temp = await R2.Listen(device, readCancellationTokenSource, dataReaderObject, 80, true);

                                response += temp;

                                if (temp == "+" || temp == "*")
                                {
                                    packetStart = true;
                                }
                                else if (temp == "$" || temp == "&")
                                {
                                    packetEnd = true;
                                }

                                if (!packetStart && packetEnd)
                                {
                                    packetEnd = false;
                                }
                            }

                            //If a start and end char are found, begin parsing
                            if (packetStart && packetEnd)//foreach (string response in temp)
                            {
                                packetStart = false;
                                packetEnd   = false;

                                R2Model = await R2ReadPacketResponseAsync.ParseR2PacketResponse(response);

                                if (R2Model.R2M2WPacketModel != null || R2Model.R2NRDPacketModel != null)
                                {
                                    if (R2Model.R2M2WPacketModel != null)
                                    {
                                        //Set Database Variables
                                        endpointId = R2Model.R2M2WPacketModel.EndpointId;
                                        reading    = R2Model.R2M2WPacketModel.Reading;
                                        date       = R2Model.R2M2WPacketModel.ReadTime.Date;
                                        time       = R2Model.R2M2WPacketModel.ReadTime.TimeOfDay;
                                        flag       = R2Model.R2M2WPacketModel.Flag;
                                        rssi       = R2Model.R2M2WPacketModel.RSSI;
                                    }
                                    if (R2Model.R2NRDPacketModel != null)
                                    {
                                        //Set Database Variables
                                        endpointId = R2Model.R2NRDPacketModel.EndpointId;
                                        reading    = R2Model.R2NRDPacketModel.Reading;
                                        date       = R2Model.R2NRDPacketModel.ReadTime.Date;
                                        time       = R2Model.R2NRDPacketModel.ReadTime.TimeOfDay;
                                        flag       = R2Model.R2NRDPacketModel.Flag;
                                        rssi       = R2Model.R2NRDPacketModel.RSSI;
                                    }

                                    //Add to display list
                                    if (lineCount > 21)
                                    {
                                        OutputBuilder.Remove(0, OutputBuilder.ToString().IndexOf('\n') + 1);
                                    }
                                    OutputBuilder.Append("ID: " + endpointId + "\n");
                                    R2Packet = OutputBuilder.ToString();

                                    lineCount++;
                                    //Update Database

                                    if (!(ReadIds.Contains(endpointId)))// && (Meters.Where(meter => meter.MeterInfo.MeterId == endpointId)).Any())
                                    {
                                        MeterModel receivedMeter = Meters.FirstOrDefault(meter => meter.MeterInfo.MeterId == endpointId);

                                        if (receivedMeter != null)
                                        {
                                            int index = Meters.IndexOf(receivedMeter);
                                            Meters[index].MeterInfo.Reading = reading;
                                            Meters[index].ReadUpdated       = true;
                                            MeterSyncQueue.Enqueue(Meters[index].MeterInfo);
                                        }
                                        else
                                        {
                                            MeterSyncQueue.Enqueue(new JsonMeterModel()
                                            {
                                                MeterId = endpointId, Reading = reading
                                            });
                                        }

                                        ReadIds.Add(endpointId);
                                        ReadEndpoints++;

                                        //await Task.Delay(10);
                                        ////(@ID, @Read, @Date, @Time, @Codes, @RSSI, @HiUse, @Voltage);";
                                        //Database.UpdateReadCommand.Parameters.Add(new SqliteParameter("Id", endpointId));
                                        //Database.UpdateReadCommand.Parameters.Add(new SqliteParameter("Read", reading));
                                        //Database.UpdateReadCommand.Parameters.Add(new SqliteParameter("Date", date));
                                        //Database.UpdateReadCommand.Parameters.Add(new SqliteParameter("Time", time));
                                        //Database.UpdateReadCommand.Parameters.Add(new SqliteParameter("Codes", flag));
                                        //Database.UpdateReadCommand.Parameters.Add(new SqliteParameter("RSSI", rssi));
                                        ////Database.UpdateReadCommand.Parameters.Add(new SqliteParameter("HiUse", hiUse));
                                        ////Database.UpdateReadCommand.Parameters.Add(new SqliteParameter("Voltage", voltage));

                                        //Database.ExecuteCommand(Database.UpdateReadCommand);

                                        //if (Database.DatabaseFile != null && _userFolder != null)
                                        //{
                                        //    await Database.DatabaseFile.CopyAsync(_userFolder, _userFile.Name, NameCollisionOption.ReplaceExisting);
                                        //}
                                    }
                                }
                            }
                        }
                        //end thread

                        await PushReadsToCloud();

                        SyncStatus = "Syncronized";
                    }
                }
            }
        }