Consistent Item Names When Adding Things to the Model: A Small Violentmonkey Script

Hi everyone,

Renaming every proposed channel Item when adding a Thing to the semantic model can get repetitive. I’ve made a small Violentmonkey userscript that does this automatically in Main UI’s “Create Equipment from Thing” dialog.

Naming Format

The script converts proposed names to:

ThingInCamelCase_ChannelInCamelCase

For example:

Before After
airQ_GuestRoom_Status_of_Sensors AirQGuestRoom_StatusOfSensors
airQ_GuestRoom_Show_WLAN_Status_with_LED AirQGuestRoom_ShowWlanStatusWithLed

Both parts begin with a capital letter, technically PascalCase. Acronyms are normalized: WLAN becomes Wlan, and LED becomes Led.

What It Does

  • Uses the Equipment’s Name field as the prefix.
  • Extracts the channel portion from openHAB’s proposed Item name.
  • Updates proposed channel Item names as their fields appear.
  • Leaves the Equipment name and channel labels unchanged.

It runs locally in your browser. No API token or openHAB server changes are required. It does not rename existing Items or create Items automatically.

Installation

  1. Install the Violentmonkey browser extension.
  2. Create a new userscript and paste in the script shared with this post.
  3. Adjust the @match lines to your openHAB address, including the protocol and port. For example:
    // @match http://openhab.local:8080/settings/things/*
  4. Save and enable the script, then reload openHAB.
  5. Open a Thing and choose Add to Model.

The match covers Thing settings pages so the script can load before you navigate into the dialog. Renaming runs only on the /add-to-model page.

Limitations

The current version expects English Name labels and openHAB’s default EquipmentName_Channel_Name proposals. It supports ASCII letters and digits; accented or non-Latin names may need adjustments.

Feedback and improvements are welcome, especially for other UI languages and openHAB versions!

// ==UserScript==
// @name         openHAB Equipment Item Names
// @namespace    openhab.local
// @version      1.0.0
// @description  Use ThingInCamelCase_ChannelInCamelCase for proposed channel Item names.
// @match        http://192.168.69.10:8080/settings/things/*
// @match        http://openhab.local:8080/settings/things/*
// @match        http://c3po:8080/settings/things/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(() => {
	'use strict';

	const channelNames = new WeakMap();
	let scheduled = false;
	let updating = false;

	function toCamelCase(value) {
		const words = value
			.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
			.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
			.split(/[^a-zA-Z0-9]+/)
			.filter(Boolean);

		return words.map(word => {
			const lower = word.toLowerCase();
			return lower[0].toUpperCase() + lower.slice(1);
		}).join('');
	}

	function isNameInput(input) {
		if (input.type === 'hidden' || input.disabled || input.readOnly) return false;

		const row = input.closest('.item-content, .item-input, .form-group');
		const label = row && row.querySelector('.item-label, label, .item-title');
		if (label && label.textContent.trim() === 'Name') return true;

		return Array.from(input.labels || []).some(label => label.textContent.trim() === 'Name');
	}

	function setValue(input, value) {
		if (input.value === value) return;
		const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
		setter.call(input, value);
		input.dispatchEvent(new Event('input', { bubbles: true }));
		input.dispatchEvent(new Event('change', { bubbles: true }));
	}

	function updateNames() {
		scheduled = false;
		if (!/^\/settings\/things\/[^/]+\/add-to-model\/?$/.test(location.pathname)) return;

		const inputs = Array.from(document.querySelectorAll('input')).filter(isNameInput);
		const thingInput = inputs.shift();
		if (!thingInput || !thingInput.value.trim()) return;

		const thingName = thingInput.value.trim();
		const prefix = toCamelCase(thingName);
		if (!prefix) return;

		updating = true;
		try {
			for (const input of inputs) {
				let channel = channelNames.get(input);
				if (!channel) {
					const proposed = input.value.trim();
					if (!proposed.startsWith(thingName + '_')) continue;
					channel = toCamelCase(proposed.slice(thingName.length + 1));
					if (!channel) continue;
					channelNames.set(input, channel);
				}
				setValue(input, prefix + '_' + channel);
			}
		} finally {
			updating = false;
		}
	}

	function scheduleUpdate() {
		if (updating || scheduled) return;
		scheduled = true;
		requestAnimationFrame(updateNames);
	}

	new MutationObserver(scheduleUpdate).observe(document.body, {
		childList: true,
		subtree: true,
		attributes: true,
		attributeFilter: ['value']
	});
	document.addEventListener('input', scheduleUpdate);
	document.addEventListener('change', scheduleUpdate);
	window.addEventListener('popstate', scheduleUpdate);
	scheduleUpdate();
})();

Extended above script towards the “Add Points to Model” as well as “Add Link to item…” dialog.

// ==UserScript==
// @name         openHAB Equipment Item Names
// @namespace    openhab.local
// @version      1.3.2
// @description  Use ThingInCamelCase_ChannelInCamelCase for proposed channel Item names.
// @match        http://192.168.69.10:8080/settings/things/*
// @match        http://openhab.local:8080/settings/things/*
// @match        http://c3po:8080/settings/things/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(() => {
	'use strict';

	const channelNames = new WeakMap();
	let scheduled = false;
	let updating = false;

	function toCamelCase(value) {
		const words = value
			.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
			.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
			.split(/[^a-zA-Z0-9]+/)
			.filter(Boolean);

		return words.map(word => {
			const lower = word.toLowerCase();
			return lower[0].toUpperCase() + lower.slice(1);
		}).join('');
	}

	function isNameInput(input) {
		if (input.type === 'hidden' || input.disabled || input.readOnly) return false;

		const row = input.closest('.item-content, .item-input, .form-group');
		const label = row && row.querySelector('.item-label, label, .item-title');
		if (label && label.textContent.trim() === 'Name') return true;

		return Array.from(input.labels || []).some(label => label.textContent.trim() === 'Name');
	}

	function setValue(input, value) {
		if (input.value === value) return;
		const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
		setter.call(input, value);
		input.dispatchEvent(new Event('input', { bubbles: true }));
		input.dispatchEvent(new Event('change', { bubbles: true }));
	}

	function updateNames() {
		scheduled = false;
		const singleChannel = /^\/settings\/things\/[^/]+\/links\/new\/?$/.test(location.pathname);
		if (!singleChannel && !/^\/settings\/things\/[^/]+\/add-to-model\/?$/.test(location.pathname)) return;

		const page = document.querySelector('.page-current') || document;
		const inputs = Array.from(page.querySelectorAll('input')).filter(isNameInput);
		if (singleChannel) {
			const nameInput = inputs[0];
			const groupsSection = findSection(page, 'Parent Groups');
			const channelSection = findSection(page, 'Channel');
			const groups = groupsSection ? Array.from(groupsSection.querySelectorAll('.chip-label, .chip-text')) : [];
			const channelLabel = channelSection && channelSection.querySelector('.item-title');
			if (!nameInput || groups.length !== 1 || !channelLabel) return;
			const prefix = toCamelCase(groups[0].textContent.trim());
			const channel = toCamelCase(channelLabel.textContent.trim());
			if (!prefix || !channel) return;
			updating = true;
			try {
				setValue(nameInput, prefix + '_' + channel);
			} finally {
				updating = false;
			}
			return;
		}

		const parentSection = findSection(page, 'Parent Group');
		let thingName;
		if (parentSection) {
			const parentName = parentSection.querySelector('.item-footer, .item-text');
			if (!parentName || !parentName.textContent.trim()) return;
			thingName = parentName.textContent.trim();
		} else {
			const thingInput = inputs.shift();
			if (!thingInput || !thingInput.value.trim()) return;
			thingName = thingInput.value.trim();
		}
		const prefix = toCamelCase(thingName);
		if (!prefix) return;

		updating = true;
		try {
			for (const input of inputs) {
				let channel = channelNames.get(input);
				if (!channel) {
					const proposed = input.value.trim();
					if (!proposed.startsWith(thingName + '_')) continue;
					channel = toCamelCase(proposed.slice(thingName.length + 1));
					if (!channel) continue;
					channelNames.set(input, channel);
				}
				setValue(input, prefix + '_' + channel);
			}
		} finally {
			updating = false;
		}
	}

	function findSection(page, title) {
		const heading = Array.from(page.querySelectorAll('.block-title, .item-divider, .item-title'))
			.find(element => element.textContent.trim() === title);
		if (!heading) return null;
		const groupBox = heading.closest('.group-box');
		if (groupBox) return groupBox;
		const list = heading.closest('.list');
		if (list) return list;
		let sibling = heading.nextElementSibling;
		while (sibling && !sibling.matches('.block-title')) {
			if (sibling.matches('.list')) return sibling;
			const nestedList = sibling.querySelector('.list');
			if (nestedList) return nestedList;
			sibling = sibling.nextElementSibling;
		}
		return null;
	}

	function scheduleUpdate() {
		if (updating || scheduled) return;
		scheduled = true;
		requestAnimationFrame(updateNames);
	}

	new MutationObserver(scheduleUpdate).observe(document.body, {
		childList: true,
		subtree: true,
		characterData: true,
		attributes: true,
		attributeFilter: ['value', 'class', 'disabled', 'readonly']
	});
	document.addEventListener('input', scheduleUpdate);
	document.addEventListener('change', scheduleUpdate);
	window.addEventListener('popstate', scheduleUpdate);
	window.setInterval(scheduleUpdate, 500);
	scheduleUpdate();
})();

This is a neat little timesaver — renaming those proposed items one by one is one of my least favorite chores in Main UI. Thanks for sharing it!

// ==UserScript==
// @name         openHAB Equipment Item Names
// @namespace    openhab.local
// @version      1.3.6
// @description  Use ThingInCamelCase_ChannelInCamelCase for proposed channel Item names.
// @match        http://192.168.69.10:8080/settings/things/*
// @match        http://openhab.local:8080/settings/things/*
// @match        http://c3po:8080/settings/things/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(() => {
	'use strict';

	const channelNames = new WeakMap();
	let scheduled = false;
	let updating = false;

	function toCamelCase(value) {
		const words = value
			.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
			.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
			.split(/[^a-zA-Z0-9]+/)
			.filter(Boolean);

		return words.map(word => {
			const lower = word.toLowerCase();
			return lower[0].toUpperCase() + lower.slice(1);
		}).join('');
	}

	// Thing names keep their own casing ("BMW iX1" -> "BMWiX1"), only all-lowercase words get capitalized.
	function toThingName(value) {
		return value
			.split(/[^a-zA-Z0-9]+/)
			.filter(Boolean)
			.map(word => word === word.toLowerCase() ? word[0].toUpperCase() + word.slice(1) : word)
			.join('');
	}

	// Same as openHAB's normalizeLabel(), used for proposed names when no parent group is picked.
	function normalizeLabel(label) {
		return label.normalize('NFKD')
			.replace(/[\u0300-\u036f]/g, '')
			.trim()
			.replace(/\s+/g, '_')
			.replace(/[^0-9a-z_]/gi, '')
			.replace(/^([0-9])/, '_$1');
	}

	function isNameInput(input) {
		if (input.type === 'hidden') return false;

		const row = input.closest('.item-content, .item-input, .form-group');
		const label = row && row.querySelector('.item-label, label, .item-title');
		if (label && label.textContent.trim() === 'Name') return true;

		return Array.from(input.labels || []).some(label => label.textContent.trim() === 'Name');
	}

	function isEditable(input) {
		return !input.disabled && !input.readOnly;
	}

	function setValue(input, value) {
		if (input.value === value) return;
		const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
		setter.call(input, value);
		input.dispatchEvent(new Event('input', { bubbles: true }));
		input.dispatchEvent(new Event('change', { bubbles: true }));
	}

	function updateNames() {
		scheduled = false;
		const singleChannel = /^\/settings\/things\/[^/]+\/links\/new\/?$/.test(location.pathname);
		if (!singleChannel && !/^\/settings\/things\/[^/]+\/add-to-model\/?$/.test(location.pathname)) return;

		const page = document.querySelector('.page-current') || document;
		const nameInputs = Array.from(page.querySelectorAll('input')).filter(isNameInput);
		if (singleChannel) {
			const nameInput = nameInputs.filter(isEditable)[0];
			const groupsSection = findSection(page, 'Parent Groups');
			const channelSection = findSection(page, 'Channel');
			const groups = groupsSection ? Array.from(groupsSection.querySelectorAll('.chip-label, .chip-text')) : [];
			const channelLabel = channelSection && channelSection.querySelector('.item-title');
			if (!nameInput || groups.length !== 1 || !channelLabel) return;
			const prefix = toThingName(groups[0].textContent.trim());
			const channel = toCamelCase(channelLabel.textContent.trim());
			if (!prefix || !channel) return;
			updating = true;
			try {
				setValue(nameInput, prefix + '_' + channel);
			} finally {
				updating = false;
			}
			return;
		}

		// Add Equipment dialog: the first Name input is the equipment (disabled when an existing group is picked), the others are its points.
		// Add Points dialog: only point inputs, the prefix comes from the Parent Group picker or the Thing label.
		const equipmentDialog = Array.from(page.querySelectorAll('.block-title'))
			.some(element => element.textContent.trim() === 'Equipment');
		let thingName;
		let thingDisplayName;
		if (equipmentDialog) {
			const equipmentInput = nameInputs.shift();
			thingName = equipmentInput ? equipmentInput.value.trim() : '';
			if (!thingName) return;
		} else {
			// Points only: openHAB prefixes with the picked parent group's name, or the normalized Thing label if none is picked.
			const parentSection = findSection(page, 'Parent Group');
			const parentItem = parentSection && parentSection.querySelector('.itemlist-item');
			if (parentItem) {
				const footer = parentItem.querySelector('.item-footer');
				const title = parentItem.querySelector('.item-title');
				thingName = (footer && footer.textContent.trim()) || (title && title.textContent.trim()) || '';
			} else {
				const thingSection = findSection(page, 'Source Thing');
				const thingLabel = thingSection && thingSection.querySelector('.item-title');
				if (!thingLabel || !thingLabel.textContent.trim()) return;
				thingName = normalizeLabel(thingLabel.textContent);
				thingDisplayName = thingLabel.textContent.trim();
			}
			if (!thingName) return;
		}
		const inputs = nameInputs.filter(isEditable);
		const prefix = toThingName(thingDisplayName || thingName);
		if (!prefix) return;

		updating = true;
		try {
			for (const input of inputs) {
				let channel = channelNames.get(input);
				if (!channel) {
					const proposed = input.value.trim();
					if (!proposed.startsWith(thingName + '_')) continue;
					channel = toCamelCase(proposed.slice(thingName.length + 1));
					if (!channel) continue;
					channelNames.set(input, channel);
				}
				setValue(input, prefix + '_' + channel);
			}
		} finally {
			updating = false;
		}
	}

	function findSection(page, title) {
		const heading = Array.from(page.querySelectorAll('.block-title, .item-divider, .item-title'))
			.find(element => element.textContent.trim() === title);
		if (!heading) return null;
		const groupBox = heading.closest('.group-box');
		if (groupBox) return groupBox;
		const list = heading.closest('.list');
		if (list) return list;
		let sibling = heading.nextElementSibling;
		while (sibling && !sibling.matches('.block-title')) {
			if (sibling.matches('.list')) return sibling;
			const nestedList = sibling.querySelector('.list');
			if (nestedList) return nestedList;
			sibling = sibling.nextElementSibling;
		}
		return null;
	}

	function scheduleUpdate() {
		if (updating || scheduled) return;
		scheduled = true;
		requestAnimationFrame(updateNames);
	}

	new MutationObserver(scheduleUpdate).observe(document.body, {
		childList: true,
		subtree: true,
		characterData: true,
		attributes: true,
		attributeFilter: ['value', 'class', 'disabled', 'readonly']
	});
	document.addEventListener('input', scheduleUpdate);
	document.addEventListener('change', scheduleUpdate);
	window.addEventListener('popstate', scheduleUpdate);
	window.setInterval(scheduleUpdate, 500);
	scheduleUpdate();
})()