Beispiel #1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "config/{region}/{campus}/{building}")] HttpRequest req,
            [Blob("shared", Connection = "AzureWebJobsStorage")] CloudBlobContainer container,
            string region,
            string campus,
            string building,
            ILogger log)
        {
            bool prerequisites = true;
            var  errors        = new StringBuilder();

            var blobDataService = new BlobDataService();

            var atlasConfigFile = Environment.GetEnvironmentVariable("AtlasConfigFile") ?? "atlasConfig.json";

            if (string.IsNullOrEmpty(building))
            {
                prerequisites = false;
                errors.Append("Required query {building} was not defined");
            }

            var result = "";

            if (prerequisites)
            {
                try
                {
                    var config = await blobDataService.ReadBlobData <BuildingConfig[]>(container, atlasConfigFile);

                    var buildingCfg = config.FirstOrDefault(cfg => cfg.BuildingId.ToLower() == $"{region}/{campus}/{building}".ToLower());
                    if (buildingCfg != null)
                    {
                        result = JsonConvert.SerializeObject(buildingCfg);
                    }
                }
                catch (Exception ex)
                {
                    log.LogError(ex.Message);
                }
            }
            else
            {
                log.LogError(errors.ToString());
                return(new NotFoundResult());
            }

            return(new OkObjectResult(result));
        }
Beispiel #2
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            [Blob("shared", Connection = "AzureWebJobsStorage")] CloudBlobContainer container,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            bool prerequisites = true;

            var    errors  = new StringBuilder();
            string siteMap = "sitemap";

            string rebuild = req.Query["rebuild"];
            bool   full    = rebuild == "full";

            var siteMapFile = Environment.GetEnvironmentVariable("SiteMapFile");

            if (string.IsNullOrEmpty(siteMapFile))
            {
                prerequisites = false;
                errors.Append("DataBase Connection String property {siteMapFile} is not defined!");
            }

            var atlasConfigFile = Environment.GetEnvironmentVariable("AtlasConfigFile") ?? "atlasConfig.json";
            var bds             = new BlobDataService();

            if (prerequisites)
            {
                await container.CreateIfNotExistsAsync();

                var siteMapRef = container.GetBlockBlobReference(siteMapFile);

                try
                {
                    if (!string.IsNullOrEmpty(rebuild))
                    {
                        if (prerequisites)
                        {
                            // Custom Sitemap builder code
                        }
                        else
                        {
                            if (prerequisites)
                            {
                                using (var ms = new MemoryStream())
                                {
                                    await siteMapRef.DownloadToStreamAsync(ms);

                                    ms.Position = 0;
                                    using (StreamReader reader = new StreamReader(ms, Encoding.UTF8))
                                    {
                                        var bacmapstr = reader.ReadToEnd();
                                        return(new OkObjectResult(bacmapstr));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    errors.Append(ex.Message);
                }
            }

            if (!prerequisites || errors.Length > 0)
            {
                log.LogError(errors.ToString());
                return(new NotFoundResult());
            }

            return(new OkObjectResult(siteMap));
        }
Beispiel #3
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "statesim")] HttpRequest req,
            [Blob("shared", Connection = "AzureWebJobsStorage")] CloudBlobContainer container,
            ILogger log)
        {
            var atlasConfigFile = Environment.GetEnvironmentVariable("AtlasConfigFile") ?? "atlasConfig.json";
            var blobDataService = new BlobDataService();
            var atlasConfig     = await blobDataService.ReadBlobData <BuildingConfig[]>(container, atlasConfigFile);

            foreach (var buildingConfig in atlasConfig)
            {
                var  buidingFileBase       = buildingConfig.BuildingId.ToLower().Replace("/", "_");
                var  buildingStateFileName = $"{buidingFileBase}_state.json";
                var  buildingStateRef      = container.GetBlockBlobReference(buildingStateFileName);
                bool buildInitialState     = !await buildingStateRef.ExistsAsync();

                var buildingStateSet = new Dictionary <string, UnitStateSet>();

                if (buildInitialState)
                {
                    Random         rnd = new Random();
                    List <Feature> features;

                    var  atlasFeaturesFileName = $"{buidingFileBase}_featuremap.json".ToLower();
                    var  featureMapRef         = container.GetBlockBlobReference(atlasFeaturesFileName);
                    bool useAtlas = !await featureMapRef.ExistsAsync();

                    if (useAtlas)
                    {
                        features = await MapsService.FetchFeaturesFromAtlas(buildingConfig.DatasetId, buildingConfig.SubscriptionKey);

                        await featureMapRef.UploadTextAsync(JsonConvert.SerializeObject(features));
                    }
                    else
                    {
                        features = await blobDataService.ReadBlobData <List <Feature> >(container, atlasFeaturesFileName);
                    }
                    foreach (var feature in features)
                    {
                        var name = $"{buildingConfig.BuildingId}/{feature.Properties.LevelId}/{feature.Properties.Name}";
                        if (!buildingStateSet.ContainsKey(name))
                        {
                            buildingStateSet.Add(name, new UnitStateSet {
                                unitName = feature.Id, states = GetDefaultStates(rnd, buildingConfig.StateSets)
                            });
                        }
                    }
                    await buildingStateRef.UploadTextAsync(JsonConvert.SerializeObject(buildingStateSet));
                }
                else
                {
                    buildingStateSet = await blobDataService.ReadBlobData <Dictionary <string, UnitStateSet> >(container, buildingStateFileName);
                }

                foreach (var stateSetCfg in buildingConfig.StateSets)
                {
                    if (stateSetCfg != null)
                    {
                        var mapsService = new MapsService(buildingConfig.SubscriptionKey, buildingConfig.DatasetId, stateSetCfg.StateSetId.ToString());
                        foreach (var buildingState in buildingStateSet)
                        {
                            if (buildingState.Value.states.ContainsKey(stateSetCfg.StateSetName))
                            {
                                await mapsService.UpdateTagState(
                                    stateSetCfg.StateSetName,
                                    buildingState.Value.unitName,
                                    buildingState.Value.states[stateSetCfg.StateSetName]);
                            }
                        }
                    }
                }
            }

            return(new OkObjectResult("Ok"));
        }
Beispiel #4
0
        public static async Task Run([EventHubTrigger("updatestate", Connection = "EventHubCS")] EventData[] events,
                                     [Blob("refdata", Connection = "AzureWebJobsStorage")] CloudBlobContainer container,
                                     ILogger log)
        {
            var  atlasConfigFile  = Environment.GetEnvironmentVariable("AtlasConfigFile") ?? "atlasConfig.json";
            var  exceptions       = new List <Exception>();
            bool prerequisites    = true;
            bool updateRecentData = false;

            var recentDataFile  = Environment.GetEnvironmentVariable("RecentDataFile");
            var blobDataService = new BlobDataService();
            var atlasConfig     = await blobDataService.ReadBlobData <BuildingConfig[]>(container, atlasConfigFile);

            var mapsServices = new Dictionary <string, MapsService>();

            foreach (var buildingConfig in atlasConfig)
            {
                foreach (var stateSet in buildingConfig.StateSets)
                {
                    string statesetid = stateSet.StateSetId.ToString();
                    if (!mapsServices.ContainsKey(statesetid))
                    {
                        mapsServices.Add(statesetid, new MapsService(buildingConfig.SubscriptionKey, buildingConfig.DatasetId, statesetid));
                    }
                }
            }


            if (prerequisites)
            {
                await container.CreateIfNotExistsAsync();

                var bacmapRef = container.GetBlockBlobReference(recentDataFile);

                IEnumerable <dynamic> recentdata;
                using (var ms = new MemoryStream())
                {
                    await bacmapRef.DownloadToStreamAsync(ms);

                    ms.Position = 0;
                    using (StreamReader reader = new StreamReader(ms, Encoding.UTF8))
                    {
                        var bacmapstr = reader.ReadToEnd();
                        recentdata = JsonConvert.DeserializeObject <IEnumerable <dynamic> >(bacmapstr);
                    }
                }

                foreach (EventData eventData in events)
                {
                    try
                    {
                        string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
                        var    dataItems   = JsonConvert.DeserializeObject <IEnumerable <TagObject> >(messageBody);

                        if (dataItems != null)
                        {
                            foreach (var dataItem in dataItems)
                            {
                                if (dataItem != null)
                                {
                                    foreach (var i in recentdata.Where(tag => tag.DeviceId == dataItem.DeviceId))
                                    {
                                        //var cv = i.CurrentValue as JValue;
                                        double curVal = double.MinValue;
                                        var    cv     = i.CurrentValue;
                                        if (cv != null)
                                        {
                                            Double.TryParse(((JValue)cv).Value.ToString(), out curVal);
                                        }

                                        if (dataItem.Value != curVal)
                                        {
                                            i.CurrentValue   = dataItem.Value;
                                            updateRecentData = true;
                                            var res = mapsServices[dataItem.DeviceId].UpdateTagState(dataItem.TagName, dataItem.MapFeatureId, dataItem.Value.ToString());
                                        }
                                    }
                                }
                            }
                        }

                        // Replace these two lines with your processing logic.
                        log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
                        await Task.Yield();
                    }
                    catch (Exception e)
                    {
                        // We need to keep processing the rest of the batch - capture this exception and continue.
                        // Also, consider capturing details of the message that failed processing so it can be processed again later.
                        exceptions.Add(e);
                    }
                }
                if (updateRecentData)
                {
                    var rd = JsonConvert.SerializeObject(recentdata);
                    await bacmapRef.UploadTextAsync(rd);
                }
            }

            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

            if (exceptions.Count > 1)
            {
                throw new AggregateException(exceptions);
            }

            if (exceptions.Count == 1)
            {
                throw exceptions.Single();
            }
        }
Beispiel #5
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "roomdata/{region}/{campus}/{building}")] HttpRequest req,
            [Blob("shared", Connection = "AzureWebJobsStorage")] CloudBlobContainer container,
            string region,
            string campus,
            string building,
            ILogger log)
        {
            bool prerequisites = true;
            var  errors        = new StringBuilder();

            var atlasConfigFile = Environment.GetEnvironmentVariable("AtlasConfigFile") ?? "atlasConfig.json";

            bool rebuild = false;

            Boolean.TryParse(req.Query["rebuild"], out rebuild);

            if (string.IsNullOrEmpty(building))
            {
                prerequisites = false;
                errors.Append("Required query {building} was not defined");
            }

            var blobDataService = new BlobDataService();
            var atlasConfig     = await blobDataService.ReadBlobData <BuildingConfig[]>(container, atlasConfigFile);

            var buildingConfig = atlasConfig.FirstOrDefault(b => b.BuildingId.ToLower() == $"{region}/{campus}/{building}".ToLower());

            if (buildingConfig == null)
            {
                prerequisites = false;
                errors.Append($"Atlas config for {building} was not found");
            }

            var  atlasFeaturesFileName = $"{region}_{campus}_{building}_FeatureMap.json".ToLower();
            var  featureMapref         = container.GetBlockBlobReference(atlasFeaturesFileName);
            bool useAtlas = rebuild || !await featureMapref.ExistsAsync();

            List <Feature> features;


            if (prerequisites)
            {
                var rdi = new Dictionary <string, Dictionary <string, RoomDataItem> >();
                try
                {
                    if (useAtlas)
                    {
                        features = await MapsService.FetchFeaturesFromAtlas(buildingConfig.DatasetId, buildingConfig.SubscriptionKey);

                        await featureMapref.UploadTextAsync(JsonConvert.SerializeObject(features));
                    }
                    else
                    {
                        features = await blobDataService.ReadBlobData <List <Feature> >(container, atlasFeaturesFileName);
                    }

                    foreach (var feature in features)
                    {
                        var levelId = $"{region}/{campus}/{building}/{GetLevelName(feature.Properties.LevelId)}".ToLower();
                        if (!rdi.ContainsKey(levelId))
                        {
                            rdi.Add(levelId, new Dictionary <string, RoomDataItem>());
                        }
                        if (!rdi[levelId].ContainsKey(feature.Properties.Name))
                        {
                            rdi[levelId].Add(feature.Properties.Name.Replace("-", ""),
                                             new RoomDataItem()
                            {
                                name    = feature.Properties.Name,
                                type    = GetFeatureType(feature.Properties.CategoryId),
                                unitId  = feature.Id,
                                polygon = feature.Geometry.Coordinates[0]
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.LogError(ex.Message);
                }

                return(new OkObjectResult(JsonConvert.SerializeObject(rdi)));
            }
            else
            {
                log.LogError(errors.ToString());
                return(new NotFoundResult());
            }
        }
Beispiel #6
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "state/{region}/{campus}/{building}/{floor}/{room}")] HttpRequest req,
            [Blob("shared", Connection = "AzureWebJobsStorage")] CloudBlobContainer container,
            string region,
            string campus,
            string building,
            string floor,
            string room,
            ILogger log)
        {
            bool prerequisites = true;
            var  errors        = new StringBuilder();

            var atlasConfigFile = Environment.GetEnvironmentVariable("AtlasConfigFile") ?? "atlasConfig.json";

            if (string.IsNullOrEmpty(room))
            {
                prerequisites = false;
                errors.Append("Required query parameter {room} was not defined");
            }

            var blobDataService = new BlobDataService();
            var atlasConfig     = await blobDataService.ReadBlobData <BuildingConfig[]>(container, atlasConfigFile);

            var buildingConfig = atlasConfig.FirstOrDefault(b => b.BuildingId.ToLower() == $"{region}/{campus}/{building}".ToLower());

            if (buildingConfig == null)
            {
                prerequisites = false;
                errors.Append($"Atlas config for {building} was not found");
            }

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();


            var atlasFeaturesFileName = $"{region}_{campus}_{building}_featuremap.json".ToLower();
            var featureMapref         = container.GetBlockBlobReference(atlasFeaturesFileName);

            List <Feature> features;


            if (prerequisites)
            {
                var rdi = new Dictionary <string, Dictionary <string, RoomDataItem> >();
                try
                {
                    features = await blobDataService.ReadBlobData <List <Feature> >(container, atlasFeaturesFileName);

                    var    jo       = JObject.Parse(requestBody);
                    string stateSet = null;
                    string value    = null;

                    if (jo != null)
                    {
                        var jp = jo.First as JProperty;
                        if (jp != null)
                        {
                            stateSet = jp.Name;
                            value    = jp.Value.ToString();
                        }
                    }

                    var stateSetCfg = buildingConfig.StateSets.FirstOrDefault(ss => ss.StateSetName.ToLower() == stateSet.ToLower());

                    if (stateSetCfg != null)
                    {
                        var feature = features.FirstOrDefault(f => f.Properties.Name.ToLower().Replace("-", "") == room.ToLower().Replace("-", ""));
                        if (feature != null)
                        {
                            var mapsService = new MapsService(buildingConfig.SubscriptionKey, buildingConfig.DatasetId, stateSetCfg.StateSetId.ToString());
                            await mapsService.UpdateTagState(stateSetCfg.StateSetName, feature.Id, value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.LogError(ex.Message);
                }

                return(new OkObjectResult(JsonConvert.SerializeObject(rdi)));
            }
            else
            {
                log.LogError(errors.ToString());
                return(new NotFoundResult());
            }
        }