public void Execute(NestClient nest) { var listSubscriptions = new List <IDisposable>(); IDisposable subscription; //All thermostats: subscription = nest.WhenThermostatUpdated().Subscribe(thermostats => { // Handle thermostat update... }); listSubscriptions.Add(subscription); //All smoke alarms: subscription = nest.WhenSmokeCOAlarmUpdated().Subscribe(thermostats => { // Handle smoke+co alarm update... }); listSubscriptions.Add(subscription); //All cameras: subscription = nest.WhenCameraUpdated().Subscribe(thermostats => { // Handle camera update... }); listSubscriptions.Add(subscription); //Unsubscribe from events foreach (var item in listSubscriptions) { subscription.Dispose(); } }
//https://stackoverflow.com/search?q=%5Bnest-api%5D+C%23 //https://stackoverflow.com/questions/49540651/how-to-listen-for-changes-in-values-of-nest-device-parameters-in-c-sharp-console //https://stackoverflow.com/questions/24624806/deserializing-json-in-c-sharp-for-the-nest-api public void Execute(NestClient temp) { var nest = new NestClient(); // Get the token string from your safe place. var token = "abc123"; // Authenticate with an existing token. nest.StartWithToken(token); nest.WhenValueChanged() .Subscribe(args => { // Handle exceptions here. }); nest.WhenAuthRevoked() .Subscribe(args => { // Your previously authenticated connection has become unauthenticated. // Recommendation: Relaunch an auth flow with nest.launchAuthFlow(). }); //onAuthSuccess // Handle success here. Start pulling from Nest API. // }
public void Execute(NestClient temp) { // A request code you can verify later. string AUTH_TOKEN_REQUEST_CODE = "123"; // Set the configuration values. var nestConfig = new NestConfig( clientId: "client-id", clientSecret: "client-secret", redirectUrl: "https://redirect-url", state: AUTH_TOKEN_REQUEST_CODE); var oauth2 = new NestOauth2(nestConfig); // Launch the auth flow if you don't already have a token. var requestUrl = oauth2.GetClientCodeUrl(); //TODO: GET requestUrl in webbrowser. different way on different platform // If authorized, you can receive resulting url that contains the authorization code. string resultingUrl = null; var authorizationCode = oauth2.ParseAuthorizationCode(resultingUrl); //receive the token var token = oauth2.CreateToken(authorizationCode); // Save the token to a safe place here so it can be re-used later. }
public void Execute(NestClient nest) { var myCamera = new Camera(); // Get id from Camera#getDeviceId. string camId = myCamera.DeviceId; // Set camera to start streaming. nest.Cameras.SetIsStreaming(camId, true); }
public void Execute(NestClient nest) { //Subscribe to event var subscription = nest.WhenMetadataUpdated().Subscribe(data => { // Handle metadata update... do action. }); //Unsubscribe from event subscription.Dispose(); }
public void Verify_Parsing_Exception_Is_Thrown_And_Response_Is_Logged() { var listLogger = new ListLogger(); var nestClient = new NestClient(null, listLogger); var nestSummary = "not json"; Assert.Throws <JsonReaderException>(() => nestClient.GetNestSummary(nestSummary)); Assert.True(listLogger.log.Count(x => x.Equals("Parsing: " + nestSummary)) == 1); }
public void Execute(NestClient nest) { //Subscribe to event var subscription = nest.WhenStructureUpdated().Subscribe(structures => { // Handle structure update... }); //Unsubscribe from event subscription.Dispose(); }
public void Execute(NestClient nest) { //Subscribe to event var subscription = nest.WhenDeviceUpdated().Subscribe(update => { var cameras = update.Cameras; var smokeCOAlarms = update.SmokeCOAlarms; var thermostats = update.Thermostats; // Handle updates here. }); //Unsubscribe from event subscription.Dispose(); }
public void GetHomeOrAwayStatus() { var listLogger = new ListLogger(); var nestClient = new NestClient(config.NestDecryptedAccessToken, listLogger); var homeStatus = nestClient .GetStructures() .Single(x => x.Name.Equals("home", StringComparison.OrdinalIgnoreCase)).Away; output.WriteLine(homeStatus); Assert.True(homeStatus.Equals("home", StringComparison.OrdinalIgnoreCase) || homeStatus.Equals("away", StringComparison.OrdinalIgnoreCase)); }
public static void ExecuteAll(NestClient nest) { foreach (var type in Assembly.GetExecutingAssembly().GetExportedTypes()) { if (type.GetCustomAttribute <ExampleAttribute>() == null) { continue; } var instance = Activator.CreateInstance(type) as IExample; if (instance == null) { continue; } Execute(nest, instance); } }
public void Execute(NestClient nest) { var thermostat = new Thermostat(); // Get id from Thermostat#getDeviceId string thermostatId = thermostat.DeviceId; // The temperature in Farhenheit to set. (Note: type long) long newTempF = 75; // Set thermostat target temp (in degrees F). nest.Thermostats.SetTargetTemperatureF(thermostatId, newTempF); float newTempC = 23.5F; //Set thermostat target temp, in half degrees Celsius nest.Thermostats.SetTargetTemperatureC(thermostatId, newTempC); }
public void Execute(NestClient nest) { var myCamera = new Camera(); // Get id from Camera#getDeviceId. string camId = myCamera.DeviceId; // Set camera to start streaming with an optional success callback. nest.Cameras.SetIsStreaming(camId, true, new Callback() { OnSuccess = () => { // The update to the camera succeeded. }, OnFailure = (ex) => { // The update to the camera failed. }, }); }
private static async Task GetAndStoreAccessToken(string file, NestClient client) { try { Console.WriteLine("Login to authorize and enter your pin here."); // Get the URl to load in a browser for the PIN var authUrl = client.GetAuthorizationUrl(); string browser = GetDefaultBrowser(); Process processHandle; if (!String.IsNullOrEmpty(browser)) { processHandle = Process.Start(browser, authUrl); } else { processHandle = Process.Start(authUrl); } Console.Write("Enter your PIN:"); // Read back the pin var authToken = Console.ReadLine(); // Close the started process if (processHandle != null && !processHandle.HasExited) { processHandle.Kill(); } // get an access token to use with the API await client.GetAccessToken(authToken); File.WriteAllText(file, client.AccessToken); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
private DeviceReadings GetReadings(string username, string password) { var nestClient = new NestClient(username, password); nestClient.Authenticate().Wait(); var devicesTask = nestClient.GetDevices(); devicesTask.Wait(); dynamic result = devicesTask.Result; var devices = result.device; Type devicesType = devices.GetType(); var devicesFirstProp = devicesType.GetProperties().First(x => x.Name == "First"); dynamic firstDevice = devicesFirstProp.GetValue(devices).Value; var shareds = result.shared; Type sharedType = shareds.GetType(); var sharedFirstProp = sharedType.GetProperties().First(x => x.Name == "First"); dynamic firstShared = sharedFirstProp.GetValue(shareds).Value; double currentHumidity = firstDevice.current_humidity; double currentTemp = firstShared.current_temperature; double targetTemp = firstShared.target_temperature; int autoAway = firstShared.auto_away; bool heatState = firstShared.hvac_heater_state == "true"; Console.WriteLine(heatState); var readings = new DeviceReadings() { CurrentHumidity = currentHumidity, CurrentTemp = currentTemp, TargetTemp = targetTemp, AutoAway = autoAway, HeatState = heatState, }; return(readings); }
public void Execute(NestClient nest) { var myThermostat = new Thermostat(); // Get id from Thermostat#getDeviceId string thermostatId = myThermostat.DeviceId; // The temperature in Celsius to set. (Note: type double) double newTempC = 22.5; // Set thermostat target temp (in degrees C) with an optional success callback. nest.Thermostats.SetTargetTemperatureC(thermostatId, newTempC, new Callback() { OnSuccess = () => { // The update to the thermostat succeeded. }, OnFailure = (ex) => { // The update to the thermostat failed. }, }); }
public static void Execute(NestClient client, IExample example) { var exampleName = example.GetType().GetCustomAttribute <ExampleAttribute>()?.Name ?? example.GetType().Name; log.Info($"--------------------------------------------------------------------------------"); log.Info($"---------------- EXAMPLE \"{exampleName}\" START"); try { example.Execute(client); } catch (Exception ex) { log.Error("Failed to execute \"{exampleName}\".", ex); } finally { log.Info($"---------------- EXAMPLE \"{exampleName}\" END"); log.Info($"--------------------------------------------------------------------------------"); log.Info($"Presss ENTER to continue."); Console.ReadLine(); } }
static void Main(string[] args) { var accessToken = String.Empty; // Get location of executable var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "accesstoken.txt"); if (File.Exists(file)) { accessToken = File.ReadAllText(file); } var client = new NestClient(PRODUCT_ID, PRODUCT_SECRET); if (!String.IsNullOrEmpty(accessToken)) { client.SetAccessToken(accessToken, DateTime.UtcNow.AddYears(1)); } // TODO load access token if (!client.IsAuthValid()) { GetAndStoreAccessToken(file, client).Wait(); } NestDataModel result = client.GetNestDataAsync().Result; Devices deviecs = client.GetDevicesAsync().Result; var cameras = client.GetCamerasAsync().Result; var thermostats = client.GetThermostatsAsync().Result; var smokeCoAlarms = client.GetSmokeCoAlarms().Result; }
private void PutToNest(string binName, string fileName, IEnumerable<string> keys, IEnumerable<string> vals) { Exception primaryServiceException; var nestClient = new NestClient(); nestClient.Put(FixNestBinNameBase(binName), FixNestBinNameBase(fileName), keys, vals, out primaryServiceException); if (primaryServiceException != null) { StreamLogger.writeMsgToConsole(streamTaskId, primaryServiceException.Message, StreamLogger.msgType.Error, "TwitterStreamingDacq.StreamTask", "PutToNest", true); } }
static void Main(string[] args) { log.Info($"Nest DotNet SDK v{NestClient.SdkVersion}"); var configPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"data\"); var settings = new Settings(configPath); var tokenConfig = settings.Read <NestToken>("nest.token"); if (string.IsNullOrEmpty(tokenConfig?.Token)) {// var nestConfig = NestConfig.FromJson(settings.ReadJson("nest")); var getter = new TokenGetter(nestConfig); tokenConfig = getter.GetToken(); settings.Write("nest.token", tokenConfig); } using (var nest = new NestClient()) { nest.StartWithToken(tokenConfig.Token); //string structureId = "<your structure id>"; //nest.Structures.SetAway(structureId, AwayState.Away); //nest.Thermostats.setHVACMode(thermostatId_LivingRoom, "cool"); //nest.Thermostats.setTargetTemperatureC(thermostatId_LivingRoom, 23.5);//in half degrees Celsius (0.5℃). //ExampleExecutor.Execute(nest, new Example1()); //ExecuteAllExamples(nest); nest.StreamingError += (ex) => { Console.WriteLine("NEST ERROR.", ex); }; nest.WhenError().Subscribe(error => { log.Warn($"NEST ERROR: {error.Type} {error.Error}:{error.Message}"); }); nest.WhenAnyUpdated().Subscribe(data => { log.Info($"NEST UPDATE: {data}"); }); nest.WhenValueAdded() .Subscribe(e => { log.Info($"VALUE ADDED: {e?.Path} = {e?.Data}"); }); nest.WhenValueChanged() .Subscribe(e => { log.Info($"VALUE CHANGED: {e?.Path} = {e?.OldData} -> {e?.Data}"); }); nest.WhenValueRemoved() .Subscribe(e => { log.Info($"VALUE REMOVED: {e?.Path}"); }); log.Info("Monitor running. Presss ENTER to exit."); Console.ReadLine(); log.Info("Monitor exit."); } }