Пример #1
0
        public void TestListTagsPrefix()
        {
            // should allow listing tag by prefix

            ImageUploadParams uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(m_testImagePath),
                Tags = "api_test_custom1"
            };

            m_cloudinary.Upload(uploadParams);

            uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(m_testImagePath),
                Tags = "api_test_brustom"
            };

            m_cloudinary.Upload(uploadParams);

            ListTagsResult result = m_cloudinary.ListTagsByPrefix("api_test");

            Assert.IsTrue(result.Tags.Contains("api_test_brustom"));

            result = m_cloudinary.ListTagsByPrefix("nononothereisnosuchtag");

            Assert.IsTrue(result.Tags.Length == 0);
        }
        public void TestListTagsPrefix()
        {
            // should allow listing tag by prefix
            var tag1 = $"{GetMethodTag()}_1";
            var tag2 = $"{GetMethodTag()}_2";;
            var tag3 = $"{GetMethodTag()}_3";;

            ImageUploadParams uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(m_testImagePath),
                Tags = $"{tag1},{m_apiTag}"
            };

            m_cloudinary.Upload(uploadParams);

            uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(m_testImagePath),
                Tags = $"{tag2},{m_apiTag}"
            };

            m_cloudinary.Upload(uploadParams);

            ListTagsResult result = m_cloudinary.ListTagsByPrefix(m_apiTag);

            Assert.Contains(tag2, result.Tags);

            result = m_cloudinary.ListTagsByPrefix(tag3);

            Assert.IsTrue(result.Tags.Length == 0);
        }
        public void TestListTags()
        {
            // should allow listing tags
            UploadTestResource();

            ListTagsResult result = m_cloudinary.ListTags(new ListTagsParams());

            Assert.Greater(result.Tags.Length, 0);
        }
Пример #4
0
 public async Task <ListTagsResult> ListTagsAsync(ListTagsParams parameters)
 {
     using (
         var response = await Api.CallAsync(HttpMethod.Get,
                                            new UrlBuilder(Api.ApiUrlV.ResourceType("tags").Add(Api.GetCloudinaryParam(parameters.ResourceType)).BuildUrl(), parameters.ToParamsDictionary()).ToString(), null, null, null))
     {
         return(await ListTagsResult.Parse(response));
     }
 }
Пример #5
0
        // 装入以前的标签信息
        // 如果读卡器上有多个标签,则出现对话框让从中选择一个。列表中和右侧 PII 相同的,优先被选定
        // parameters:
        //      adjust_right    是否自动调整右侧元素。即,把左侧的锁定状态元素覆盖到右侧。调整前要询问。如果不同意调整,可以放弃,然后改为放一个空白标签并装载保存
        int LoadOldChip(bool adjust_right,
                        out string strError)
        {
            strError = "";
            if (string.IsNullOrEmpty(Program.MainForm.RfidCenterUrl))
            {
                strError = "尚未配置 RFID 中心 URL";
                return(-1);
            }
            RfidChannel channel = StartRfidChannel(
                Program.MainForm.RfidCenterUrl,
                out strError);

            if (channel == null)
            {
                return(-1);
            }
            try
            {
                ListTagsResult result = channel.Object.ListTags("*");
                if (result.Value == -1)
                {
                    strError = result.ErrorInfo;
                    return(-1);
                }

                // 出现对话框让选择一个
                SelectTagDialog dialog = new SelectTagDialog();
                dialog.Tags = result.Results;
                dialog.ShowDialog(this);
                if (dialog.DialogResult == DialogResult.Cancel)
                {
                    return(0);
                }

                // 装载标签详细信息
                GetTagInfoResult result1 = channel.Object.GetTagInfo(dialog.SelectedTag.ReaderName,
                                                                     dialog.SelectedTag.UID);

                return(1);
            }
            catch (Exception ex)
            {
                strError = "出现异常: " + ex.Message;
                return(-1);
            }
            finally
            {
                EndRfidChannel(channel);
            }
        }
Пример #6
0
        // 增加了无标签时延迟等待功能。敏捷响应
        public ListTagsResult ListTags(string reader_name, string style)
        {
            TimeSpan       length       = TimeSpan.FromSeconds(2);
            ListTagsResult result       = null;
            string         current_uids = "";
            DateTime       start        = DateTime.Now;

            while (DateTime.Now - start < length ||
                   result == null)
            {
                result = _listTags(reader_name, style);

                if (result != null && result.Results != null)
                {
                    current_uids = BuildUids(result.Results);
                }
                else
                {
                    current_uids = "";
                }

                // 只要本次和上次 tag 数不同,立刻就返回
                if (CompareLastUids(current_uids))
                {
                    SetLastUids(current_uids);
                    return(result);
                }

                if (result.Value == -1)
                {
                    return(result);
                }

                /*
                 * // TODO: 如果本次和上次都是 2,是否立即返回?可否先对比一下 uid,有差别再返回?
                 * if (result.Results != null
                 *  && result.Results.Count > 0)
                 * {
                 *  SetLastUids(current_uids);
                 *  return result;
                 * }
                 */
                Thread.Sleep(10);
            }

            SetLastUids(current_uids);
            return(result);
        }
Пример #7
0
        public void TestListTags()
        {
            // should allow listing tags

            ImageUploadParams uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(m_testImagePath),
                Tags = "api_test_custom"
            };

            m_cloudinary.Upload(uploadParams);

            ListTagsResult result = m_cloudinary.ListTags();

            Assert.IsTrue(result.Tags.Contains("api_test_custom"));
        }
Пример #8
0
        public ListTagsResult ListTags(ListTagsParams parameters)
        {
            UrlBuilder urlBuilder = new UrlBuilder(
                m_api.ApiUrlV.
                ResourceType("tags").
                Add(Api.GetCloudinaryParam <ResourceType>(parameters.ResourceType)).
                BuildUrl(),
                parameters.ToParamsDictionary());

            using (HttpWebResponse response = m_api.Call(
                       HttpMethod.GET, urlBuilder.ToString(), null, null))
            {
                ListTagsResult result = ListTagsResult.Parse(response);
                return(result);
            }
        }
 private void AssertListTagNotEmpty(ListTagsResult result)
 {
     Assert.Greater(result.Tags.Length, 0);
 }
 private void AssertListTagNotEmpty(ListTagsResult result)
 {
     Assert.Greater(result.Tags.Length, 0, result.Error?.Message);
 }
Пример #11
0
        // 增加了无标签时延迟等待功能。敏捷响应
        public ListTagsResult ListTags(string reader_name, string style)
        {
            if (Program.Rfid.Pause)
            {
                return new ListTagsResult
                       {
                           Value     = -1,
                           ErrorInfo = "RFID 功能处于暂停状态",
                           ErrorCode = "paused"
                       }
            }
            ;

            Program.Rfid.IncApiCount();
            try
            {
                if (Program.Rfid.Pause)
                {
                    return new ListTagsResult
                           {
                               Value     = -1,
                               ErrorInfo = "RFID 功能处于暂停状态",
                               ErrorCode = "paused"
                           }
                }
                ;

                string session_id = StringUtil.GetParameterByPrefix(style, "session");

                TimeSpan       length       = TimeSpan.FromSeconds(2);
                ListTagsResult result       = null;
                string         current_uids = "";
                DateTime       start        = DateTime.Now;
                while (DateTime.Now - start < length ||
                       result == null)
                {
                    result = _listTags(reader_name, style);

                    if (result != null && result.Results != null)
                    {
                        current_uids = BuildUids(result.Results);
                    }
                    else
                    {
                        current_uids = "";
                    }

                    // TODO: 这里的比较应该按照 Session 来进行
                    // 只要本次和上次 tag 数不同,立刻就返回
                    if (CompareLastUids(session_id, current_uids))
                    {
                        SetLastUids(session_id, current_uids);
                        return(result);
                    }

                    if (result.Value == -1)
                    {
                        return(result);
                    }

                    /*
                     * // TODO: 如果本次和上次都是 2,是否立即返回?可否先对比一下 uid,有差别再返回?
                     * if (result.Results != null
                     *  && result.Results.Count > 0)
                     * {
                     *  SetLastUids(current_uids);
                     *  return result;
                     * }
                     */
                    Thread.Sleep(10);
                }

                SetLastUids(session_id, current_uids);
                return(result);
            }
            catch (Exception ex)
            {
                return(new ListTagsResult
                {
                    Value = -1,
                    ErrorInfo = $"ListTags() 出现异常:{ex.Message}"
                });
            }
            finally
            {
                Program.Rfid.DecApiCount();
            }
        }

        // parameters:
        //      style   如果为 "getTagInfo",表示要在结果中返回 TagInfo
        ListTagsResult _listTags(string reader_name, string style)
        {
            InventoryResult result = new InventoryResult();

            if (Program.MainForm.ErrorState != "normal")
            {
                return new ListTagsResult
                       {
                           Value     = -1,
                           ErrorInfo = $"{Program.MainForm.ErrorStateInfo}",
                           ErrorCode = $"state:{Program.MainForm.ErrorState}"
                       }
            }
            ;

            List <OneTag> tags = new List <OneTag>();

            // uid --> OneTag
            Hashtable uid_table = new Hashtable();

            foreach (Reader reader in Program.Rfid.Readers)
            {
#if NO
                if (reader_name == "*" || reader.Name == reader_name)
                {
                }
                else
                {
                    continue;
                }
#endif

                if (Reader.MatchReaderName(reader_name, reader.Name) == false)
                {
                    continue;
                }

                InventoryResult inventory_result = Program.Rfid.Inventory(reader.Name, "");

                if (inventory_result.Value == -1)
                {
                    return(new ListTagsResult {
                        Value = -1, ErrorInfo = inventory_result.ErrorInfo, ErrorCode = inventory_result.ErrorCode
                    });
                }

                foreach (InventoryInfo info in inventory_result.Results)
                {
                    OneTag tag = null;
                    if (uid_table.ContainsKey(info.UID))
                    {
                        // 重复出现的,追加 读卡器名字
                        tag             = (OneTag)uid_table[info.UID];
                        tag.ReaderName += "," + reader.Name;
                    }
                    else
                    {
                        // 首次出现
                        tag = new OneTag
                        {
                            Protocol   = info.Protocol,
                            ReaderName = reader.Name,
                            UID        = info.UID,
                            DSFID      = info.DsfID
                        };

                        uid_table[info.UID] = tag;
                        tags.Add(tag);
                    }

                    if (StringUtil.IsInList("getTagInfo", style) &&
                        tag.TagInfo == null)
                    {
                        // TODO: 这里要利用 Hashtable 缓存
                        GetTagInfoResult result0 = Program.Rfid.GetTagInfo(reader.Name, info);
                        if (result0.Value == -1)
                        {
                            tag.TagInfo = null;
                            // TODO: 如何报错?写入操作历史?
                            // $"读取标签{info.UID}信息时出错:{result0.ToString()}"
                        }
                        else
                        {
                            tag.TagInfo = result0.TagInfo;
                        }
                    }
#if NO
                    GetTagInfoResult result0 = Program.Rfid.GetTagInfo(reader.Name, info);
                    if (result0.Value == -1)
                    {
                        // TODO: 如何报错?写入操作历史?
                        Program.MainForm.OutputText($"读取标签{info.UID}信息时出错:{result0.ToString()}", 2);
                        continue;
                    }

                    LogicChip chip = LogicChip.From(result0.TagInfo.Bytes,
                                                    (int)result0.TagInfo.BlockSize,
                                                    "" // result0.TagInfo.LockStatus
                                                    );
                    Element pii = chip.FindElement(ElementOID.PII);
                    if (pii == null)
                    {
                        Program.MainForm.Invoke((Action)(() =>
                        {
                            // 发送 UID
                            SendKeys.SendWait($"uid:{info.UID}\r");
                        }));
                    }
                    else
                    {
                        Program.MainForm.Invoke((Action)(() =>
                        {
                            // 发送 PII
                            SendKeys.SendWait($"pii:{pii.Text}\r");
                        }));
                    }
#endif
                }
            }

            return(new ListTagsResult {
                Results = tags
            });

#if NO
            InventoryResult result = new InventoryResult();
            List <OneTag>   tags   = new List <OneTag>();
            _lockTagList.EnterReadLock();
            try
            {
                foreach (OneTag tag in _tagList)
                {
                    if (reader_name == "*" || tag.ReaderName == reader_name)
                    {
                        tags.Add(tag);
                    }
                }
                return(new ListTagsResult {
                    Results = tags
                });
            }
            finally
            {
                _lockTagList.ExitReadLock();
            }
#endif
        }
Пример #12
0
        // 更新标签列表
        bool UpdateChipList()
        {
            string strError = "";

            if (string.IsNullOrEmpty(Program.MainForm.RfidCenterUrl))
            {
                strError = "尚未配置 RFID 中心 URL";
                goto ERROR1;
            }
            RfidChannel channel = StartRfidChannel(
                Program.MainForm.RfidCenterUrl,
                out strError);

            if (channel == null)
            {
                strError = "StartRfidChannel() error";
                goto ERROR1;
            }
            try
            {
                ListTagsResult result = channel.Object.ListTags("*", null);
                if (result.Value == -1)
                {
                    strError = result.ErrorInfo;
                    goto ERROR1;
                }

                List <Task> tasks    = new List <Task>();
                bool        is_empty = false;

                this.Invoke((Action)(() =>
                {
                    is_empty = this.listView1.Items.Count == 0;

                    List <ListViewItem> items = new List <ListViewItem>();
                    foreach (OneTag tag in result.Results)
                    {
                        ListViewItem item = FindItem(this.listView1,
                                                     tag.ReaderName,
                                                     tag.UID);
                        if (item == null)
                        {
                            item = new ListViewItem(tag.ReaderName);
                            ListViewUtil.ChangeItemText(item, 1, tag.UID);
                            item.Tag = tag;
                            this.listView1.Items.Add(item);

                            if (tag.TagInfo == null)
                            {
                                // 启动单独的线程去填充 .TagInfo
                                tasks.Add(Task.Run(() => { GetTagInfo(item); }));
                            }
                        }

                        items.Add(item);
                    }

                    // 交叉运算得到比 items 中多出来的 ListViewItem,删除它们
                    List <ListViewItem> delete_items = new List <ListViewItem>();
                    foreach (ListViewItem item in this.listView1.Items)
                    {
                        if (items.IndexOf(item) == -1)
                        {
                            delete_items.Add(item);
                        }
                    }

                    foreach (ListViewItem item in delete_items)
                    {
                        this.listView1.Items.Remove(item);
                    }
                }));

                // 再建立一个 task,等待 tasks 执行完以后,自动选定一个 item
                if (tasks.Count > 0)
                {
                    Task.Run(() =>
                    {
                        Task.WaitAll(tasks.ToArray());
                        this.Invoke((Action)(() =>
                        {
                            // 首次填充,自动设好选定状态
                            if (is_empty)
                            {
                                SelectItem(this.SelectedPII);

                                if (string.IsNullOrEmpty(this.SelectedPII) == false &&
                                    this.AutoCloseDialog)
                                {
                                    this.button_OK_Click(this, new EventArgs());
                                }
                            }
                        }));
                    });
                }
                return(true);
            }
            catch (Exception ex)
            {
                strError = "UpdateChipList() 出现异常: " + ExceptionUtil.GetDebugText(ex);
                goto ERROR1;
            }
            finally
            {
                EndRfidChannel(channel);
            }
ERROR1:
            MessageBox.Show(this, strError);
            return(false);
        }
Пример #13
0
        // 增加了无标签时延迟等待功能。敏捷响应
        // parameters:
        //      style   风格。逗号间隔的字符串内容
        //              session:会话ID
        //              dont_delay  不根据 session 来进行探测、延迟。也就是说确保要做一次 invetnory 并且立即返回
        public ListTagsResult ListTags(string reader_name, string style)
        {
            if (Program.Rfid.Pause)
            {
                return new ListTagsResult
                       {
                           Value     = -1,
                           ErrorInfo = "RFID 功能处于暂停状态",
                           ErrorCode = "paused"
                       }
            }
            ;

            string lockNameList = StringUtil.GetParameterByPrefix(style, "getLockState");

            if (lockNameList != null)
            {
                lockNameList = StringUtil.UnescapeString(lockNameList);
            }

            bool output_time = false;

            Program.Rfid.IncApiCount();
            try
            {
                if (Program.Rfid.Pause)
                {
                    return new ListTagsResult
                           {
                               Value     = -1,
                               ErrorInfo = "RFID 功能处于暂停状态",
                               ErrorCode = "paused"
                           }
                }
                ;

                // 2019/12/15
                bool dont_delay = StringUtil.IsInList("dont_delay", style);

                string session_id = StringUtil.GetParameterByPrefix(style, "session");

                if (output_time)
                {
                    Program.MainForm.OutputHistory($"session start: {session_id}, reader_name={reader_name}, style={style}");
                }

                TimeSpan length = TimeSpan.FromSeconds(2);

                ListTagsResult     result      = null;
                GetLockStateResult lock_result = null;

                string   current_uids = "";
                DateTime start        = DateTime.Now;
                while (DateTime.Now - start < length ||
                       result == null)
                {
                    Stopwatch watch = null;

                    // 执行 inventory
                    if (string.IsNullOrEmpty(reader_name) == false)
                    {
                        if (output_time)
                        {
                            watch = new Stopwatch();
                        }
                        else
                        {
                            watch = null;
                        }
                        watch?.Start();
                        result = _listTags(reader_name, style);
                        // testing
                        //if (reader_name.StartsWith("M201"))
                        //    Thread.Sleep(5000);
                        watch?.Stop();
                        if (output_time)
                        {
                            Program.MainForm.OutputHistory($"{session_id} inventory time:{watch.Elapsed.TotalSeconds}, count:{result.Results?.Count}");
                        }
                    }
                    else
                    {
                        if (output_time)
                        {
                            Program.MainForm.OutputHistory($"{session_id} inventory skipped");
                        }
                        result = new ListTagsResult();
                    }

                    // 执行门锁状态获取
                    // 目前是 1:1 次数分配
                    if (lockNameList != null)
                    {
                        Thread.Sleep(100);

                        if (output_time)
                        {
                            watch = new Stopwatch();
                        }
                        else
                        {
                            watch = null;
                        }
                        watch?.Start();
                        lock_result = GetShelfLockState(lockNameList);
                        watch?.Stop();
                        if (output_time)
                        {
                            Program.MainForm.OutputHistory($"{session_id} getLockState time:{watch.Elapsed.TotalSeconds}, count:{lock_result.States?.Count}");
                        }
                        // 从此开始 result.GetLockStateResult 就有值了
                        result.GetLockStateResult = lock_result;
                    }
                    else
                    {
                        if (output_time)
                        {
                            Program.MainForm.OutputHistory($"{session_id} getLockState skipped");
                        }
                    }

                    // 判断 inventory 结果
                    if (string.IsNullOrEmpty(reader_name) == false)
                    {
                        // 立即返回
                        if (dont_delay)
                        {
                            return(result);
                        }

                        if (result != null && result.Results != null)
                        {
                            current_uids = BuildUids(result.Results);
                        }
                        else
                        {
                            current_uids = "";
                        }

                        // TODO: 这里的比较应该按照 Session 来进行
                        // 只要本次和上次 tag 数不同,立刻就返回
                        if (CompareLastUids(session_id, current_uids))
                        {
                            SetLastUids(session_id, current_uids);
                            return(result);
                        }

                        if (result.Value == -1)
                        {
                            return(result);
                        }
                    }


                    // 判断门锁状态
                    if (lockNameList != null)
                    {
                        // 这里的疑问是,如果 _listTags 没有出错,是否应该坚持返回正确结果?
                        if (lock_result.Value != -1)
                        {
                            string current_states = BuildStateString(lock_result.States);
                            if (CompareLastUids(session_id + "_lock", current_states))
                            {
                                SetLastUids(session_id + "_lock", current_states);
                                return(result);
                            }
                        }
                    }

                    /*
                     * // TODO: 如果本次和上次都是 2,是否立即返回?可否先对比一下 uid,有差别再返回?
                     * if (result.Results != null
                     *  && result.Results.Count > 0)
                     * {
                     *  SetLastUids(current_uids);
                     *  return result;
                     * }
                     */
                    Thread.Sleep(10);  // 10? 200?
                }

                SetLastUids(session_id, current_uids);
                return(result);
            }
            catch (Exception ex)
            {
                return(new ListTagsResult
                {
                    Value = -1,
                    // TODO: 如何返回异常信息?
                    ErrorInfo = $"ListTags() 出现异常:{ExceptionUtil.GetDebugText(ex)}"
                });
            }
            finally
            {
                Program.Rfid.DecApiCount();
            }
        }
Пример #14
0
        // 增加了无标签时延迟等待功能。敏捷响应
        // parameters:
        //      style   风格。逗号间隔的字符串内容
        //              session:会话ID
        //              dont_delay  不根据 session 来进行探测、延迟。也就是说确保要做一次 invetnory 并且立即返回
        public ListTagsResult ListTags(string reader_name, string style)
        {
            if (Program.Rfid.Pause)
            {
                return new ListTagsResult
                       {
                           Value     = -1,
                           ErrorInfo = "RFID 功能处于暂停状态",
                           ErrorCode = "paused"
                       }
            }
            ;

            string lockNameList = StringUtil.GetParameterByPrefix(style, "getLockState");

            if (lockNameList != null)
            {
                lockNameList = StringUtil.UnescapeString(lockNameList);
            }

            bool output_time = false;

            Program.Rfid.IncApiCount();
            try
            {
                if (Program.Rfid.Pause)
                {
                    return new ListTagsResult
                           {
                               Value     = -1,
                               ErrorInfo = "RFID 功能处于暂停状态",
                               ErrorCode = "paused"
                           }
                }
                ;

                // 2019/12/15
                bool dont_delay = StringUtil.IsInList("dont_delay", style);

                string session_id = StringUtil.GetParameterByPrefix(style, "session");

                if (output_time)
                {
                    Program.MainForm.OutputHistory($"session start: {session_id}, reader_name={reader_name}, style={style}");
                }

                TimeSpan length = TimeSpan.FromSeconds(2);

                ListTagsResult     result      = null;
                GetLockStateResult lock_result = null;

                string   current_uids = "";
                DateTime start        = DateTime.Now;
                while (DateTime.Now - start < length ||
                       result == null)
                {
                    Stopwatch watch = null;

                    // 执行 inventory
                    if (string.IsNullOrEmpty(reader_name) == false)
                    {
                        if (output_time)
                        {
                            watch = new Stopwatch();
                        }
                        else
                        {
                            watch = null;
                        }
                        watch?.Start();
                        result = _listTags(reader_name, style);
                        // testing
                        //if (reader_name.StartsWith("M201"))
                        //    Thread.Sleep(5000);
                        watch?.Stop();
                        if (output_time)
                        {
                            Program.MainForm.OutputHistory($"{session_id} inventory time:{watch.Elapsed.TotalSeconds}, count:{result.Results?.Count}");
                        }
                    }
                    else
                    {
                        if (output_time)
                        {
                            Program.MainForm.OutputHistory($"{session_id} inventory skipped");
                        }
                        result = new ListTagsResult();
                    }

                    // 执行门锁状态获取
                    // 目前是 1:1 次数分配
                    if (lockNameList != null)
                    {
                        if (output_time)
                        {
                            watch = new Stopwatch();
                        }
                        else
                        {
                            watch = null;
                        }
                        watch?.Start();
                        lock_result = GetShelfLockState(lockNameList);
                        watch?.Stop();
                        if (output_time)
                        {
                            Program.MainForm.OutputHistory($"{session_id} getLockState time:{watch.Elapsed.TotalSeconds}, count:{lock_result.States?.Count}");
                        }
                        // 从此开始 result.GetLockStateResult 就有值了
                        result.GetLockStateResult = lock_result;
                    }
                    else
                    {
                        if (output_time)
                        {
                            Program.MainForm.OutputHistory($"{session_id} getLockState skipped");
                        }
                    }

                    // 判断 inventory 结果
                    if (string.IsNullOrEmpty(reader_name) == false)
                    {
                        // 立即返回
                        if (dont_delay)
                        {
                            return(result);
                        }

                        if (result != null && result.Results != null)
                        {
                            current_uids = BuildUids(result.Results);
                        }
                        else
                        {
                            current_uids = "";
                        }

                        // TODO: 这里的比较应该按照 Session 来进行
                        // 只要本次和上次 tag 数不同,立刻就返回
                        if (CompareLastUids(session_id, current_uids))
                        {
                            SetLastUids(session_id, current_uids);
                            return(result);
                        }

                        if (result.Value == -1)
                        {
                            return(result);
                        }
                    }


                    // 判断门锁状态
                    if (lockNameList != null)
                    {
                        // 这里的疑问是,如果 _listTags 没有出错,是否应该坚持返回正确结果?
                        if (lock_result.Value != -1)
                        {
                            string current_states = BuildStateString(lock_result.States);
                            if (CompareLastUids(session_id + "_lock", current_states))
                            {
                                SetLastUids(session_id + "_lock", current_states);
                                return(result);
                            }
                        }
                    }

                    /*
                     * // TODO: 如果本次和上次都是 2,是否立即返回?可否先对比一下 uid,有差别再返回?
                     * if (result.Results != null
                     *  && result.Results.Count > 0)
                     * {
                     *  SetLastUids(current_uids);
                     *  return result;
                     * }
                     */
                    Thread.Sleep(10);  // 10? 200?
                }

                SetLastUids(session_id, current_uids);
                return(result);
            }
            catch (Exception ex)
            {
                return(new ListTagsResult
                {
                    Value = -1,
                    // TODO: 如何返回异常信息?
                    ErrorInfo = $"ListTags() 出现异常:{ExceptionUtil.GetDebugText(ex)}"
                });
            }
            finally
            {
                Program.Rfid.DecApiCount();
            }
        }

        //static uint _currenAntenna = 1;
        //DateTime _lastTime;

        // parameters:
        //      reader_name_list    读卡器名字列表。形态为 "*" 或 "name1,name2" 或 "name1:1|2|3|4,name2"
        //      style   如果为 "getTagInfo",表示要在结果中返回 TagInfo
        ListTagsResult _listTags(string reader_name_list, string style)
        {
            InventoryResult result = new InventoryResult();

            if (Program.MainForm.ErrorState != "normal")
            {
                return new ListTagsResult
                       {
                           Value     = -1,
                           ErrorInfo = $"{Program.MainForm.ErrorStateInfo}",
                           ErrorCode = $"state:{Program.MainForm.ErrorState}"
                       }
            }
            ;

            List <OneTag> tags = new List <OneTag>();

            // uid --> OneTag
            Hashtable uid_table = new Hashtable();

            foreach (Reader reader in Program.Rfid.Readers)
            {
#if NO
                if (reader_name == "*" || reader.Name == reader_name)
                {
                }
                else
                {
                    continue;
                }
#endif

                // 顺便要从 reader_name_list 中解析出天线部分
                if (Reader.MatchReaderName(reader_name_list, reader.Name, out string antenna_list) == false)
                {
                    continue;
                }

                InventoryResult inventory_result = Program.Rfid.Inventory(reader.Name,
                                                                          antenna_list,
                                                                          style // ""
                                                                          );

                if (inventory_result.Value == -1)
                {
                    return(new ListTagsResult {
                        Value = -1, ErrorInfo = inventory_result.ErrorInfo, ErrorCode = inventory_result.ErrorCode
                    });
                }

                foreach (InventoryInfo info in inventory_result.Results)
                {
                    OneTag tag = null;
                    if (uid_table.ContainsKey(info.UID))
                    {
                        // 重复出现的,追加 读卡器名字
                        tag             = (OneTag)uid_table[info.UID];
                        tag.ReaderName += "," + reader.Name;
                    }
                    else
                    {
                        // 首次出现
                        tag = new OneTag
                        {
                            Protocol   = info.Protocol,
                            ReaderName = reader.Name,
                            UID        = info.UID,
                            DSFID      = info.DsfID,
                            AntennaID  = info.AntennaID, // 2019/9/25
                            // InventoryInfo = info    // 有些冗余的字段
                        };

                        /*
                         * // testing
                         * tag.AntennaID = _currenAntenna;
                         * if (DateTime.Now - _lastTime > TimeSpan.FromSeconds(5))
                         * {
                         *  _currenAntenna++;
                         *  if (_currenAntenna > 50)
                         *      _currenAntenna = 1;
                         *  _lastTime = DateTime.Now;
                         * }
                         */

                        uid_table[info.UID] = tag;
                        tags.Add(tag);
                    }

                    if (StringUtil.IsInList("getTagInfo", style) &&
                        tag.TagInfo == null)
                    {
                        // TODO: 这里要利用 Hashtable 缓存
                        GetTagInfoResult result0 = Program.Rfid.GetTagInfo(reader.Name, info);
                        if (result0.Value == -1)
                        {
                            tag.TagInfo = null;
                            // TODO: 如何报错?写入操作历史?
                            // $"读取标签{info.UID}信息时出错:{result0.ToString()}"
                        }
                        else
                        {
                            tag.TagInfo = result0.TagInfo;
                        }
                    }
#if NO
                    GetTagInfoResult result0 = Program.Rfid.GetTagInfo(reader.Name, info);
                    if (result0.Value == -1)
                    {
                        // TODO: 如何报错?写入操作历史?
                        Program.MainForm.OutputText($"读取标签{info.UID}信息时出错:{result0.ToString()}", 2);
                        continue;
                    }

                    LogicChip chip = LogicChip.From(result0.TagInfo.Bytes,
                                                    (int)result0.TagInfo.BlockSize,
                                                    "" // result0.TagInfo.LockStatus
                                                    );
                    Element pii = chip.FindElement(ElementOID.PII);
                    if (pii == null)
                    {
                        Program.MainForm.Invoke((Action)(() =>
                        {
                            // 发送 UID
                            SendKeys.SendWait($"uid:{info.UID}\r");
                        }));
                    }
                    else
                    {
                        Program.MainForm.Invoke((Action)(() =>
                        {
                            // 发送 PII
                            SendKeys.SendWait($"pii:{pii.Text}\r");
                        }));
                    }
#endif
                }
            }

            return(new ListTagsResult {
                Results = tags
            });

#if NO
            InventoryResult result = new InventoryResult();
            List <OneTag>   tags   = new List <OneTag>();
            _lockTagList.EnterReadLock();
            try
            {
                foreach (OneTag tag in _tagList)
                {
                    if (reader_name == "*" || tag.ReaderName == reader_name)
                    {
                        tags.Add(tag);
                    }
                }
                return(new ListTagsResult {
                    Results = tags
                });
            }
            finally
            {
                _lockTagList.ExitReadLock();
            }
#endif
        }
Пример #15
0
        // 更新标签列表
        bool UpdateChipList(bool show_messageBox)
        {
            int nRet = Interlocked.Increment(ref _inUpdate);

            try
            {
                if (nRet != 1)
                {
                    return(false);
                }
                string strError = "";
                if (string.IsNullOrEmpty(Program.MainForm.RfidCenterUrl))
                {
                    strError = "尚未配置 RFID 中心 URL";
                    goto ERROR1;
                }

                RfidChannel channel = StartRfidChannel(
                    Program.MainForm.RfidCenterUrl,
                    out strError);
                if (channel == null)
                {
                    strError = "StartRfidChannel() error";
                    goto ERROR1;
                }
                try
                {
                    ListTagsResult result = channel.Object.ListTags("*");
                    if (result.Value == -1)
                    {
                        strError = result.ErrorInfo;
                        goto ERROR1;
                    }

                    List <Task> tasks    = new List <Task>();
                    bool        is_empty = false;

                    this.Invoke((Action)(() =>
                    {
                        is_empty = this.listView_tags.Items.Count == 0;

                        List <ListViewItem> items = new List <ListViewItem>();
                        foreach (OneTag tag in result.Results)
                        {
                            ListViewItem item = FindItem(this.listView_tags,
                                                         tag.ReaderName,
                                                         tag.UID);
                            if (item == null)
                            {
                                item = new ListViewItem(tag.ReaderName);
                                ListViewUtil.ChangeItemText(item, 1, tag.UID);
                                item.Tag = new ItemInfo {
                                    OneTag = tag
                                };
                                this.listView_tags.Items.Add(item);

                                if (tag.TagInfo == null)
                                {
                                    // 启动单独的线程去填充 .TagInfo
                                    tasks.Add(Task.Run(() => { GetTagInfo(item); }));
                                }
                            }

                            items.Add(item);
                        }

                        // 交叉运算得到比 items 中多出来的 ListViewItem,删除它们
                        List <ListViewItem> delete_items = new List <ListViewItem>();
                        foreach (ListViewItem item in this.listView_tags.Items)
                        {
                            if (items.IndexOf(item) == -1)
                            {
                                delete_items.Add(item);
                            }
                        }

                        foreach (ListViewItem item in delete_items)
                        {
                            this.listView_tags.Items.Remove(item);
                        }
                    }));

                    // 再建立一个 task,等待 tasks 执行完以后,自动选定一个 item
                    if (tasks.Count > 0)
                    {
                        Task.Run(() =>
                        {
                            Task.WaitAll(tasks.ToArray());
                            this.Invoke((Action)(() =>
                            {
                                // 首次填充,自动设好选定状态
                                if (is_empty)
                                {
                                    SelectItem(this.SelectedID != null ? this.SelectedID : this.SelectedPII);

                                    if (string.IsNullOrEmpty(this.SelectedPII) == false &&
                                        this.AutoCloseDialog)
                                    {
                                        this.button_OK_Click(this, new EventArgs());
                                    }
                                }
                            }));

                            //this.Invoke((Action)(() =>
                            //{
                            FillEntityInfo();
                            //}));

                            if (this._mode == "auto_fix_eas")
                            {
                                this.Invoke((Action)(() =>
                                {
                                    AutoFixEas();
                                }));
                            }
                        });
                    }
                    return(true);
                }
                catch (RemotingException ex)
                {
                    strError = "UpdateChipList() 出现异常: " + ex.Message;
                    goto ERROR1;
                }
                catch (Exception ex)
                {
                    strError = "UpdateChipList() 出现异常: " + ExceptionUtil.GetDebugText(ex);
                    goto ERROR1;
                }
                finally
                {
                    EndRfidChannel(channel);
                }

ERROR1:
                if (show_messageBox)
                {
                    this.ShowMessageBox(strError);
                }
                else
                {
                    this.ShowMessage(strError, "red", true);
                }
                return(false);
            }
            finally
            {
                Interlocked.Decrement(ref _inUpdate);
            }
        }