Ejemplo n.º 1
0
        public bool AuthenticateAnonymousDevice(string device_id, string device_token)
        {
            TableOperation retrieveOperation = TableOperation.Retrieve <DynamicTableEntity>(device_id,
                                                                                            device_token);

            try
            {
                DynamicTableEntity device_entity = (DynamicTableEntity)this.DevicesTable.Execute
                                                       (retrieveOperation).Result;
                if (device_entity == null)
                {
                    return(false);
                }
                else
                {
                    IStorageDevice device = this.DeviceEntityResolver(device_entity.PartitionKey,
                                                                      device_entity.RowKey, device_entity.Timestamp, device_entity.Properties,
                                                                      device_entity.ETag);
                    OverlordIdentity.InitializeDeviceIdentity(device_id, device_token,
                                                              device.Sensors.Select(s => s.Key).ToArray <string>());
                    return(true);
                }
            }
            catch (Exception e)
            {
                Log.ReadTableFailure(string.Format
                                         ("Failed to retrieve device entity: Id: {0}, Token: {1}.", device_id, device_token), e);
                throw;
            }
        }
        public IStorageDeviceReading AddDeviceReading(DateTime time, IDictionary <string, object> values)
        {
            OverlordIdentity.AddClaim(Resource.Storage, StorageAction.FindDevice);
            IStorageDevice device = this.GetCurrentDevice();

            return(this.AddDeviceReading(device, time, values));
        }
Ejemplo n.º 3
0
        public IStorageDevice GetCurrentDevice()
        {
            IStorageDevice device = this.FindDevice(OverlordIdentity.CurrentDeviceId.ToGuid(),
                                                    OverlordIdentity.CurrentDeviceToken);

            if (device == null)
            {
                throw new NullReferenceException("Could not find current device id.");
            }
            return(device);
        }
Ejemplo n.º 4
0
        internal static DynamicTableEntity CreateDeviceTableEntity(IStorageDevice device)
        {
            Dictionary <string, EntityProperty> dictionary = new Dictionary <string, EntityProperty>();

            dictionary.Add("UserId", new EntityProperty(device.UserId));
            dictionary.Add("Name", new EntityProperty(device.Name));
            dictionary.Add("Description", new EntityProperty(device.Description));
            dictionary.Add("Location", new EntityProperty(JsonConvert.SerializeObject(device.Location)));
            string sensors_json = JsonConvert.SerializeObject(device.Sensors);

            dictionary.Add("Sensors", new EntityProperty(sensors_json));
            return(new DynamicTableEntity(device.Id.ToUrn(), device.Token, device.ETag, dictionary));
        }
Ejemplo n.º 5
0
        internal IStorageDevice DeviceEntityResolver(string partitionKey, string rowKey,
                                                     DateTimeOffset timestamp, IDictionary <string, EntityProperty> properties, string etag)
        {
            IStorageDevice device = new IStorageDevice();

            device.Id          = Guid.ParseExact(partitionKey, "D");
            device.Token       = rowKey;
            device.ETag        = etag;
            device.UserId      = properties["UserId"].GuidValue.Value;
            device.Name        = properties["Name"].StringValue;
            device.Description = properties.Keys.Contains("Description") ?
                                 properties["Description"].StringValue : null;
            device.Sensors = JsonConvert.DeserializeObject <IDictionary <string, IStorageSensor> >
                                 (properties["Sensors"].StringValue);
            device.Location = properties.Keys.Contains("Location") ?
                              JsonConvert.DeserializeObject <Common.GeoIp>(properties["Location"].StringValue) : null;
            return(device);
        }
Ejemplo n.º 6
0
        public IStorageSensor AddSensor(string sensor_name, string sensor_units,
                                        IList <Guid> sensor_channels, IList <IStorageAlert> sensor_alerts)
        {
            if (!sensor_name.IsVaildSensorName())
            {
                throw new ArgumentException(
                          string.Format("Invalid sensor name: {0}", sensor_name));
            }
            OverlordIdentity.AddClaim(Resource.Storage, StorageAction.FindDevice);
            IStorageDevice device = this.GetCurrentDevice();
            IStorageSensor sensor = new IStorageSensor()
            {
                DeviceId = device.Id,
                Name     = sensor_name,
                Unit     = sensor_units,
                Channels = sensor_channels,
                Alerts   = sensor_alerts
            };

            if (device.Sensors.Keys.Contains(sensor_name))
            {
                device.Sensors.Remove(sensor_name);
            }
            device.Sensors.Add(sensor_name, sensor);
            try
            {
                OverlordIdentity.AddClaim(Resource.Storage, StorageAction.UpdateDevice);
                this.UpdateDevice(device);
                Log.WriteTableSuccess(string.Format("Added sensor {0} to device entity: Id: {1}, Token: {2}",
                                                    sensor.Name, device.Id.ToUrn(), device.Token));
                return(sensor);
            }
            catch (Exception e)
            {
                Log.ReadTableFailure(string.Format("Failed to read table for device: Id: {0}, Token: {1}.",
                                                   device.Id.ToUrn(), device.Token), e);
                throw;
            }
            finally
            {
                OverlordIdentity.DeleteClaim(Resource.Storage, StorageAction.AddSensor);
            }
        }
Ejemplo n.º 7
0
        public IStorageDevice AddDevice(IStorageUser user, string name, string token, GeoIp location,
                                        string id = null)
        {
            IStorageDevice device = new IStorageDevice()
            {
                Id      = string.IsNullOrEmpty(id) ? Guid.NewGuid() : id.UrnToGuid(),
                UserId  = user.Id,
                Token   = token,
                Name    = name,
                Sensors = new Dictionary <string, IStorageSensor>()
            };

            try
            {
                TableOperation insert_device_operation = TableOperation
                                                         .Insert(AzureStorage.CreateDeviceTableEntity(device));
                TableResult result;
                result      = this.DevicesTable.Execute(insert_device_operation);
                device.ETag = result.Etag;
                user.Devices.Add(device.Id);
                TableOperation update_user_operation = TableOperation.Merge(CreateUserTableEntity(user));
                result    = this.UsersTable.Execute(update_user_operation);
                user.ETag = result.Etag;
                Log.WriteTableSuccess(string.
                                      Format("Added device entity: {0}, Id: {1}, Token {2} to Devices table.",
                                             device.Name, device.Id.ToUrn(), device.Token));
                Log.WriteTableSuccess(string.Format("Added device entity: {0}, Id: {1}, to User entity {2}.",
                                                    device.Name, device.Id.ToUrn(), device.Token, user.Id.ToUrn()));
                return(device);
            }
            catch (Exception e)
            {
                Log.WriteTableFailure(string.Format("Failed to add device entity: {0}, Id: {1}, Token {2}.",
                                                    device.Name, device.Id.ToUrn(), device.Token), e);
                throw;
            }
            finally
            {
                OverlordIdentity.DeleteClaim(Resource.Storage, StorageAction.AddDevice);
            }
        }
Ejemplo n.º 8
0
        public IStorageDevice UpdateDevice(IStorageDevice device)
        {
            TableOperation update_device_operation = TableOperation.Merge(CreateDeviceTableEntity(device));

            try
            {
                TableResult result = this.DevicesTable.Execute(update_device_operation);
                Log.WriteTableSuccess(string.Format("Updated device entity: {0}, Id: {1}, Token: {2}",
                                                    device.Name, device.Id.ToUrn(), device.Token, device.Id.ToUrn()));
                device.ETag = result.Etag;
                return(device);
            }
            catch (Exception e)
            {
                Log.WriteTableFailure(string.Format("Failed to update device entity: Id: {0}, Token: {1}.",
                                                    device.Id.ToUrn(), device.Token), e);
                throw;
            }
            finally
            {
                OverlordIdentity.DeleteClaim(Resource.Storage, StorageAction.UpdateDevice);
            }
        }
Ejemplo n.º 9
0
        public IStorageChannel AddChannel(string channel_name, string channel_description,
                                          string sensor_type, string channel_units, List <IStorageAlert> alerts)
        {
            OverlordIdentity.AddClaim(Resource.Storage, StorageAction.FindDevice);
            IStorageDevice device = this.GetCurrentDevice();

            IStorageChannel channel = new IStorageChannel()
            {
                Id          = Guid.NewGuid(),
                Name        = channel_name,
                Description = channel_description,
                SensorType  = sensor_type,
                Alerts      = alerts
            };

            try
            {
                TableOperation insert_channel_operation = TableOperation
                                                          .Insert(AzureStorage.CreateChannelTableEntity(channel));
                TableResult result;
                result = this.ChannelsTable.Execute(insert_channel_operation);
                Log.WriteTableSuccess(string.Format("Added Channel entity: {0}, Id: {1}.",
                                                    channel.Name, channel.Id.ToUrn()));
                return(channel);
            }
            catch (Exception e)
            {
                Log.WriteTableFailure(string.Format("Failed to add Channel entity: {0}, Id: {1}.", channel.Name,
                                                    channel.Id), e);
                throw;
            }
            finally
            {
                OverlordIdentity.DeleteClaim(Resource.Storage, StorageAction.AddChannel);
            }
        }
Ejemplo n.º 10
0
        public IStorageDeviceReading AddDeviceReading(IStorageDevice device, DateTime time, IDictionary <string, object> values)
        {
            if (values.Any(v => !v.Key.IsVaildSensorName()))
            {
                string bad_sensors = values.Where(v => !v.Key.IsVaildSensorName())
                                     .Select(v => v.Key + ":" + v.Value).Aggregate((a, b) => { return(a + " " + b + ","); });
                throw new ArgumentException("Device reading has bad sensor names. {0}", bad_sensors);
            }

            if (values.Any(v => v.Key.ToSensorType() != v.Value.GetType().UnderlyingSystemType))
            {
                string bad_sensors = values.Where(v => v.Key.ToSensorType() !=
                                                  v.Value.GetType().UnderlyingSystemType)
                                     .Select(v => v.Key + ":" + v.Value).Aggregate((a, b) => { return(a + " " + b + ","); });
                throw new ArgumentException(string.Format("Device reading has bad sensor values: {0}",
                                                          bad_sensors));
            }
            IStorageDeviceReading reading = new IStorageDeviceReading()
            {
                DeviceId     = device.Id,
                Time         = time,
                SensorValues = values
            };
            TableOperation insert_operation = TableOperation
                                              .InsertOrMerge(AzureStorage.CreateDeviceReadingEntity(reading));
            TableResult result;

            try
            {
                result       = this.SensorReadingsTable.Execute(insert_operation);
                reading.ETag = result.Etag;
                Log.WriteTableSuccess(string.Format
                                          ("Added device reading entity: Partition: {0}, RowKey: {1}, Sensor values: {2}",
                                          reading.Time.GeneratePartitionKey(),
                                          string.Format(CultureInfo.InvariantCulture, DeviceReadingKeyFormat,
                                                        reading.DeviceId, reading.Time.GetTicks()),
                                          reading.SensorValues
                                          .Select(v => v.Key + ":" + v.Value)
                                          .Aggregate((a, b) => { return(a + "," + b + " "); })));
            }
            catch (Exception e)
            {
                Log.WriteTableFailure(string.Format
                                          ("Added device reading entity: Partition: {0}, RowKey: {1}, {2}",
                                          reading.Time.GeneratePartitionKey(),
                                          string.Format(CultureInfo.InvariantCulture, DeviceReadingKeyFormat,
                                                        reading.DeviceId, reading.Time.GetTicks()),
                                          reading.SensorValues
                                          .Select(v => v.Key + ":" + v.Value)
                                          .Aggregate((a, b) => { return(a + "," + b + " "); })), e);
                throw;
            }
            finally
            {
                OverlordIdentity.DeleteClaim(Resource.Storage, StorageAction.AddDeviceReading);
            }

            try
            {
                IStorageDigestMessage message = new IStorageDigestMessage()
                {
                    Device       = device,
                    Time         = time,
                    SensorValues = reading.SensorValues,
                    ETag         = reading.ETag
                };
                this.DigestQueue.AddMessage(new CloudQueueMessage(JsonConvert.SerializeObject(message, this.jss)));
                Log.WriteQueueSuccess(string.Format
                                          ("Added digest message for device reading entity: Partition: {0}, RowKey: {1}, Sensor values: {2}",
                                          reading.Time.GeneratePartitionKey(),
                                          string.Format(CultureInfo.InvariantCulture, DeviceReadingKeyFormat,
                                                        reading.DeviceId, reading.Time.GetTicks()),
                                          reading.SensorValues
                                          .Select(v => v.Key + ":" + v.Value)
                                          .Aggregate((a, b) => { return(a + "," + b + " "); })));
                return(reading);
            }
            catch (Exception e)
            {
                Log.WriteQueueFailure(string.Format
                                          ("Failed to add digest message for device reading entity: Partition: {0}, RowKey: {1}, {2}",
                                          reading.Time.GeneratePartitionKey(),
                                          string.Format(CultureInfo.InvariantCulture, DeviceReadingKeyFormat,
                                                        reading.DeviceId, reading.Time.GetTicks()),
                                          reading.SensorValues
                                          .Select(v => v.Key + ":" + v.Value)
                                          .Aggregate((a, b) => { return(a + "," + b + " "); })), e);
                throw;
            }
        }
Ejemplo n.º 11
0
        public static IStorageDevice FindDevice(this IList <IStorageDevice> list, IStorageDevice device)
        {
            IStorageDeviceEq eq = new IStorageDeviceEq();

            return(list.FirstOrDefault(d => eq.Equals(device, d)));
        }
Ejemplo n.º 12
0
 public static bool ContainsDevice(this IList <IStorageDevice> list, IStorageDevice device)
 {
     return(list.Contains(device, new IStorageDeviceEq()));
 }