/// <summary>
        /// Toggle Lighting State
        /// </summary>
        /// <param name="fiDeviceID"></param>
        /// <param name="fbToggleStatus"></param>
        private void ToggleLutronLight(int fiDeviceID, bool fbToggleStatus)
        {
            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices
                                           .Where(x => x.device_id == fiDeviceID &&
                                                  x.object_instance == (int?)LutronObjectType.Lighting_State)
                                           .Select(x => x).FirstOrDefault();

                if (loBACnetDeviceDetail != null && loBACnetDeviceDetail.object_instance != null)
                {
                    BacnetAddress loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id);
                    loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net);

                    IList <BacnetValue> loBacnetValueList;
                    moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_BINARY_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, out loBacnetValueList);


                    BacnetValue   loBacnetNewValue = new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_ENUMERATED, fbToggleStatus == true ? 1 : 0);
                    BacnetValue[] loWriteValue     = { loBacnetNewValue };

                    moBacnetClient.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_BINARY_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, loWriteValue);

                    //BacnetValue[] loNewBacnetValue = { new BacnetValue(Convert.ToSingle(111)) };

                    ////bacnet_client.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_BINARY_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_ACTION, loNewBacnetValue);
                    ////bacnet_client.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_INPUT, 0), BacnetPropertyIds.PROP_PRESENT_VALUE, loNewBacnetValue);
                    //bacnet_client.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_INPUT, 0), BacnetPropertyIds.PROP_PRESENT_VALUE, loNewBacnetValue);
                }
            }

            //bool ret = WriteScalarValue(1, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, 2), BacnetPropertyIds.PROP_PRESENT_VALUE, loNewValue);
        }
        /// <summary>
        /// Get current lightlign level from simulator will be between 1 to 100
        /// </summary>
        /// <param name="fiDeviceID"></param>
        /// <returns></returns>
        private string GetLutronLightLevel(Int32 fiDeviceID)
        {
            IList <BacnetValue> loBacnetValueList;

            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices
                                           .Where(x => x.device_id == fiDeviceID &&
                                                  x.object_instance == (int?)LutronObjectType.Lighting_Level)
                                           .Select(x => x).FirstOrDefault();


                BacnetAddress loBacnetAddress;
                loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id);
                loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net);

                moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, out loBacnetValueList);
            }

            if (loBacnetValueList != null && loBacnetValueList.Count > 0)
            {
                return(loBacnetValueList[0].Value.ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
        public void FillAvailableDevicesForSchedule()
        {
            var loAvailableDevices = new BindingList <KeyValuePair <string, string> >();

            loAvailableDevices.Add(new KeyValuePair <string, string>("-1", "Select device"));

            using (var loDataContext = new ESDLutronEntities())
            {
                var loDeviceList = loDataContext
                                   .BACnetDevices
                                   .Where(x => x.object_type == LutronFloorObjectType.Device)
                                   .Select(x => new { x.object_name, x.device_id }).Distinct().ToList();

                if (loDeviceList != null && loDeviceList.Count > 0)
                {
                    foreach (var loDevice in loDeviceList)
                    {
                        loAvailableDevices.Add(new KeyValuePair <string, string>(Convert.ToString(loDevice.device_id), Convert.ToString(loDevice.object_name)));
                    }
                }
            }

            ddlScheduleDevice.DataSource    = loAvailableDevices;
            ddlScheduleDevice.ValueMember   = "Key";
            ddlScheduleDevice.DisplayMember = "Value";
        }
        /// <summary>
        /// Get current light state for device
        /// </summary>
        /// <param name="fiDeviceID"></param>
        /// <returns></returns>
        private bool GetLutronLightState(Int32 fiDeviceID)
        {
            IList <BacnetValue> loBacnetValueList;

            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices
                                           .Where(x => x.device_id == fiDeviceID &&
                                                  x.object_type.ToUpper() == LutronFloorObjectType.Lighting_State)
                                           .Select(x => x).FirstOrDefault();


                BacnetAddress loBacnetAddress;
                loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id);
                loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net);

                moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_BINARY_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, out loBacnetValueList);
            }

            if (loBacnetValueList != null && loBacnetValueList.Count > 0)
            {
                return(Convert.ToBoolean(Convert.ToInt32(loBacnetValueList[0].Value)));
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Register COV event which we want to get, Here AV is registered for COV notification
        /// </summary>
        /// <param name="fiDeviceID"></param>
        private void RegisterCOVForObjectsOfDevice(Int32 fiDeviceID)
        {
            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices
                                           .Where(x => x.device_id == fiDeviceID &&
                                                  x.object_instance == (int?)LutronObjectType.Lighting_Level)
                                           .Select(x => x).FirstOrDefault();


                BacnetAddress loBacnetAddress;
                loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id);
                loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net);

                moBacnetClient.SubscribeCOVRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, (uint)loBACnetDeviceDetail.object_instance), 0, false, false, 60);
            }
        }
        private void ddlScheduleDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            int liDeviceID;

            if (ddlScheduleDevice.SelectedValue.GetType() == typeof(KeyValuePair <string, string>))
            {
                System.Reflection.PropertyInfo loPropertyInfo = ddlScheduleDevice.SelectedValue.GetType().GetProperty("Key");
                String lsSelectedValue = (String)(loPropertyInfo.GetValue(ddlScheduleDevice.SelectedValue, null));
                liDeviceID = Convert.ToInt32(lsSelectedValue);

                string lsSecondFloorPresentValue = GetLutronLightLevel(2);
                ChangeLightBrightnessForSecondFloor(Convert.ToInt32(lsSecondFloorPresentValue));
            }
            else
            {
                liDeviceID = Convert.ToInt32(ddlScheduleDevice.SelectedValue);
            }


            var loAvailableObjects = new BindingList <KeyValuePair <string, string> >();

            loAvailableObjects.Add(new KeyValuePair <string, string>("PlaceHolder|-1", "Select object"));

            using (var loDataContext = new ESDLutronEntities())
            {
                var loObjectList = loDataContext
                                   .BACnetDevices
                                   .Where(x => x.device_id == liDeviceID &&
                                          (x.object_type == LutronFloorObjectType.Lighting_Level || x.object_type == LutronFloorObjectType.Lighting_State))
                                   .Select(x => new { x.object_instance, x.object_name, x.object_type }).Distinct().ToList();

                if (loObjectList != null && loObjectList.Count > 0)
                {
                    foreach (var loObject in loObjectList)
                    {
                        loAvailableObjects.Add(new KeyValuePair <string, string>(Convert.ToString(loObject.object_type + "|" + loObject.object_instance), Convert.ToString(loObject.object_name)));
                    }
                }
            }

            ddlScheduleObject.DataSource    = loAvailableObjects;
            ddlScheduleObject.ValueMember   = "Key";
            ddlScheduleObject.DisplayMember = "Value";
        }
        /// <summary>
        /// Set Lighting Level as per trackbar value between 1 to 100
        /// </summary>
        /// <param name="fiDeviceID"></param>
        private void ChangeLutronLightLevel(Int32 fiDeviceID)
        {
            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices
                                           .Where(x => x.device_id == fiDeviceID &&
                                                  x.object_instance == (int?)LutronObjectType.Lighting_Level)
                                           .Select(x => x).FirstOrDefault();


                BacnetAddress loBacnetAddress;
                loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id);
                loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net);

                BacnetValue   loNewBacnetValue           = new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_REAL, Convert.ToSingle(trackBarLightingLevel.Value));
                BacnetValue[] loWriteNewBacnetValueValue = { loNewBacnetValue };
                moBacnetClient.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, loWriteNewBacnetValueValue);
            }
        }
        /// <summary>
        /// Temporary method
        /// </summary>
        /// <param name="fiDeviceID"></param>
        /// <param name="foBacnetObjectId"></param>
        /// <param name="foBacnetPropertyIds"></param>
        /// <param name="foBacnetValue"></param>
        /// <returns></returns>
        static bool WriteScalarValue(int fiDeviceID, BacnetObjectId foBacnetObjectId, BacnetPropertyIds foBacnetPropertyIds, BacnetValue foBacnetValue)
        {
            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices
                                           .Where(x => x.device_id == fiDeviceID &&
                                                  x.object_instance == (int?)LutronObjectType.Lighting_State)
                                           .Select(x => x).FirstOrDefault();


                BacnetAddress adr;

                //// Looking for the device
                adr = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id);
                if (adr == null)
                {
                    return(false);              // not found
                }
                adr.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net);

                //// Property Write


                IList <BacnetValue> NoScalarValue;
                moBacnetClient.ReadPropertyRequest(adr, foBacnetObjectId, foBacnetPropertyIds, out NoScalarValue);

                //var loWirteList = NoScalarValue.ToList();
                //loWirteList[0].Value = 5;

                //NoScalarValue[0].Value = 5;
                //List<BacnetValue> loWriteValue = new List<BacnetValue>();
                //loWriteValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_REAL, 5));

                BacnetValue   loBacnetNewValue = new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_REAL, Convert.ToSingle(foBacnetValue.Value));
                BacnetValue[] loWriteValue     = { loBacnetNewValue };

                moBacnetClient.WritePropertyRequest(adr, foBacnetObjectId, foBacnetPropertyIds, loWriteValue);

                return(true);
            }
        }
        /// <summary>
        ///  Change light level for floor (AV)
        /// </summary>
        /// <param name="fiFloorID"></param>
        private void ChangeLutronLightLevel(Int32 fiFloorID)
        {
            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                //var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices
                //                            .Where(x => x.device_id == fiDeviceID
                //                                  && x.object_type == LutronFloorObjectType.Lighting_Level)
                //                             .Select(x => x).FirstOrDefault();


                var loBACnetDeviceDetail = (from DM in loESDLutronEntities.BACnetDeviceMappings
                                            join D in loESDLutronEntities.BACnetDevices on DM.device_id equals D.device_id
                                            where DM.floor_id == fiFloorID &&
                                            D.object_type.ToUpper() == LutronFloorObjectType.Lighting_Level &&
                                            D.object_instance != 7    //// 7 is for alarm event
                                            select new
                {
                    network_id = D.network_id,
                    device_id = D.device_id,
                    object_instance = D.object_instance,
                    object_name = D.object_name,
                    routed_source = D.routed_source,
                    routed_net = D.routed_net
                }).Distinct().ToList();


                if (loBACnetDeviceDetail != null && loBACnetDeviceDetail.Count > 0)
                {
                    foreach (var loData in loBACnetDeviceDetail)
                    {
                        BacnetAddress loBacnetAddress;
                        loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loData.network_id);
                        loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loData.routed_source, (ushort)loData.routed_net);

                        BacnetValue   loNewBacnetValue           = new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_REAL, Convert.ToSingle(trbkLightSense.Value));
                        BacnetValue[] loWriteNewBacnetValueValue = { loNewBacnetValue };
                        moBacnetClient.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, (uint)loData.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, loWriteNewBacnetValueValue);
                    }
                }
            }
        }
        /// <summary>
        /// get current light level for floor
        /// </summary>
        /// <param name="fiFloorID"></param>
        /// <returns></returns>
        private string GetLutronLightLevel(Int32 fiFloorID)
        {
            IList <BacnetValue> loBacnetValueList;

            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                var loBACnetDeviceDetail = (from DM in loESDLutronEntities.BACnetDeviceMappings
                                            join D in loESDLutronEntities.BACnetDevices on DM.device_id equals D.device_id
                                            where DM.floor_id == fiFloorID &&
                                            D.object_type.ToUpper() == LutronFloorObjectType.Lighting_Level
                                            select new
                {
                    network_id = D.network_id,
                    device_id = D.device_id,
                    object_instance = D.object_instance,
                    object_name = D.object_name,
                    routed_source = D.routed_source,
                    routed_net = D.routed_net
                }).Distinct().FirstOrDefault();


                BacnetAddress loBacnetAddress;
                loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id);
                loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net);

                moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, out loBacnetValueList);
            }

            if (loBacnetValueList != null && loBacnetValueList.Count > 0)
            {
                return(loBacnetValueList[0].Value.ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
        /// <summary>
        /// InIt bacnet and UI
        /// </summary>
        public LutronLight()
        {
            InitializeComponent();

            chkLightOnOff.Appearance  = Appearance.Button;
            chkLightOnOff.TextAlign   = ContentAlignment.MiddleCenter;
            chkLightOnOff.MinimumSize = new Size(75, 25); //To prevent shrinkage!

            //// Bacnet on UDP/IP/Ethernet
            moBacnetClient = new BacnetClient(new BacnetIpUdpProtocolTransport(47808, false)); // (0xBAC0, false));
            moBacnetClient.Start();                                                            // go

            //// Set handler for OnCOVNotification
            moBacnetClient.OnCOVNotification += new BacnetClient.COVNotificationHandler(handler_OnCOVNotification);

            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                ddlDeviceList.DataSource    = loESDLutronEntities.BACnetDevices.Select(x => new { id = x.device_id, name = x.device_id }).Distinct().OrderBy(x => x.id).ToList();
                ddlDeviceList.ValueMember   = "id";
                ddlDeviceList.DisplayMember = "name";
            }

            RegisterCOVForObjectsOfDevice((Int32)ddlDeviceList.SelectedValue);
        }
        /// <summary>
        /// handler to assign alarm enrolment instance on event notification
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="adr"></param>
        /// <param name="low_limit"></param>
        /// <param name="high_limit"></param>
        static void handler_OnWhoIs(BacnetClient sender, BacnetAddress adr, int low_limit, int high_limit)
        {
            if (low_limit != -1 && 1 < low_limit)
            {
                return;
            }
            else if (high_limit != -1 && 1 > high_limit)
            {
                return;
            }

            using (var loESDLutronEntities = new ESDLutronEntities())
            {
                Int32?liAlarmEnrolment = loESDLutronEntities.BACnetDevices
                                         .Where(x => x.device_id == 1 &&
                                                x.object_type.ToUpper() == LutronFloorObjectType.ALERT_ENROLLMENT)
                                         .Select(x => x.object_instance).FirstOrDefault();

                if (liAlarmEnrolment != null)
                {
                    sender.Iam((uint)liAlarmEnrolment, new BacnetSegmentations());
                }
            }
        }
        private void btnSchedule_Click(object sender, EventArgs e)
        {
            Int32  liDeviceID        = Convert.ToInt32(ddlScheduleDevice.SelectedValue);
            Int32  liObjectID        = Convert.ToInt32(Convert.ToString(ddlScheduleObject.SelectedValue).Split('|')[1]);
            string lsNewPresentvalue = Convert.ToString(txtScheduleValue.Text);
            Int32  liDaySelected     = Convert.ToInt32(ddlScheduleDay.SelectedValue);

            if (liDeviceID > -1 && liObjectID > -1 && !string.IsNullOrEmpty(lsNewPresentvalue) &&
                !string.IsNullOrEmpty(txtScheduleHours.Text) &&
                !string.IsNullOrEmpty(txtScheduleMinutes.Text) &&
                !string.IsNullOrEmpty(txtScheduleSeconds.Text))
            {
                using (var loESDLutronEntities = new ESDLutronEntities())
                {
                    var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices
                                               .Where(x => x.device_id == liDeviceID &&
                                                      x.object_type.ToUpper() == LutronFloorObjectType.Device)
                                               .Select(x => x).FirstOrDefault();


                    int?liTopInstanceID = loESDLutronEntities.BACnetDevices
                                          .Where(x => x.device_id == liDeviceID &&
                                                 x.object_type.ToUpper() == LutronFloorObjectType.SCHEDULE)
                                          .Select(x => x.object_instance).OrderByDescending(x => x.Value).FirstOrDefault();


                    BacnetAddress loBacnetAddress;
                    loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id);
                    loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net);

                    //var deviceObjId = new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, (uint)liDeviceID);
                    //var objectIdList = await moBacnetClient.ReadPropertyAsync(loBacnetAddress, deviceObjId, BacnetPropertyIds.PROP_OBJECT_LIST);

                    //IList<BacnetValue> loDeviceObject;
                    //moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, (uint)liDeviceID), BacnetPropertyIds.PROP_OBJECT_LIST, out loDeviceObject);

                    //IList<BacnetValue> loScheduleValues;
                    //moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_SCHEDULE, (uint)11), BacnetPropertyIds.PROP_LIST_OF_OBJECT_PROPERTY_REFERENCES, out loScheduleValues);


                    //IList<BacnetValue> loWeekValues;
                    //moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_SCHEDULE, (uint)11), BacnetPropertyIds.PROP_WEEKLY_SCHEDULE, out loWeekValues);



                    //IList<BacnetValue> loObjectName;
                    //moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_SCHEDULE, (uint)11), BacnetPropertyIds.PROP_OBJECT_NAME, out loObjectName);


                    //var loData = values
                    //              .Where(x => ((BacnetObjectId)values[0].Value).Type == BacnetObjectTypes.OBJECT_SCHEDULE)
                    //              .Select(x => x.Value.GetType().GetProperty("Instance"))


                    IList <BacnetValue> loScheduleValues;
                    moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_SCHEDULE, (uint)2), BacnetPropertyIds.PROP_EXCEPTION_SCHEDULE, out loScheduleValues);



                    ICollection <BacnetPropertyValue> loBacnetPropertyValueList = new List <BacnetPropertyValue>();

                    BacnetPropertyValue loNewPropertyValue = new BacnetPropertyValue();
                    List <BacnetValue>  loBacnetValue      = new List <BacnetValue>();


                    #region set schedule

                    ////    Create new instance id based on largest available
                    //if(liTopInstanceID)
                    liTopInstanceID = liTopInstanceID != null ? liTopInstanceID + 1 : 1;

                    //// Set schedule object name
                    loBacnetValue      = new List <BacnetValue>();
                    loNewPropertyValue = new BacnetPropertyValue();
                    loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_CHARACTER_STRING, "Schedule" + " " + liTopInstanceID));

                    loNewPropertyValue.value    = loBacnetValue;
                    loNewPropertyValue.property = new BacnetPropertyReference((uint)BacnetPropertyIds.PROP_OBJECT_NAME, ASN1.BACNET_ARRAY_ALL);

                    loBacnetPropertyValueList.Add(loNewPropertyValue);


                    //// Set effective period for schedule object
                    loBacnetValue      = new List <BacnetValue>();
                    loNewPropertyValue = new BacnetPropertyValue();
                    loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_DATE, DateTime.Today.AddDays(-1)));
                    loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_DATE, DateTime.Today.AddMonths(1)));

                    loNewPropertyValue.value    = loBacnetValue;
                    loNewPropertyValue.property = new BacnetPropertyReference((uint)BacnetPropertyIds.PROP_EFFECTIVE_PERIOD, ASN1.BACNET_ARRAY_ALL);

                    loBacnetPropertyValueList.Add(loNewPropertyValue);
                    #endregion


                    //// Set object reference to update it's value with schedule object
                    loBacnetValue      = new List <BacnetValue>();
                    loNewPropertyValue = new BacnetPropertyValue();

                    BacnetDeviceObjectPropertyReference loPropertyReference = new BacnetDeviceObjectPropertyReference();


                    //BACnetCalendarEntry loBACnetCalendarEntry = new BACnetCalendarEntry();


                    //// Add AV 1 present value change
                    loPropertyReference.ArrayIndex = -1;
                    loPropertyReference.DeviceId   = new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, (uint)liDeviceID);
                    loPropertyReference.ObjectId   = new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, (uint)liObjectID);
                    loPropertyReference.PropertyId = BacnetPropertyIds.PROP_PRESENT_VALUE;

                    loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_OBJECT_PROPERTY_REFERENCE,
                                                      loPropertyReference));

                    // Add AV 2 present value change
                    loPropertyReference            = new BacnetDeviceObjectPropertyReference();
                    loPropertyReference.ArrayIndex = -1;
                    loPropertyReference.DeviceId   = new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, (uint)liDeviceID);
                    loPropertyReference.ObjectId   = new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, (uint)2);
                    loPropertyReference.PropertyId = BacnetPropertyIds.PROP_PRESENT_VALUE;

                    loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_OBJECT_PROPERTY_REFERENCE,
                                                      loPropertyReference));

                    loNewPropertyValue.value    = loBacnetValue;
                    loNewPropertyValue.property = new BacnetPropertyReference((uint)BacnetPropertyIds.PROP_LIST_OF_OBJECT_PROPERTY_REFERENCES, ASN1.BACNET_ARRAY_ALL);

                    loBacnetPropertyValueList.Add(loNewPropertyValue);



                    //// Add weekly schedule for object
                    loBacnetValue      = new List <BacnetValue>();
                    loNewPropertyValue = new BacnetPropertyValue();

                    //// setup weekday to add schedule (0 = Monday, 1 = Tuesday ....., 6 = Sunday)
                    BacnetWeeklySchedule loBacnetWeeklySchedule = new BacnetWeeklySchedule();
                    loBacnetWeeklySchedule.days[liDaySelected] = new List <DaySchedule>();

                    //// Schedule to update AV 1,2 at specified time
                    loBacnetWeeklySchedule.days[liDaySelected].Add(
                        new DaySchedule(new DateTime(1, 1, 1, Convert.ToInt32(txtScheduleHours.Text),
                                                     Convert.ToInt32(txtScheduleMinutes.Text), Convert.ToInt32(txtScheduleSeconds.Text)),
                                        Convert.ToSingle((new Random()).Next(100, 999))));

                    //// Schedule to update AV 1,2 after 5 mins of schedule
                    loBacnetWeeklySchedule.days[liDaySelected].Add(new DaySchedule(DateTime.Now.AddMinutes(1), Convert.ToSingle(lsNewPresentvalue)));


                    loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_WEEKLY_SCHEDULE, loBacnetWeeklySchedule));

                    loNewPropertyValue.value    = loBacnetValue;
                    loNewPropertyValue.property = new BacnetPropertyReference((uint)BacnetPropertyIds.PROP_WEEKLY_SCHEDULE, ASN1.BACNET_ARRAY_ALL);

                    loBacnetPropertyValueList.Add(loNewPropertyValue);



                    //// Add exception schedule
                    //loBacnetValue = new List<BacnetValue>();
                    //loNewPropertyValue = new BacnetPropertyValue();

                    //loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_TIME, new DateTime(2017,9,11,15,10,0)));
                    //loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_REAL, 333));
                    //loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_DATE, DateTime.Today.Date));


                    //loNewPropertyValue.value = loBacnetValue;
                    //loNewPropertyValue.property = new BacnetPropertyReference((uint)BacnetPropertyIds.PROP_EXCEPTION_SCHEDULE, ASN1.BACNET_ARRAY_ALL);
                    //loBacnetPropertyValueList.Add(loNewPropertyValue);



                    loBacnetValue      = new List <BacnetValue>();
                    loNewPropertyValue = new BacnetPropertyValue();

                    BacnetWeeklyExceptionSchedule loBacnetWeeklyExceptionSchedule = new BacnetWeeklyExceptionSchedule();

                    List <ExceptionScheduleTimeValue>[] loExceptionSchedulTimeValue = new List <ExceptionScheduleTimeValue> [1];
                    loExceptionSchedulTimeValue[0] = new List <ExceptionScheduleTimeValue>();
                    loExceptionSchedulTimeValue[0].Add(new ExceptionScheduleTimeValue(DateTime.Now.AddMinutes(2), Convert.ToSingle(111)));


                    loBacnetWeeklyExceptionSchedule.loExceptionScheduleArray    = new List <ExceptionScheduleArray> [1];
                    loBacnetWeeklyExceptionSchedule.loExceptionScheduleArray[0] = new List <ExceptionScheduleArray>();
                    loBacnetWeeklyExceptionSchedule.loExceptionScheduleArray[0].Add(new ExceptionScheduleArray(new DateTime(1, 1, 1, 18, 30, 1), loExceptionSchedulTimeValue));

                    loBacnetValue.Add(new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_SPECIAL_EVENT, loBacnetWeeklyExceptionSchedule));

                    loNewPropertyValue.value    = loBacnetValue;
                    loNewPropertyValue.property = new BacnetPropertyReference((uint)BacnetPropertyIds.PROP_EXCEPTION_SCHEDULE, ASN1.BACNET_ARRAY_ALL);

                    loBacnetPropertyValueList.Add(loNewPropertyValue);

                    moBacnetClient.CreateObjectRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_SCHEDULE, (uint)liTopInstanceID), loBacnetPropertyValueList);
                }
            }
            else
            {
                if (liDeviceID < 0)
                {
                    MessageBox.Show("Please select device");
                }
                else if (liObjectID < 0)
                {
                    MessageBox.Show("Please select object");
                }
                else
                {
                    MessageBox.Show("Schedule is not setup properly, please review.");
                }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Get all object & object's instance detail of available devices
        /// Insert network, device, object & object's instance into DB
        /// </summary>
        static void InsertBACnetDeviceDetailInDB()
        {
            if (loBACnetDeviceModel != null && loBACnetDeviceModel.loBACnetDeviceList.Count > 0)
            {
                using (var loESDLutronEntities = new ESDLutronEntities())
                {
                    //// Declare list to instert device in DB
                    List <BACnetDevice>        loInsertBACnetDeviceList    = new List <BACnetDevice>();
                    List <BACnetDeviceMapping> loInsertBACnetDeviceMapping = new List <BACnetDeviceMapping>();

                    //// Remove all exists device on each application run
                    loESDLutronEntities.BACnetDevices.RemoveRange(loESDLutronEntities.BACnetDevices.AsEnumerable());
                    loESDLutronEntities.BACnetDeviceMappings.RemoveRange(loESDLutronEntities.BACnetDeviceMappings.AsEnumerable());

                    foreach (var loBacnetDevice in loBACnetDeviceModel.loBACnetDeviceList)
                    {
                        //// Get all bacnet object available for device
                        IList <BacnetValue> loObjectValueList;
                        moBacnetClient.ReadPropertyRequest(loBacnetDevice.loBACnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, loBacnetDevice.inDeviceID), BacnetPropertyIds.PROP_OBJECT_LIST, out loObjectValueList);

                        foreach (BacnetValue loObjectValue in loObjectValueList)
                        {
                            //// Get each object's instance details and object name to store in DB
                            IList <BacnetValue> loObjectNameList;
                            moBacnetClient.ReadPropertyRequest(loBacnetDevice.loBACnetAddress,
                                                               new BacnetObjectId((BacnetObjectTypes)((BacnetObjectId)loObjectValue.Value).Type, ((BacnetObjectId)loObjectValue.Value).Instance),
                                                               BacnetPropertyIds.PROP_OBJECT_NAME, out loObjectNameList);

                            //string lsObjectType = ((BacnetObjectId)loObjectValue.Value).type.ToString();
                            //string lsObjectInstanceNumber = ((BacnetObjectId)loObjectValue.Value).Instance.ToString();

                            //// add to entity model for DB bulk insert
                            loInsertBACnetDeviceList.Add(
                                new BACnetDevice
                            {
                                network_id      = loBacnetDevice.loBACnetAddress.ToString(),
                                device_id       = Convert.ToInt32(loBacnetDevice.inDeviceID),
                                object_type     = ((BacnetObjectId)loObjectValue.Value).type.ToString(),
                                object_instance = Convert.ToInt32(((BacnetObjectId)loObjectValue.Value).Instance.ToString()),
                                object_name     = loObjectNameList != null && loObjectNameList.Count > 0 ? loObjectNameList[0].Value.ToString() : null,
                                routed_source   = loBacnetDevice.loBACnetAddress.RoutedSource.ToString(),
                                routed_net      = loBacnetDevice.loBACnetAddress.RoutedSource.net
                            });

                            int?liSuiteID = null, liRoomID = null;

                            if (((BacnetObjectId)loObjectValue.Value).type.ToString().ToUpper() == "OBJECT_ANALOG_VALUE")
                            {
                                if (Convert.ToInt32(((BacnetObjectId)loObjectValue.Value).Instance.ToString()) < 4)
                                {
                                    liSuiteID = 1;
                                }
                                else
                                {
                                    liSuiteID = 2;
                                }

                                liRoomID = Convert.ToInt32(((BacnetObjectId)loObjectValue.Value).Instance.ToString());
                            }

                            loInsertBACnetDeviceMapping.Add(
                                new BACnetDeviceMapping
                            {
                                device_id       = Convert.ToInt32(loBacnetDevice.inDeviceID),
                                object_instance = Convert.ToInt32(((BacnetObjectId)loObjectValue.Value).Instance.ToString()),
                                floor_id        = Convert.ToInt32(loBacnetDevice.inDeviceID),
                                suite_id        = liSuiteID,
                                room_id         = liRoomID,
                            });
                        }
                    }

                    //// Insert into DB (table: BACnetDevices)
                    if (loInsertBACnetDeviceList != null && loInsertBACnetDeviceList.Count > 0)
                    {
                        loESDLutronEntities.BACnetDevices.AddRange(loInsertBACnetDeviceList);
                        loESDLutronEntities.BACnetDeviceMappings.AddRange(loInsertBACnetDeviceMapping);
                        loESDLutronEntities.SaveChanges();
                    }
                }
            }
        }