...
 
Commits (15)
......@@ -2,7 +2,7 @@
/* get all information necessary from MySQL and openTSDB */
function getAllParameters() {
mysqllookup()
//mysqllookup()
opentsdblookup()
}
......@@ -50,7 +50,7 @@ function opentsdblookup() {
lookup = { "metric": tag_metrics[i] }
try {
$.ajax({
url: "http://"+hostname+":8888/opentsdblookup",
url: "http://"+hostname+":4242/api/search/lookup",
dataType: "json",
error: showError,
success: getOpenTSDBParams,
......@@ -68,9 +68,11 @@ function opentsdblookup() {
};
function getOpenTSDBParams(data, status, jqXHRob) {
function getOpenTSDBParams(dataConverted, status, jqXHRob) {
var dataConverted = JSON.parse(data)
console.log("dataConverted: ", dataConverted)
//var dataConverted = JSON.parse(data)
//console.log("dataConverted: ", dataConverted)
all_parameters[dataConverted["metric"]] = []
......
var imported = document.createElement('script');
imported.type ="text/javascript"
imported.src = 'hostname.js';
document.head.appendChild(imported);
setTimeout(function () {
console.log(hostname)
}, 5000);
/* get all information necessary from MySQL and openTSDB */
function getAllParameters() {
mysqllookup()
//mysqllookup()
opentsdblookup()
}
......@@ -58,7 +50,7 @@ function opentsdblookup() {
lookup = { "metric": tag_metrics[i] }
try {
$.ajax({
url: "http://"+hostname+":8888/opentsdblookup",
url: "http://"+hostname+":4242/api/search/lookup",
dataType: "json",
error: showError,
success: getOpenTSDBParams,
......@@ -76,9 +68,11 @@ function opentsdblookup() {
};
function getOpenTSDBParams(data, status, jqXHRob) {
function getOpenTSDBParams(dataConverted, status, jqXHRob) {
var dataConverted = JSON.parse(data)
console.log("data: ", data)
//var dataConverted = JSON.parse(data)
//console.log("dataConverted: ", dataConverted)
all_parameters[dataConverted["metric"]] = []
......
var hostname = "amm-csr2.bucknell.edu"
var hostname = "amm-csr2"
var hostname = "amm-csr1.bucknell.edu"
var hostname = "amm-csr2.bucknell.edu"
......@@ -72,7 +72,9 @@ console.log("sensors: ", sensors)
html += '<select id="Sensor-'+id.toString()+'" onchange="changeSensor(this.id, this.value)"'+'style="display:inline-block;">';
for (var i = 0; i < sensors.length; i++) {
if (initial == "true" || initial == "true1") {
if (initial == "true") {
html += '<option selected value="' + sensors[i] + '">' + sensors[i].split(".")[0].split(":")[1] + '</option>' // hardcoded to use first tag (sensor_name)
selected += "." + sensors[i]
/*if (initial == "true") {
html += '<option selected value="Temperature.C">Temperature</option>'
selected += "." + "Temperature.C"
for (var j = 0; j < sensors.length; j++) {
......@@ -90,10 +92,11 @@ console.log("sensors: ", sensors)
}
}
break
}
}*/
} else {
if (i == 0) {
if (tag_metrics.indexOf(selected) != -1) {
//openTSDB
html += '<option selected value="' + sensors[i] + '">' + sensors[i].split(".")[0].split(":")[1] + '</option>' // hardcoded to use first tag (sensor_name)
selected += "." + sensors[i]
} else {
......@@ -114,7 +117,9 @@ console.log("sensors: ", sensors)
// units
if (initial == "true" || initial == "true1") {
if (initial == "true") {
html += '<p id = "Unit-'+id.toString()+'" style="display:inline-block; margin-left:10px; margin-right:10px; margin-top:0; margin-bottom:0;' + '">' + sensors[0].split(".")[2].split(":")[1] + '</p>'
units[id] = sensors[0].split(".")[2].split(":")[1] // hardcoded to use sensor_units
/*if (initial == "true") {
var ind = sensors.indexOf("Temperature.C")
html += '<p id = "Unit-'+id.toString()+'" style="display:inline-block; margin-left:10px; margin-right:10px; margin-top:0; margin-bottom:0;' + '">' + sensors[ind].split(".")[1] + '</p>'
units[id] = sensors[ind].split(".")[1]
......@@ -122,8 +127,8 @@ console.log("sensors: ", sensors)
var ind = sensors.indexOf("Dissolved Oxygen.mg/L")
html += '<p id = "Unit-'+id.toString()+'" style="display:inline-block; margin-left:10px; margin-right:10px; margin-top:0; margin-bottom:0;' + '">' + sensors[ind].split(".")[1] + '</p>'
units[id] = sensors[ind].split(".")[1]
}
} else {
}*/
//} else {
if (tag_metrics.indexOf(selected) != -1) {
// openTSDB
html += '<p id = "Unit-'+id.toString()+'" style="display:inline-block; margin-left:10px; margin-right:10px; margin-top:0; margin-bottom:0;' + '">' + sensors[0].split(".")[2].split(":")[1] + '</p>'
......
......@@ -30,7 +30,7 @@ function drawParameters(id, initial) {
var html = '<div style="clear:left;"><div style="float:left;">';
// remove
html += '<button id="Remove-'+id.toString()+'" class="remove-button" onclick="removeParameter(this.id);">Remove</button>';
html += '<button id="Remove-'+id.toString()+'" class="remove-button" title="Click to this parameter" onclick="removeParameter(this.id);">Remove</button>';
// axis
html += '<select id="Axis-'+id.toString()+'" onchange="updateAxis(this.id, this.selectedIndex)"' +'">';
......@@ -71,8 +71,8 @@ function drawParameters(id, initial) {
console.log("sensors: ", sensors)
html += '<select id="Sensor-'+id.toString()+'" onchange="changeSensor(this.id, this.value)"'+'style="display:inline-block;">';
for (var i = 0; i < sensors.length; i++) {
if (initial == "true" || initial == "true1") {
if (initial == "true") {
//if (initial == "true" || initial == "true1") {
/*if (initial == "true") {
html += '<option selected value="Temperature.C">Temperature</option>'
selected += "." + "Temperature.C"
for (var j = 0; j < sensors.length; j++) {
......@@ -90,10 +90,11 @@ console.log("sensors: ", sensors)
}
}
break
}
} else {
}*/
//} else {
if (i == 0) {
if (tag_metrics.indexOf(selected) != -1) {
//openTSDB
html += '<option selected value="' + sensors[i] + '">' + sensors[i].split(".")[0].split(":")[1] + '</option>' // hardcoded to use first tag (sensor_name)
selected += "." + sensors[i]
} else {
......@@ -113,8 +114,10 @@ console.log("sensors: ", sensors)
//console.log("sensors: ", sensors)
// units
if (initial == "true" || initial == "true1") {
if (initial == "true") {
//if (initial == "true" || initial == "true1") {
//html += '<p id = "Unit-'+id.toString()+'" style="display:inline-block; margin-left:10px; margin-right:10px; margin-top:0; margin-bottom:0;' + '">' + sensors[0].split(".")[2].split(":")[1] + '</p>'
//units[id] = sensors[0].split(".")[2].split(":")[1] // hardcoded to use sensor_units
/*if (initial == "true") {
var ind = sensors.indexOf("Temperature.C")
html += '<p id = "Unit-'+id.toString()+'" style="display:inline-block; margin-left:10px; margin-right:10px; margin-top:0; margin-bottom:0;' + '">' + sensors[ind].split(".")[1] + '</p>'
units[id] = sensors[ind].split(".")[1]
......@@ -122,8 +125,8 @@ console.log("sensors: ", sensors)
var ind = sensors.indexOf("Dissolved Oxygen.mg/L")
html += '<p id = "Unit-'+id.toString()+'" style="display:inline-block; margin-left:10px; margin-right:10px; margin-top:0; margin-bottom:0;' + '">' + sensors[ind].split(".")[1] + '</p>'
units[id] = sensors[ind].split(".")[1]
}
} else {
}*/
//} else {
if (tag_metrics.indexOf(selected) != -1) {
// openTSDB
html += '<p id = "Unit-'+id.toString()+'" style="display:inline-block; margin-left:10px; margin-right:10px; margin-top:0; margin-bottom:0;' + '">' + sensors[0].split(".")[2].split(":")[1] + '</p>'
......
......@@ -174,7 +174,7 @@ console.log("hostname: ", hostname)
/* default start and end dates */
var start = new Date(2014,6-1,20);
var start = new Date(2014,11-1,19);
var end = new Date();
/* set start date on the calendar; if a date is chosen by user, then query data and update graph */
......@@ -790,7 +790,8 @@ console.log("min2: ", min2)
}
queryCmd.push({"aggregator": "max", "downsample": downsample, "metric": parameter_names[i].split(".")[0], "rate": "false", "tags": {"sensor_name":sensor, "sensor_processing": processing, "sensor_units": units}})
//queryCmd.push({"aggregator": "max", "downsample": downsample, "metric": parameter_names[i].split(".")[0], "rate": "false", "tags": {"sensor_name":sensor, "sensor_processing": processing, "sensor_units": units}})
queryCmd.push({"aggregator": "max", "metric": parameter_names[i].split(".")[0], "rate": "false", "tags": {"sensor_name":sensor, "sensor_processing": processing, "sensor_units": units}})
param_indices[parameter_names[i]] = index
index += 1
......@@ -850,14 +851,15 @@ console.log("min2: ", min2)
console.log("queryCmd: ", queryCmd)
var query = { "start":start.getTime()/1000, "end":end.getTime()/1000, "queries":queryCmd }
var query = { "start":(start.getTime()/1000) >> 0, "end":(end.getTime()/1000) >> 0, "queries":queryCmd }
console.log("query: ", query)
try {
$.ajax({
url: "http://"+hostname+":8888/query",
//url: "http://"+hostname+":8888/query",
url: "http://"+hostname+":4242/api/query",
dataType: "json",
error: showError,
success: createGraph,
......@@ -896,10 +898,10 @@ console.log("data: ", data)
var sensor_info = parameter_names[i]
// if there is data
if (data[count][0][sensor_info].length != 0) {
for (var j = 0; j < data[count][0][sensor_info].length; j++) {
domains["min"][axis] = Math.min(domains["min"][axis], data[count][0][sensor_info][j]["y"])
domains["max"][axis] = Math.max(domains["max"][axis], data[count][0][sensor_info][j]["y"])
if (data[count]["dps"].length != 0) {
for (var j in data[count]["dps"]) {
domains["min"][axis] = Math.min(domains["min"][axis], data[count]["dps"][j])
domains["max"][axis] = Math.max(domains["max"][axis], data[count]["dps"][j])
}
}
count += 1
......@@ -936,10 +938,10 @@ console.log("shown_parameters: ", shown_parameters)
try {
if (tag_metrics.indexOf(sensor_info.split(".")[0]) == -1) {
// in mySQL
if (data[count][0][sensor_info].length != 0) {
if (data[count][sensor_info].length != 0) {
series.push( { name: sensor_info.split(".")[0]+"."+sensor_info.split(".")[1],
color: colorScheme[series.length],
data: data[count][0][sensor_info],
data: data[count][sensor_info],
scale: axes[axis] })
units_being_used.push(sensor_info.split(".")[2])
......@@ -950,17 +952,17 @@ console.log("shown_parameters: ", shown_parameters)
}
} else {
// hardcoded to use sensor_name
if (data[count][0][sensor_info].length != 0) {
if (data[count]["dps"].length != 0) {
if (sensor_info.split(".")[0] == "Table") {
series.push( { name: "CR1000"+"."+sensor_info.split(".")[1].split(":")[1],
color: colorScheme[series.length],
data: data[count][0][sensor_info],
data: data[count]["dps"],
scale: axes[axis]})
units_being_used.push(sensor_info.split(".")[3].split(":")[1])
} else {
series.push( { name: sensor_info.split(".")[0].split(":")[1],
color: colorScheme[series.length],
data: data[count][0][sensor_info] ,
data: data[count]["dps"] ,
scale: axes[axis]})
units_being_used.push(sensor_info.split(".")[3].split(":")[1])
}
......@@ -1001,6 +1003,14 @@ console.log("shown_parameters: ", shown_parameters)
console.log("axes: ", axes)
console.log("series: ", series)
for (var blah = 0; blah < series.length; blah++) {
var data_array = []
for (asdf in series[blah]["data"]) {
data_array.push({"x":parseInt(asdf),"y":series[blah]["data"][asdf]});
}
series[blah]["data"] = data_array
}
try {
......
......@@ -174,7 +174,7 @@ console.log("hostname: ", hostname)
/* default start and end dates */
var start = new Date(2014,6-1,20);
var start = new Date(2014,11-1,19);
var end = new Date();
/* set start date on the calendar; if a date is chosen by user, then query data and update graph */
......@@ -329,7 +329,7 @@ console.log("hostname: ", hostname)
// query string
url_query = url_query.substring(1)
try {
var settings = url_query.split(";")
var settings = url_query.split("&")
for (var x = 0; x < settings.length; x++) {
var setting = settings[x]
console.log(setting)
......@@ -790,7 +790,8 @@ console.log("min2: ", min2)
}
queryCmd.push({"aggregator": "max", "downsample": downsample, "metric": parameter_names[i].split(".")[0], "rate": "false", "tags": {"sensor_name":sensor, "sensor_processing": processing, "sensor_units": units}})
//queryCmd.push({"aggregator": "max", "downsample": downsample, "metric": parameter_names[i].split(".")[0], "rate": "false", "tags": {"sensor_name":sensor, "sensor_processing": processing, "sensor_units": units}})
queryCmd.push({"aggregator": "max", "metric": parameter_names[i].split(".")[0], "rate": "false", "tags": {"sensor_name":sensor, "sensor_processing": processing, "sensor_units": units}})
param_indices[parameter_names[i]] = index
index += 1
......@@ -850,14 +851,15 @@ console.log("min2: ", min2)
console.log("queryCmd: ", queryCmd)
var query = { "start":start.getTime()/1000, "end":end.getTime()/1000, "queries":queryCmd }
var query = { "start":(start.getTime()/1000) >> 0, "end":(end.getTime()/1000) >> 0, "queries":queryCmd }
console.log("query: ", query)
try {
$.ajax({
url: "http://"+hostname+":8888/query",
//url: "http://"+hostname+":8888/query",
url: "http://"+hostname+":4242/api/query",
dataType: "json",
error: showError,
success: createGraph,
......@@ -896,10 +898,10 @@ console.log("data: ", data)
var sensor_info = parameter_names[i]
// if there is data
if (data[count][0][sensor_info].length != 0) {
for (var j = 0; j < data[count][0][sensor_info].length; j++) {
domains["min"][axis] = Math.min(domains["min"][axis], data[count][0][sensor_info][j]["y"])
domains["max"][axis] = Math.max(domains["max"][axis], data[count][0][sensor_info][j]["y"])
if (data[count]["dps"].length != 0) {
for (var j in data[count]["dps"]) {
domains["min"][axis] = Math.min(domains["min"][axis], data[count]["dps"][j])
domains["max"][axis] = Math.max(domains["max"][axis], data[count]["dps"][j])
}
}
count += 1
......@@ -936,10 +938,10 @@ console.log("shown_parameters: ", shown_parameters)
try {
if (tag_metrics.indexOf(sensor_info.split(".")[0]) == -1) {
// in mySQL
if (data[count][0][sensor_info].length != 0) {
if (data[count][sensor_info].length != 0) {
series.push( { name: sensor_info.split(".")[0]+"."+sensor_info.split(".")[1],
color: colorScheme[series.length],
data: data[count][0][sensor_info],
data: data[count][sensor_info],
scale: axes[axis] })
units_being_used.push(sensor_info.split(".")[2])
......@@ -950,17 +952,17 @@ console.log("shown_parameters: ", shown_parameters)
}
} else {
// hardcoded to use sensor_name
if (data[count][0][sensor_info].length != 0) {
if (data[count]["dps"].length != 0) {
if (sensor_info.split(".")[0] == "Table") {
series.push( { name: "CR1000"+"."+sensor_info.split(".")[1].split(":")[1],
color: colorScheme[series.length],
data: data[count][0][sensor_info],
data: data[count]["dps"],
scale: axes[axis]})
units_being_used.push(sensor_info.split(".")[3].split(":")[1])
} else {
series.push( { name: sensor_info.split(".")[0].split(":")[1],
color: colorScheme[series.length],
data: data[count][0][sensor_info] ,
data: data[count]["dps"] ,
scale: axes[axis]})
units_being_used.push(sensor_info.split(".")[3].split(":")[1])
}
......@@ -1001,6 +1003,14 @@ console.log("shown_parameters: ", shown_parameters)
console.log("axes: ", axes)
console.log("series: ", series)
for (var blah = 0; blah < series.length; blah++) {
var data_array = []
for (asdf in series[blah]["data"]) {
data_array.push({"x":asdf,"y":series[blah]["data"][asdf]});
}
series[blah]["data"] = data_array
}
try {
......
......@@ -21,6 +21,7 @@
<script src="Scripts/rickshaw.min.js"></script>
<script src="Scripts/jquery-1.9.0.min.js"></script>
<script src="Scripts/jquery-1.9.0.js"></script>
<script src="Scripts/jquery-ui.js"></script>
<script src="Scripts/rickshaw.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
......@@ -50,7 +51,12 @@
<div class="compare-label">End Date:</div>
<input type="text" id="end-date" class="text ui-widget-content ui-corner-all compare-input">
</div>
<!--
<div id="unit">
<input type="radio" name="unit" value="meters/second" checked>meters/second<br>
<input type="radio" name="unit" value="miles/hour">miles/hour
</div>
-->
</body>
......@@ -59,7 +65,7 @@
/* default start and end dates */
var start = new Date(2014,6-1,20);
var start = new Date(2014,11-1,1);
var end = new Date();
/* set start date on the calendar; if a date is chosen by user, then query data and update graph */
......@@ -85,28 +91,30 @@
function main() {
var dict = {}
dict["sensor_name"] = "WindDir"
dict["sensor_processing"] = "Smp"
dict["sensor_units"] = "degrees"
//dict["sensor_processing"] = "Smp"
//dict["sensor_units"] = "degrees"
var command = {"aggregator": "max", "metric": "Table", "rate": "false", "tags": dict}
var dict2 = {}
dict2["sensor_name"] = "WindSpeed"
dict2["sensor_processing"] = "Smp"
dict2["sensor_units"] = "meters/second"
//dict2["sensor_processing"] = "Smp"
//dict2["sensor_units"] = "meters/second"
var command2 = {"aggregator": "max", "metric": "Table", "rate": "false", "tags": dict2}
var queryData =
{
"start": start.getTime(),
"end": end.getTime(),
"db" : "OpenTSDB",
"start": (start.getTime()/1000) >> 0,
"end": (end.getTime()/1000) >> 0,
//"db" : "OpenTSDB",
"queries": [command, command2]
//"queries": [command]
}
console.log(queryData);
try {
$.ajax({
url: "http://"+hostname+":8888/query",
url: "http://amm-csr2:4242/api/query",
dataType: "json",
error: showError,
success: createGraph,
......@@ -127,37 +135,74 @@
};
function createGraph(data, status, jqXHRob) {
console.log(data);
// var unit = document.getElementById('unit').value;
var size = 16;
var showData = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var maxWindSpeed = 0
var maxWindSpeed = 0;
var speedDistr = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
//var speedDistr = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
for (var i = 0; i < data[0][0]["Table.sensor_name:WindDir.sensor_processing:Smp.sensor_units:degrees"].length; i++) {
var index = Math.floor(data[0][0]["Table.sensor_name:WindDir.sensor_processing:Smp.sensor_units:degrees"][i]["y"]/23)
var speedDistr = new Array(16);
for (var q = 0; q < 16; q++) {
speedDistr[q] = [0,0,0,0];
}
console.log("speedDistr: ", speedDistr);
var count = 0
for (var i in data[0]["dps"]) {
count += 1;
var index = Math.floor(data[0]["dps"][i]/23)
//var value = Math.floor(data[0]["dps"][i];
if (index < 16) {
showData[index] += 1
var speed = data[1][0]["Table.sensor_name:WindSpeed.sensor_processing:Smp.sensor_units:meters/second"][i]["y"]
if (speed < 0.5) {
speedDistr[index][0] += 1;
} else if (speed < 1) {
speedDistr[index][1] += 1;
} else if (speed < 1.5) {
speedDistr[index][2] += 1;
var speed = data[1]["dps"][i]
/*
if (unit == 'meters/second') {
*/
if (speed < 1) {
speedDistr[index][0] += 1;
} else if (speed < 2) {
speedDistr[index][1] += 1;
} else if (speed < 3) {
speedDistr[index][2] += 1;
} else {
speedDistr[index][3] += 1;
}
/*
} else {
speedDistr[index][3] += 1;
if (speed < meter_secTOmile_hr(0.5)) {
speedDistr[index][0] += 1;
} else if (speed < meter_secTOmile_hr(1)) {
speedDistr[index][1] += 1;
} else if (speed < meter_secTOmile_hr(1.5)) {
speedDistr[index][2] += 1;
} else {
speedDistr[index][3] += 1;
}
}
*/
} else {
console.log("invalid index");
}
}
console.log("speedDistr: ",speedDistr);
var percentages = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for (var i = 0; i < showData.length; i++) {
percentages[i] = showData[i]*100/data[0][0]["Table.sensor_name:WindDir.sensor_processing:Smp.sensor_units:degrees"].length
percentages[i] = showData[i]*100/count
speedDistr[i][0] = speedDistr[i][0]/(showData[i])*(percentages[i])
speedDistr[i][1] = speedDistr[i][1]/(showData[i])*(percentages[i])
......@@ -177,30 +222,35 @@ console.log(percentages)
.set('title', "Wind Dir and Wind Speed")
.set('labels', ['','NE','','E','','SE','','S','','SW','','W','','NW','','N'])
.set('labels.position', 'edge')
.set('tooltips',['0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5',
'0-0.5', '0.5-1', '1-1.5', '>1.5'
.set('tooltips',['0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3',
'0-1', '1-2', '2-3', '>3'
])
.set('key', ['0-0.5', '0.5-1', '1-1.5', '>1.5'])
.set('key', ['0-1', '1-2', '2-3', '>3'])
.set('key.interactive', true)
.set('gutter.top', 50)
.draw();
/*
if (unit == "miles/hour") {
rose.set('key', ['a','b','c','d'])
}
*/
};
function mpsTOmph(mps) {
function meter_secTOmile_hr(mps) {
return mps*3600/1609.34
}
......
......@@ -21,6 +21,7 @@
<script src="Scripts/rickshaw.min.js"></script>
<script src="Scripts/jquery-1.9.0.min.js"></script>
<script src="Scripts/jquery-1.9.0.js"></script>
<script src="Scripts/jquery-ui.js"></script>
<script src="Scripts/rickshaw.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
......@@ -29,7 +30,7 @@
<script src="Scripts/RangeSlider.js"> </script>
<script src="Scripts/RangeSliderPreview.js"> </script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="IWrote/hostname.js"></script>
......@@ -50,7 +51,12 @@
<div class="compare-label">End Date:</div>
<input type="text" id="end-date" class="text ui-widget-content ui-corner-all compare-input">
</div>
<!--
<div id="unit">
<input type="radio" name="unit" value="meters/second" checked>meters/second<br>
<input type="radio" name="unit" value="miles/hour">miles/hour
</div>
-->
</body>
......@@ -59,7 +65,7 @@
/* default start and end dates */
var start = new Date(2014,6-1,20);
var start = new Date(2014,11-1,1);
var end = new Date();
/* set start date on the calendar; if a date is chosen by user, then query data and update graph */
......@@ -85,28 +91,30 @@
function main() {
var dict = {}
dict["sensor_name"] = "WindDir"
dict["sensor_processing"] = "Smp"
dict["sensor_units"] = "degrees"
//dict["sensor_processing"] = "Smp"
//dict["sensor_units"] = "degrees"
var command = {"aggregator": "max", "metric": "Table", "rate": "false", "tags": dict}
var dict2 = {}
dict2["sensor_name"] = "WindSpeed"
dict2["sensor_processing"] = "Smp"
dict2["sensor_units"] = "meters/second"
//dict2["sensor_processing"] = "Smp"
//dict2["sensor_units"] = "meters/second"
var command2 = {"aggregator": "max", "metric": "Table", "rate": "false", "tags": dict2}
var queryData =
{
"start": start.getTime(),
"end": end.getTime(),
"db" : "OpenTSDB",
"start": (start.getTime()/1000) >> 0,
"end": (end.getTime()/1000) >> 0,
//"db" : "OpenTSDB",
"queries": [command, command2]
//"queries": [command]
}
console.log(queryData);
try {
$.ajax({
url: "http://134.82.132.5:8888/query",
url: "http://amm-csr2:4242/api/query",
dataType: "json",
error: showError,
success: createGraph,
......@@ -127,37 +135,74 @@
};
function createGraph(data, status, jqXHRob) {
console.log(data);
// var unit = document.getElementById('unit').value;
var size = 16;
var showData = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var maxWindSpeed = 0
var maxWindSpeed = 0;
var speedDistr = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
for (var i = 0; i < data[0][0]["Table.sensor_name:WindDir.sensor_processing:Smp.sensor_units:degrees"].length; i++) {
var index = Math.floor(data[0][0]["Table.sensor_name:WindDir.sensor_processing:Smp.sensor_units:degrees"][i]["y"]/23)
//var speedDistr = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
var speedDistr = new Array(16);
for (var q = 0; q < 16; q++) {
speedDistr[q] = [0,0,0,0];
}
console.log("speedDistr: ", speedDistr);
var count = 0
for (var i in data[0]["dps"]) {
count += 1;
var index = Math.floor(data[0]["dps"][i]/23)
//var value = Math.floor(data[0]["dps"][i];
if (index < 16) {
showData[index] += 1
var speed = data[1][0]["Table.sensor_name:WindSpeed.sensor_processing:Smp.sensor_units:meters/second"][i]["y"]
if (speed < 0.5) {
speedDistr[index][0] += 1;
} else if (speed < 1) {
speedDistr[index][1] += 1;
} else if (speed < 1.5) {
speedDistr[index][2] += 1;
var speed = data[1]["dps"][i]
/*
if (unit == 'meters/second') {
*/
if (speed < 0.5) {
speedDistr[index][0] += 1;
} else if (speed < 1) {
speedDistr[index][1] += 1;
} else if (speed < 1.5) {
speedDistr[index][2] += 1;
} else {
speedDistr[index][3] += 1;
}
/*
} else {
speedDistr[index][3] += 1;
if (speed < meter_secTOmile_hr(0.5)) {
speedDistr[index][0] += 1;
} else if (speed < meter_secTOmile_hr(1)) {
speedDistr[index][1] += 1;
} else if (speed < meter_secTOmile_hr(1.5)) {
speedDistr[index][2] += 1;
} else {
speedDistr[index][3] += 1;
}
}
*/
} else {
console.log("invalid index");
}
}
console.log("speedDistr: ",speedDistr);
var percentages = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for (var i = 0; i < showData.length; i++) {
percentages[i] = showData[i]*100/data[0][0]["Table.sensor_name:WindDir.sensor_processing:Smp.sensor_units:degrees"].length
percentages[i] = showData[i]*100/count
speedDistr[i][0] = speedDistr[i][0]/(showData[i])*(percentages[i])
speedDistr[i][1] = speedDistr[i][1]/(showData[i])*(percentages[i])
......@@ -198,9 +243,14 @@ console.log(percentages)
.set('key.interactive', true)
.set('gutter.top', 50)
.draw();
/*
if (unit == "miles/hour") {
rose.set('key', ['a','b','c','d'])
}
*/
};
function mpsTOmph(mps) {
function meter_secTOmile_hr(mps) {
return mps*3600/1609.34
}
......
campbell.db
campbell.log
*.pyc
# Configuration file
[opentsdb]
server = http://amm-csr2:4242/api
[pakbus]
host = 60e90457.eairlink.com
......@@ -13,11 +15,12 @@ my_node_id = 0x802
# datalogger name and it's pakbus ID
#"CR1000": 1,
datalogger_pakbus_id = {"CR800_1": 2,
#
datalogger_pakbus_id = {"CR1000": 1,
"CR800_1": 2,
"CR800_2": 3}
#datalogger_pakbus_id = {"CR1000": 1}
#datalogger_pakbus_id = {"CR800_2": 3}
datalogger_security_code = {"CR1000": 4369,
"CR800_1": 4369,
......
......@@ -66,11 +66,14 @@ class DataLogger:
self.log.info("{}@{} has serial number {}".format(metric_id, pakbus_id, self.serno))
self.log.debug("Getting table defs")
self.FileData = pakbus.fileupload(socket,
self.FileData, RespCode = pakbus.fileupload(socket,
self.pakbus_id,
self.my_node_id,
FileName = '.TDF',
SecurityCode = self.security_code)[0]
SecurityCode = self.security_code)
# todo, check resp code!
self.log.debug(" -- table def RespCode was: {}".format(RespCode))
#self.log.debug("Filedata = {}".format(self.FileData))
self.tabledef = pakbus.parse_tabledef(self.FileData)
......@@ -126,7 +129,7 @@ class DataLogger:
if rslt and rslt[0] and rslt[1] and rslt[0] != "Null" and rslt[1] != "Null":
self.last_collect["ts"] = rslt[0]
self.last_collect["NextRecNbr"] = rslt[1]
self.log.debug("Datalogger resuming from recnumber {} last uploaded on {}".format(rslt[1], rslt[0]))
self.log.info("Datalogger resuming from recnumber {} last uploaded on {}".format(rslt[1], rslt[0]))
else:
self.update_local_db("Null", "Null")
......@@ -160,8 +163,9 @@ class DataLogger:
list_of_tables += [Table(self.tabledef[tableno]['Header']['TableName'], self.tabledef, tableno)]
else:
if (count > 0):
self.FileData = pakbus.fileupload(socket, self.pakbus_id, self.my_node_id, FileName = '.TDF')[0]
return self.getTables(count-1)
self.FileData, RespCode = pakbus.fileupload(socket, self.pakbus_id, self.my_node_id, FileName = '.TDF')
self.log.debug(" -- table def RespCode was: {}".format(RespCode))
return self.getTables(socket, count-1)
else:
# raise exception??
print "Could not get tables for datalogger with metric: " + str(self.metric_id) + " and pakbus: " + str(self.pakbus_id) + " after 3 tries."
......
......@@ -71,17 +71,17 @@ if not vars().has_key('transact'):
#
# Send packet over PakBus
#
# - add signature nullifier
# - quote \xBC and \xBD characters
# - frame packet with \xBD characters
# Calculate signature for PakBus packets
#
def send(s, pkt):
# s: socket object
# pkt: unquoted, unframed PakBus packet (just header + message)
frame = quote(pkt + calcSigNullifier(calcSigFor(pkt)))
s.send('\xBD' + frame + '\xBD')
def calcSigFor(buff, seed = 0xAAAA):
sig = seed
for x in buff:
x = ord(x)
j = sig
sig = (sig <<1) & 0x1FF
if sig >= 0x100: sig += 1
sig = ((((sig + (j >>8) + x) & 0xFF) | (j <<8))) & 0xFFFF
return sig
#
......@@ -156,47 +156,9 @@ def PakBus_hdr(DstNodeId, SrcNodeId, HiProtoCode = 0x1, ExpMoreCode = 0x0, LinkS
#
################################################################################
#
# Calculate signature for PakBus packets
#
def calcSigFor(buff, seed = 0xAAAA):
sig = seed
for x in buff:
x = ord(x)
j = sig
sig = (sig <<1) & 0x1FF
if sig >= 0x100: sig += 1
sig = ((((sig + (j >>8) + x) & 0xFF) | (j <<8))) & 0xFFFF
return sig
#
# Calculate signature nullifier needed to create valid PakBus packets
#
def calcSigNullifier(sig):
nulb = nullif = ''
for i in 1,2:
sig = calcSigFor(nulb, sig)
sig2 = (sig<<1) & 0x1FF
if sig2 >= 0x100: sig2 += 1
nulb = chr((0x100 - (sig2 + (sig >>8))) & 0xFF)
nullif += nulb
return nullif
#
# Quote PakBus packet
#
def quote(pkt):
pkt = string.replace(pkt, '\xBC', '\xBC\xDC') # quote \xBC characters
pkt = string.replace(pkt, '\xBD', '\xBC\xDD') # quote \xBD characters
return pkt
#
# Unquote PakBus packet
#
def unquote(pkt):
pkt = string.replace(pkt, '\xBC\xDD', '\xBD') # unquote \xBD characters
pkt = string.replace(pkt, '\xBC\xDC', '\xBC') # unquote \xBC characters
return pkt
################################################################################
......@@ -1056,7 +1018,9 @@ def decode_pkt(pkt):
# pkt: buffer containing unquoted packet, signature nullifier stripped
# Initialize output variables
hdr = {'LinkState': None, 'DstPhyAddr': None, 'ExpMoreCode': None, 'Priority': None, 'SrcPhyAddr': None, 'HiProtoCode': None, 'DstNodeId': None, 'HopCnt': None, 'SrcNodeId': None}
hdr = {'LinkState': None, 'DstPhyAddr': None, 'ExpMoreCode': None,
'Priority': None, 'SrcPhyAddr': None, 'HiProtoCode': None,
'DstNodeId': None, 'HopCnt': None, 'SrcNodeId': None}
msg = {'MsgType': None, 'TranNbr': None, 'raw': None}
try:
......@@ -1250,9 +1214,9 @@ def clock_sync(s, DstNodeId, SrcNodeId, SecurityCode = 0x1111, min_adjust = 0.1,
for j in range(10):
pkt, TranNbr = pkt_clock_cmd(DstNodeId, SrcNodeId)
t1 = time.time() # timestamp directly before sending clock command
send(s, pkt)
s.send(pkt)
reftime = time.time() # reference time (UTC)
hdr, msg = wait_pkt(s, DstNodeId, SrcNodeId, TranNbr)
hdr, msg = s.wait_pkt(DstNodeId, SrcNodeId, TranNbr)
t2 = time.time() # timestamp directly after receiving clock response
# Calculate time difference
......@@ -1281,8 +1245,8 @@ def clock_sync(s, DstNodeId, SrcNodeId, SecurityCode = 0x1111, min_adjust = 0.1,
# Adjust clock
adjust = max(min(-tdiff, max_adjust), -max_adjust)
pkt, TranNbr = pkt_clock_cmd(DstNodeId, SrcNodeId, time_to_nsec(adjust, epoch = 0))
send(s, pkt)
hdr, msg = wait_pkt(s, DstNodeId, SrcNodeId, TranNbr)
s.send(pkt)
hdr, msg = s.wait_pkt(DstNodeId, SrcNodeId, TranNbr)
else:
adjust = 0
......@@ -1301,60 +1265,7 @@ def clock_sync(s, DstNodeId, SrcNodeId, SecurityCode = 0x1111, min_adjust = 0.1,
#
################################################################################
#
# Wait for an incoming packet
#
### added here: changed timeout from 5 to 10
def wait_pkt(s, SrcNodeId, DstNodeId, TranNbr, timeout = 10):
# s: socket object
# SrcNodeId: source node ID (12-bit int)
# DstNodeId: destination node ID (12-bit int)
# TranNbr: expected transaction number
# timeout: timeout in seconds
import time, socket
max_time = time.time() + 0.9 * timeout
# remember current timeout setting
s_timeout = s.gettimeout()
# Loop until timeout is reached
while time.time() < max_time:
s.settimeout(timeout)
try:
rcv = recv(s)
except socket.timeout:
rcv = ''
hdr, msg = decode_pkt(rcv)
# ignore packets that are not for us
if hdr['DstNodeId'] != DstNodeId or hdr['SrcNodeId'] != SrcNodeId:
continue
# Respond to incoming hello command packets
if msg['MsgType'] == 0x09:
pkt = pkt_hello_response(hdr['SrcNodeId'], hdr['DstNodeId'], msg['TranNbr'])
send(s, pkt)
continue
# Handle "please wait" packets
if msg['TranNbr'] == TranNbr and msg['MsgType'] == 0xa1:
timeout = msg['WaitSec']
max_time += timeout
continue
# this should be the packet we are waiting for
if msg['TranNbr'] == TranNbr:
break
else:
hdr = {}
msg = {}
# restore previous timeout setting
s.settimeout(s_timeout)
return hdr, msg
#
......@@ -1384,8 +1295,8 @@ def filedownload(s, DstNodeId, SrcNodeId, FileName, FileData, SecurityCode = 0x1
# Download Swath bytes after FileOffset from FileData
pkt, TranNbr = pkt_filedownload_cmd(DstNodeId, SrcNodeId, FileName, FileData[FileOffset:FileOffset+Swath], FileOffset = FileOffset, TranNbr = TranNbr, CloseFlag = CloseFlag)
send(s, pkt)
hdr, msg = wait_pkt(s, DstNodeId, SrcNodeId, TranNbr)
s.send(pkt)
hdr, msg = s.wait_pkt(DstNodeId, SrcNodeId, TranNbr)
try:
RespCode = msg['RespCode']
......@@ -1421,9 +1332,9 @@ def fileupload(s, DstNodeId, SrcNodeId, FileName, SecurityCode = 0x1111):
# Upload chunk from file starting at FileOffset
pkt, TranNbr = pkt_fileupload_cmd(DstNodeId, SrcNodeId, FileName, FileOffset = FileOffset, TranNbr = TranNbr, CloseFlag = 0x00)
send(s, pkt)
hdr, msg = wait_pkt(s, DstNodeId, SrcNodeId, TranNbr)
#s.send(pkt)
#hdr, msg = s.wait_pkt(DstNodeId, SrcNodeId, TranNbr)
hdr, msg = s.send_and_wait(pkt, DstNodeId, SrcNodeId, TranNbr)
#print 'msg = ', msg, '\n'
try:
......@@ -1459,8 +1370,8 @@ def getvalues(s, DstNodeId, SrcNodeId, TableName, Type, FieldName, Swath = 1, Se
## i = 0
## while i < 100:
pkt, TranNbr = pkt_getvalues_cmd(DstNodeId, SrcNodeId, TableName, Type, FieldName, Swath, SecurityCode)
send(s, pkt)
hdr, msg = wait_pkt(s, DstNodeId, SrcNodeId, TranNbr)
s.send(pkt)
hdr, msg = s.wait_pkt(DstNodeId, SrcNodeId, TranNbr)
#print 'hdr = ', hdr
#print 'msg = ', msg
#print '\n'
......@@ -1523,8 +1434,10 @@ def collect_data(s, DstNodeId, SrcNodeId, TableDef, TableName, FieldNames = [],
# Send collect data request
pkt, TranNbr = pkt_collectdata_cmd(DstNodeId, SrcNodeId, tablenbr, tabledefsig, FieldNbr = fieldnbr, CollectMode = CollectMode, P1 = P1, P2 = P2, SecurityCode = SecurityCode)
send(s, pkt)
hdr, msg = wait_pkt(s, DstNodeId, SrcNodeId, TranNbr)
#s.send(pkt)
#hdr, msg = s.wait_pkt(DstNodeId, SrcNodeId, TranNbr)
hdr, msg = s.send_and_wait(pkt, DstNodeId, SrcNodeId, TranNbr)
try:
RecData, MoreRecsExist = parse_collectdata(msg['RecData'], TableDef, FieldNbr = fieldnbr)
except:
......@@ -1612,15 +1525,17 @@ def get_cr1000_serial(s, DstNodeId, SrcNodeId, SecurityCode = 0x1111):
1, #1 = serial number
1, #1 = serial number
SecurityCode)
send(s, pkt)
hdr, msg = wait_pkt(s, DstNodeId, SrcNodeId, TranNbr)
hdr, msg = s.send_and_wait(pkt, DstNodeId, SrcNodeId, TranNbr)
#s.send(pkt)
#hdr, msg = s.wait_pkt(DstNodeId, SrcNodeId, TranNbr)
if msg['Outcome'] == 1:
if 'Outcome' in msg and msg['Outcome'] == 1:
# success
return decode_bin(['UInt4'], msg['Settings'][0]['SettingValue'])[0][0]
else:
elif 'Outcome' in msg:
raise PakBusException("Failed to get serial, outcome was: {}".format(msg['Outcome']))
else:
raise PakBusException("Failed to get serial number.")
#
# Check if remote host is available
#
......@@ -1631,7 +1546,7 @@ def ping_node(s, DstNodeId, SrcNodeId):
# send hello command and wait for response packet
pkt, TranNbr = pkt_hello_cmd(DstNodeId, SrcNodeId)
send(s, pkt)
hdr, msg = wait_pkt(s, DstNodeId, SrcNodeId, TranNbr)
s.send(pkt)
hdr, msg = s.wait_pkt(DstNodeId, SrcNodeId, TranNbr)
return msg
This diff is collapsed.
......@@ -2,7 +2,7 @@
# setup logging FIRST.
import logging
LOGFMT = '%(asctime)s %(name)-30s %(levelname)-8s %(message).160s'
LOGFMT = '%(asctime)s %(name)-30s %(levelname)-8s %(message).240s'
logging.basicConfig(level = logging.DEBUG,
format = LOGFMT)
......@@ -14,8 +14,10 @@ import pakbus
import time
import json
import socket
import paksock
import requests
from API import SensorClient
#from API import SensorClient
import threading
from threading import Event
......@@ -27,12 +29,14 @@ from sensorTag import SensorTag
class DatabaseAL (threading.Thread):
"database abstraction layer"
def __init__(self):
def __init__(self, server):
threading.Thread.__init__(self)
self.name = "DatabaseAL worker thread"
self.setDaemon(True)
self.log = logging.getLogger('DatabaseAL')
self.client = SensorClient()
#self.client = SensorClient()
self.server = server
self.dataq = Queue(maxsize = 1024*1024)
self.shutdown_evt = Event()
......@@ -40,32 +44,73 @@ class DatabaseAL (threading.Thread):
"append data to the db"
#self.log.debug("Got data: {} {} {}".format(timestamp, values, tags))
# append a tuple
if type(tags) is SensorTag:
print tags
#if type(tags) is SensorTag:
# print tags
if self.dataq.full():
self.log.error("DataQ is full! Data is lost!")
else:
self.dataq.put( (timestamp, values, tags) )
def busy(self):
return not self.dataq.empty()
def put(self, worklist):
#format is (unix timestamp, value, Tags)
m = set()
t = set()
p = []
for w in worklist:
ts, val, tags = w
if tags.metric not in m:
m.add(tags.metric)
for k,v in tags.toTagData().items():
kv_str = "{}={}".format(k,v)
if kv_str not in t:
t.add(kv_str)
p += [{'metric': tags.metric,
'timestamp': ts,
'value': val,
'tags': tags.toTagData(),
}]
#self.log.debug("putting data: "+json.dumps(p))
self.log.info("putting metrics:"+str(m))
self.log.info("with tags:"+str(t))
r = requests.post('{}/put?details'.format(self.server),
data = json.dumps(p))
if r.status_code != requests.codes.ok:
self.log.error("put failed: "+ r.text)
for ts, val, tags in worklist:
self.append( ts, val, tags)
#else:
#self.log.info("put {} samples.".format(len(worklist)))
def run(self):
while not self.shutdown_evt.wait(5):
while not self.shutdown_evt.wait(1):
if self.shutdown_evt.is_set():
break
if self.dataq.empty():
continue
worklist = []
while not self.dataq.empty():
while not self.dataq.empty() and len(worklist) < 2500:
worklist.append(self.dataq.get())
self.log.info("Putting a batch of {} samples".format(len(worklist)))
# now batch processes the worklist
if len(worklist) > 0:
try:
i = self.client.multiplePut(worklist)
self.log.info("Pushed {} samples to OpenTSDB.".format(i))
try:
#i = self.client.multiplePut(worklist)
self.put(worklist)
self.log.info("Pushed {} samples to OpenTSDB.".format(len(worklist)))
except Exception as x:
self.log.error("Push failed, error ={}; worklist = {}".format(x, worklist))
......@@ -138,7 +183,7 @@ def main():
logging.getLogger("ZeroMQLayer.ZeroMQClient").setLevel(logging.DEBUG)
try:
db = None
db = DatabaseAL()
db = DatabaseAL(cf.get("opentsdb", "server"))
db.start()
while True:
......@@ -149,9 +194,12 @@ def main():
# open socket
skt = None
while skt == None:
skt = pakbus.open_socket(host, port, timeout)
#skt = pakbus.open_socket(host, port, timeout)
skt = paksock.PakSock(host, port, timeout, my_node_id)
if skt == None:
logging.error("Failed to open socket, retry")
logging.info(" ... waiting for connect")
skt.have_socket_evt.wait()
#if (len(pakbus_ids) != len(metric_ids)):
......@@ -189,20 +237,27 @@ def main():
for metric, dl in dataloggers.iteritems():
dl.collect(skt)
#logging.warn("all done, exiting")
#exit();
logging.warn("got samples all, waiting for opentsdb queue to empty")
while (db.busy()):
time.sleep(1)
logging.warn("all done and pushed, exiting")
exit();
#shutdown connection
skt.shutdown(socket.SHUT_RDWR)
skt.close()
skt = None
#skt.shutdown(socket.SHUT_RDWR)
#skt.close()
#skt = None
skt.shutdown()
time.sleep(database_update_time_gap)
# reopen socket
while skt == None:
skt = pakbus.open_socket(host, port, timeout)
if skt == None:
while not skt.have_socket:
skt.open()
if not skt.have_socket:
logging.error("Failed to reopen socket, retry")
time.sleep(5)
except socket.error as msg:
logging.error("Socket died with: {}".format(msg))
......
import sqlite3
import paksock
from datalogger import DataLogger
import logging
logging.basicConfig(level=logging.DEBUG)
#skt = paksock.PakSock('60e90457.eairlink.com', 6785, 30, 0x802)
#d = DataLogger('campbell.db', skt, 0x802,
#"CR800_2",
#3, # pakbus ID
#)
#exit()
#CR800_2@3 has serial number 26948
db = sqlite3.connect('campbell.db')
c = db.cursor()
c.execute ("SELECT * FROM campbell")
for campbell_id, serialno in c.fetchall():
print ("serial number: {}".format(serialno))
c.execute("SELECT last_upload, last_recno FROM datalogger " +\
"WHERE campbell_id == ? AND" +\
"(last_upload IS NOT NULL and last_recno IS NOT NULL) AND " +\
'(date(last_upload) == "2015-03-01")' +\
"ORDER BY last_upload DESC LIMIT 10", (campbell_id,)
)
for last_upload, last_recno in c.fetchall():
print (" {}: {}".format(last_upload, last_recno))
c.execute ("DELETE FROM datalogger "+\
"WHERE campbell_id = ? AND "+\
'date(last_upload) > "2015-03-01"', (campbell_id,))
db.commit()
\ No newline at end of file
CR800_2
CR800_1
Table
\ No newline at end of file