Skip to content

ScriptingPublications

Kamil Baczkowicz edited this page Jan 23, 2016 · 1 revision

Samples

Simplest publication script

mqttspy.publish("/mqtt-spy/script/sample1/", "hello :)");

Handling stop requests (mqtt-spy only)

In order to stop a script after a stop request or an error, follow this example.

// Wrap the script in a method, so that you can do "return false;" in case of an error or stop request
function publish()
{
	var Thread = Java.type("java.lang.Thread");

	for (i = 0; i < 10; i++)
	{
		mqttspy.publish("/mqtt-spy/script/sample2/", "hello" + i);

		// Make sure you wrap the Thread.sleep in try/catch, and do return on exception
		try 
		{
			Thread.sleep(1000);
		}
		catch(err) 
		{
			return false;				
		}
	}

	// This means all OK, script has completed without any issues and as expected
	return true;
}

publish();

Publishing current time

function publishTime()
{
	var Thread = Java.type("java.lang.Thread");
	var Date = Java.type("java.util.Date");
	var SimpleDateFormat = Java.type("java.text.SimpleDateFormat");
	
	var TIME_FORMAT_WITH_SECONDS = "HH:mm:ss";
	var TIME_WITH_SECONDS_SDF = new SimpleDateFormat(TIME_FORMAT_WITH_SECONDS);

	while (true)
	{
		var currentTime = TIME_WITH_SECONDS_SDF.format(new Date());
		
		mqttspy.publish("/time/", currentTime, 0, false);

		// Sleep for 1 second and handle a stop request 
		try 
		{
			Thread.sleep(1000);				
		}
		catch(err) 
		{
			return false;				
		}
		
		// Keep mqtt-spy informed the script is still running
		mqttspy.touch();
	}

	return true;
}

publishTime();

Publishing an image

function publishImage()
{
	var Files = Java.type("java.nio.file.Files");
	var Paths = Java.type("java.nio.file.Paths");
	var Path = Java.type("java.nio.file.Path");

	var path = Paths.get("/home/user/Desktop/image.png");
	var data = Files.readAllBytes(path);
	
	mqttspy.publish("topicForImages", data, 0, false);

	return true;
}

publishImage();