Ubidots Developer Guides
Help CenterAPI ReferenceData APICommunity
  • Welcome to our Dev Guides
  • ⚡️ Getting Started
    • What is Ubidots?
    • Devices, Variables, and Dots
    • Technical FAQs
    • Business FAQs
  • 🧩Integration Guides
    • Industrial IoT
      • Advantech
      • Amplified Engineering
      • AWS
      • Azimut
      • Balena
      • Bivocom
      • CESVA
      • Controllino
      • Digital Communications Technologies (DCT)
      • Everactive
      • Golioth
      • Kepware
      • Kunbus
      • Monnit
      • MultiTech
      • NCD.io
      • Node-RED
      • Omicron IoT
      • Red Lion
      • Robustel
      • Senquip
      • Sielco
      • Siemens
      • Strega
      • vNode
      • WAGO
      • Weintek
      • YuDash
    • Cellular
      • Blues Wireless
      • Digi International
      • Hologram
      • Monogoto
      • Particle
      • Quectel
      • Soracom
    • LoRaWAN
      • AonChip
      • Chirpstack
      • Decentlab
      • Helium
      • ioThings
      • LORIOT
      • Milesight
      • MOKOSmart
      • RAKwireless
      • Sagemcom
      • Seeed Studio
      • Senet
      • The Things Industries
        • The Things Stack
        • The Things Network
    • Sigfox
      • Digital Matter
      • McThings
      • Sigfox
      • Suntech
      • Thinxtra
      • UnaBiz
    • Satellite
      • Swarm
    • Dev Kits
      • Adafruit
      • Advantech
      • AloriumTech
      • Arduino
      • Blues Wireless
      • DFRobot
      • Dragino
      • Electric Imp
      • Espressif Systems
      • McThings
      • Microchip Technology
      • Onion
      • Particle
      • Pycom
      • RAKwireless
      • Raspberry Pi
      • Seeed Studio
      • Sodaq
      • STMicroelectronics
      • Texas Instruments
      • Thinxtra
      • Verse Technology
    • Weather
      • Weather Plugins
      • Ambient Weather
    • Tools
      • Gambit Communications
      • PubNub
  • 📊Dashboards & Widgets
    • HTML Canvas
      • 3rd party packages
      • Preload Dashboard data
      • Built-in library
        • Properties
        • Methods
        • Listening events
        • API
      • Examples
        • Basics
        • Create an LCD screen with the HTML Canvas
        • Interacting with dashboard data
        • Change header's custom style
        • Adding real time using Socket.IO
        • Delete Variable data from a Device
        • Delete Variable data from Groups or Types of Devices
        • Navigation through Dashboard
        • Using a React library
      • Code editor
        • HTML Tab
        • CSS Tab
        • JavaScript Tab
    • Custom UI
      • Paragraph
      • Input combo
        • Text
        • Numeric
        • Numeric with buttons
        • Date
        • Time
        • Toggle
        • Dropdown
        • Multiple selection dropdown
      • Button
    • Custom Style
      • Dashboards
      • Widgets
    • Line chart
    • Pages
      • Getting started
      • Development
      • API
        • Page creation
        • Publish
  • 🤖UbiFunctions
    • Getting Started
      • Creating an UbiFunction
      • Coding an UbiFunction
      • Testing an UbiFunction
      • Authentication
      • Execution Time
      • Logs
    • Runtimes
      • Python
      • NodeJS
      • Custom Runtimes
    • Invocation
      • Time-based Trigger
      • HTTPS
      • MQTT Publish
      • Ubidots Event
    • Advanced
      • Account Token
      • Execution time
      • Raw Functions
      • CORS Policy
      • Async Execution
      • DaaS (Decoder as a Service)
      • Developing and Managing UbiFunctions with Ubidots CLI
    • Examples
    • Specs and Limits
    • Storage
      • File Storage API
      • Mutiple files
  • 🧩Plugins
    • What is a plugin?
    • Public vs. Private
    • Public plugins
      • Cron
      • Webhook
    • Private Plugins
      • Cron
      • Webhook
      • Widget
      • Device
    • Plugins development
      • Getting started
      • Cron
      • Webhook
      • Widget
      • Device
      • view.xml
      • view_widget.xml
    • Plugins deployment
      • Cron and Webhook
      • Widget
      • Device
    • Using the plugins
      • Cron and Webhook
      • Widget
      • Device
  • 📈SYNTHETIC VARIABLES
    • Getting started
      • Creating synthetic variables
      • Synthetic Variables' editor
    • Expressions
      • Mathematical
      • Date range
      • Rolling
      • Special functions
    • Specs and limits
    • Examples
      • Mathematical
      • Date range
      • Rolling
      • Special functions
  • ⌨️Developer tools
    • Javascript SDK
      • Overview
      • Getting started
      • Ubidots class
        • Get methods
        • Filter methods
        • Ubidots objects
          • Entity object
          • Paginator
      • Examples
    • CLI
      • Overview
      • Installing
      • Usage
      • SDK for UbiFunctions
  • 🏗️Apps
    • App builder
      • Custom sidebar
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Dashboards & Widgets
  2. HTML Canvas
  3. Examples

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.

PreviousAdding real time using Socket.IONextDelete Variable data from Groups or Types of Devices

Last updated 1 year ago

Was this helpful?

📊