Example #1
0
        public bool RemoveSubscription(string id, DeviceSubscription deviceSubscription)
        {
            if (!this.devices.TryGetValue(Preconditions.CheckNonWhiteSpace(id, nameof(id)), out ConnectedDevice device))
            {
                throw new ArgumentException($"A connection for {id} not found.");
            }

            // setting 'hasChanged' to false, so if no device connection, it doesn't indicate status change
            bool hasChanged = false;

            device.DeviceConnection.Filter(d => d.IsActive)
            .ForEach(d =>
            {
                hasChanged = false;     // if there is no old value, that means no subscription, so this is not a change
                d.Subscriptions.AddOrUpdate(
                    deviceSubscription,
                    false,
                    (_, old) =>
                {
                    hasChanged = old != false;
                    return(false);
                });
            });

            return(hasChanged);
        }
 public Task RemoveSubscription(string id, DeviceSubscription deviceSubscription)
 {
     Events.RemovingSubscription(id, deviceSubscription);
     this.ConnectionManager.RemoveSubscription(id, deviceSubscription);
     this.HandleSubscriptions(id, new List <(DeviceSubscription, bool)> {
         (deviceSubscription, false)
     });
     return(Task.CompletedTask);
 }
Example #3
0
        public async Task <ApiResponse> PostDeviceNotificationAsync(DeviceSubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException(nameof(subscription));
            }

            return(await DoApiRequestAsync($"device/notification", HttpMethod.Post, subscription));
        }
Example #4
0
        public async Task <ApiResponse> DeleteDeviceNotificationAsync(DeviceSubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException(nameof(subscription));
            }

            return(await DoApiRequestAsync($"device/notification/{subscription.ApplicationName}/{subscription.DeviceToken}", HttpMethod.Delete));
        }
Example #5
0
 public void RemoveSubscription(string id, DeviceSubscription deviceSubscription)
 {
     if (!this.devices.TryGetValue(Preconditions.CheckNonWhiteSpace(id, nameof(id)), out ConnectedDevice device))
     {
         throw new ArgumentException($"A connection for {id} not found.");
     }
     device.DeviceConnection.Filter(d => d.IsActive)
     .ForEach(d => d.Subscriptions[deviceSubscription] = false);
 }
Example #6
0
 private bool UnsubscribeOutput(SubscriptionState state, DeviceSubscription deviceSubscription)
 {
     Logger.Debug($"Unsubscribing output device: {{{deviceSubscription.Device.LogName()}}}");
     if (string.IsNullOrEmpty(deviceSubscription.Device.ProviderName) || string.IsNullOrEmpty(deviceSubscription.Device.DeviceHandle))
     {
         Logger.Error($"Failed to unsubscribe output device. Providername or devicehandle missing from: {{{deviceSubscription.Device.LogName()}}}");
         return(false);
     }
     return(_context.IOController.UnsubscribeOutput(GetOutputSubscriptionRequest(state.StateGuid, deviceSubscription)));
 }
Example #7
0
 public static void ErrorAddingSubscription(Exception ex, string id, DeviceSubscription subscription)
 {
     if (ex.HasTimeoutException())
     {
         Log.LogDebug((int)EventIds.ErrorAddingSubscription, ex, Invariant($"Timed out while adding subscription {subscription} for client {id}. Will try again when connected."));
     }
     else
     {
         Log.LogDebug((int)EventIds.ErrorAddingSubscription, ex, Invariant($"Error adding subscription {subscription} for client {id}."));
     }
 }
Example #8
0
 static Task AddOrRemoveSubscription(IDeviceListener listener, bool add, DeviceSubscription subscription)
 {
     if (add)
     {
         return(listener.AddSubscription(subscription));
     }
     else
     {
         return(listener.RemoveSubscription(subscription));
     }
 }
Example #9
0
        public void Push(DeviceSubscription subscription, Payload payload)
        {
            var context = new PushContext {
                Subscription = subscription, Payload = payload
            };

            if (OperationContext.Current != null)
            {
                context.Callback = OperationContext.Current.GetCallbackChannel <IPushCallback>();
            }

            if (subscription.Channel.PlatformType == PlatformType.Apple)
            {
                var notification = new AppleNotification(subscription.SubscriptionId)
                {
                    Tag = context
                };
                if (payload != null)
                {
                    var p = new AppleNotificationPayload();
                    p.Alert = new AppleNotificationAlert {
                        Body = payload.Alert
                    };
                    p.Badge              = payload.Badge;
                    p.Sound              = payload.Sound;
                    p.CustomJson         = payload.Custom; //https://github.com/caniusq/PushSharp
                    notification.Payload = p;
                }

                PushBrokerManager.Broker.QueueNotification(notification, subscription.Channel.ApplicationId);
            }
            else if (subscription.Channel.PlatformType == PlatformType.Beyondbit)
            {
                var notification = new BeyondBit.PushClientLib.BeyondBitNotification {
                    DeviceToken = subscription.SubscriptionId, Tag = context
                };
                if (payload != null)
                {
                    var bnp = new BeyondBit.PushClientLib.BeyondbitNotificationPayload();
                    bnp.Alert            = payload.Alert;
                    bnp.Badge            = payload.Badge;
                    bnp.Sound            = payload.Sound;
                    bnp.CustomJson       = payload.Custom;
                    notification.Payload = bnp;
                }

                PushBrokerManager.Broker.QueueNotification(notification, subscription.Channel.ApplicationId);
            }
            else
            {
                throw new NotImplementedException();
            }
        }
Example #10
0
            public static void ErrorProcessingSubscription(string id, DeviceSubscription subscription, bool addSubscription, Exception ex)
            {
                string operation = addSubscription ? "adding" : "removing";

                if (ex.HasTimeoutException())
                {
                    Log.LogDebug((int)EventIds.ErrorAddingSubscription, ex, Invariant($"Timed out while processing subscription {subscription} for client {id}. Will try to add subscription when the device is online."));
                }
                else
                {
                    Log.LogWarning((int)EventIds.ErrorRemovingSubscription, ex, Invariant($"Error {operation} subscription {subscription} for client {id}."));
                }
            }
Example #11
0
            public static void ErrorProcessingSubscription(string id, DeviceSubscription subscription, bool addSubscription, RetryingEventArgs r)
            {
                Exception ex         = r.LastException;
                string    operation  = addSubscription ? "adding" : "removing";
                int       retryCount = r.CurrentRetryCount;

                if (ex.HasTimeoutException())
                {
                    Log.LogDebug((int)EventIds.ErrorAddingSubscription, ex, Invariant($"Timed out while processing subscription {subscription} for client {id} on attempt {retryCount}."));
                }
                else
                {
                    Log.LogDebug((int)EventIds.ErrorRemovingSubscription, ex, Invariant($"Error {operation} subscription {subscription} for client {id} on attempt {retryCount}."));
                }
            }
Example #12
0
        public async Task RemoveSubscription(string id, DeviceSubscription deviceSubscription)
        {
            Events.RemovingSubscription(id, deviceSubscription);
            this.connectionManager.RemoveSubscription(id, deviceSubscription);
            try
            {
                Option <ICloudProxy> cloudProxy = await this.connectionManager.GetCloudConnection(id);

                await this.ProcessSubscription(id, cloudProxy, deviceSubscription, false);
            }
            catch (Exception e)
            {
                Events.ErrorRemovingSubscription(e, id, deviceSubscription);
            }
        }
Example #13
0
        public static IEnumerable <(DeviceSubscription, bool)> GetDeviceSubscriptions(IReadOnlyDictionary <string, bool> topics, string id)
        {
            return(topics.Select(
                       subscriptionRegistration =>
            {
                string topicName = subscriptionRegistration.Key;
                bool addSubscription = subscriptionRegistration.Value;
                DeviceSubscription deviceSubscription = GetDeviceSubscription(topicName);
                if (deviceSubscription == DeviceSubscription.Unknown)
                {
                    Events.UnknownTopicSubscription(topicName, id);
                }

                return (deviceSubscription, addSubscription);
            }));
        }
Example #14
0
        public async Task <IActionResult> Post([Bind(DeviceSubscription.USER_INPUT_FIELDS)] DeviceSubscription device)
        {
            if (!device.PushEndpoint.StartsWith("https://fcm.googleapis.com/fcm/send"))
            {
                return(Forbid("PushEndpoint must start with https://fcm.googleapis.com/fcm/send"));
            }

            if (!Uri.IsWellFormedUriString(device.PushEndpoint, UriKind.Absolute))
            {
                return(Forbid("Not well formed Url"));
            }

            _context.DevicesSubscriptions.Add(device);
            await _context.SaveChangesAsync();

            return(Ok());
        }
Example #15
0
        public Task RemoveSubscription(string id, DeviceSubscription deviceSubscription)
        {
            Events.RemovingSubscription(id, deviceSubscription);
            var hasChanged = this.ConnectionManager.RemoveSubscription(id, deviceSubscription);

            if (hasChanged)
            {
                this.HandleSubscriptions(id, new List <(DeviceSubscription, bool)> {
                    (deviceSubscription, false)
                });
            }
            else
            {
                Events.UnchangedSubscription(id, deviceSubscription);
            }

            return(Task.CompletedTask);
        }
Example #16
0
 public async Task AddSubscription(string id, DeviceSubscription deviceSubscription)
 {
     Events.AddingSubscription(id, deviceSubscription);
     this.connectionManager.AddSubscription(id, deviceSubscription);
     try
     {
         Option <ICloudProxy> cloudProxy = this.connectionManager.GetCloudConnection(id);
         await this.ProcessSubscription(id, cloudProxy, deviceSubscription, true);
     }
     catch (Exception e)
     {
         Events.ErrorAddingSubscription(e, id, deviceSubscription);
         if (!e.HasTimeoutException())
         {
             throw;
         }
     }
 }
Example #17
0
        public IHttpActionResult PostInitializeDeviceOwner(string deviceCode, string customDeviceName)
        {
            var acc = User.GetCurrentUserAccount(_context.Accounts);

            var device = _context.Devices.SingleOrDefault(d => d.Sid == deviceCode);

            if (device == null)
            {
                return(BadRequest($"Device with identifier '{deviceCode}' is not registered."));
            }

            var ownerSubscriptions = _context.DeviceSubscriptions
                                     .Where(s => s.DeviceId == device.Id && s.Role == SubscriptionRole.Owner);

            if (ownerSubscriptions.Count() > 0)
            {
                return(BadRequest("Device owner is already initialzied."));
            }

            if (!string.IsNullOrWhiteSpace(customDeviceName))
            {
                device.CustomDeviceName = customDeviceName;
            }

            var subs = new DeviceSubscription()
            {
                AccountId = acc.Id,
                Account   = acc,
                DeviceId  = device.Id,
                Device    = device,
                Role      = SubscriptionRole.Owner,
            };

            _context.DeviceSubscriptions.Add(subs);
            _context.SaveChanges();

            return(Ok(new {
                subs.Id,
                subs.DeviceId,
                subs.Device.CustomDeviceName,
                subs.Role,
            }));
        }
 static Task AddOrRemoveSubscription(IDeviceListener listener, bool add, DeviceSubscription subscription)
 {
     try
     {
         if (add)
         {
             return(listener.AddSubscription(subscription));
         }
         else
         {
             return(listener.RemoveSubscription(subscription));
         }
     }
     catch (Exception e)
     {
         Events.FailedToChangeSubscriptionState(e, subscription.ToString(), listener.Identity.Id);
         return(Task.CompletedTask);
     }
 }
        async Task <IActionResult> CreateSubscriptionAsync(DeviceConfig config, Guid token, Guid appId)
        {
            const string baseUrl = "https://api.smartthings.com";
            string       path    = $"/installedapps/{appId}/subscriptions";

            DeviceSubscription subscription = new DeviceSubscription
            {
                sourceType = "DEVICE",
                device     = new DeviceSubscriptionInfo
                {
                    componentId      = config.ComponentId,
                    deviceId         = config.DeviceId.ToString(),
                    capability       = "contactSensor",
                    attribute        = "contact",
                    stateChangeOnly  = true,
                    subscriptionName = "contact_subscription",
                    value            = "open"
                }
            };

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(baseUrl);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());
            HttpResponseMessage response = await client.PostAsJsonAsync(path, subscription);

            if (response.IsSuccessStatusCode)
            {
                Debug.Print("Subscription was successful");
            }
            else
            {
                Debug.Print("Subscription was not successful");
                Debug.Print(response.StatusCode.ToString());
                Debug.Print(response.ReasonPhrase);
            }
            return(Ok(new InstallResponse()));
        }
Example #20
0
 public static void RemovingSubscription(string id, DeviceSubscription subscription)
 {
     Log.LogDebug((int)EventIds.RemovingSubscription, Invariant($"Removing subscription {subscription} for client {id}."));
 }
Example #21
0
 public bool CheckClientSubscription(string id, DeviceSubscription subscription) =>
 this.GetSubscriptions(id)
 .Filter(s => s.TryGetValue(subscription, out bool isActive) && isActive)
Example #22
0
        internal async Task ProcessSubscription(string id, Option <ICloudProxy> cloudProxy, DeviceSubscription deviceSubscription, bool addSubscription)
        {
            switch (deviceSubscription)
            {
            case DeviceSubscription.C2D:
                if (addSubscription)
                {
                    cloudProxy.ForEach(c => c.StartListening());
                }
                break;

            case DeviceSubscription.DesiredPropertyUpdates:
                await cloudProxy.ForEachAsync(c => addSubscription?c.SetupDesiredPropertyUpdatesAsync() : c.RemoveDesiredPropertyUpdatesAsync());

                break;

            case DeviceSubscription.Methods:
                if (addSubscription)
                {
                    await cloudProxy.ForEachAsync(c => c.SetupCallMethodAsync());

                    await this.invokeMethodHandler.ProcessInvokeMethodSubscription(id);
                }
                else
                {
                    await cloudProxy.ForEachAsync(c => c.RemoveCallMethodAsync());
                }
                break;

            case DeviceSubscription.ModuleMessages:
            case DeviceSubscription.TwinResponse:
            case DeviceSubscription.Unknown:
                // No Action required
                break;
            }
        }
Example #23
0
 public static void ErrorAddingSubscription(Exception ex, string id, DeviceSubscription subscription)
 {
     Log.LogWarning((int)EventIds.ErrorAddingSubscription, ex, Invariant($"Error adding subscription {subscription} for client {id}."));
 }
Example #24
0
 public Task RemoveSubscription(string id, DeviceSubscription deviceSubscription)
 => this.subscriptionProcessor.RemoveSubscription(id, deviceSubscription);
Example #25
0
 public Task RemoveSubscription(string id, DeviceSubscription deviceSubscription) => WhenCalled();
Example #26
0
 public SubscriptionPattern(string pattern, DeviceSubscription subscription)
 {
     this.Pattern      = Preconditions.CheckNotNull(pattern);
     this.Subscription = subscription;
 }
Example #27
0
 public Task RemoveSubscription(DeviceSubscription subscription) => Task.CompletedTask;
Example #28
0
 public Task RemoveSubscription(DeviceSubscription subscription)
 => this.edgeHub.RemoveSubscription(this.Identity.Id, subscription);
Example #29
0
 public Task AddSubscription(DeviceSubscription subscription)
 => this.edgeHub.AddSubscription(this.Identity.Id, subscription);
Example #30
0
 public static void ProcessingSubscription(string id, DeviceSubscription deviceSubscription)
 {
     Log.LogInformation((int)EventIds.ProcessingSubscription, Invariant($"Processing subscription {deviceSubscription} for client {id}."));
 }