overview.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // vim: expandtab shiftwidth=4:
  2. var httpclient = function() {
  3. this.get = function(url, callback) {
  4. var req = new XMLHttpRequest();
  5. req.onreadystatechange = function () {
  6. if (req.readyState == 4 && req.status == 200) {
  7. callback(req.responseText)
  8. }
  9. }
  10. req.open('GET', url, true);
  11. req.send(null);
  12. }
  13. }
  14. function date_diff(start, end) {
  15. var day = 1000 * 60 * 60 * 24;
  16. return (Math.round((end.getTime() - start.getTime()) / day));
  17. }
  18. var chart = null;
  19. var render_graph = function(url, chartid) {
  20. var client = new httpclient();
  21. client.get(url, function(jsondata) {
  22. var ctx = document.getElementById(chartid).getContext('2d');
  23. if (! ctx) {
  24. console.log('Unable to find chart element ' + chartid);
  25. return;
  26. }
  27. var data = JSON.parse(jsondata);
  28. // The query on the server returns an already sorted array
  29. var minDate = new Date(data.labels[0]);
  30. var maxDate = new Date(data.labels[data.labels.length -1]);
  31. var days = date_diff(minDate, maxDate);
  32. var xaxisunit = 'day';
  33. if (days > 7)
  34. xaxisunit = 'week';
  35. else if (days > 31)
  36. xaxisunit = 'month';
  37. var graphdata = {
  38. labels : data.labels,
  39. datasets: [{
  40. borderColor: 'rgba(255, 140, 51, 1)',
  41. fill : false,
  42. pointRadius: 0,
  43. label : 'Temperature',
  44. data : data.temp
  45. }, {
  46. borderColor: 'rgba(0, 140, 255, 1)',
  47. fill : false,
  48. label : 'Humidity',
  49. pointRadius: 0,
  50. data : data.humidity
  51. }]
  52. };
  53. if (!chart) {
  54. chart = new Chart(ctx, {
  55. type: 'line',
  56. data: graphdata,
  57. options: {
  58. elements: {
  59. line: {
  60. tension: 0, // disable bezier curves
  61. }
  62. },
  63. legend: {
  64. display: true,
  65. labels: {
  66. fontColor: 'rgb(255, 99, 132)'
  67. }
  68. },
  69. scales: {
  70. xAxes: [{
  71. type: 'time',
  72. distribution: 'linear',
  73. time: {
  74. unit: xaxisunit
  75. }
  76. }]
  77. }
  78. }
  79. });
  80. } else {
  81. chart.options.scales = {
  82. xAxes: [{
  83. type: 'time',
  84. distribution: 'linear',
  85. time: {
  86. unit: xaxisunit
  87. }
  88. }]
  89. };
  90. chart.data = graphdata;
  91. chart.update();
  92. }
  93. });
  94. }