Example #1
0
        public void setSlaveDevice(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            IntPtr slaveDeviceObj   = IntPtr.Zero;
            UInt32 slaveDeviceCount = 0;

            Console.WriteLine("Trying to get the slave devices.");
            BS2ErrorCode result = (BS2ErrorCode)API.BS2_GetSlaveDevice(sdkContext, deviceID, out slaveDeviceObj, out slaveDeviceCount);

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
            }
            else if (slaveDeviceCount > 0)
            {
                List <BS2Rs485SlaveDevice> slaveDeviceList = new List <BS2Rs485SlaveDevice>();
                IntPtr curSlaveDeviceObj = slaveDeviceObj;
                int    structSize        = Marshal.SizeOf(typeof(BS2Rs485SlaveDevice));

                for (int idx = 0; idx < slaveDeviceCount; ++idx)
                {
                    BS2Rs485SlaveDevice item = (BS2Rs485SlaveDevice)Marshal.PtrToStructure(curSlaveDeviceObj, typeof(BS2Rs485SlaveDevice));
                    slaveDeviceList.Add(item);
                    curSlaveDeviceObj = (IntPtr)((long)curSlaveDeviceObj + structSize);
                }

                Console.WriteLine("+----------------------------------------------------------------------------------------------------------+");
                for (UInt32 idx = 0; idx < slaveDeviceCount; ++idx)
                {
                    BS2Rs485SlaveDevice slaveDevice = slaveDeviceList[(int)idx];
                    Console.WriteLine("[{0:000}] ==> SlaveDevice id[{1, 10}] type[{2, 3}] model[{3, 16}] enable[{4}], connected[{5}]",
                                      idx,
                                      slaveDevice.deviceID,
                                      slaveDevice.deviceType,
                                      API.productNameDictionary[(BS2DeviceTypeEnum)slaveDevice.deviceType],
                                      Convert.ToBoolean(slaveDevice.enableOSDP),
                                      Convert.ToBoolean(slaveDevice.connected));
                }
                Console.WriteLine("+----------------------------------------------------------------------------------------------------------+");
                Console.WriteLine("Enter the index of the slave device which you want to connect: [INDEX_1,INDEX_2 ...]");
                Console.Write(">>>> ");
                char[]           delimiterChars     = { ' ', ',', '.', ':', '\t' };
                string[]         slaveDeviceIndexs  = Console.ReadLine().Split(delimiterChars);
                HashSet <UInt32> connectSlaveDevice = new HashSet <UInt32>();

                if (slaveDeviceIndexs.Length == 0)
                {
                    Console.WriteLine("All of the slave device will be disabled.");
                }
                else
                {
                    foreach (string slaveDeviceIndex in slaveDeviceIndexs)
                    {
                        if (slaveDeviceIndex.Length > 0)
                        {
                            UInt32 item;
                            if (UInt32.TryParse(slaveDeviceIndex, out item))
                            {
                                if (item < slaveDeviceCount)
                                {
                                    connectSlaveDevice.Add(slaveDeviceList[(int)item].deviceID);
                                }
                            }
                        }
                    }
                }

                curSlaveDeviceObj = slaveDeviceObj;
                for (int idx = 0; idx < slaveDeviceCount; ++idx)
                {
                    BS2Rs485SlaveDevice item = (BS2Rs485SlaveDevice)Marshal.PtrToStructure(curSlaveDeviceObj, typeof(BS2Rs485SlaveDevice));

                    if (connectSlaveDevice.Contains(item.deviceID))
                    {
                        if (item.enableOSDP != 1)
                        {
                            item.enableOSDP = 1;
                            Marshal.StructureToPtr(item, curSlaveDeviceObj, false);
                        }
                    }
                    else
                    {
                        if (item.enableOSDP != 0)
                        {
                            item.enableOSDP = 0;
                            Marshal.StructureToPtr(item, curSlaveDeviceObj, false);
                        }
                    }

                    curSlaveDeviceObj = (IntPtr)((long)curSlaveDeviceObj + structSize);
                }

                Console.WriteLine("Trying to set the slave devices.");
                result = (BS2ErrorCode)API.BS2_SetSlaveDevice(sdkContext, deviceID, slaveDeviceObj, slaveDeviceCount);

                API.BS2_ReleaseObject(slaveDeviceObj);

                if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                {
                    Console.WriteLine("Got error({0}).", result);
                }
                else
                {
                    slaveControl(sdkContext, slaveDeviceList);
                }
            }
            else
            {
                Console.WriteLine(">>> There is no slave device in the device.");
            }
        }
Example #2
0
        public void setDstConfig(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            Console.WriteLine("How many daylight saving time schedules do you want to set? [1(default)-2]");
            Console.Write(">>>> ");
            BS2DstConfig config = Util.AllocateStructure <BS2DstConfig>();

            config.numSchedules = (byte)Util.GetInput(1);
            if (config.numSchedules < 0 || config.numSchedules > 2)
            {
                Console.WriteLine("Invalid parameter");
                return;
            }

            for (int idx = 0; idx < config.numSchedules; ++idx)
            {
                Console.WriteLine("Configure DST schedule #{0}", idx);
                Console.WriteLine("   Enter the OFFSET of the time in seconds. [Ex) 3600 means it will add 1 hour after the DST starts.]");
                Console.Write(">>>");
                config.schedules[idx].timeOffset = (int)Util.GetInput();

                Console.WriteLine("   Please enter the value for the STARTING TIME.");
                Console.WriteLine("      Enter the YEAR to start the DST schedule #{0}. [0(default) means every year]", idx);
                Console.Write("   >>>");
                config.schedules[idx].startTime.year = Util.GetInput((UInt16)0);
                Console.WriteLine("      Enter the MONTH to start the DST schedule #{0}. [0(Jan), 1(Feb), ... , 11(Dec)]", idx);
                Console.Write("   >>>");
                config.schedules[idx].startTime.month = (byte)Util.GetInput();
                Console.WriteLine("      Enter the ORDINAL of the WEEK to start the DST schedule #{0}. [0(1st week), 1(2nd week), ... , -1(Last week)]", idx);
                Console.WriteLine("      The start of the week is based on Monday.");
                Console.Write("   >>>");
                config.schedules[idx].startTime.ordinal = (sbyte)Util.GetInput();
                Console.WriteLine("      Enter the DAY of the WEEK to start the DST schedule #{0}. [0(Sun), 1(Mon), ... , 6(Sat)]", idx);
                Console.Write("   >>>");
                config.schedules[idx].startTime.weekDay = (byte)Util.GetInput();
                Console.WriteLine("      Enter the HOUR to start the DST schedule #{0}. [0 ~ 23]", idx);
                Console.Write("   >>>");
                config.schedules[idx].startTime.hour = (byte)Util.GetInput();
                Console.WriteLine("      Enter the MINUTE to start the DST schedule #{0}. [0 ~ 59]", idx);
                Console.Write("   >>>");
                config.schedules[idx].startTime.minute = (byte)Util.GetInput();
                Console.WriteLine("      Enter the SECOND to start the DST schedule #{0}. [0 ~ 59]", idx);
                Console.Write("   >>>");
                config.schedules[idx].startTime.second = (byte)Util.GetInput();

                Console.WriteLine("   Please enter the value for the ENDING TIME.");
                Console.WriteLine("      Enter the YEAR to end the DST schedule #{0}. [0(default) means every year]", idx);
                Console.Write("   >>>");
                config.schedules[idx].endTime.year = Util.GetInput((UInt16)0);
                Console.WriteLine("      Enter the MONTH to end the DST schedule #{0}. [0(Jan), 1(Feb), ... , 11(Dec)]", idx);
                Console.Write("   >>>");
                config.schedules[idx].endTime.month = (byte)Util.GetInput();
                Console.WriteLine("      Enter the ORDINAL of the WEEK to end the DST schedule #{0}. [0(1st week), 1(2nd week), ... , -1(Last week)]", idx);
                Console.WriteLine("      The start of the week is based on Monday.");
                Console.Write("   >>>");
                config.schedules[idx].endTime.ordinal = (sbyte)Util.GetInput();
                Console.WriteLine("      Enter the DAY of the WEEK to end the DST schedule #{0}. [0(Sun), 1(Mon), ... , 6(Sat)]", idx);
                Console.Write("   >>>");
                config.schedules[idx].startTime.weekDay = (byte)Util.GetInput();
                Console.WriteLine("      Enter the HOUR to end the DST schedule #{0}. [0 ~ 23]", idx);
                Console.Write("   >>>");
                config.schedules[idx].endTime.hour = (byte)Util.GetInput();
                Console.WriteLine("      Enter the MINUTE to end the DST schedule #{0}. [0 ~ 59]", idx);
                Console.Write("   >>>");
                config.schedules[idx].endTime.minute = (byte)Util.GetInput();
                Console.WriteLine("      Enter the SECOND to end the DST schedule #{0}. [0 ~ 59]", idx);
                Console.Write("   >>>");
                config.schedules[idx].endTime.second = (byte)Util.GetInput();
            }

            Console.WriteLine("Trying to set Daylight Saving Time configuration.");
            BS2ErrorCode result = (BS2ErrorCode)API.BS2_SetDstConfig(sdkContext, deviceID, ref config);

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }
            else
            {
                Console.WriteLine("Set DstConfig Succeeded");
            }
        }
Example #3
0
        public void setInputConfig(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            BS2InputConfig config = Util.AllocateStructure <BS2InputConfig>();

            Console.WriteLine("Please enter Number of inputs.");
            Console.Write(">>>> ");
            config.numInputs = (byte)Util.GetInput();
            if (config.numInputs < 0 || config.numInputs > 10)
            {
                Console.WriteLine("Invalid parameter (numInputs)");
                return;
            }

            Console.WriteLine("Please enter Number of supervised-inputs.");
            Console.Write(">>>> ");
            config.numSupervised = (byte)Util.GetInput();
            if (config.numSupervised < 0 || config.numSupervised > 8)
            {
                Console.WriteLine("Invalid parameter (numSupervised)");
                return;
            }

            for (int idx = 0; idx < BS2Envirionment.BS2_MAX_INPUT_NUM; ++idx)
            {
                if (idx < config.numSupervised)
                {
                    Console.WriteLine(">>>> supervised_inputs[{0}]", idx);

                    config.supervised_inputs[idx].portIndex = (byte)idx;

                    Console.Write("    Please enter enabled (0, 1) : ");
                    config.supervised_inputs[idx].enabled = (byte)Util.GetInput();

                    Console.Write("    Please enter superviced_index : ");
                    config.supervised_inputs[idx].supervised_index = (byte)Util.GetInput();

                    if (255 == config.supervised_inputs[idx].supervised_index)
                    {
                        Console.Write("    Please enter shortInput.minValue : ");
                        config.supervised_inputs[idx].config.shortInput.minValue = (UInt16)Util.GetInput();
                        Console.Write("    Please enter shortInput.maxValue : ");
                        config.supervised_inputs[idx].config.shortInput.maxValue = (UInt16)Util.GetInput();

                        Console.Write("    Please enter openInput.minValue : ");
                        config.supervised_inputs[idx].config.openInput.minValue = (UInt16)Util.GetInput();
                        Console.Write("    Please enter openInput.maxValue : ");
                        config.supervised_inputs[idx].config.openInput.maxValue = (UInt16)Util.GetInput();

                        Console.Write("    Please enter onInput.minValue : ");
                        config.supervised_inputs[idx].config.onInput.minValue = (UInt16)Util.GetInput();
                        Console.Write("    Please enter onInput.maxValue : ");
                        config.supervised_inputs[idx].config.onInput.maxValue = (UInt16)Util.GetInput();

                        Console.Write("    Please enter offInput.minValue : ");
                        config.supervised_inputs[idx].config.offInput.minValue = (UInt16)Util.GetInput();
                        Console.Write("    Please enter offInput.maxValue : ");
                        config.supervised_inputs[idx].config.offInput.maxValue = (UInt16)Util.GetInput();
                    }
                    else
                    {
                        config.supervised_inputs[idx].config.shortInput.minValue = 0;
                        config.supervised_inputs[idx].config.shortInput.maxValue = 0;
                        config.supervised_inputs[idx].config.openInput.minValue  = 0;
                        config.supervised_inputs[idx].config.openInput.maxValue  = 0;
                        config.supervised_inputs[idx].config.onInput.minValue    = 0;
                        config.supervised_inputs[idx].config.onInput.maxValue    = 0;
                        config.supervised_inputs[idx].config.offInput.minValue   = 0;
                        config.supervised_inputs[idx].config.offInput.maxValue   = 0;
                    }
                }
                else
                {
                    config.supervised_inputs[idx].portIndex                  = (byte)idx;
                    config.supervised_inputs[idx].enabled                    = 0;
                    config.supervised_inputs[idx].supervised_index           = 1;
                    config.supervised_inputs[idx].config.shortInput.minValue = 0;
                    config.supervised_inputs[idx].config.shortInput.maxValue = 0;
                    config.supervised_inputs[idx].config.openInput.minValue  = 0;
                    config.supervised_inputs[idx].config.openInput.maxValue  = 0;
                    config.supervised_inputs[idx].config.onInput.minValue    = 0;
                    config.supervised_inputs[idx].config.onInput.maxValue    = 0;
                    config.supervised_inputs[idx].config.offInput.minValue   = 0;
                    config.supervised_inputs[idx].config.offInput.maxValue   = 0;
                }
            }

            Console.WriteLine("Trying to set input configuration.");
            BS2ErrorCode result = (BS2ErrorCode)API.BS2_SetInputConfig(sdkContext, deviceID, ref config);

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }
            else
            {
                Console.WriteLine("Set InputConfig Succeeded");
            }
        }
Example #4
0
        public void setVoipConfig(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            BS2VoipConfig config = Util.AllocateStructure <BS2VoipConfig>();

            string url = "192.168.0.1";

            byte[] str = Encoding.UTF8.GetBytes(url);
            Array.Clear(config.serverUrl, 0, BS2Envirionment.BS2_URL_SIZE);
            Array.Copy(str, 0, config.serverUrl, 0, str.Length);

            config.serverPort = 5061;

            string userId = "홍길동";

            byte[] str2 = Encoding.UTF8.GetBytes(userId);
            Array.Clear(config.userID, 0, BS2Envirionment.BS2_USER_ID_SIZE);
            Array.Copy(str2, 0, config.userID, 0, str2.Length);

            string pwd = "123456";

            byte[] str3 = Encoding.UTF8.GetBytes(pwd);
            Array.Clear(config.userPW, 0, BS2Envirionment.BS2_USER_ID_SIZE);
            Array.Copy(str3, 0, config.userPW, 0, str3.Length);

            config.bUse       = 1;
            config.dtmfMode   = 0;
            config.exitButton = 1;

            config.numPhonBook = 2;
            string phoneNumber = "010-1234-5678";

            byte[] str4 = Encoding.UTF8.GetBytes(phoneNumber);
            Array.Clear(config.phonebook[0].phoneNumber, 0, BS2Envirionment.BS2_USER_ID_SIZE);
            Array.Copy(str4, 0, config.phonebook[0].phoneNumber, 0, str4.Length);

            string descript = "홍길동 나아가신다.";

            byte[] str5 = Encoding.UTF8.GetBytes(descript);
            Array.Clear(config.phonebook[0].descript, 0, BS2Envirionment.BS2_MAX_DESCRIPTION_NAME_LEN);
            Array.Copy(str5, 0, config.phonebook[0].descript, 0, str5.Length);

            string phoneNumber2 = "010-9874-1234";

            byte[] str6 = Encoding.UTF8.GetBytes(phoneNumber2);
            Array.Clear(config.phonebook[1].phoneNumber, 0, BS2Envirionment.BS2_USER_ID_SIZE);
            Array.Copy(str6, 0, config.phonebook[1].phoneNumber, 0, str6.Length);

            string descript2 = "사임당 나아가신다.";

            byte[] str7 = Encoding.UTF8.GetBytes(descript2);
            Array.Clear(config.phonebook[1].descript, 0, BS2Envirionment.BS2_MAX_DESCRIPTION_NAME_LEN);
            Array.Copy(str7, 0, config.phonebook[1].descript, 0, str7.Length);


            Console.WriteLine("Trying to set Voip configuration.");
            BS2ErrorCode result = (BS2ErrorCode)API.BS2_SetVoipConfig(sdkContext, deviceID, ref config);

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
            }
        }
Example #5
0
        public void getAuthGroup(IntPtr sdkContext, uint deviceID, bool isMasterDevice)
        {
            IntPtr       authGroupObj = IntPtr.Zero;
            UInt32       numAuthGroup = 0;
            BS2ErrorCode result       = BS2ErrorCode.BS_SDK_SUCCESS;

            Console.WriteLine("Do you want to get all auth groups? [Y/n]");
            Console.Write(">>>> ");
            if (Util.IsYes())
            {
                Console.WriteLine("Trying to get all auth gruops from device.");
                result = (BS2ErrorCode)API.BS2_GetAllAuthGroup(sdkContext, deviceID, out authGroupObj, out numAuthGroup);
            }
            else
            {
                Console.WriteLine("Enter the ID of the access group which you want to get: [ID_1,ID_2 ...]");
                Console.Write(">>>> ");
                char[]        delimiterChars  = { ' ', ',', '.', ':', '\t' };
                string[]      authGroupIDs    = Console.ReadLine().Split(delimiterChars);
                List <UInt32> authGroupIDList = new List <UInt32>();

                foreach (string authGroupID in authGroupIDs)
                {
                    if (authGroupID.Length > 0)
                    {
                        UInt32 item;
                        if (UInt32.TryParse(authGroupID, out item))
                        {
                            authGroupIDList.Add(item);
                        }
                    }
                }

                if (authGroupIDList.Count > 0)
                {
                    IntPtr authGroupIDObj    = Marshal.AllocHGlobal(4 * authGroupIDList.Count);
                    IntPtr curAuthGroupIDObj = authGroupIDObj;
                    foreach (UInt32 item in authGroupIDList)
                    {
                        Marshal.WriteInt32(curAuthGroupIDObj, (Int32)item);
                        curAuthGroupIDObj = (IntPtr)((long)curAuthGroupIDObj + 4);
                    }

                    Console.WriteLine("Trying to get auth gruops from device.");
                    result = (BS2ErrorCode)API.BS2_GetAuthGroup(sdkContext, deviceID, authGroupIDObj, (UInt32)authGroupIDList.Count, out authGroupObj, out numAuthGroup);

                    Marshal.FreeHGlobal(authGroupIDObj);
                }
                else
                {
                    Console.WriteLine("Invalid parameter");
                }
            }

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
            }
            else if (numAuthGroup > 0)
            {
                IntPtr curAuthGroupObj = authGroupObj;
                int    structSize      = Marshal.SizeOf(typeof(BS2AuthGroup));

                for (int idx = 0; idx < numAuthGroup; ++idx)
                {
                    BS2AuthGroup item = (BS2AuthGroup)Marshal.PtrToStructure(curAuthGroupObj, typeof(BS2AuthGroup));
                    print(sdkContext, item);
                    curAuthGroupObj = (IntPtr)((long)curAuthGroupObj + structSize);
                }

                API.BS2_ReleaseObject(authGroupObj);
            }
            else
            {
                Console.WriteLine(">>> There is no auth group in the device.");
            }
        }
Example #6
0
        void syncLocalAndDeviceLog(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            UInt32 lastEventId = 0;
            string dbPath      = "Data Source=log.db";

            SQLiteConnection connection = new SQLiteConnection(dbPath);

            connection.Open();

            SQLiteCommand cmd = new SQLiteCommand("CREATE TABLE IF NOT EXISTS log (id int PRIMARY KEY, dateTime int, deviceID int, code int, msg text)", connection);

            cmd.ExecuteNonQuery();

            cmd.CommandText = "SELECT * FROM log ORDER BY id DESC LIMIT 1";
            SQLiteDataReader rdr = cmd.ExecuteReader();

            if (rdr.Read())
            {
                lastEventId = Convert.ToUInt32(rdr["id"]);
            }
            rdr.Close();

            Console.WriteLine("lastEventId[{0}]", lastEventId);

            const UInt32 logPageSize     = 1024;
            int          structSize      = Marshal.SizeOf(typeof(BS2Event));
            bool         runnging        = false;
            IntPtr       outEventLogObjs = IntPtr.Zero;
            UInt32       outNumEventLogs = 0;

            cmd.CommandText = "INSERT INTO log (Id, dateTime, deviceID, code, msg) VALUES (@IdParam, @dateTimeParam, @deviceIDParam, @codeParam, @msgParam)";

            do
            {
                Console.WriteLine("Get logs from device[{0}] lastEventId[{1}].", deviceID, lastEventId);
                BS2ErrorCode result = (BS2ErrorCode)API.BS2_GetLog(sdkContext, deviceID, lastEventId, logPageSize, out outEventLogObjs, out outNumEventLogs);
                if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                {
                    Console.WriteLine("Got error({0}).", result);
                    break;
                }

                if (outNumEventLogs > 0)
                {
                    IntPtr curEventLogObjs = outEventLogObjs;

                    SQLiteTransaction transaction = connection.BeginTransaction();
                    for (int idx = 0; idx < outNumEventLogs; idx++)
                    {
                        BS2Event eventLog = (BS2Event)Marshal.PtrToStructure(curEventLogObjs, typeof(BS2Event));
                        Console.WriteLine(">>> Insert log[{0}] into database.", eventLog.id);
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("@IdParam", eventLog.id);
                        cmd.Parameters.AddWithValue("@dateTimeParam", eventLog.dateTime);
                        cmd.Parameters.AddWithValue("@deviceIDParam", eventLog.deviceID);
                        cmd.Parameters.AddWithValue("@codeParam", eventLog.code);
                        cmd.Parameters.AddWithValue("@msgParam", Util.GetLogMsg(eventLog));
                        cmd.ExecuteNonQuery();
                        curEventLogObjs = (IntPtr)((long)curEventLogObjs + structSize);
                        lastEventId     = eventLog.id;
                    }

                    transaction.Commit();

                    API.BS2_ReleaseObject(outEventLogObjs);
                }

                if (outNumEventLogs < logPageSize)
                {
                    runnging = false;
                }
            }while (runnging);

            connection.Close();
        }
Example #7
0
        void getFilteredLog(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            Type   structureType   = typeof(BS2Event);
            int    structSize      = Marshal.SizeOf(structureType);
            IntPtr uid             = IntPtr.Zero;
            UInt16 eventCode       = 0;
            UInt32 start           = 0;
            UInt32 end             = 0;
            byte   tnaKey          = 0;
            IntPtr outEventLogObjs = IntPtr.Zero;
            UInt32 outNumEventLogs = 0;

            Console.WriteLine("Which event do you want to get? [0: All]");
            Console.Write(">>>> ");
            eventCode = Util.GetInput((UInt16)0);

            Console.WriteLine("When do you want to get the log from? [yyyy-MM-dd HH:mm:ss]");
            Console.Write(">>>> ");
            if (!Util.GetTimestamp("yyyy-MM-dd HH:mm:ss", 0, out start))
            {
                return;
            }

            Console.WriteLine("When do you want to get the log to? [yyyy-MM-dd HH:mm:ss]");
            Console.Write(">>>> ");
            if (!Util.GetTimestamp("yyyy-MM-dd HH:mm:ss", 0, out end))
            {
                return;
            }

            Console.WriteLine("Which tnaKey do you want to get? [0: All(default), 1-16]");
            Console.Write(">>>> ");
            tnaKey = Util.GetInput(0);

            if (tnaKey > BS2Envirionment.BS2_MAX_TNA_KEY)
            {
                Console.WriteLine("Invalid tnaKey : {0}", tnaKey);
                return;
            }

            Console.WriteLine("Which user do you want to the log for? [userID]");
            Console.Write(">>>> ");
            string userIDStr = Console.ReadLine();

            if (userIDStr.Length > 0)
            {
                byte[] uidArray    = Encoding.ASCII.GetBytes(userIDStr);
                byte[] outUidArray = new byte[BS2Envirionment.BS2_USER_ID_SIZE];

                uid = Marshal.AllocHGlobal(BS2Envirionment.BS2_USER_ID_SIZE);
                for (int idx = 0; idx < BS2Envirionment.BS2_USER_ID_SIZE; idx++)
                {
                    outUidArray[idx] = 0;
                }

                Array.Copy(uidArray, outUidArray, uidArray.Length);
                Marshal.Copy(outUidArray, 0, uid, BS2Envirionment.BS2_USER_ID_SIZE);
            }

            BS2ErrorCode result = (BS2ErrorCode)API.BS2_GetFilteredLog(sdkContext, deviceID, uid, eventCode, start, end, tnaKey, out outEventLogObjs, out outNumEventLogs);

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
            }
            else if (outNumEventLogs > 0)
            {
                IntPtr curEventLogObjs = outEventLogObjs;
                for (int idx = 0; idx < outNumEventLogs; idx++)
                {
                    BS2Event eventLog = (BS2Event)Marshal.PtrToStructure(curEventLogObjs, structureType);
                    Console.WriteLine(Util.GetLogMsg(eventLog));
                    curEventLogObjs = (IntPtr)((long)curEventLogObjs + structSize);
                }

                API.BS2_ReleaseObject(outEventLogObjs);
            }
            else
            {
                Console.WriteLine("There are no matching logs.");
            }

            if (uid != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(uid);
            }
        }
Example #8
0
        void getLogBlob(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            const UInt32 defaultLogPageSize = 1024;
            Type         structureType      = typeof(BS2EventBlob);
            int          structSize         = Marshal.SizeOf(structureType);
            bool         getAllLog          = false;
            UInt32       lastEventId        = 0;
            UInt32       amount;
            IntPtr       outEventLogObjs = IntPtr.Zero;
            UInt32       outNumEventLogs = 0;

            cbOnLogReceived = new API.OnLogReceived(NormalLogReceived);

            Console.WriteLine("What is the ID of the last log which you have? [0: None]");
            Console.Write(">>>> ");
            lastEventId = Util.GetInput((UInt32)0);
            Console.WriteLine("How many logs do you want to get? [0: All]");
            Console.Write(">>>> ");
            amount = Util.GetInput((UInt32)0);

            if (amount == 0)
            {
                getAllLog = true;
                amount    = defaultLogPageSize;
            }

            do
            {
                outEventLogObjs = IntPtr.Zero;
                BS2ErrorCode result = (BS2ErrorCode)API.BS2_GetLogBlob(sdkContext, deviceID, (ushort)BS2EventMaskEnum.JOB_CODE, lastEventId, amount, out outEventLogObjs, out outNumEventLogs);
                if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                {
                    Console.WriteLine("Got error({0}).", result);
                    break;
                }

                if (outNumEventLogs > 0)
                {
                    IntPtr curEventLogObjs = outEventLogObjs;
                    for (UInt32 idx = 0; idx < outNumEventLogs; idx++)
                    {
                        BS2EventBlob eventLog = (BS2EventBlob)Marshal.PtrToStructure(curEventLogObjs, structureType);


                        DateTime eventTime = Util.ConvertFromUnixTimestamp(eventLog.info.dateTime);

                        byte[] userID = new byte[BS2Envirionment.BS2_USER_ID_SIZE];
                        Array.Clear(userID, 0, BS2Envirionment.BS2_USER_ID_SIZE);
                        Array.Copy(eventLog.objectID, userID, userID.Length);

                        Console.WriteLine("Got log(idx[{0}], timestamp[{1}], event id[{2}], userID[{3}], jobcode[{4}])."
                                          , idx
                                          , eventTime.ToString("yyyy-MM-dd HH:mm:ss")
                                          , eventLog.id
                                          , System.Text.Encoding.ASCII.GetString(userID).TrimEnd('\0')
                                          , eventLog.jobCode);


                        curEventLogObjs += structSize;
                        lastEventId      = eventLog.id;
                    }

                    API.BS2_ReleaseObject(outEventLogObjs);
                }

                if (outNumEventLogs < defaultLogPageSize)
                {
                    break;
                }
            }while (getAllLog);
        }
Example #9
0
        void getImageLog(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            BS2SimpleDeviceInfo deviceInfo;
            int            structSize        = Marshal.SizeOf(typeof(BS2Event));
            UInt16         imageLogEventCode = (UInt16)BS2EventCodeEnum.DEVICE_TCP_CONNECTED;
            BS2EventConfig eventConfig       = Util.AllocateStructure <BS2EventConfig>();

            eventConfig.numImageEventFilter = 1;
            eventConfig.imageEventFilter[0].mainEventCode = (byte)(imageLogEventCode >> 8);
            eventConfig.imageEventFilter[0].scheduleID    = (UInt32)BS2ScheduleIDEnum.ALWAYS;

            Console.WriteLine("Trying to get the device[{0}] information.", deviceID);
            BS2ErrorCode result = (BS2ErrorCode)API.BS2_GetDeviceInfo(sdkContext, deviceID, out deviceInfo);

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Can't get device information(errorCode : {0}).", result);
                return;
            }

            Console.WriteLine("Trying to activate image log.");
            result = (BS2ErrorCode)API.BS2_SetEventConfig(sdkContext, deviceID, ref eventConfig);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }

            Console.WriteLine("Trying to clear log for quick test.");
            result = (BS2ErrorCode)API.BS2_ClearLog(sdkContext, deviceID);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }

            Console.WriteLine("Trying to disconnect device[{0}] for quick test.", deviceID);
            result = (BS2ErrorCode)API.BS2_DisconnectDevice(sdkContext, deviceID);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }

            Thread.Sleep(500); //waiting for socket close

            Console.WriteLine("Trying to connect device[{0}].", deviceID);
            result = (BS2ErrorCode)API.BS2_ConnectDeviceViaIP(sdkContext, new IPAddress(BitConverter.GetBytes(deviceInfo.ipv4Address)).ToString(), deviceInfo.port, out deviceID);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }

            IntPtr outEventLogObjs = IntPtr.Zero;
            UInt32 outNumEventLogs = 0;

            result = (BS2ErrorCode)API.BS2_GetLog(sdkContext, deviceID, 0, 1024, out outEventLogObjs, out outNumEventLogs);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }

            if (outNumEventLogs > 0)
            {
                IntPtr curEventLogObjs = outEventLogObjs;
                for (int idx = 0; idx < outNumEventLogs; idx++)
                {
                    BS2Event eventLog = (BS2Event)Marshal.PtrToStructure(curEventLogObjs, typeof(BS2Event));
                    if (Convert.ToBoolean(eventLog.image))
                    {
                        Console.WriteLine("Trying to get image log[{0}].", eventLog.id);

                        IntPtr imageObj  = IntPtr.Zero;
                        UInt32 imageSize = 0;

                        result = (BS2ErrorCode)API.BS2_GetImageLog(sdkContext, deviceID, eventLog.id, out imageObj, out imageSize);
                        if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                        {
                            Console.WriteLine("Got error({0}).", result);
                        }
                        else
                        {
                            int        written = 0;
                            FileStream file    = new FileStream(String.Format("{0}.jpg", eventLog.id), FileMode.Create, FileAccess.Write);

                            Console.WriteLine("Trying to save image log[{0}].", eventLog.id);
                            WriteFile(file.Handle, imageObj, (int)imageSize, out written, IntPtr.Zero);
                            file.Close();

                            if (written != imageSize)
                            {
                                Console.WriteLine("Got error({0}).", result);
                            }
                            else
                            {
                                Console.WriteLine("Successfully saved the image log[{0}].", eventLog.id);
                                Process.Start(file.Name);
                            }
                        }
                        break;
                    }

                    curEventLogObjs = (IntPtr)((long)curEventLogObjs + structSize);
                }

                API.BS2_ReleaseObject(outEventLogObjs);
            }

            eventConfig.numImageEventFilter = 0;

            Console.WriteLine("Trying to deactivate image log.");
            result = (BS2ErrorCode)API.BS2_SetEventConfig(sdkContext, deviceID, ref eventConfig);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }
        }
Example #10
0
        public void setCardConfig(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            BS2FactoryConfig factoryConfig;

            Console.WriteLine("Trying to get factory config");
            BS2ErrorCode result = (BS2ErrorCode)API.BS2_GetFactoryConfig(sdkContext, deviceID, out factoryConfig);

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }

            UInt16 cardModel = 0;
            IntPtr ptrModel  = Marshal.StringToHGlobalAnsi(Encoding.UTF8.GetString(factoryConfig.modelName).TrimEnd('\0'));

            result = (BS2ErrorCode)API.BS2_GetCardModel(ptrModel, out cardModel);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
                return;
            }

            BS2CardConfig cardConfig = Util.AllocateStructure <BS2CardConfig>();

            Console.WriteLine("Choose byte order: [0: MSB(default), 1: LSB]");
            Console.Write(">>>> ");
            cardConfig.byteOrder = Util.GetInput((byte)BS2CardByteOrderEnum.MSB);
            Console.WriteLine("Do you want to use wiegand format? [y/N]");
            Console.Write(">>>> ");
            if (Util.IsNo())
            {
                cardConfig.useWiegandFormat = 0;
            }
            else
            {
                cardConfig.useWiegandFormat = 1;
            }

            BS2CardModelEnum cardModelEnum = (BS2CardModelEnum)cardModel;

            if (cardModelEnum == BS2CardModelEnum.OMPW || cardModelEnum == BS2CardModelEnum.OIPW)
            {
                Console.WriteLine("Enter the card format id [0(default)]");
                Console.Write(">>>> ");
                cardConfig.formatID = Util.GetInput((UInt32)0);

                Console.WriteLine("Choose card data type: [0: Binary(default), 1: ASCII, 2: UTF16, 3: BCD]");
                Console.Write(">>>> ");
                cardConfig.dataType = Util.GetInput((byte)BS2CardDataTypeEnum.BINARY);
                Console.WriteLine("Do you want to use secondary key? [y/N]");
                Console.Write(">>>> ");
                if (Util.IsNo())
                {
                    cardConfig.useSecondaryKey = 0;
                }
                else
                {
                    cardConfig.useSecondaryKey = 1;
                }

                if (cardModelEnum == BS2CardModelEnum.OMPW) // mifare card
                {
                    Console.WriteLine("Enter the start block index for mifare card [0(default)]");
                    Console.Write(">>>> ");
                    cardConfig.mifare.startBlockIndex = Util.GetInput((UInt16)0);
                    Console.WriteLine("Enter the hexadecimal primary key for mifare card. [KEY1-KEY2-...-KEY6]");
                    Console.Write(">>>> ");
                    enterSmartcardKey(cardConfig.mifare.primaryKey);
                    Console.WriteLine("Enter the hexadecimal secondary key for mifare card. [KEY1-KEY2-...-KEY6]");
                    Console.Write(">>>> ");
                    enterSmartcardKey(cardConfig.mifare.secondaryKey);

                    Console.WriteLine("Enter the app id for desfire card. [ID1-ID2-ID3]");
                    Console.Write(">>>> ");
                    enterSmartcardKey(cardConfig.desfire.appID);
                    Console.WriteLine("Enter the file id for desfire card [0(default)]");
                    Console.Write(">>>> ");
                    cardConfig.desfire.fileID = Util.GetInput((byte)0);

#if false //Not yet implemented
                    Console.WriteLine("Enter the encryption type for desfire card [0: DES(default), 1: AES]");
                    Console.Write(">>>> ");
                    cardConfig.desfire.encryptionType = Util.GetInput((byte)0);
#else
                    cardConfig.desfire.encryptionType = 0;
#endif
                    Console.WriteLine("Enter the hexadecimal primary key for desfire card. [KEY1-KEY2-...-KEY16]");
                    Console.Write(">>>> ");
                    enterSmartcardKey(cardConfig.desfire.primaryKey);
                    Console.WriteLine("Enter the hexadecimal secondary key for desfire card. [KEY1-KEY2-...-KEY16]");
                    Console.Write(">>>> ");
                    enterSmartcardKey(cardConfig.desfire.secondaryKey);
                }
                else // iclass card
                {
                    Console.WriteLine("Enter the start block index for iclass card [0(default)]");
                    Console.Write(">>>> ");
                    cardConfig.iclass.startBlockIndex = Util.GetInput((UInt16)0);
                    Console.WriteLine("Enter the hexadecimal primary key for iclass card. [KEY1-KEY2-...-KEY8]");
                    Console.Write(">>>> ");
                    enterSmartcardKey(cardConfig.iclass.primaryKey);
                    Console.WriteLine("Enter the hexadecimal secondary key for iclass card. [KEY1-KEY2-...-KEY8]");
                    Console.Write(">>>> ");
                    enterSmartcardKey(cardConfig.iclass.secondaryKey);
                }
            }

            Console.WriteLine("Trying to set card configuration.");
            result = (BS2ErrorCode)API.BS2_SetCardConfig(sdkContext, deviceID, ref cardConfig);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Got error({0}).", result);
            }
        }
Example #11
0
        public void removeBlacklist(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            BS2ErrorCode result = BS2ErrorCode.BS_SDK_SUCCESS;

            Console.WriteLine("Do you want to remove all blacklist? [Y/n]");
            Console.Write(">>>> ");
            if (Util.IsYes())
            {
                Console.WriteLine("Trying to remove all blacklist from device.");
                result = (BS2ErrorCode)API.BS2_RemoveAllBlackList(sdkContext, deviceID);
            }
            else
            {
                IntPtr blacklistObj;
                UInt32 numBlacklist;

                Console.WriteLine("Trying to get blacklists from device.");
                result = (BS2ErrorCode)API.BS2_GetAllBlackList(sdkContext, deviceID, out blacklistObj, out numBlacklist);
                if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                {
                    Console.WriteLine("Got error({0}).", result);
                }
                else if (numBlacklist > 0)
                {
                    List <BS2BlackList> blackList = new List <BS2BlackList>();
                    IntPtr curBlacklistObj        = blacklistObj;
                    int    structSize             = Marshal.SizeOf(typeof(BS2BlackList));

                    for (int idx = 0; idx < numBlacklist; ++idx)
                    {
                        BS2BlackList item = (BS2BlackList)Marshal.PtrToStructure(curBlacklistObj, typeof(BS2BlackList));
                        blackList.Add(item);
                        curBlacklistObj = (IntPtr)((long)curBlacklistObj + structSize);
                    }

                    Console.WriteLine("+----------------------------------------------------------------------------------------------------------+");
                    for (int idx = 0; idx < numBlacklist; ++idx)
                    {
                        Console.WriteLine("[{0:000}] ==> Blacklist issueCount[{0}] cardID[{1}-{2}-{3}-{4}-{5}-{6}-{7}-{8}]",
                                          idx,
                                          blackList[idx].issueCount,
                                          blackList[idx].cardID[BS2Environment.BS2_CARD_DATA_SIZE - 1],
                                          blackList[idx].cardID[BS2Environment.BS2_CARD_DATA_SIZE - 2],
                                          blackList[idx].cardID[BS2Environment.BS2_CARD_DATA_SIZE - 3],
                                          blackList[idx].cardID[BS2Environment.BS2_CARD_DATA_SIZE - 4],
                                          blackList[idx].cardID[BS2Environment.BS2_CARD_DATA_SIZE - 5],
                                          blackList[idx].cardID[BS2Environment.BS2_CARD_DATA_SIZE - 6],
                                          blackList[idx].cardID[BS2Environment.BS2_CARD_DATA_SIZE - 7],
                                          blackList[idx].cardID[BS2Environment.BS2_CARD_DATA_SIZE - 8]);
                    }
                    Console.WriteLine("+----------------------------------------------------------------------------------------------------------+");
                    Console.WriteLine("Enter the index of the blacklist which you want to remove: [INDEX_1,INDEX_2 ...]");
                    Console.Write(">>>> ");
                    char[]        delimiterChars  = { ' ', ',', '.', ':', '\t' };
                    string[]      blackListIndexs = Console.ReadLine().Split(delimiterChars);
                    HashSet <int> blackListSet    = new HashSet <int>();

                    if (blackListIndexs.Length == 0)
                    {
                        Console.WriteLine("Invalid parameter.");
                    }
                    else
                    {
                        foreach (string index in blackListIndexs)
                        {
                            if (index.Length > 0)
                            {
                                UInt32 item;
                                if (UInt32.TryParse(index, out item))
                                {
                                    if (item < numBlacklist)
                                    {
                                        blackListSet.Add((int)item);
                                    }
                                }
                            }
                        }

                        if (blackListSet.Count > 0)
                        {
                            foreach (int index in blackListSet)
                            {
                                Marshal.StructureToPtr(blackList[index], blacklistObj + structSize, false);
                            }

                            Console.WriteLine("Trying to remove blacklist from device.");
                            result = (BS2ErrorCode)API.BS2_RemoveBlackList(sdkContext, deviceID, blacklistObj, (UInt32)blackListSet.Count);
                            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                            {
                                Console.WriteLine("Got error({0}).", result);
                            }
                        }
                    }

                    API.BS2_ReleaseObject(blacklistObj);
                }
                else
                {
                    Console.WriteLine(">>> There is no blacklist in the device.");
                }
            }
        }
Example #12
0
        public void writeCard(IntPtr sdkContext, UInt32 deviceID, bool isMasterDevice)
        {
            BS2SimpleDeviceInfo deviceInfo;
            BS2SmartCardData    smartCard = Util.AllocateStructure <BS2SmartCardData>();

            BS2ErrorCode result = (BS2ErrorCode)API.BS2_GetDeviceInfo(sdkContext, deviceID, out deviceInfo);

            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Can't get device information(errorCode : {0}).", result);
                return;
            }

            Console.WriteLine("choose the format for the card: [2: SecureCredential(default), 3: AccessOn]");
            Console.Write(">>>> ");
            smartCard.header.cardType = Util.GetInput((byte)BS2CardTypeEnum.SECURE);

            if (Convert.ToBoolean(deviceInfo.pinSupported))
            {
                Console.WriteLine("Do you want to set pin code? [y/N]");
                Console.Write(">>>> ");
                if (!Util.IsNo())
                {
                    Console.WriteLine("Enter the pin code which you want to set");
                    Console.Write(">>>> ");
                    string pinCodeStr = Console.ReadLine();
                    IntPtr pinChar    = Marshal.StringToHGlobalAnsi(pinCodeStr);
                    IntPtr pinCode    = Marshal.AllocHGlobal(BS2Environment.BS2_PIN_HASH_SIZE);
                    //result = (BS2ErrorCode)API.BS2_MakePinCode(sdkContext, pinCodeStr, pinCode);
                    result = (BS2ErrorCode)API.BS2_MakePinCode(sdkContext, pinChar, pinCode);

                    if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                    {
                        Console.WriteLine("Got error({0}).", result);
                        Marshal.FreeHGlobal(pinCode);
                        return;
                    }

                    Marshal.Copy(pinCode, smartCard.credentials.pin, 0, BS2Environment.BS2_PIN_HASH_SIZE);
                    Marshal.FreeHGlobal(pinChar);
                    Marshal.FreeHGlobal(pinCode);
                }
            }

            if (Convert.ToBoolean(deviceInfo.fingerSupported))
            {
                Console.WriteLine("How many fingerprint templates do you want to set? [0(default)-{0}]", BS2Environment.BS2_SMART_CARD_MAX_TEMPLATE_COUNT);
                Console.Write(">>>> ");
                smartCard.header.numOfTemplate = Util.GetInput((byte)0);
            }
            else
            {
                smartCard.header.numOfTemplate = 0;
            }

            Array.Clear(smartCard.credentials.templateData, 0, BS2Environment.BS2_SMART_CARD_MAX_TEMPLATE_COUNT * BS2Environment.BS2_FINGER_TEMPLATE_SIZE);
            if (smartCard.header.numOfTemplate > 0)
            {
                Console.WriteLine("Enter the size of template which you want to set. [{0}(default)-{1}]", BS2Environment.BS2_SMART_CARD_MIN_TEMPLATE_SIZE, BS2Environment.BS2_FINGER_TEMPLATE_SIZE);
                Console.Write(">>>> ");
                smartCard.header.templateSize = Util.GetInput((UInt16)BS2Environment.BS2_SMART_CARD_MIN_TEMPLATE_SIZE);

                BS2Fingerprint fingerprint = Util.AllocateStructure <BS2Fingerprint>();
                fingerprint.index = 0;

                UInt32 outquality;
                for (byte idx = 0; idx < smartCard.header.numOfTemplate; ++idx)
                {
                    Console.WriteLine("Place your finger on the device for fingerprint template[{0}] extraction", idx);
                    result = (BS2ErrorCode)API.BS2_ScanFingerprintEx(sdkContext, deviceID, ref fingerprint, 0, (UInt32)BS2FingerprintQualityEnum.QUALITY_STANDARD, (byte)BS2FingerprintTemplateFormatEnum.FORMAT_SUPREMA, out outquality, null);
                    if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                    {
                        if (result == BS2ErrorCode.BS_SDK_ERROR_EXTRACTION_LOW_QUALITY || result == BS2ErrorCode.BS_SDK_ERROR_CAPTURE_LOW_QUALITY)
                        {
                            Console.WriteLine("Bad fingerprint quality. Tty agin.");
                            continue;
                        }
                        else
                        {
                            Console.WriteLine("Got error({0}).", result);
                            return;
                        }
                    }

                    Array.Copy(fingerprint.data, 0, smartCard.credentials.templateData, idx * smartCard.header.templateSize, smartCard.header.templateSize);
                }

                Console.WriteLine("Is it duress finger? [0 : Normal(default), 1 : Duress]");
                Console.Write(">>>> ");
                smartCard.header.duressMask = Util.GetInput((byte)BS2FingerprintFlagEnum.NORMAL);
            }
            else
            {
                smartCard.header.templateSize = (UInt16)BS2Environment.BS2_SMART_CARD_MIN_TEMPLATE_SIZE;
                smartCard.header.duressMask   = (byte)BS2FingerprintFlagEnum.NORMAL;
            }

            Console.WriteLine("Enter the issue count which you want to set");
            Console.Write(">>>> ");
            smartCard.header.issueCount = (UInt16)Util.GetInput();

            Console.WriteLine("Enter the card id which you want to write on the card");
            Console.Write(">>>> ");

            UInt64 cardID    = 0;
            string cardIDStr = Console.ReadLine();

            if (cardIDStr.Length > BS2Environment.BS2_CARD_DATA_SIZE)
            {
                Console.WriteLine("Card id should less than {0} words.", BS2Environment.BS2_CARD_DATA_SIZE);
                return;
            }
            else if (!UInt64.TryParse(cardIDStr, out cardID) || cardID == 0)
            {
                Console.WriteLine("Invalid card id");
                return;
            }
            else
            {
                byte[] cardIDArray = BitConverter.GetBytes(cardID);
                if (!BitConverter.IsLittleEndian)
                {
                    Array.Reverse(cardIDArray);
                }

                Array.Clear(smartCard.cardID, 0, BS2Environment.BS2_CARD_DATA_SIZE);

                for (int idx = 0; idx < cardIDArray.Length; ++idx)
                {
                    smartCard.cardID[BS2Environment.BS2_CARD_DATA_SIZE - idx - 1] = cardIDArray[idx];
                }
            }

            if ((BS2CardTypeEnum)smartCard.header.cardType == BS2CardTypeEnum.ACCESS)
            {
                Console.WriteLine("Enter the ID of the access group which you want to remove: [ID_1,ID_2 ...]");
                Console.Write(">>>> ");
                char[]   delimiterChars = { ' ', ',', '.', ':', '\t' };
                string[] accessGroupIDs = Console.ReadLine().Split(delimiterChars);
                int      idx            = 0;
                Array.Clear(smartCard.accessOnData.accessGroupID, 0, BS2Environment.BS2_SMART_CARD_MAX_ACCESS_GROUP_COUNT);

                foreach (string accessGroupID in accessGroupIDs)
                {
                    if (accessGroupID.Length > 0)
                    {
                        UInt16 item;
                        if (UInt16.TryParse(accessGroupID, out item))
                        {
                            smartCard.accessOnData.accessGroupID[idx++] = item;
                            if (idx >= BS2Environment.BS2_SMART_CARD_MAX_ACCESS_GROUP_COUNT)
                            {
                                break;
                            }
                        }
                    }
                }

                Console.WriteLine("Enter start time which you want to set. [default(Today), yyyy-MM-dd HH:mm:ss]");
                Console.Write(">>>> ");
                if (!Util.GetTimestamp("yyyy-MM-dd HH:mm:ss", 0, out smartCard.accessOnData.startTime))
                {
                    return;
                }

                Console.WriteLine("Enter end time which you want to set. [default(Today), yyyy-MM-dd HH:mm:ss]");
                Console.Write(">>>> ");
                if (!Util.GetTimestamp("yyyy-MM-dd HH:mm:ss", 0, out smartCard.accessOnData.endTime))
                {
                    return;
                }

                // card auth mode
                //Console.WriteLine("Enter card authentication mode which you want to set:");
                //Console.WriteLine(" [2: Card only, 3: Card+Biometric, 4: Card+PIN, 5: Card+Biometric/PIN, 6: Card+Biometric+PIN]");
                //Console.Write(">>>> ");
                //smartCard.header.cardAuthMode = Util.GetInput((byte)BS2CardAuthModeEnum.NONE);
            }

            result = computeCRC(smartCard, out smartCard.header.hdrCRC, out smartCard.header.cardCRC);
            if (result != BS2ErrorCode.BS_SDK_SUCCESS)
            {
                Console.WriteLine("Can't compute CRC16({0})", result);
            }
            else
            {
                Console.WriteLine("Trying to write card.");
                result = (BS2ErrorCode)API.BS2_WriteCard(sdkContext, deviceID, ref smartCard);
                if (result != BS2ErrorCode.BS_SDK_SUCCESS)
                {
                    Console.WriteLine("Got error({0}).", result);
                }
            }
        }