Beispiel #1
0
        public async Task <ResponseData <Dashboard> > DashBoardForMobile(string uuid)
        {
            try
            {
                var response = new ResponseData <Dashboard>();

                var lAppliance = _accountApplianceService.GetApplianceByUUID(uuid);
                if (!TelitApi.IsConnected)
                {
                    await TelitApi.CheckIOTConnection();
                }
                if (lAppliance != null && lAppliance.Count() > 0)
                {
                    foreach (var item in lAppliance)
                    {
                        var thingFind = await TelitApi.ThingFind(item.SerialNumber);

                        Telit.ThingFind.Params _params = new Telit.ThingFind.Params();
                        string applianceEnvironment    = string.Empty;
                        if (thingFind != null && thingFind.Things != null && thingFind.Things.success && thingFind.Things.@params != null)
                        {
                            _params = thingFind.Things.@params;
                        }

                        if (_params != null && _params.alarms != null && _params.alarms.env != null && _params.alarms.env.state >= 0 && _params.alarms.env.state < 16)
                        {
                            applianceEnvironment = Convert.ToString(_params.alarms.env.state, 2).PadLeft(4, '0');
                            var array = !string.IsNullOrEmpty(applianceEnvironment) ? applianceEnvironment.ToArray() : new char[] { };
                            item.IsOn = _params != null && _params.alarms != null && _params.alarms.on != null?CheckApplianceIsOn(Convert.ToInt16(_params.alarms.on.state)) : false;

                            item.IsConnected  = _params.connected;
                            item.Cellular     = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[2].ToString())) : false;
                            item.Power        = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[3].ToString())) : false;
                            item.Wifi         = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[1].ToString())) : false;
                            item.WiFiInternet = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[0].ToString())) : false;
                            item.TrustLevel   = _params.alarms.trust != null ? (int?)_params.alarms.trust.state : null;
                        }
                    }
                }

                var dashboard = new Dashboard()
                {
                    ApplianceDTO   = lAppliance,
                    IsIOTConnected = TelitApi.IsConnected
                };
                response.Data   = dashboard;
                response.Status = ResponseStatus.Success.ToString();
                return(response);
            }
            catch (Exception ex)
            {
                var response = new ResponseData <Dashboard>();
                response.Message = ex.Message;
                response.Status  = ResponseStatus.Error.ToString();
                return(response);
            }
        }
Beispiel #2
0
        public async Task <ResponseData <bool> > UpdateAppliance(string subscriptionId, string update)
        {
            try
            {
                var accountAppliance = _accountApplianceService.GetAccountApplianceBySubScription(subscriptionId);
                var appliance        = _applianceService.GetApplianceById(accountAppliance.FirstOrDefault().ApplianceId.Value);
                var response         = new ResponseData <bool>();
                var thingFind        = await TelitApi.ThingFind(appliance.SerialNumber);

                Telit.ThingFind.Params _params = new Telit.ThingFind.Params();
                _params = thingFind.Things.@params;

                var success = await TelitApi.UpdateStatusOfAppliance(_params.iccid, update == Configuration.Disable?true : false);

                if (success)
                {
                    appliance.Status = update == Configuration.Enable ? true : false;
                    _applianceService.Update(appliance);
                    if (!appliance.Status.Value)
                    {
                        accountAppliance.FirstOrDefault().SubscriptionId = null;
                        _accountApplianceService.Update(accountAppliance.FirstOrDefault());
                    }

                    response.Message = ResponseMessage.Success;
                }
                else
                {
                    response.Message = ResponseMessage.Error;
                }
                response.Status = ResponseStatus.Success.ToString();
                return(response);
            }
            catch (Exception ex)
            {
                var response = new ResponseData <bool>();
                response.Message = ex.Message;
                response.Status  = ResponseStatus.Error.ToString();
                return(response);
            }
        }
Beispiel #3
0
        public async Task <ResponseData <ApplianceDTO> > SetupThink([FromBody] ApplianceDTO appliance)
        {
            try
            {
                var response = new ResponseData <ApplianceDTO>();
                var things   = await TelitApi.ThingList();

                bool isMatching              = false;
                bool hasSerialNumber         = false;
                Telit.ThingList.Result thing = new Telit.ThingList.Result();
                if (things != null && things.things != null && things.things.success && things.things.@params != null && [email protected] != null && [email protected]() > 0)
                {
                    foreach (var item in [email protected])
                    {
                        if (item.key == appliance.SerialNumber)
                        {
                            hasSerialNumber = true;
                            if (item.loc != null && item.loc.addr != null)
                            {
                                isMatching = await calculateAddressAsync(appliance.Street1.Trim(), appliance.City.Trim(), _stateService.GetStateById(appliance.StateId.Value).Name, appliance.ZipCode.Trim(), item.loc.lat, item.loc.lng);

                                thing = item;
                                break;
                            }
                        }
                    }
                }

                if (!hasSerialNumber)
                {
                    response.Message = ResponseMessage.SerialNumberInCorrect;
                    response.Status  = ResponseStatus.Success.ToString();
                    return(response);
                }

                if (isMatching)
                {
                    var isSerialNumberExist = _applianceService.GetApplianceBySerialNumber(appliance.SerialNumber);

                    var thingFind = await TelitApi.ThingFind(thing.key);

                    bool thingIsOn                 = false;
                    bool thingIsConnected          = false;
                    bool thingCellular             = false;
                    bool thingPower                = false;
                    bool thingWifi                 = false;
                    bool thingWifiInternet         = false;
                    int? thingTrustLevel           = null;
                    Telit.ThingFind.Params _params = new Telit.ThingFind.Params();
                    string applianceEnvironment    = string.Empty;

                    if (thingFind != null && thingFind.Things != null && thingFind.Things.success && thingFind.Things.@params != null)
                    {
                        _params = thingFind.Things.@params;
                    }

                    if (_params != null && _params.alarms != null && _params.alarms.env != null && _params.alarms.env.state >= 0 && _params.alarms.env.state < 16)
                    {
                        applianceEnvironment = Convert.ToString(_params.alarms.env.state, 2).PadLeft(4, '0');
                        var array = !string.IsNullOrEmpty(applianceEnvironment) ? applianceEnvironment.ToArray() : new char[] { };
                        thingIsOn         = Convert.ToBoolean(_params.alarms.on.state);
                        thingIsConnected  = _params.connected;
                        thingCellular     = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[2].ToString())) : false;
                        thingPower        = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[3].ToString())) : false;
                        thingWifi         = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[1].ToString())) : false;
                        thingWifiInternet = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[0].ToString())) : false;
                        thingTrustLevel   = _params.alarms.trust != null ? (int?)_params.alarms.trust.state : null;
                    }

                    if (isSerialNumberExist == null)
                    {
                        var app = _applianceService.Insert(new Appliance()
                        {
                            AccountId       = appliance.AccountId,
                            Cellular        = thingCellular,
                            IsConnected     = thingIsConnected,
                            City            = appliance.City,
                            DeviceName      = _params != null && _params.attrs != null && _params.attrs.name != null ? _params.attrs.name.value : string.Empty,
                            OsVersion       = "",
                            GeoFenceEnabled = _params.alarms != null && _params.alarms.timerState != null && _params.alarms.timerState.state != 0 ? true : false,
                            Lat             = _params.loc != null ? _params.loc.lat : 0,
                            Lon             = _params.loc != null ? _params.loc.lng : 0,
                            SerialNumber    = appliance.SerialNumber,
                            Power           = thingPower,
                            StateId         = appliance.StateId,
                            Street1         = appliance.Street1,
                            Street2         = appliance.Street2,
                            TimerEnabled    = _params.alarms != null && _params.alarms.timerState != null && _params.alarms.timerState.state != 0 ? true : false,
                            TriggerMile     = Convert.ToDecimal(_appSettings.TriggerMiles),
                            Wifi            = thingWifi,
                            WiFiInternet    = thingWifiInternet,
                            ZipCode         = appliance.ZipCode,
                            TrustLevel      = thingTrustLevel != null ? thingTrustLevel : 0,
                            IsOn            = thingIsOn
                        });
                        if (app != null)
                        {
                            var accountAppliance = _accountApplianceService.Insert(new AccountAppliance()
                            {
                                AccountId      = app.AccountId,
                                AirGapVersion  = "",
                                ApplianceId    = app.Id,
                                IsQRCodeScaned = false,
                                IsVerified     = false
                            });

                            appliance.Id = app.Id;

                            if (_params.attrs != null && _params.attrs.timerSchedule != null)
                            {
                                var    timerScheduleDTO = JsonConvert.DeserializeObject <TimerScheduleFromTelit>(_params.attrs.timerSchedule.value);
                                char[] weekDayArray     = timerScheduleDTO.Weekdays.ToCharArray();
                                char[] weekEndArray     = timerScheduleDTO.Weekends.ToCharArray();
                                string valueWeekDay     = string.Empty;
                                string valueWeekEnd     = string.Empty;

                                for (int i = 0; i < weekDayArray.Length; i++)
                                {
                                    if (weekDayArray[i] == '1')
                                    {
                                        valueWeekDay += i + 1 + ",";
                                    }
                                }

                                for (int i = 0; i < weekEndArray.Length; i++)
                                {
                                    if (weekEndArray[i] == '1')
                                    {
                                        valueWeekEnd += i + 1 + ",";
                                    }
                                }

                                if (!string.IsNullOrEmpty(valueWeekDay))
                                {
                                    var timerScheduleOfWeekDays = new TimerSchedule()
                                    {
                                        TimerTypeId  = Configuration.Weekdays,
                                        ApplianceId  = app.Id,
                                        ActiveValues = !string.IsNullOrEmpty(valueWeekDay) ? valueWeekDay.Remove(valueWeekDay.Length - 1) : string.Empty
                                    };
                                    _timerScheduleService.Insert(timerScheduleOfWeekDays);
                                }

                                if (!string.IsNullOrEmpty(valueWeekEnd))
                                {
                                    var timerScheduleOfWeekEnd = new TimerSchedule()
                                    {
                                        TimerTypeId  = Configuration.Weekends,
                                        ApplianceId  = app.Id,
                                        ActiveValues = !string.IsNullOrEmpty(valueWeekEnd) ? valueWeekEnd.Remove(valueWeekEnd.Length - 1) : string.Empty
                                    };

                                    _timerScheduleService.Insert(timerScheduleOfWeekEnd);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (isSerialNumberExist.AccountId == null)
                        {
                            isSerialNumberExist.AccountId       = appliance.AccountId;
                            isSerialNumberExist.Street1         = appliance.Street1;
                            isSerialNumberExist.Street2         = appliance.Street2;
                            isSerialNumberExist.City            = appliance.City;
                            isSerialNumberExist.StateId         = appliance.StateId;
                            isSerialNumberExist.ZipCode         = appliance.ZipCode;
                            isSerialNumberExist.Lat             = _params.loc != null ? _params.loc.lat : 0;
                            isSerialNumberExist.Lon             = _params.loc != null ? _params.loc.lng : 0;
                            isSerialNumberExist.Cellular        = thingCellular;
                            isSerialNumberExist.IsConnected     = thingIsConnected;
                            isSerialNumberExist.DeviceName      = _params != null && _params.attrs != null && _params.attrs.name != null ? _params.attrs.name.value : string.Empty;
                            isSerialNumberExist.OsVersion       = "";
                            isSerialNumberExist.GeoFenceEnabled = _params.alarms != null && _params.alarms.timerState != null && _params.alarms.timerState.state != 0 ? true : false;
                            isSerialNumberExist.Power           = thingPower;
                            isSerialNumberExist.TimerEnabled    = _params.alarms != null && _params.alarms.timerState != null && _params.alarms.timerState.state != 0 ? true : false;
                            isSerialNumberExist.Wifi            = thingWifi;
                            isSerialNumberExist.WiFiInternet    = thingWifiInternet;
                            isSerialNumberExist.ZipCode         = appliance.ZipCode;
                            isSerialNumberExist.TrustLevel      = thingTrustLevel != null ? thingTrustLevel : 0;
                            isSerialNumberExist.IsOn            = thingIsOn;
                            isSerialNumberExist.TriggerMile     = Convert.ToDecimal(_appSettings.TriggerMiles);
                            _applianceService.Update(isSerialNumberExist);
                            var accountAppliance = _accountApplianceService.Insert(new AccountAppliance()
                            {
                                AccountId      = appliance.AccountId,
                                AirGapVersion  = "",
                                ApplianceId    = isSerialNumberExist.Id,
                                IsQRCodeScaned = false,
                                IsVerified     = false
                            });
                            appliance.Id = isSerialNumberExist.Id;

                            if (_params.attrs != null && _params.attrs.timerSchedule != null)
                            {
                                var    timerScheduleDTO = JsonConvert.DeserializeObject <TimerScheduleFromTelit>(_params.attrs.timerSchedule.value);
                                char[] weekDayArray     = timerScheduleDTO.Weekdays.ToCharArray();
                                char[] weekEndArray     = timerScheduleDTO.Weekends.ToCharArray();
                                string valueWeekDay     = string.Empty;
                                string valueWeekEnd     = string.Empty;

                                for (int i = 0; i < weekDayArray.Length; i++)
                                {
                                    if (weekDayArray[i] == '1')
                                    {
                                        valueWeekDay += i + 1 + ",";
                                    }
                                }

                                for (int i = 0; i < weekEndArray.Length; i++)
                                {
                                    if (weekEndArray[i] == '1')
                                    {
                                        valueWeekEnd += i + 1 + ",";
                                    }
                                }

                                var timerSchedule = _timerScheduleService.GetTimerScheduleByApplianceId(appliance.Id);
                                if (timerSchedule != null && timerSchedule.Count > 0)
                                {
                                    foreach (var item in timerSchedule)
                                    {
                                        if (item.TimerTypeId == Configuration.Weekdays)
                                        {
                                            item.ActiveValues = !string.IsNullOrEmpty(valueWeekDay) ? valueWeekDay.Remove(valueWeekDay.Length - 1) : string.Empty;
                                        }

                                        if (item.TimerTypeId == Configuration.Weekends)
                                        {
                                            item.ActiveValues = !string.IsNullOrEmpty(valueWeekEnd) ? valueWeekEnd.Remove(valueWeekEnd.Length - 1) : string.Empty;
                                        }
                                        _timerScheduleService.Update(item);
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(valueWeekDay))
                                    {
                                        var timerScheduleOfWeekDays = new TimerSchedule()
                                        {
                                            TimerTypeId  = Configuration.Weekdays,
                                            ApplianceId  = isSerialNumberExist.Id,
                                            ActiveValues = !string.IsNullOrEmpty(valueWeekDay) ? valueWeekDay.Remove(valueWeekDay.Length - 1) : string.Empty
                                        };
                                        _timerScheduleService.Insert(timerScheduleOfWeekDays);
                                    }

                                    if (!string.IsNullOrEmpty(valueWeekEnd))
                                    {
                                        var timerScheduleOfWeekEnd = new TimerSchedule()
                                        {
                                            TimerTypeId  = Configuration.Weekends,
                                            ApplianceId  = isSerialNumberExist.Id,
                                            ActiveValues = !string.IsNullOrEmpty(valueWeekEnd) ? valueWeekEnd.Remove(valueWeekEnd.Length - 1) : string.Empty
                                        };

                                        _timerScheduleService.Insert(timerScheduleOfWeekEnd);
                                    }
                                }
                            }
                        }
                        else
                        {
                            response.Status  = ResponseStatus.Success.ToString();
                            response.Message = ResponseMessage.SerialNumberIsExist;
                            return(response);
                        }
                    }
                }

                appliance.IsMatching      = isMatching;
                appliance.HasSerialNumber = hasSerialNumber;
                response.Data             = appliance;
                response.Status           = ResponseStatus.Success.ToString();
                return(response);
            }
            catch (Exception ex)
            {
                var response = new ResponseData <ApplianceDTO>();
                response.Message = ex.Message;
                response.Status  = ResponseStatus.Error.ToString();
                return(response);
            }
        }
        public async Task <IActionResult> UpdateStatusFromTelit([FromBody] RequestTelit request)
        {
            try
            {
                Event _event    = null;
                var   appliance = _applianceService.GetApplianceBySerialNumber(request.thing);
                if (appliance == null)
                {
                    return(Json(new { success = true, message = ResponseMessage.SerialNumberInCorrect }));
                }

                if (request.key.ToLower() == Configuration.TurnOn)
                {
                    if (appliance != null)
                    {
                        var thingFind = await TelitApi.ThingFind(request.thing);

                        Telit.ThingFind.Params _params = new Telit.ThingFind.Params();
                        bool isMatching = false;
                        if (thingFind != null && thingFind.Things != null && thingFind.Things.success && thingFind.Things.@params != null)
                        {
                            _params = thingFind.Things.@params;
                            if (_params.loc != null)
                            {
                                isMatching = DistanceBetweenPlaces(appliance.Lat.Value, appliance.Lon.Value, _params.loc.lat, _params.loc.lng) <= Convert.ToDouble(_appSettings.Miles) ? true : false;
                                if (!isMatching)
                                {
                                    appliance.StateId = _params.loc != null && _params.loc.addr != null && _stateService.GetStateByNameOrCode(_params.loc.addr.state) != null ? (long?)_stateService.GetStateByNameOrCode(_params.loc.addr.state).Id : null;
                                    appliance.Street1 = _params.loc != null && _params.loc.addr != null ? _params.loc.addr.streetNumber + " " + _params.loc.addr.street : string.Empty;
                                    appliance.Street2 = string.Empty;
                                    appliance.Lat     = _params.loc != null ? _params.loc.lat : 0;
                                    appliance.Lon     = _params.loc != null ? _params.loc.lng : 0;
                                    appliance.City    = _params.loc != null && _params.loc.addr != null ? _params.loc.addr.city : string.Empty;
                                    appliance.ZipCode = _params.loc != null && _params.loc.addr != null ? _params.loc.addr.zipCode : string.Empty;
                                }
                            }
                        }

                        appliance.IsOn = Convert.ToBoolean(Convert.ToInt16(request.value));
                        if (Convert.ToInt16(request.value) == Configuration.Off)
                        {
                            appliance.TimerEnabled    = true;
                            appliance.GeoFenceEnabled = true;
                        }
                        _applianceService.Update(appliance);

                        if (Convert.ToInt32(request.value) == (Int32)AlarmStatus.OffScheduleTimer || Convert.ToInt32(request.value) == (Int32)AlarmStatus.OnScheduleTimer)
                        {
                            request.msg = ResponseMessage.ScheduleTimerChange;
                        }

                        _event = new Event()
                        {
                            ApplianceId = Convert.ToInt64(appliance.Id),
                            EventTypeId = Constant.EventType.ConnectionChange,
                            EventDetail = Constant.ResponseMessage.ConnectionChange,
                            Timestamp   = DateTime.UtcNow,
                            Message     = request.msg
                        };

                        _eventService.Insert(_event);
                    }
                }
                else if (request.key.ToLower() == Configuration.Name)
                {
                    if (appliance != null)
                    {
                        appliance.DeviceName = request.value;
                        _applianceService.Update(appliance);
                    }
                }
                else if (request.key.ToLower() == Configuration.Env)
                {
                    var applianceEnvironment = Convert.ToString(Convert.ToInt16(request.value), 2).PadLeft(4, '0');
                    var array = !string.IsNullOrEmpty(applianceEnvironment) ? applianceEnvironment.ToArray() : new char[] { };
                    if (appliance != null)
                    {
                        bool isPowerStatusChange        = appliance.Power != (array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[3].ToString())) : false) ? true : false;
                        bool isWifiStatusChange         = appliance.Wifi != (array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[1].ToString())) : false) ? true : false;
                        bool isWiFiInternetStatusChange = appliance.WiFiInternet != (array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[0].ToString())) : false) ? true : false;
                        appliance.Cellular     = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[2].ToString())) : false;
                        appliance.Power        = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[3].ToString())) : false;
                        appliance.Wifi         = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[1].ToString())) : false;
                        appliance.WiFiInternet = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[0].ToString())) : false;

                        var thingFind = await TelitApi.ThingFind(request.thing);

                        Telit.ThingFind.Params _params = new Telit.ThingFind.Params();
                        bool isMatching = false;
                        if (thingFind != null && thingFind.Things != null && thingFind.Things.success && thingFind.Things.@params != null)
                        {
                            _params = thingFind.Things.@params;
                            if (_params.loc != null)
                            {
                                isMatching = DistanceBetweenPlaces(appliance.Lat.Value, appliance.Lon.Value, _params.loc.lat, _params.loc.lng) <= Convert.ToDouble(_appSettings.Miles) ? true : false;
                                if (!isMatching)
                                {
                                    appliance.StateId = _params.loc != null && _params.loc.addr != null && _stateService.GetStateByNameOrCode(_params.loc.addr.state) != null ? (long?)_stateService.GetStateByNameOrCode(_params.loc.addr.state).Id : null;
                                    appliance.Street1 = _params.loc != null && _params.loc.addr != null ? _params.loc.addr.streetNumber + " " + _params.loc.addr.street : string.Empty;
                                    appliance.Street2 = string.Empty;
                                    appliance.Lat     = _params.loc != null ? _params.loc.lat : 0;
                                    appliance.Lon     = _params.loc != null ? _params.loc.lng : 0;
                                    appliance.City    = _params.loc != null && _params.loc.addr != null ? _params.loc.addr.city : string.Empty;
                                    appliance.ZipCode = _params.loc != null && _params.loc.addr != null ? _params.loc.addr.zipCode : string.Empty;
                                }
                            }
                        }

                        _applianceService.Update(appliance);
                        var lAccount = _accountApplianceService.GetAccountByApplianceId(appliance.Id, true);

                        if (isPowerStatusChange)
                        {
                            _event = new Event()
                            {
                                ApplianceId = Convert.ToInt64(appliance.Id),
                                EventTypeId = Constant.EventType.HomePowerLoss,
                                EventDetail = Constant.ResponseMessage.ManualConnectedStatusChange,
                                Timestamp   = DateTime.UtcNow,
                                Message     = appliance.DeviceName + "(" + appliance.SerialNumber.Substring(appliance.SerialNumber.Length - 4) + ")" + ": " + Constant.ResponseMessage.HomePower + " " + (array.Length == 4 && Convert.ToBoolean(Convert.ToInt16(array[3].ToString())) ? Configuration.TurnOn.ToUpper() : Configuration.TurnOff.ToUpper())
                            };

                            var insEvent = _eventService.Insert(_event);

                            if (lAccount != null && lAccount.Count > 0)
                            {
                                foreach (var item in lAccount)
                                {
                                    var notificationPreference = _notificationPreferenceService.GetNotificationPreferenceByAccountId(item.Id.Value);
                                    if (notificationPreference.Any(x => x.EventTypeId == Constant.EventType.HomePowerLoss && x.ApplianceId == appliance.Id))
                                    {
                                        var temp = notificationPreference.FirstOrDefault(x => x.EventTypeId == Constant.EventType.HomePowerLoss && x.ApplianceId == appliance.Id);

                                        var accountAppliance = _accountApplianceService.GetAccountApplianceByAccountIdAndApplianceId(temp.AccountId, temp.ApplianceId);
                                        if (accountAppliance.PhoneType == Configuration.Android)
                                        {
                                            var pushGcmotification = new AndroidGcmPushNotification(_appSettings);
                                            pushGcmotification.InitPushNotification(accountAppliance.DeviceToken, insEvent.Message);
                                            System.Threading.Thread.Sleep(1000);
                                        }
                                        else
                                        {
                                            var applePush = new ApplePushNotificationService(_appSettings);
                                            applePush.PushMessage(insEvent.Message, accountAppliance.DeviceToken, 0, null).Wait();
                                            System.Threading.Thread.Sleep(1000);
                                        }

                                        var notification = new Notification()
                                        {
                                            AccountId   = accountAppliance.AccountId,
                                            ApplianceId = accountAppliance.ApplianceId,
                                            EventId     = insEvent.Id,
                                            Timestamp   = DateTime.UtcNow
                                        };

                                        _notificationService.Insert(notification);
                                    }
                                }
                            }
                        }

                        if (isWifiStatusChange)
                        {
                            _event = new Event()
                            {
                                ApplianceId = Convert.ToInt64(appliance.Id),
                                EventTypeId = request.msg != null && request.msg == Constant.EventType.StatusChangeFromGeoFence.ToString() ? Constant.EventType.StatusChangeFromGeoFence : Constant.EventType.NetWorkStatusChange,
                                EventDetail = Constant.ResponseMessage.Wifi,
                                Timestamp   = DateTime.UtcNow,
                                Message     = appliance.DeviceName + "(" + appliance.SerialNumber.Substring(appliance.SerialNumber.Length - 4) + ")" + ": " + Constant.ResponseMessage.Wifi + " " + (array.Length == 4 && Convert.ToBoolean(Convert.ToInt16(array[1].ToString())) ? Configuration.TurnOn.ToUpper() : Configuration.TurnOff.ToUpper())
                            };

                            var insEvent = _eventService.Insert(_event);

                            if (lAccount != null && lAccount.Count > 0)
                            {
                                foreach (var item in lAccount)
                                {
                                    var notificationPreference = _notificationPreferenceService.GetNotificationPreferenceByAccountId(item.Id.Value);
                                    if (notificationPreference.Any(x => x.EventTypeId == Constant.EventType.NetWorkStatusChange && x.ApplianceId == appliance.Id))
                                    {
                                        var temp             = notificationPreference.FirstOrDefault(x => x.EventTypeId == Constant.EventType.NetWorkStatusChange && x.ApplianceId == appliance.Id);
                                        var accountAppliance = _accountApplianceService.GetAccountApplianceByAccountIdAndApplianceId(temp.AccountId, temp.ApplianceId);
                                        if (accountAppliance.PhoneType == Configuration.Android)
                                        {
                                            var pushGcmotification = new AndroidGcmPushNotification(_appSettings);
                                            pushGcmotification.InitPushNotification(accountAppliance.DeviceToken, insEvent.Message);
                                            System.Threading.Thread.Sleep(1000);
                                        }
                                        else
                                        {
                                            var applePush = new ApplePushNotificationService(_appSettings);
                                            applePush.PushMessage(insEvent.Message, accountAppliance.DeviceToken, 0, null).Wait();
                                            System.Threading.Thread.Sleep(1000);
                                        }

                                        var notification = new Notification()
                                        {
                                            AccountId   = accountAppliance.AccountId,
                                            ApplianceId = accountAppliance.ApplianceId,
                                            EventId     = insEvent.Id,
                                            Timestamp   = DateTime.UtcNow
                                        };

                                        _notificationService.Insert(notification);
                                    }
                                }
                            }
                        }

                        if (isWiFiInternetStatusChange)
                        {
                            _event = new Event()
                            {
                                ApplianceId = Convert.ToInt64(appliance.Id),
                                EventTypeId = Constant.EventType.ISPOutage,
                                EventDetail = Constant.ResponseMessage.ISPOutage,
                                Timestamp   = DateTime.UtcNow,
                                Message     = appliance.DeviceName + "(" + appliance.SerialNumber.Substring(appliance.SerialNumber.Length - 4) + ")" + ": " + Constant.ResponseMessage.ISPOutage + " " + (array.Length == 4 && Convert.ToBoolean(Convert.ToInt16(array[0].ToString())) ? Configuration.Connected : Configuration.Disconnected)
                            };

                            var insEvent = _eventService.Insert(_event);

                            if (lAccount != null && lAccount.Count > 0)
                            {
                                foreach (var item in lAccount)
                                {
                                    var notificationPreference = _notificationPreferenceService.GetNotificationPreferenceByAccountId(item.Id.Value);
                                    if (notificationPreference.Any(x => x.EventTypeId == Constant.EventType.ISPOutage && x.ApplianceId == appliance.Id))
                                    {
                                        var temp             = notificationPreference.FirstOrDefault(x => x.EventTypeId == Constant.EventType.ISPOutage && x.ApplianceId == appliance.Id);
                                        var accountAppliance = _accountApplianceService.GetAccountApplianceByAccountIdAndApplianceId(temp.AccountId, temp.ApplianceId);
                                        if (accountAppliance.PhoneType == Configuration.Android)
                                        {
                                            var pushGcmotification = new AndroidGcmPushNotification(_appSettings);
                                            pushGcmotification.InitPushNotification(accountAppliance.DeviceToken, insEvent.Message);
                                            System.Threading.Thread.Sleep(1000);
                                        }
                                        else
                                        {
                                            var applePush = new ApplePushNotificationService(_appSettings);
                                            applePush.PushMessage(insEvent.Message, accountAppliance.DeviceToken, 0, null).Wait();
                                            System.Threading.Thread.Sleep(1000);
                                        }

                                        var notification = new Notification()
                                        {
                                            AccountId   = accountAppliance.AccountId,
                                            ApplianceId = accountAppliance.ApplianceId,
                                            EventId     = insEvent.Id,
                                            Timestamp   = DateTime.UtcNow
                                        };

                                        _notificationService.Insert(notification);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (request.key.ToLower() == Configuration.Trust.ToLower())
                {
                    if (appliance != null)
                    {
                        bool isStatusChange = appliance.TrustLevel != null && appliance.TrustLevel.Value.ToString() != request.value ? true : false;
                        _event = new Event()
                        {
                            ApplianceId = Convert.ToInt64(appliance.Id),
                            EventTypeId = Constant.EventType.TrustLevelChange,
                            EventDetail = Constant.ResponseMessage.TrustLevel,
                            Timestamp   = DateTime.UtcNow,
                            Message     = Constant.ResponseMessage.TrustLevel + " " + request.value
                        };

                        _eventService.Insert(_event);
                        appliance.TrustLevel = Convert.ToInt16(request.value);
                        _applianceService.Update(appliance);
                    }
                }
                else if (request.key.ToLower() == Configuration.TimmerState)
                {
                    if (appliance != null)
                    {
                        appliance.TimerEnabled = Convert.ToInt16(request.value) != Configuration.TimerDisable ? true : false;
                        _applianceService.Update(appliance);
                    }
                }
                else if (request.key.ToLower() == Configuration.TimerSchedule)
                {
                    var    timerScheduleDTO      = JsonConvert.DeserializeObject <TimerScheduleFromTelit>(request.value);
                    var    timerScheduleOldValue = JsonConvert.DeserializeObject <TimerScheduleFromTelit>(request.prev);
                    char[] weekDayArray          = timerScheduleDTO.Weekdays.ToCharArray();
                    char[] weekEndArray          = timerScheduleDTO.Weekends.ToCharArray();
                    string valueWeekDay          = string.Empty;
                    string valueWeekEnd          = string.Empty;

                    for (int i = 0; i < weekDayArray.Length; i++)
                    {
                        if (weekDayArray[i] == '1')
                        {
                            valueWeekDay += i + 1 + ",";
                        }
                    }

                    for (int i = 0; i < weekEndArray.Length; i++)
                    {
                        if (weekEndArray[i] == '1')
                        {
                            valueWeekEnd += i + 1 + ",";
                        }
                    }

                    var timerSchedule = _timerScheduleService.GetTimerScheduleByApplianceId(appliance.Id);
                    if (timerSchedule != null && timerSchedule.Count > 0)
                    {
                        foreach (var item in timerSchedule)
                        {
                            if (item.TimerTypeId == Configuration.Weekdays)
                            {
                                item.ActiveValues = !string.IsNullOrEmpty(valueWeekDay) ? valueWeekDay.Remove(valueWeekDay.Length - 1) : string.Empty;
                            }

                            if (item.TimerTypeId == Configuration.Weekends)
                            {
                                item.ActiveValues = !string.IsNullOrEmpty(valueWeekEnd) ? valueWeekEnd.Remove(valueWeekEnd.Length - 1) : string.Empty;
                            }
                            _timerScheduleService.Update(item);
                        }

                        _event = new Event()
                        {
                            ApplianceId = Convert.ToInt64(appliance.Id),
                            EventTypeId = Constant.EventType.ScheduleTimerChange,
                            EventDetail = Constant.ResponseMessage.ScheduleTimerChange,
                            Timestamp   = DateTime.UtcNow,
                            Message     = "from Weekdays: " + timerScheduleOldValue.Weekdays + " Weekends: " + timerScheduleOldValue.Weekends + " to Weekdays: " + timerScheduleDTO.Weekdays + " Weekends: " + timerScheduleDTO.Weekends
                        };

                        _eventService.Insert(_event);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(valueWeekDay))
                        {
                            var timerScheduleOfWeekDays = new TimerSchedule()
                            {
                                TimerTypeId  = Configuration.Weekdays,
                                ApplianceId  = appliance.Id,
                                ActiveValues = !string.IsNullOrEmpty(valueWeekDay) ? valueWeekDay.Remove(valueWeekDay.Length - 1) : string.Empty
                            };
                            _timerScheduleService.Insert(timerScheduleOfWeekDays);
                        }

                        if (!string.IsNullOrEmpty(valueWeekEnd))
                        {
                            var timerScheduleOfWeekEnd = new TimerSchedule()
                            {
                                TimerTypeId  = Configuration.Weekends,
                                ApplianceId  = appliance.Id,
                                ActiveValues = !string.IsNullOrEmpty(valueWeekEnd) ? valueWeekEnd.Remove(valueWeekEnd.Length - 1) : string.Empty
                            };
                            _timerScheduleService.Insert(timerScheduleOfWeekEnd);
                        }

                        _event = new Event()
                        {
                            ApplianceId = Convert.ToInt64(appliance.Id),
                            EventTypeId = Constant.EventType.ScheduleTimerChange,
                            EventDetail = Constant.ResponseMessage.ScheduleTimerChange,
                            Timestamp   = DateTime.UtcNow,
                            Message     = "from Weekdays: " + timerScheduleOldValue.Weekdays + " Weekends: " + timerScheduleOldValue.Weekends + " to Weekdays: " + timerScheduleDTO.Weekdays + " Weekends: " + timerScheduleDTO.Weekends
                        };

                        _eventService.Insert(_event);
                    }
                }
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, message = ex.Message }));
            }
            return(Json(new { success = true, message = request.msg }));
        }
Beispiel #5
0
        public async Task <ResponseData <Dashboard> > UpdateGeoFenceTrip(string uuid, string lat, string lon)
        {
            try
            {
                var response = new ResponseData <Dashboard>();

                var lAccountAppliance = _accountApplianceService.GetAccountApplianceByUUID(uuid);

                //get all appliance by uuid
                var listAppliance = _accountApplianceService.GetAllApplianceOfUUID(uuid);

                if (listAppliance != null && listAppliance.Count() > 0)
                {
                    foreach (var item in listAppliance)
                    {
                        if (item.GeoFenceEnabled == false && item.TimerEnabled == false)
                        {
                            continue;
                        }

                        bool isTurnOnNetwork = false;

                        if (item.GeoFenceEnabled.Value)
                        {
                            if (lAccountAppliance != null && lAccountAppliance.Count > 0)
                            {
                                foreach (var accountAppliance in lAccountAppliance)
                                {
                                    if (accountAppliance.ApplianceId == item.Id)
                                    {
                                        accountAppliance.Lat = Convert.ToDouble(lat);
                                        accountAppliance.Lon = Convert.ToDouble(lon);
                                        _accountApplianceService.Update(accountAppliance);
                                    }
                                }
                            }
                            var lAccounts = _accountApplianceService.GetAccountByApplianceId(item.Id, true);
                            //lAccounts = lAccounts.Where(x => x.Id != item.Id).ToList();

                            foreach (var account in lAccounts)
                            {
                                if (!isTurnOnNetwork)
                                {
                                    double lon1       = item.Lon != null && item.Lon.HasValue ? item.Lon.Value : 0;
                                    double lat1       = item.Lat != null && item.Lat.HasValue ? item.Lat.Value : 0;
                                    double lon2       = account.Lon != null && account.Lon.HasValue ? account.Lon.Value : 0;
                                    double lat2       = account.Lat != null && account.Lat.HasValue ? account.Lat.Value : 0;
                                    var    isMatching = DistanceBetweenPlaces(lon1, lat1, lon2, lat2);
                                    if (isMatching < Convert.ToDouble(item.TriggerMile))
                                    {
                                        isTurnOnNetwork = true;
                                    }
                                }
                            }

                            //get appliance in telit
                            string applianceEnvironment = string.Empty;
                            var    thingFind            = await TelitApi.ThingFind(item.SerialNumber);

                            Telit.ThingFind.Params _params = new Telit.ThingFind.Params();
                            bool?wifi = null;

                            if (thingFind != null && thingFind.Things != null && thingFind.Things.success && thingFind.Things.@params != null)
                            {
                                _params = thingFind.Things.@params;
                            }

                            if (_params != null && _params.alarms != null && _params.alarms.env != null && _params.alarms.env.state >= 0 && _params.alarms.env.state < 16)
                            {
                                applianceEnvironment = Convert.ToString(_params.alarms.env.state, 2).PadLeft(4, '0');
                                var array = !string.IsNullOrEmpty(applianceEnvironment) ? applianceEnvironment.ToArray() : new char[] { };

                                wifi = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[1].ToString())) : false;
                            }

                            if (!string.IsNullOrEmpty(applianceEnvironment) && wifi != null && wifi.HasValue)
                            {
                                if (wifi.Value != isTurnOnNetwork)
                                {
                                    if (isTurnOnNetwork)
                                    {
                                        var updateTimerState = await TelitApi.UpdateTimerState(item.SerialNumber, Configuration.TimerEnable, true);

                                        string message = "Update from Geofence";
                                        await TelitApi.UpdateAlarmState(item.SerialNumber, AlarmStatus.OnGeofence, message);

                                        var UpdateNetwork = await TelitApi.UpdateEnvironment(item.SerialNumber, Convert.ToInt32(ReplaceAt(applianceEnvironment, 1, '1'), 2), Constant.EventType.StatusChangeFromGeoFence.ToString());

                                        var isSuccess = await TelitApi.UpdateAlarmState(item.SerialNumber, AlarmStatus.OnGeofence, string.Empty);
                                    }
                                    else
                                    {
                                        var updateTimerState = await TelitApi.UpdateTimerState(item.SerialNumber, Configuration.TimerDisable, false);

                                        string message = "Update from Geofence";
                                        await TelitApi.UpdateAlarmState(item.SerialNumber, AlarmStatus.OffGeofence, message);

                                        var UpdateNetwork = await TelitApi.UpdateEnvironment(item.SerialNumber, Convert.ToInt32(ReplaceAt(applianceEnvironment, 1, '0'), 2), Constant.EventType.StatusChangeFromGeoFence.ToString());

                                        var isSuccess = await TelitApi.UpdateAlarmState(item.SerialNumber, AlarmStatus.OffGeofence, string.Empty);
                                    }
                                }
                            }
                        }
                    }
                }

                response.Status = ResponseStatus.Success.ToString();
                return(response);
            }
            catch (Exception ex)
            {
                var response = new ResponseData <Dashboard>();
                response.Message = ex.Message;
                response.Status  = ResponseStatus.Error.ToString();
                return(response);
            }
        }
Beispiel #6
0
        public async Task <ResponseData <Dashboard> > Index(string accountid, string applianceid)
        {
            try
            {
                var accountAppliance = _accountApplianceService.GetAccountApplianceByAccountId(Convert.ToInt64(accountid));
                var _event           = _eventService.GetEventByApplianceId(Convert.ToInt64(applianceid));
                var lAccounts        = _accountApplianceService.GetAccountByApplianceId(Convert.ToInt64(applianceid), true);
                List <AccountApplianceDTO> accountApplianceDTO = new List <AccountApplianceDTO>();

                if (accountAppliance != null && accountAppliance.Count > 0)
                {
                    foreach (var item in accountAppliance)
                    {
                        accountApplianceDTO.Add(new AccountApplianceDTO(item));
                    }
                }

                lAccounts = lAccounts.Where(x => x.Id != Convert.ToInt64(accountid)).ToList();

                if (!TelitApi.IsConnected)
                {
                    TelitApi.CheckIOTConnection().Wait();
                }

                var appliance = _applianceService.GetApplianceById(Convert.ToInt64(applianceid));
                var thingFind = await TelitApi.ThingFind(appliance.SerialNumber);



                Telit.ThingFind.Params _params = new Telit.ThingFind.Params();
                string applianceEnvironment    = string.Empty;

                ApplianceDTO applianceDTO = new ApplianceDTO();

                if (thingFind != null && thingFind.Things != null && thingFind.Things.success && thingFind.Things.@params != null)
                {
                    _params = thingFind.Things.@params;
                }

                if (_params != null && _params.alarms != null && _params.alarms.env != null && _params.alarms.env.state >= 0 && _params.alarms.env.state < 16)
                {
                    applianceEnvironment = Convert.ToString(_params.alarms.env.state, 2).PadLeft(4, '0');
                    var array = !string.IsNullOrEmpty(applianceEnvironment) ? applianceEnvironment.ToArray() : new char[] { };

                    applianceDTO.Cellular     = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[2].ToString())) : false;
                    applianceDTO.Power        = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[3].ToString())) : false;
                    applianceDTO.Wifi         = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[1].ToString())) : false;
                    applianceDTO.WiFiInternet = array.Length == 4 ? Convert.ToBoolean(Convert.ToInt16(array[0].ToString())) : false;
                }

                applianceDTO.TimerEnabled = _params != null && _params.alarms != null && _params.alarms.timerState != null ? (Convert.ToInt64(_params.alarms.timerState.state) != 0 ? true : false) : false;
                applianceDTO.DeviceName   = _params != null && _params.attrs != null && _params.attrs.name != null ? _params.attrs.name.value : appliance.DeviceName;
                applianceDTO.SerialNumber = appliance.SerialNumber;
                applianceDTO.TriggerMile  = appliance.TriggerMile;
                applianceDTO.Id           = appliance.Id;
                applianceDTO.IsOn         = _params != null && _params.alarms != null && _params.alarms.on != null?CheckApplianceIsOn(Convert.ToInt16(_params.alarms.on.state)) : false;

                applianceDTO.IsConnected     = _params.connected;
                applianceDTO.Lat             = appliance.Lat;
                applianceDTO.Lon             = appliance.Lon;
                applianceDTO.GeoFenceEnabled = appliance.GeoFenceEnabled;
                applianceDTO.Status          = appliance.Status;

                if (_params != null && _params.alarms != null)
                {
                    applianceDTO.TrustLevel = _params.alarms.trust != null ? (int?)_params.alarms.trust.state : 3;
                }

                var plans = _stripeService.GetPlans();

                var      subscriptionId = _accountApplianceService.GetAccountApplianceByAccountIdAndApplianceId(Convert.ToInt64(accountid), Convert.ToInt64(applianceid));
                DateTime?expireDate     = null;
                bool     cancelAtEnd    = false;
                if (subscriptionId != null && !string.IsNullOrEmpty(subscriptionId.SubscriptionId))
                {
                    var stripe = _stripeService.RetrieveSubscription(subscriptionId.SubscriptionId);
                    // current period end
                    expireDate  = stripe.CurrentPeriodEnd;
                    cancelAtEnd = stripe.CancelAtPeriodEnd;
                }

                var dashboard = new Dashboard()
                {
                    AccountAppliance     = accountApplianceDTO,
                    Events               = _event,
                    ListAccountsDTO      = lAccounts,
                    IsIOTConnected       = TelitApi.IsConnected,
                    Plans                = plans,
                    AppDTO               = applianceDTO,
                    ExpireDate           = expireDate,
                    CancelAtEnd          = cancelAtEnd,
                    IsApplianceConnected = applianceDTO.IsConnected.Value
                };

                var response = new ResponseData <Dashboard>();

                response.Data    = dashboard;
                response.Message = ResponseMessage.Success;
                response.Status  = ResponseStatus.Success.ToString();
                return(response);
            }
            catch (Exception ex)
            {
                var response = new ResponseData <Dashboard>();
                response.Message = ex.Message;
                response.Status  = ResponseStatus.Error.ToString();
                return(response);
            }
        }
Beispiel #7
0
        public async Task <ResponseData <Dashboard> > SetAirGapOn(string applianceid, string accountId, string airGapAlwaysStatus)
        {
            try
            {
                var appliance = _applianceService.GetApplianceById(Convert.ToInt64(applianceid));
                var account   = _accountService.GetAccountById(appliance.AccountId.Value);
                var thingFind = await TelitApi.ThingFind(appliance.SerialNumber);

                Telit.ThingFind.Params _params = new Telit.ThingFind.Params();
                string applianceEnvironment    = string.Empty;


                if (thingFind != null && thingFind.Things != null && thingFind.Things.success && thingFind.Things.@params != null)
                {
                    _params = thingFind.Things.@params;
                }
                bool isOn = _params != null && _params.alarms != null && _params.alarms.on != null?CheckApplianceIsOn(Convert.ToInt16(_params.alarms.on.state)) : false;

                if (airGapAlwaysStatus.ToLower() == Configuration.TurnOff.ToLower())
                {
                    appliance.TimerEnabled    = true;
                    appliance.GeoFenceEnabled = true;
                    var isSuccess = await TelitApi.UpdateTimerState(appliance.SerialNumber, Configuration.TimerEnable, appliance.IsOn.Value);
                }
                else
                {
                    if (isOn == false)
                    {
                        string message   = "Update from WebPortal by " + account.Email;
                        var    isSuccess = await TelitApi.UpdateAlarmState(appliance.SerialNumber, airGapAlwaysStatus == Configuration.TurnOff.ToLower()?AlarmStatus.OffPortal : AlarmStatus.OnPortal, message);

                        var updateTimerState = await TelitApi.UpdateTimerState(appliance.SerialNumber, Configuration.TimerDisable, appliance.IsOn.Value);
                    }
                    else
                    {
                        var updateTimerState = await TelitApi.UpdateTimerState(appliance.SerialNumber, Configuration.TimerDisable, appliance.IsOn.Value);
                    }

                    appliance.TimerEnabled    = false;
                    appliance.GeoFenceEnabled = false;
                }

                _applianceService.Update(appliance);

                var _event = new Event()
                {
                    ApplianceId = Convert.ToInt64(applianceid),
                    AccountId   = Convert.ToInt64(accountId),
                    EventTypeId = Constant.EventType.AlwaysOnStatusChange,
                    EventDetail = Constant.ResponseMessage.AlwaysOnStatusChange,
                    Timestamp   = DateTime.UtcNow,
                    Message     = Constant.ResponseMessage.AlwaysOnStatusChange + " " + airGapAlwaysStatus.ToUpper()
                };

                _eventService.Insert(_event);

                var response = new ResponseData <Dashboard>();
                response.Message = ResponseMessage.Success;
                response.Status  = ResponseStatus.Success.ToString();
                return(response);
            }
            catch (Exception ex)
            {
                var response = new ResponseData <Dashboard>();
                response.Message = ex.Message;
                response.Status  = ResponseStatus.Error.ToString();
                return(response);
            }
        }