d_sellers1

Calculate Circadian sine

Jun 15th, 2022
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var sunrise = "06:00"; //Hard-coded sunrise
  2. var sunset = "18:00"; //Hard-coded sunset
  3.  
  4. var color_min = 2700; // Color temp at sunrise and sunset
  5. var color_max = 6500; // Color temp at noon
  6.  
  7. function map(x, in_min, in_max, out_min, out_max)
  8. {
  9.     return Math.round((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
  10. }
  11.  
  12. //If light is operating in RGB, do not set the color_temp except if the the light
  13. //has just been turned on.
  14. if (msg.topic != "turn_on") {
  15.     if (msg.payload.attributes.color_mode != "color_temp") {
  16.         return;
  17.     }
  18. }
  19.  
  20. var today = new Date();
  21. var today_date = today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate();
  22. var today_time = today.getHours() + ":" + String(today.getMinutes()).padStart(2, '0');
  23.  
  24. var unix_sunrise = new Date(today_date + ' ' + sunrise).getTime() / 1000;
  25. var unix_sunset = new Date(today_date + ' ' + sunset).getTime() / 1000;
  26. var unix_now = new Date().getTime() / 1000;
  27. var brightness = ""
  28.  
  29. var color_temp = color_min;
  30.  
  31. var day_progress = (unix_now-unix_sunrise) / (unix_sunset-unix_sunrise);
  32.  
  33. if (unix_now >= unix_sunrise && unix_now <= unix_sunset)
  34. {
  35.     var color_sine = Math.sin(((360 * day_progress)-90) * (Math.PI/180));
  36.    
  37.     color_temp = map(color_sine, -1.0, 1.0, color_min, color_max);
  38. }
  39.  
  40. day_progress = Math.round(day_progress * 100); //Round to a whole number
  41. node.status({text: color_temp + "K @ " + today_time + " (" + day_progress + "%)" });
  42.  
  43. /*msg.payload = {domain: "light", service: "turn_on",
  44.     data: {
  45.         entity_id: msg.payload.entity_id,
  46.         kelvin: color_temp,  }
  47.     };
  48. */
  49.     //msg.payload.domain = "light";
  50.     //msg.payload.service = "turn_on";
  51.    
  52.     //msg.payload.data = msg.payload.data || {}
  53.     msg.payload.data.kelvin = color_temp
  54. return msg;
  55.  
Advertisement
Add Comment
Please, Sign In to add comment