/// <summary>
        /// Get all current taglist of device
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private async Task <Dictionary <string, JObject> > GetCurrentDeviceTagList(Device device)
        {
            DateTime removedatetime = DateTime.Now;

            removedatetime = removedatetime.AddSeconds(-IotGateway.KeyFrameTimeout);
            List <QueryFilter> filters = new List <QueryFilter>()
            {
                new QueryFilter("DeviceID", device.ID, FilterOperator.Equals, LogicalOperator.AND),
                new QueryFilter("DateTime", removedatetime, FilterOperator.GreaterThan)
            };

            //QueryFilter filter = new QueryFilter("DeviceID", device.ID, FilterOperator.Equals);
            var list = await new TagLastSeen().ReadAsync(filters);

            Dictionary <string, JObject> tags = new Dictionary <string, JObject>();

            foreach (var read in list)
            {
                var tag = new RfidTag
                {
                    Rfid     = read.RFID,
                    DateSeen = read.DateTime.ToString()
                };
                tags.Add(read.RFID, JObject.FromObject(tag));
            }
            return(tags);
        }
        private async Task <Dictionary <string, RfidTag> > GetAddedTags(string deviceName)
        {
            Innotrack.DeviceManager.Entities.Device device = Innotrack.DeviceManager.Entities.Device.GetDeviceByName(deviceName);
            List <QueryFilter> filters = new List <QueryFilter>()
            {
                new QueryFilter("HostSeen", false, FilterOperator.Equals, LogicalOperator.AND),
                new QueryFilter("DeviceID", device.ID, FilterOperator.Equals)
            };

            TagList = await new TagReads().ReadAsync(filters);

            int count = 0;
            Dictionary <string, RfidTag> tags = new Dictionary <string, RfidTag>();

            foreach (var read in TagList)
            {
                var tag = new RfidTag
                {
                    Rfid     = read.EPC,
                    DateSeen = read.DateTime.ToString()
                };
                count += 1;
                if (!tags.ContainsKey(read.EPC))
                {
                    tags.Add(read.EPC, tag);
                }
                //read.HostSeen = true;
                //read.Update();
            }

            return(tags);
        }
Esempio n. 3
0
        public async Task <string> PullItem(Stream streamdata)
        {
            try
            {
                StreamReader reader = new StreamReader(streamdata);
                string       res    = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();

                JsonItemToPull jitp = JsonConvert.DeserializeObject <JsonItemToPull>(res);
                if (jitp != null)
                {
                    var ctx = await RemoteDatabase.GetDbContextAsync();

                    var currentpullItem = ctx.PullItems.GetByServerId(jitp.ServerPullItemId);
                    if (currentpullItem != null)
                    {
                        ctx.PullItems.Remove(currentpullItem);
                        await ctx.SaveChangesAsync();
                    }
                    var user          = ctx.GrantedUsers.GetByServerId(jitp.userId);
                    var pullItemToAdd = new SmartDrawerDatabase.DAL.PullItem
                    {
                        ServerPullItemId = jitp.ServerPullItemId,
                        PullItemDate     = jitp.pullItemDate,
                        Description      = string.IsNullOrEmpty(jitp.description) ? " " : jitp.description,
                        GrantedUser      = user,
                        TotalToPull      = jitp.listOfTagToPull.Length,
                    };
                    ctx.PullItems.Add(pullItemToAdd);
                    foreach (string uid in jitp.listOfTagToPull)
                    {
                        RfidTag tag = ctx.RfidTags.AddIfNotExisting(uid);
                        ctx.PullItemsDetails.Add(new PullItemDetail
                        {
                            PullItem = pullItemToAdd,
                            RfidTag  = tag,
                        });
                    }
                    await ctx.SaveChangesAsync();

                    ctx.Database.Connection.Close();
                    ctx.Dispose();

                    if (MyHostEvent != null)
                    {
                        MyHostEvent(this, new MyHostEventArgs("PullItemsRequest", null));
                    }
                    return("Success : " + pullItemToAdd.ServerPullItemId);
                }
                return("Error : Bad Parameters");
            }
            catch (Exception exp)
            {
                return("Exception : " + exp.InnerException + "-" + exp.Message);
            }
        }
        static Task MessageHandler(Microsoft.Azure.ServiceBus.Message msg, CancellationToken token)
        {
            string  itemJson = Encoding.UTF8.GetString(msg.Body);
            RfidTag tag      = JsonSerializer.Deserialize <RfidTag>(itemJson);

            Console.WriteLine($"Item Received: {tag.Product} Price: {tag.Price}");
            list.Add(tag);

            return(Task.CompletedTask);
        }
        private Dictionary <string, RfidTag> AddTagRead(string deviceName, string rfid, string dateseen)
        {
            Dictionary <string, RfidTag> tags = new Dictionary <string, RfidTag>();
            var tag = new RfidTag
            {
                Rfid     = rfid,
                DateSeen = dateseen
            };

            tags.Add(rfid, tag);
            return(tags);
        }
Esempio n. 6
0
        private RfidTag[] GetOrderItems()
        {
            _logger.LogInformation("Tag Reader Console");

            // Create a sample order
            RfidTag[] orderItems = new RfidTag[]
            {
                new RfidTag()
                {
                    Product = "Ball", Price = 4.99
                },
                new RfidTag()
                {
                    Product = "Whistle", Price = 1.95
                },
                new RfidTag()
                {
                    Product = "Bat", Price = 12.99
                },
                new RfidTag()
                {
                    Product = "Bat", Price = 12.99
                },
                new RfidTag()
                {
                    Product = "Gloves", Price = 7.99
                },
                new RfidTag()
                {
                    Product = "Gloves", Price = 7.99
                },
                new RfidTag()
                {
                    Product = "Cap", Price = 9.99
                },
                new RfidTag()
                {
                    Product = "Cap", Price = 9.99
                },
                new RfidTag()
                {
                    Product = "Shirt", Price = 14.99
                },
                new RfidTag()
                {
                    Product = "Shirt", Price = 14.99
                },
            };

            // Display the order data.
            _logger.LogInformation($"Order contains {orderItems.Length} items.");
            return(orderItems);
        }
Esempio n. 7
0
        public static async Task Start()
        {
            Console.WriteLine("Starting Checkout");
            ServiceBusConfig serviceBusConfig = Program.InitServiceBusConfig();

            await ManageQueue(serviceBusConfig);

            QueueClient queueClient = new QueueClient(serviceBusConfig.ConnectionString, _queueName);

            //Items in Basket
            var basket = RfidTag.CreateBasket();

            Console.WriteLine($"Basket contains {basket.Length} items, Total cost: {basket.Sum(p => p.Price)}");

            int    itemCnt   = 0;
            int    sentCnt   = 0;
            double totalCost = 0.0;
            var    random    = new Random();

            while (itemCnt < 11)
            {
                RfidTag rfidTag = basket[itemCnt];

                string itemJson = JsonSerializer.Serialize(rfidTag);
                var    message  = new Microsoft.Azure.ServiceBus.Message(Encoding.UTF8.GetBytes(itemJson))
                {
                    Label = "RFID_Demo",
                    //Required to find duplicate message detection.
                    MessageId = rfidTag.TagId
                };
                await queueClient.SendAsync(message);

                Console.WriteLine($"Sent: {rfidTag.Product} ");

                //Duplicate logic - When following condition will be true, it will cause same item to be sent multiple times.
                //Increment number, This will cause code to send same product message multiple times when random value will be <= 0.3
                if (random.NextDouble() > 0.4)
                {
                    itemCnt++;
                }

                sentCnt++;
                totalCost += rfidTag.Price;
                Thread.Sleep(100);
            }
            Console.WriteLine($"Total {sentCnt} items scanned by RFID and total cost is {totalCost} (Including Duplicates)");
        }
Esempio n. 8
0
        private async Task ScanOrderItems(RfidTag[] orderItems)
        {
            var random = new Random(DateTime.Now.Millisecond);


            // Send the order with random duplicate tag reads
            int sentCount = 0;
            int position  = 0;

            _logger.LogInformation("Reading tags...");

            while (position < 10)
            {
                RfidTag rfidTag = orderItems[position];

                // Create a new  message from the order item RFID tag.
                var orderJson = JsonConvert.SerializeObject(rfidTag);

                var tagReadMessage = new Message(Encoding.UTF8.GetBytes(orderJson))
                {
                    MessageId = rfidTag.TagId
                };

                // Send the message
                await _queueClient.SendAsync(tagReadMessage);

                _logger.LogInformation($"Sent: { orderItems[position].Product } - MessageId: { tagReadMessage.MessageId }");

                // Randomly cause a duplicate message to be sent.
                if (random.NextDouble() > 0.4)
                {
                    position++;
                }

                sentCount++;

                Thread.Sleep(100);
            }

            _logger.LogInformation($"{sentCount} total tag reads.");
        }
Esempio n. 9
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Tag Reader Console");

            QueueClient queueClient = new QueueClient(AccountDetails.ConnectionString, AccountDetails.QueueName);


            // Create a sample order
            RfidTag[] orderItems = new RfidTag[]
            {
                new RfidTag()
                {
                    Product = "Ball", Price = 4.99
                },
                new RfidTag()
                {
                    Product = "Whistle", Price = 1.95
                },
                new RfidTag()
                {
                    Product = "Bat", Price = 12.99
                },
                new RfidTag()
                {
                    Product = "Bat", Price = 12.99
                },
                new RfidTag()
                {
                    Product = "Gloves", Price = 7.99
                },
                new RfidTag()
                {
                    Product = "Gloves", Price = 7.99
                },
                new RfidTag()
                {
                    Product = "Cap", Price = 9.99
                },
                new RfidTag()
                {
                    Product = "Cap", Price = 9.99
                },
                new RfidTag()
                {
                    Product = "Shirt", Price = 14.99
                },
                new RfidTag()
                {
                    Product = "Shirt", Price = 14.99
                },
            };

            // Display the order data.
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Order contains {0} items.", orderItems.Length);
            Console.ForegroundColor = ConsoleColor.Yellow;

            double orderTotal = 0.0;

            foreach (RfidTag tag in orderItems)
            {
                Console.WriteLine("{0} - ${1}", tag.Product, tag.Price);
                orderTotal += tag.Price;
            }


            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Order value = ${0}.", orderTotal);
            Console.WriteLine();
            Console.ResetColor();

            Console.WriteLine("Press enter to scan...");
            Console.ReadLine();

            Random random = new Random(DateTime.Now.Millisecond);


            // Send the order with random duplicate tag reads
            int sentCount = 0;
            int position  = 0;

            Console.WriteLine("Reading tags...");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Cyan;

            // Comment in to create session id
            var sessionId = Guid.NewGuid().ToString();

            Console.WriteLine($"SessionId: { sessionId }");

            while (position < 10)
            {
                RfidTag rfidTag = orderItems[position];

                // Create a new  message from the order item RFID tag.
                var orderJson      = JsonConvert.SerializeObject(rfidTag);
                var tagReadMessage = new Message(Encoding.UTF8.GetBytes(orderJson));

                // Comment in to set session id.
                tagReadMessage.SessionId = sessionId;

                // Send the message
                await queueClient.SendAsync(tagReadMessage);

                Console.WriteLine($"Sent: { orderItems[position].Product }");

                Thread.Sleep(100);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("{0} total tag reads.", sentCount);
            Console.WriteLine();
            Console.ResetColor();

            Console.ReadLine();
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Checkout Console");



            // Create the NamespaceManager
            NamespaceManager namespaceMgr =
                //new NamespaceManager(serviceBusUri, credentials);
                NamespaceManager.CreateFromConnectionString(AccountDetails.ConnectionString);

            // Create the MessagingFactory
            MessagingFactory factory =
                //MessagingFactory.Create(serviceBusUri, credentials);
                MessagingFactory.CreateFromConnectionString(AccountDetails.ConnectionString);

            // Delete the queue if it exists.
            if (namespaceMgr.QueueExists(AccountDetails.QueueName))
            {
                namespaceMgr.DeleteQueue(AccountDetails.QueueName);
            }



            // Create a description for the queue.
            QueueDescription rfidCheckoutQueueDescription =
                new QueueDescription(AccountDetails.QueueName)
            {
                // Comment in to require duplicate detection
                RequiresDuplicateDetection          = true,
                DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10),

                // Comment in to require sessions
                RequiresSession = true
            };



            // Create a queue based on the queue description.
            namespaceMgr.CreateQueue(rfidCheckoutQueueDescription);

            // Use the MessagingFactory to create a queue client for the
            // specified queue.
            QueueClient queueClient = factory.CreateQueueClient(AccountDetails.QueueName);

            Console.WriteLine("Receiving tag read messages...");
            while (true)
            {
                int    receivedCount = 0;
                double billTotal     = 0.0;

                // Comment in to use a session receiver
                Console.ForegroundColor = ConsoleColor.Cyan;
                var messageSession = queueClient.AcceptMessageSession();
                Console.WriteLine("Accepted session: " + messageSession.SessionId);


                Console.ForegroundColor = ConsoleColor.Yellow;


                while (true)
                {
                    // Receive a tag read message.

                    // Swap comments to use a session receiver
                    //var receivedTagRead = queueClient.Receive(TimeSpan.FromSeconds(5));
                    var receivedTagRead = messageSession.Receive(TimeSpan.FromSeconds(5));

                    if (receivedTagRead != null)
                    {
                        // Process the message.
                        RfidTag tag = receivedTagRead.GetBody <RfidTag>();
                        Console.WriteLine("Bill for {0}", tag.Product);
                        receivedCount++;
                        billTotal += tag.Price;

                        // Mark the message as complete
                        receivedTagRead.Complete();
                    }
                    else
                    {
                        break;
                    }
                }

                if (receivedCount > 0)
                {
                    // Bill the customer.
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine
                        ("Bill customer ${0} for {1} items.", billTotal, receivedCount);
                    Console.WriteLine();
                    Console.ResetColor();
                }
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Tag Reader Console");



            // Create the MessagingFactory
            MessagingFactory factory = MessagingFactory.CreateFromConnectionString(AccountDetails.ConnectionString); //MessagingFactory.Create(serviceBusUri, credentials);

            // Use the MessagingFactory to create a queue client for the 
            // specified queue.
            QueueClient queueClient = factory.CreateQueueClient(AccountDetails.QueueName);

            // Create a sample order
            RfidTag[] orderItems = new RfidTag[]
            {
                new RfidTag() { Product = "Ball", Price = 4.99 },
                new RfidTag() { Product = "Whistle", Price = 1.95 },
                new RfidTag() { Product = "Bat", Price = 12.99 },
                new RfidTag() { Product = "Bat", Price = 12.99 },
                new RfidTag() { Product = "Gloves", Price = 7.99 },
                new RfidTag() { Product = "Gloves", Price = 7.99 },
                new RfidTag() { Product = "Cap", Price = 9.99 },
                new RfidTag() { Product = "Cap", Price = 9.99 },
                new RfidTag() { Product = "Shirt", Price = 14.99 },
                new RfidTag() { Product = "Shirt", Price = 14.99 },
            };

            // Display the order data.
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Order contains {0} items.", orderItems.Length);
            Console.ForegroundColor = ConsoleColor.Yellow;

            double orderTotal = 0.0;
            foreach (RfidTag tag in orderItems)
            {
                Console.WriteLine("{0} - ${1}", tag.Product, tag.Price);
                orderTotal += tag.Price;
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Order value = ${0}.", orderTotal);
            Console.WriteLine();
            Console.ResetColor();

            Console.WriteLine("Press enter to scan...");
            Console.ReadLine();

            // Send the order with random duplicate tag reads
            int sentCount = 0;
            int position = 0;
            Random random = new Random(DateTime.Now.Millisecond);

            Console.WriteLine("Reading tags...");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Cyan;

            var sessionId = Guid.NewGuid().ToString();
          
            while (position < 10)
            {
                RfidTag rfidTag = orderItems[position];
                
                // Create a new brokered message from the order item RFID tag.
                BrokeredMessage tagRead = new BrokeredMessage(rfidTag);

                // Comment in to set message id.
                tagRead.MessageId = rfidTag.TagId;

                // Comment in to set session id.
                tagRead.SessionId = sessionId;


                // Send the message
                queueClient.Send(tagRead);
                //Console.WriteLine("Sent: {0}", orderItems[position].Product);
                Console.WriteLine("Sent: {0} - MessageId: {1}", orderItems[position].Product, tagRead.MessageId);

                // Randomly cause a duplicate message to be sent.
                if (random.NextDouble() > 0.4) position++;
                sentCount++;

                Thread.Sleep(100);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("{0} total tag reads.", sentCount);
            Console.WriteLine();
            Console.ResetColor();
            Console.ReadLine();

        }
Esempio n. 12
0
        public string AddOrUpdateProduct(Stream streamdata)
        {
            try
            {
                StreamReader reader = new StreamReader(streamdata);
                string       res    = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();

                JsonProductAddOrUpdate jsonProducts = JsonConvert.DeserializeObject <JsonProductAddOrUpdate>(res);
                if (jsonProducts != null)
                {
                    var ctx       = RemoteDatabase.GetDbContext();
                    int nbSuccess = 0;
                    for (int loop = 0; loop < jsonProducts.listOfProducts.Length; loop++)
                    {
                        int LastCol = 100;
                        while (LastCol > 0 && string.IsNullOrEmpty(jsonProducts.listOfProducts[loop].productInfo[LastCol]))
                        {
                            LastCol--;
                        }

                        for (int bcl = 0; bcl < LastCol; bcl++)
                        {
                            if (string.IsNullOrEmpty(jsonProducts.listOfProducts[loop].productInfo[bcl]))
                            {
                                jsonProducts.listOfProducts[loop].productInfo[bcl] = " ";
                            }
                        }

                        RfidTag tag = ctx.RfidTags.AddIfNotExisting(jsonProducts.listOfProducts[loop].tagUID);
                        Product p   = ctx.Products.GetByTagUid(jsonProducts.listOfProducts[loop].tagUID);
                        if (p != null)
                        {
                            ctx.Products.Attach(p);
                            p.ProductInfo0     = jsonProducts.listOfProducts[loop].productInfo[0];
                            p.ProductInfo1     = jsonProducts.listOfProducts[loop].productInfo[1];
                            p.ProductInfo2     = jsonProducts.listOfProducts[loop].productInfo[2];
                            p.ProductInfo3     = jsonProducts.listOfProducts[loop].productInfo[3];
                            p.ProductInfo4     = jsonProducts.listOfProducts[loop].productInfo[4];
                            p.ProductInfo5     = jsonProducts.listOfProducts[loop].productInfo[5];
                            p.ProductInfo6     = jsonProducts.listOfProducts[loop].productInfo[6];
                            p.ProductInfo7     = jsonProducts.listOfProducts[loop].productInfo[5];
                            p.ProductInfo8     = jsonProducts.listOfProducts[loop].productInfo[8];
                            p.ProductInfo9     = jsonProducts.listOfProducts[loop].productInfo[9];
                            p.ProductInfo10    = jsonProducts.listOfProducts[loop].productInfo[10];
                            p.ProductInfo11    = jsonProducts.listOfProducts[loop].productInfo[11];
                            p.ProductInfo12    = jsonProducts.listOfProducts[loop].productInfo[12];
                            p.ProductInfo13    = jsonProducts.listOfProducts[loop].productInfo[13];
                            p.ProductInfo14    = jsonProducts.listOfProducts[loop].productInfo[14];
                            p.ProductInfo15    = jsonProducts.listOfProducts[loop].productInfo[15];
                            p.ProductInfo16    = jsonProducts.listOfProducts[loop].productInfo[16];
                            p.ProductInfo17    = jsonProducts.listOfProducts[loop].productInfo[17];
                            p.ProductInfo18    = jsonProducts.listOfProducts[loop].productInfo[18];
                            p.ProductInfo19    = jsonProducts.listOfProducts[loop].productInfo[19];
                            ctx.Entry(p).State = System.Data.Entity.EntityState.Modified;
                            nbSuccess++;
                        }
                        else
                        {
                            var newProduct = new Product
                            {
                                RfidTag       = tag,
                                ProductInfo0  = jsonProducts.listOfProducts[loop].productInfo[0],
                                ProductInfo1  = jsonProducts.listOfProducts[loop].productInfo[1],
                                ProductInfo2  = jsonProducts.listOfProducts[loop].productInfo[2],
                                ProductInfo3  = jsonProducts.listOfProducts[loop].productInfo[3],
                                ProductInfo4  = jsonProducts.listOfProducts[loop].productInfo[4],
                                ProductInfo5  = jsonProducts.listOfProducts[loop].productInfo[5],
                                ProductInfo6  = jsonProducts.listOfProducts[loop].productInfo[6],
                                ProductInfo7  = jsonProducts.listOfProducts[loop].productInfo[5],
                                ProductInfo8  = jsonProducts.listOfProducts[loop].productInfo[8],
                                ProductInfo9  = jsonProducts.listOfProducts[loop].productInfo[9],
                                ProductInfo10 = jsonProducts.listOfProducts[loop].productInfo[10],
                                ProductInfo11 = jsonProducts.listOfProducts[loop].productInfo[11],
                                ProductInfo12 = jsonProducts.listOfProducts[loop].productInfo[12],
                                ProductInfo13 = jsonProducts.listOfProducts[loop].productInfo[13],
                                ProductInfo14 = jsonProducts.listOfProducts[loop].productInfo[14],
                                ProductInfo15 = jsonProducts.listOfProducts[loop].productInfo[15],
                                ProductInfo16 = jsonProducts.listOfProducts[loop].productInfo[16],
                                ProductInfo17 = jsonProducts.listOfProducts[loop].productInfo[17],
                                ProductInfo18 = jsonProducts.listOfProducts[loop].productInfo[18],
                                ProductInfo19 = jsonProducts.listOfProducts[loop].productInfo[19],
                            };
                            ctx.Products.Add(newProduct);
                            nbSuccess++;
                        }
                        ctx.SaveChanges();
                    }
                    ctx.Database.Connection.Close();
                    ctx.Dispose();

                    if (MyHostEvent != null)
                    {
                        MyHostEvent(this, new MyHostEventArgs("AddOrUpdateProduct", nbSuccess + " Product(s) added"));
                    }
                    return("Success");
                }
                else
                {
                    return("Failed : List of product is null or empty");
                }
            }
            catch (Exception exp)
            {
                return("failed : " + exp.InnerException);
            }
        }