예제 #1
0
        public ClimateItem CurrentReading(AppKeyConfig AppConfig)
        {
            ClimateItem item = null;

            // Get the access and refresh tokens if they exist, if they don't exist we cannot proceceed and return null
            NibeAuth auth = getNibeAuthJson();

            if (auth == null)
            {
                return(null);
            }

            // Access and refresh token exist,  try to access using the access token
            item = GetReadingWithAccessCode(auth.access_token, AppConfig);

            // If we get null back, it didn't work and we try to refresh with the refresh token
            if (item == null)
            {
                // If it didn't work to get a new access token we bail out and return null
                auth = Refresh(AppConfig);


                if (auth == null)
                {
                    return(null);
                }

                // It worked to get a new access token, try agin to get data using the new access token
                item = GetReadingWithAccessCode(auth.access_token, AppConfig);
            }

            // If get an item back we return it, it we get null back we can't still access data and return null
            return(item);
        }
예제 #2
0
        public ClimateItem GetReadingWithAccessCode(string accessCode, AppKeyConfig config)
        {
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessCode);

            var uri = new UriBuilder(config.NibeHost)
            {
                Path  = $"/api/v1/systems/27401/parameters",
                Query = "parameterIds=outdoor_temperature&parameterIds=indoor_temperature"
            }.Uri;


            var response = client.GetAsync(uri).Result;

            if (!response.IsSuccessStatusCode)
            {
                // If it didn't work, return null
                return(null);
            }
            string contentResult = response.Content.ReadAsStringAsync().Result;

            NibeTemp nibeOutdoorTemp = JsonConvert.DeserializeObject <List <NibeTemp> >(contentResult)[0];
            NibeTemp nibeIndoorTemp  = JsonConvert.DeserializeObject <List <NibeTemp> >(contentResult)[1];

            reading.OutdoorValue = nibeOutdoorTemp.displayValue.Remove(nibeOutdoorTemp.displayValue.Length - 2);
            reading.IndoorValue  = nibeIndoorTemp.displayValue.Remove(nibeIndoorTemp.displayValue.Length - 2);
            reading.TimeStamp    = DateTime.Now;

            return(reading);
        }
예제 #3
0
        public void NetatmoUnitIndoortemperature()
        {
            string responseText = "{\"body\":[{\"beg_time\":1481372100,\"value\":[[22.1]]}],\"status\":\"ok\",\"time_exec\":0.027220010757446,\"time_server\":1481371840}";


            ApiStub apiNetatmoStub = new ApiStub();

            apiNetatmoStub.Get(
                "/api/getmeasure",
                (request, args) =>
            {
                return(responseText);
            }
                );

            apiNetatmoStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NetatmoHost = apiNetatmoStub.Address;

            string actualTemp = netatmoUnit.inDoorTemperature(configs);

            Assert.Equal("22.1", actualTemp);
        }
예제 #4
0
        public void ClimateController_GetById_WithNibe_As_Source_Calls_CurrentReading_ThatReturnsNull()
        {
            ClimateItem item = null;

            // nibeMock.Setup<ClimateItem>(x => x.CurrentReading(It.IsAny<AppKeyConfig>())).Returns(item);
            AppKeyConfig ac = new AppKeyConfig()
            {
                UserName            = Configuration["NETATMO_USERNAME"],
                Password            = Configuration["NETATMO_PASSWORD"],
                NetatmoClientId     = Configuration["NETATMO_CLIENTID"],
                NetatmoClientSecret = Configuration["NETATMO_CLIENTSECRET"],
                NibeClientId        = Configuration["NIBE_CLIENTID"],
                NibeClientSecret    = Configuration["NIBE_CLIENTSECRET"],
                NibeRedirectURI     = Configuration["NIBE_REDIRECTURL"],
                NibeHost            = Configuration["NIBE_HOST"],
                NetatmoHost         = Configuration["NETATMO_HOST"],
                BuildVersion        = Configuration["BUILD_VERSION"]
            };

            nibeMock.Setup <ClimateItem>(x => x.CurrentReading(ac)).Returns(item);

            IActionResult res = _climateController.GetBySource("Nibe");

            nibeMock.Verify(x => x.CurrentReading(It.IsAny <AppKeyConfig>()), Times.AtLeastOnce());

            Assert.IsType <RedirectResult>(res);
        }
예제 #5
0
        public void NibeUnit_CurrentReading_Is_NotSuccessfulDueToMissingAuthFile()
        {
            string nibeauth  = null;
            bool   fileExist = false;

            if (File.Exists("data/nibeauth.json"))
            {
                nibeauth  = File.ReadAllText("data/nibeauth.json");
                fileExist = true;
            }

            File.Delete("data/nibeauth.json");

            Assert.False(File.Exists("data/nibeauth.json"));


            AppKeyConfig configs = new AppKeyConfig();

            ClimateItem item = nibeUnit.CurrentReading(configs);

            Assert.Null(item);
            if (fileExist)
            {
                File.WriteAllText("data/nibeauth.json", nibeauth);
            }
        }
예제 #6
0
        public void NetatmoUnitOutdoortemperature()
        {
            string responseText = "{\"body\":[{\"beg_time\":1481372100,\"value\":[[0.7]]}],\"status\":\"ok\",\"time_exec\":0.034345865249634,\"time_server\":1481371970}";


            ApiStub apiNetatmoStub = new ApiStub();

            apiNetatmoStub.Get(
                "/api/getmeasure",
                (request, args) =>
            {
                return(responseText);
            }
                );

            apiNetatmoStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NetatmoHost = apiNetatmoStub.Address;

            string actualTemp = netatmoUnit.outDoorTemperature(configs);

            Assert.Equal("0.7", actualTemp);
        }
예제 #7
0
        private void login(AppKeyConfig configs)
        {
            //Login
            var pairs = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("grant_type", "password"),
                new KeyValuePair <string, string>("client_id", configs.NetatmoClientId),
                new KeyValuePair <string, string>("client_secret", configs.NetatmoClientSecret),
                new KeyValuePair <string, string>("username", configs.UserName),
                new KeyValuePair <string, string>("password", configs.Password),
                new KeyValuePair <string, string>("scope", "read_station")
            };
            HttpClient client     = new HttpClient();
            var        outcontent = new FormUrlEncodedContent(pairs);

            var uri = new UriBuilder(configs.NetatmoHost)
            {
                Path = "/oauth2/token"
            }.Uri;


            var response = client.PostAsync(uri, outcontent).Result;

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Could not login, response: " + response.Content.ReadAsStringAsync().Result);
            }

            string contentResult = response.Content.ReadAsStringAsync().Result;

            netatmoAuth = JsonConvert.DeserializeObject <NetatmoAuth>(contentResult);
        }
예제 #8
0
        private void setDeviceAndModuleID(AppKeyConfig config)
        {
            string response = "";

            HttpClient client = new HttpClient();
            var        uri    = new UriBuilder(config.NetatmoHost)
            {
                Path  = "/api/devicelist",
                Query = "access_token=" + netatmoAuth.access_token
            }.Uri;


            var resp = client.GetAsync(uri).Result;

            if (!resp.IsSuccessStatusCode)
            {
                throw new Exception("Could not set device and module");
            }

            response = resp.Content.ReadAsStringAsync().Result;


            dynamic data = JsonConvert.DeserializeObject(response);

            deviceId = data.body.devices[0]._id;
            moduleId = data.body.modules[0]._id;
        }
        public CheckAppKeyMiddleware(RequestDelegate next, ILogger <CheckAppKeyMiddleware> logging, IOptionsMonitor <AppKeyConfig> appKeyConfigAccessor)
        {
            try {
                _logging = logging ?? throw new ArgumentNullException(nameof(logging));
                _next    = next ?? throw new ArgumentNullException(nameof(next));
                if (appKeyConfigAccessor == null)
                {
                    throw new ArgumentNullException(nameof(appKeyConfigAccessor));
                }
                _appKeyConfig = appKeyConfigAccessor.CurrentValue;
                appKeyConfigAccessor.OnChange(a =>
                {
                    if (a.HeaderName == null || a.AppKeys == null)
                    {
                        _logging.LogError("Changed AppKey configuration at runtime with invalid values");
                    }
                    _appKeyConfig.HeaderName = a.HeaderName;
                    _appKeyConfig.AppKeys    = a.AppKeys;
                });

                CheckConfiguration();
            }
            catch (Exception ex)
            {
            }
        }
예제 #10
0
        public void NibeUnit_CurrentReading_Is_SuccessfulWithRefresh()
        {
            Assert.True(File.Exists("data/nibeauth.json"));

            string  fileContentExp = "{\"access_token\":\"AAEAAI3RKfqMqpUT6gPct8J4ysi2MvAITg9iJ - fydXOLDEP1DZ_9DbX3hh2Nw3DOydyc_IvBzNJW - k9uon0I4cxNuhhJJ5Z5OQEAUuB6er10aWLS7QnHAxvyAJFgsRUA9BBvmmA21MdBexw4JaKHaIswuxQwsOe3tBefPg8S_eEm44noPJIj_Zge4tgTZyTU1pIj5NksAm0T6i - tnf - wdrPg6AfWZHn1mNBBQnEosPNnq8OatCKK3CUunbCyNspB2v3p175WWSad2stb8Bo1nfvP8ZWebKIQFSYXNYLhYDd3T6EmxqVdIIj_Z6IFeqM4pTRndaIXrPdBCGRvNYCeA5puW2SkAQAAAAEAAB_Tqc5_JXDTzgaTS0amjWGCVvLo5ZV_5lIUMOxBfc7YlrLw0y2qhvUz3GwaMRx5WQdGdHhMkZpxzQPjiN - Zm2KGeyrTwFHj_fXFfxML3Gd_mQF5jrKmRcWwBXqTUDPwdOmPqXR94b6P4PqPzIXuoKvz_MRlrNfA1XmMCKagB8QsAdDmThu7QIR2gV5ENmJUcRHRY09XAAii4kYh6tyhvs8Zec7wgPRZ1Sq6aSOPYwdI3Ux3CRXUPgWxkGBbvCKPIu3keHJoZI - k1U81ha1AD5qj6RqMuM3m72VNXYuzSya62GfNP57BPupfgO_Igv9yWqf7jxPqy_XuAEYF0cNn5hAHDz3Kp9sRieCWW7fiiZwNghVp1 - jo_mdgyd1dPwqsh6UjOJqSuqWSEGWptpxZJ2bnB1akCmqpfKvgJgiV8Ilr68Tjw2uiMPGOlZF3b5T_uRszpTNFIfz4QpWdbbaHabeiBfit4oI3AqsCLEL3MU0W8Sk1QbxikEgON6v - 2lmkJ2t_iUGa3RXh3124QltUujywVVfeEJJupJjs1vRHZmD8\",\"token_type\":\"bearer\",\"expires_in\":1800,\"refresh_token\":\"8_Ln!IAAAAGQC4_hJShmgj10Be6CXXj6SJEJCobqeQMmvBdFp - flssQAAAAGiydTTibPGsB_03OYi - ASktAwRonG9sj0vHJpewUGGmGDxawAXVE4G5mpLHNcpezmDEFg2o3sXIRrdOlymY47itMwqTJyGCSxcoUw3OOVFiMA29VZWSTLjB_hCqMUhTTgxDAo1ykF - kjG - Q84X9xpdx1VEbyBK7LCMYR2h0fcrl0 - qV7MRAhJvKcy7YJ62CXfKm5Nq1PWJ4qTONFYRtL1Z5X8rJ_jLzLYFy3I4EykDqw\",\"scope\":\"READSYSTEM\"}";
            ApiStub apiNibeStub    = new ApiStub();

            apiNibeStub.Post(
                "/oauth/token",
                (request, args) =>
            {
                return(fileContentExp);
            }
                );

            apiNibeStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NibeHost = apiNibeStub.Address;

            ClimateItem item = nibeUnit.CurrentReading(configs);

            Assert.Null(item);
        }
예제 #11
0
        public void NetatmoUnitLoginSuccessFul()
        {
            string  responseText   = "{ \"access_token\":\"544cf4071c7759831d94cdf9|fcb30814afbffd0e39381e74fe38a59a\",\"refresh_token\":\"544cf4071c7759831d94cdf9|2b2c270c1208e8f67d3bd3891e395e1a\",\"scope\":[\"read_station\"],\"expires_in\":10800,\"expire_in\":10800}";
            string  deviceResponse = netatmoData;
            ApiStub apiNetatmoStub = new ApiStub();

            apiNetatmoStub.Post(
                "/oauth2/token",
                (request, args) =>
            {
                return(responseText);
            }
                );
            apiNetatmoStub.Get(
                "/api/devicelist",
                (request, response) =>
            {
                return(deviceResponse);
            }
                );

            apiNetatmoStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NetatmoHost = apiNetatmoStub.Address;

            netatmoUnit.init(configs);
        }
예제 #12
0
 public ChatController(IHostingEnvironment environment, IStorageManager storageManager, IOptions <AppKeyConfig> appKeyConfig, IEmailManager emailManager, ApplicationDbContext dbContext)
 {
     _environment    = environment;
     _storageManager = storageManager;
     _appKeyConfig   = appKeyConfig.Value;
     _emailManager   = emailManager;
     _dbContext      = dbContext;
 }
예제 #13
0
 public InfluencerController(RoleManager <IdentityRole> roleManager, ApplicationDbContext context, UserManager <ApplicationUser> userManager, IOptions <AppKeyConfig> appkeys, IRepository <YoutubeData> youtubeRepo)
 {
     _YoutubeRepo = youtubeRepo;
     _context     = context;
     _userManager = userManager;
     AppConfigs   = appkeys.Value;
     _roleManager = roleManager;
 }
예제 #14
0
 public BlobStorageManager(
     IHttpContextAccessor contextAccessor,
     IOptions <AppKeyConfig> appKeyConfig,
     ILoggerFactory loggerFactory)
 {
     this.contextAccessor = contextAccessor;
     this.appKeyConfig    = appKeyConfig.Value;
     this.logger          = loggerFactory.CreateLogger <BlobStorageManager>();
 }
예제 #15
0
 public SocialMediaViewComponent(ApplicationDbContext context,
                                 IOptions <AppKeyConfig> appkeys,
                                 IHostingEnvironment environment,
                                 SpiikService spiikService)
 {
     _appConfig    = appkeys.Value;
     _db           = context;
     _env          = environment;
     _spiikService = spiikService;
 }
        private IOptions <AppKeyConfig> GetAppKeyConfigOptions()
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("client-secret.json")
                         .Build();

            AppKeyConfig appKeys = new AppKeyConfig();

            appKeys.TwitterConsumerKey       = config["TwitterConsumerKey"];
            appKeys.TwitterConsumerSecret    = config["TwitterConsumerSecret"];
            appKeys.TwitterAccessToken       = config["TwitterAccessToken"];
            appKeys.TwitterAccessTokenSecret = config["TwitterAccessTokenSecret"];

            return(Options.Create(appKeys));
        }
예제 #17
0
        public void NetatmoUnitCurrentReading()
        {
            string responseText = "{ \"access_token\":\"544cf4071c7759831d94cdf9|fcb30814afbffd0e39381e74fe38a59a\",\"refresh_token\":\"544cf4071c7759831d94cdf9|2b2c270c1208e8f67d3bd3891e395e1a\",\"scope\":[\"read_station\"],\"expires_in\":10800,\"expire_in\":10800}";
            //string deviceResponse = File.ReadAllText(fileDir + "netatmodeviceresponse.json");
            string  deviceResponse = netatmoData;
            ApiStub apiNetatmoStub = new ApiStub();

            apiNetatmoStub.Post(
                "/oauth2/token",
                (request, args) =>
            {
                return(responseText);
            }
                );
            apiNetatmoStub.Get(
                "/api/devicelist",
                (request, response) =>
            {
                return(deviceResponse);
            }
                );
            string responseReading = "{\"body\":[{\"beg_time\":1481372100,\"value\":[[0.7]]}],\"status\":\"ok\",\"time_exec\":0.034345865249634,\"time_server\":1481371970}";


            apiNetatmoStub.Get(
                "/api/getmeasure",
                (request, args) =>
            {
                return(responseReading);
            }
                );

            apiNetatmoStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NetatmoHost = apiNetatmoStub.Address;

            ClimateItem actualReading = netatmoUnit.CurrentReading(configs);

            Assert.NotNull(actualReading);
            Assert.Equal("0.7", actualReading.IndoorValue);
            Assert.Equal("0.7", actualReading.OutdoorValue);
            Assert.NotNull(actualReading.TimeStamp);

            Assert.True(DateTime.Now >= actualReading.TimeStamp);
        }
예제 #18
0
        public string inDoorTemperature(AppKeyConfig configs)
        {
            HttpClient client = new HttpClient();
            var        uri    = new UriBuilder(configs.NetatmoHost)
            {
                Path  = "/api/getmeasure",
                Query = "access_token=" + netatmoAuth.access_token + "&device_id=" + deviceId + "&type=Temperature&limit=1&date_end=last&scale=max"
            }.Uri;

            var     resp     = client.GetAsync(uri).Result;
            string  response = resp.Content.ReadAsStringAsync().Result;
            dynamic data     = JsonConvert.DeserializeObject(response);

            string temperature = data.body[0].value[0][0]; // temperature

            return(temperature);
        }
예제 #19
0
        public void NibeUnit_Call_Init_When_code_Is_NotNull_ButBadResponseFromApi()
        {
            ApiStub apiNibeStub = new ApiStub();

            apiNibeStub.Request(HttpMethod.Post).
            IfRoute("/oauth/token").
            Response((request, args) =>
            {
                return("{ Error, Not Authorized}");
            }
                     ).StatusCode(StatusCodes.Status401Unauthorized);

            apiNibeStub.Start();
            AppKeyConfig configs = new AppKeyConfig();

            configs.NibeHost = apiNibeStub.Address;
            Assert.Throws <Exception>(() => nibeUnit.init(configs));
        }
예제 #20
0
        public void init(AppKeyConfig config)
        {
            // Check to see if we have a code
            if (code == null)
            {
                throw new Exception("Code is null");
            }

            //Login
            var pairs = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("client_id", config.NibeClientId),
                new KeyValuePair <string, string>("client_secret", config.NibeClientSecret),
                new KeyValuePair <string, string>("code", this.code),
                new KeyValuePair <string, string>("redirect_uri", config.NibeRedirectURI),
                new KeyValuePair <string, string>("scope", "READSYSTEM")
            };

            HttpClient client     = new HttpClient();
            var        outcontent = new FormUrlEncodedContent(pairs);
            var        uri        = new UriBuilder(config.NibeHost)
            {
                Path  = "/oauth/token",
                Query = "parameterIds=outdoor_temperature&parameterIds=indoor_temperature"
            }.Uri;

            HttpResponseMessage response = client.PostAsync(uri, outcontent).Result;

            if (!response.IsSuccessStatusCode)
            {
                int statusCode = (int)response.StatusCode;
                throw new Exception(statusCode + " " + response.ReasonPhrase);
            }


            string contentResult = response.Content.ReadAsStringAsync().Result;

            nibeAuth = JsonConvert.DeserializeObject <NibeAuth>(contentResult);

            string nibeAuthJson = JsonConvert.SerializeObject(nibeAuth);

            File.WriteAllText("data/nibeauth.json", nibeAuthJson);
        }
예제 #21
0
        public void NetatmoUnitCurrentReadingDataCouldNoBeRead()
        {
            string responseText = "{ \"access_token\":\"544cf4071c7759831d94cdf9|fcb30814afbffd0e39381e74fe38a59a\",\"refresh_token\":\"544cf4071c7759831d94cdf9|2b2c270c1208e8f67d3bd3891e395e1a\",\"scope\":[\"read_station\"],\"expires_in\":10800,\"expire_in\":10800}";
            //string deviceResponse = File.ReadAllText(fileDir + "netatmodeviceresponse.json");
            string  deviceResponse = netatmoData;
            ApiStub apiNetatmoStub = new ApiStub();

            apiNetatmoStub.Post(
                "/oauth2/token",
                (request, args) =>
            {
                return(responseText);
            }
                );
            apiNetatmoStub.Get(
                "/api/devicelist",
                (request, response) =>
            {
                return(deviceResponse);
            }
                );
            string responseReading = null;


            apiNetatmoStub.Get(
                "/api/getmeasure",
                (request, args) =>
            {
                return(responseReading);
            }
                );

            apiNetatmoStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NetatmoHost = apiNetatmoStub.Address;

            ClimateItem actualReading = netatmoUnit.CurrentReading(configs);

            Assert.Null(actualReading);
        }
예제 #22
0
        public ClimateItem CurrentReading(AppKeyConfig AppConfigs)
        {
            login(AppConfigs);
            setDeviceAndModuleID(AppConfigs);
            ClimateItem reading = new ClimateItem();

            try
            {
                reading.IndoorValue  = this.inDoorTemperature(AppConfigs);
                reading.OutdoorValue = this.outDoorTemperature(AppConfigs);
                reading.TimeStamp    = DateTime.Now;
                return(reading);
            }

            // Somehow we could not get the data.
            catch
            {
                return(null);
            }
        }
예제 #23
0
        public NibeAuth Refresh(AppKeyConfig AppConfig)
        {
            string nibeAuthJson = File.ReadAllText("data/nibeauth.json");

            nibeAuth = JsonConvert.DeserializeObject <NibeAuth>(nibeAuthJson);

            //Login
            var pairs = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("grant_type", "refresh_token"),
                new KeyValuePair <string, string>("client_id", AppConfig.NibeClientId),
                new KeyValuePair <string, string>("client_secret", AppConfig.NibeClientSecret),
                new KeyValuePair <string, string>("refresh_token", nibeAuth.refresh_token)
            };
            HttpClient client     = new HttpClient();
            var        outcontent = new FormUrlEncodedContent(pairs);
            var        uri        = new UriBuilder(AppConfig.NibeHost)
            {
                Path  = "/oauth/token",
                Query = "parameterIds=outdoor_temperature&parameterIds=indoor_temperature"
            }.Uri;

            var response = client.PostAsync(uri, outcontent).Result;

            // If we could not refresh
            if (!response.IsSuccessStatusCode)
            {
                int statusCode = (int)response.StatusCode;
                return(null);
            }

            // Replace the access and refresh token in the file with the new values
            string contentResult = response.Content.ReadAsStringAsync().Result;

            nibeAuth     = JsonConvert.DeserializeObject <NibeAuth>(contentResult);
            nibeAuthJson = JsonConvert.SerializeObject(nibeAuth);
            File.WriteAllText("data/nibeauth.json", nibeAuthJson);

            // Success, a new access and refresh token is in the file
            return(nibeAuth);
        }
예제 #24
0
        public void NibeUnit_Refresh_NotOk()
        {
            ApiStub apiNibeStub = new ApiStub();

            apiNibeStub.Request(HttpMethod.Post).
            IfRoute("/oauth/token").
            Response((request, args) =>
            {
                return("{ Error, Not Authorized}");
            }
                     ).StatusCode(StatusCodes.Status401Unauthorized);

            apiNibeStub.Start();
            AppKeyConfig configs = new AppKeyConfig();

            configs.NibeHost = apiNibeStub.Address;

            NibeAuth res = nibeUnit.Refresh(configs);

            Assert.Null(res);
        }
예제 #25
0
        public void NibeUnit_GetReadingWithAccessCode_Is_NotSuccessful()
        {
            //string reading = "[{\"parameterId\":40004,\"name\":\"outdoor_temperature\",\"title\":\"outdoor temp.\",\"designation\":\"BT1\",\"unit\":\"°C\",\"displayValue\":\"2.7°C\",\"rawValue\":27},{\"parameterId\":40033,\"name\":\"indoor_temperature\",\"title\":\"room temperature\",\"designation\":\"BT50\",\"unit\":\"°C\",\"displayValue\":\"22.7°C\",\"rawValue\":227}]";
            ApiStub apiNibeStub = new ApiStub();

            apiNibeStub.Request(HttpMethod.Post).
            IfRoute("/oauth/token").
            Response((request, args) =>
            {
                return("{ Error, Not Authorized}");
            }
                     ).StatusCode(StatusCodes.Status401Unauthorized);
            apiNibeStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NibeHost = apiNibeStub.Address;

            ClimateItem item = nibeUnit.GetReadingWithAccessCode("12345", configs);

            Assert.Null(item);
        }
예제 #26
0
        public void NetatmoUnitLoginFailDueToSetDevice()
        {
            string  responseText   = "{ \"access_token\":\"544cf4071c7759831d94cdf9|fcb30814afbffd0e39381e74fe38a59a\",\"refresh_token\":\"544cf4071c7759831d94cdf9|2b2c270c1208e8f67d3bd3891e395e1a\",\"scope\":[\"read_station\"],\"expires_in\":10800,\"expire_in\":10800}";
            ApiStub apiNetatmoStub = new ApiStub();

            apiNetatmoStub.Post(
                "/oauth2/token",
                (request, args) =>
            {
                return(responseText);
            }
                );

            apiNetatmoStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NetatmoHost = apiNetatmoStub.Address;

            Exception ex = Assert.Throws <Exception>(() => netatmoUnit.init(configs));

            Assert.Equal("Could not set device and module", ex.Message);
        }
예제 #27
0
        public void NibeUnit_CurrentReading_Is_SuccessfulWithAccessCode()
        {
            string  reading     = "[{\"parameterId\":40004,\"name\":\"outdoor_temperature\",\"title\":\"outdoor temp.\",\"designation\":\"BT1\",\"unit\":\"°C\",\"displayValue\":\"2.7°C\",\"rawValue\":27},{\"parameterId\":40033,\"name\":\"indoor_temperature\",\"title\":\"room temperature\",\"designation\":\"BT50\",\"unit\":\"°C\",\"displayValue\":\"22.7°C\",\"rawValue\":227}]";
            ApiStub apiNibeStub = new ApiStub();

            apiNibeStub.Get(
                "/api/v1/systems/27401/parameters",
                (request, args) =>
            {
                return(reading);
            }
                );
            apiNibeStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NibeHost = apiNibeStub.Address;

            ClimateItem item = nibeUnit.CurrentReading(configs);

            Assert.NotNull(item);
            Assert.Equal(item.IndoorValue, "22.7");
            Assert.Equal(item.OutdoorValue, "2.7");
        }
예제 #28
0
        public void NetatmoUnitLoginFailDueToLogin()
        {
            //string deviceResponse = File.ReadAllText(fileDir + "netatmodeviceresponse.json");
            string  deviceResponse = netatmoData;
            ApiStub apiNetatmoStub = new ApiStub();

            apiNetatmoStub.Get(
                "/api/devicelist",
                (request, response) =>
            {
                return(deviceResponse);
            }
                );

            apiNetatmoStub.Start();

            AppKeyConfig configs = new AppKeyConfig();

            configs.NetatmoHost = apiNetatmoStub.Address;

            Exception ex = Assert.Throws <Exception>(() => netatmoUnit.init(configs));

            Assert.Equal("Could not login, response: ", ex.Message);
        }
예제 #29
0
 public AppKeysController(IOptions <AppKeyConfig> appKeyConfig)
 {
     this.appKeyConfig = appKeyConfig.Value;
 }
예제 #30
0
 public void init(AppKeyConfig config)
 {
     login(config);
     setDeviceAndModuleID(config);
 }