Delete Variable data from a Device

The following shows how to implement HTML Canvas Widget to delete variable data in a time window in Dynamic Dashboards

  • Create the structure. Paste the following in the HTML Code Editor Tab:

<div>
    <p id="token"></p>
    <p id="selectedDeviceID"></p>
	<p id="selectedDeviceLabel"></p>
	<select id = "labels"></select>
	<form id="date-form">
		<label for="date1">Start date:</label>
		<input type="datetime-local" id="date1" name="date1" value="2023-01-01T00:00" required>
		<br>
		<label for="date2">End date:</label>
		<input type="datetime-local" id="date2" name="date2" value="2023-01-01T12:00" required>		
		<br>
		<button type="submit">Delete values</button>
	</form>
</div>
  • Paste the following in the CSS Code Editor Tab:

    body {
      font-family: Arial, sans-serif;
      max-width: 400px;
      margin: 0 auto;
      padding: 2rem;
    }
    
    form {
      display: flex;
      flex-direction: column;
    }
    
    label, input {
      margin-bottom: 1rem;
    }
    
    button {
      cursor: pointer;
      background-color: #0077cc;
      color: white;
      padding: 0.5rem 1rem;
      border: none;
      border-radius: 4px;
      font-size: 1rem;
      font-weight: bold;
    }
    
    button:hover {
      background-color: #005aa3;
    }

  • Paste the following in the Javascript Code Editor Tab:

var ubidots = new Ubidots();
const BASE_URL = 'https://industrial.api.ubidots.com';
const API1 = '/api/v1.6';
const API2 = '/api/v2.0';
var token;
var deviceLabel;
var deviceID;
var firstTime = true;
var deviceVariables;
var dropdown = document.getElementById('labels');
var selectedVariableLabel;
var selectedVariableID;


ubidots.on('ready', async function () 
{
	token = ubidots.token;
	deviceID = ubidots.selectedDevice;
	deviceLabel = await getDeviceLabelById(deviceID, token);
	deviceVariables = await getDeviceVariables(deviceID, token);
	deleteDropdownItems(dropdown);
	populateDropdownItems(deviceVariables, dropdown);
	displayDeviceData(deviceID, deviceLabel, token);
	firstTime = false;
});

ubidots.on('selectedDevice', async function (data) 
{
	deviceID = data[0];
	displayDeviceID(deviceID);
	if(!firstTime)
	{
		deviceLabel = await getDeviceLabelById(deviceID, token);
		deviceVariables = await getDeviceVariables(deviceID, token);
		deleteDropdownItems(dropdown);
		populateDropdownItems(deviceVariables, dropdown);
		displayDeviceData(deviceID, deviceLabel, token);
	}
    
});

dropdown.addEventListener("change", function() 
{
  	//selectedVariableLabel = this.options[this.selectedIndex].value;
	const este = this.options[this.selectedIndex].value;
	selectedVariableID = este.split(":")[1].trim();
	selectedVariableLabel = este.split(":")[0].trim();

});

document.getElementById('date-form').addEventListener('submit', async function(event)
{
	// Prevents form submission and page reload
	event.preventDefault();

	//Estas son las fechas que la persona pone en los campos
	const ts1 = toTimestamp(document.getElementById('date1').value);
	const ts2 = toTimestamp(document.getElementById('date2').value);
	if(ts1 > ts2)
	{
		console.error("ERROR: end date being earlier than start date.", ts1, ts2);
		console.log("startDate: ", ts1);
		console.log("endDate: ", ts2);
		return {"ERROR": -1};
	}
	
	console.log(selectedVariableID);
	console.log("startDate: ", ts1);
	console.log("endDate: ", ts2);	
	//url quemada con el endpoint, el device y los timestamps
	var url = "https://industrial.api.ubidots.com/api/v2.0/variables/" + selectedVariableID + "/_/values/delete/?startDate=" + ts1 + "&endDate=" + ts2;
	console.log("URL: ", url);
	const response = await fetchWrapper(url, 'POST', token);
	console.log(response);

});

function displayToken(Token)
{
	document.getElementById('token').innerText = "TOKEN: " + Token;
}
function displayDeviceLabel(DeviceLabel)
{
	document.getElementById('selectedDeviceLabel').innerText = "Selected Device label: " + DeviceLabel;
}

function displayDeviceID(DeviceID)
{
	document.getElementById('selectedDeviceID').innerText = "Selected Device id: " + DeviceID;
}

function displayDeviceData(DeviceID, DeviceLabel, Token, VariableLabel)
{
	displayToken(Token);
	displayDeviceLabel(DeviceLabel);
	displayDeviceID(DeviceID);
}

function populateDropdownItems(items, dropdownObj)
{
	var isFirst = true;
	items.forEach(function(item)
	{
		if(isFirst)
		{
			selectedVariableID = item.id;
			selectedVariableLabel = item.label;
		}
		var option = document.createElement('option');
  		option.text = item.label + " : " + item.id;
  		dropdownObj.add(option);
		isFirst = false;
	});
}

function deleteDropdownItems(dropdown)
{
	while (dropdown.firstChild) 
	{
    	dropdown.removeChild(dropdown.firstChild);
  	}
}

async function getDeviceLabelById(DeviceID, Token)
{
    var url = `${BASE_URL}${API2}/devices/${DeviceID}/?fields=label`;
	var response = await fetchWrapper(url, 'GET', Token);
	return response.label;
}

async function deleteDevicesValues(DeviceID, Token)
{
	
}

async function getDeviceVariables(DeviceID, Token)
{
	const url = 'https://industrial.ubidots.com/api/v2.0/devices/' + deviceID + '/variables';
	const response = await fetchWrapper(url, 'GET', Token);
	return response.results;
}

async function fetchWrapper(url, method, token = null, payload = null)
{
	const options =
	{
    	method: method,
    	//headers: {},
		headers: {'Content-Type' : 'application/json'}
	};

	//options.headers['Content-Type'] = 'application/json';

	if (payload)
	{
    	options.body = JSON.stringify(payload);
  	}

  	if (token)
	{
    	options.headers['X-Auth-Token'] = token;
  	}

	const response = await fetch(url, options);
	const jsonData = await response.json();
	return jsonData;
}

function toTimestamp(date) 
{
	const dateObj = new Date(date);
	const timestamp = dateObj.getTime();
	return timestamp;
}

The result is a Widget as shown below:

The user can use the dropdown menu to select a variable from the current device in the Dynamic Dashboard, then select a time windows using the date pickers. Upon clicking the Delete Values button, the data for that device's variable will in the time window selected will be deleted. Note that since Ubidots schedules asynchronous task, you might need to wait a few minutes to see the values deleted.

Last updated