Mqtt receive and publish

Hello,
Has anyone work with MQTT inside scriptcase ?
Regards

Kostas

Hi, yes a made several control apps that:

  • connect to mqtt server
  • publish messages
  • subscribe topics
  • manage messages published on subscribed topics
  • last will message on disconnection

I used a javascript library, there are many, I used

but there is also

Using javascript you have to connect to MQTT server via websockets.

bye
Vincenzo

Thank you @Vincenzo for your reply.
Can you pass me something basic?
In any case, it was useful your answer

Regards
Kostas

1 Like

well shortly just to give an idea, I wrote this code in the OnScriptInit

?>

<script type="text/javascript" src="<?php echo sc_url_library("prj", "mqtt", "paho-mqtt-min.js"); ?>"> 
<script type="text/javascript">

const mqttsrv = "<?php echo $p[1]; ?>";
const mqttport = <?php echo $p[2]; ?>;	
const mqttclientid = "insertion_" + Math.floor((Math.random() * 1000) + 1);


// Create a client instance: Broker, Port, Websocket Path, Client ID
var client = new Paho.MQTT.Client(mqttsrv, mqttport, "/ws", mqttclientid);

// set callback handlers
client.onConnectionLost = function (responseObject) {
$( "#sc_connessione_top" ).removeClass( "scButton_ok" ).addClass( "scButton_default" );		
}

// function to manage messages arrived after subscription
client.onMessageArrived = function ( message ) {

// console.log( message );

var pezzimsg = message.topic.split('/'); 
var seriale = pezzimsg[0];
var topic = pezzimsg[1];

// console.log( topic + ' ==> ' + message.payloadString );

// Swal.fire({ type: 'info', title: message.topic, text: message.payloadString } );  
// console.log( '('+ topic +') is insertion?' );

if ( topic == 'insertion' ) insertion( message );

}


// Called when the connection is made
function onConnect(){
$( "#sc_connessione_top" ).removeClass( "scButton_default" ).addClass( "scButton_ok" );		
}

function connetti() {
// connessione
client.connect({ onSuccess: onConnect });	
}

$( document ).ready(function() {
    connetti();
});

// a button calls this function
function openinsertion() {

// publush a message
client.send( 'head/lock_ins', '{ "client" : "' + client.clientId + '" }' ,0, false );
 // subscribe a topic
    client.subscribe( '+/insertion' );	

}

maybe if you look other samples is more clear.
With javascript you can show info changing custom fields, or to save infos of payloads just call a blank app via ajax.

1 Like

Thank you
It is exactly what I wanted
Best Regards

Kostas

1 Like