Skip to content

Instantly share code, notes, and snippets.

@TheRyanBurke
Created December 29, 2014 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheRyanBurke/81a211bc4f638e6ee55d to your computer and use it in GitHub Desktop.
Save TheRyanBurke/81a211bc4f638e6ee55d to your computer and use it in GitHub Desktop.
ThingFabric Panel sample with publishing messages
<div>
<button ng-click='publishMsg()'>Publish!</button>
</div>
<div class="stream">
<p ng-show="stream.length===0">Awaiting messages...</p>
<table ng-show="stream.length!==0" class="table table-striped table-nonfluid">
<thead>
<tr>
<th>Timestamp</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="message in stream">
<td>{{ message.timestamp | date: 'medium' }}</td>
<td>
<pre>{{ message.payload }}</pre>
</td>
</tr>
</tbody>
</table>
</div>
$scope.init = function(element) {
// Modify these!
var CREDENTIAL_KEY = 'redacted';
var CREDENTIAL_MD5_SECRET = 'redacted';
var TOPIC = '1d6f237e609bed7c5d785f24d812354d'
.concat('/#');
// If connection IDs are not random, you will disconnect other MqttWS clients.
var connectionId = Math.floor((Math.random() * 500) + 1),
emittersToDestroy = [];
var getEmitTopic = function(event, id) {
return 'ThingFabricMqttWebSocketService'
.concat(':')
.concat(event)
.concat(':')
.concat(id);
};
$scope.stream = [];
$scope.publishMsg = function() {
ThingFabricMqttWebSocketService.publish(connectionId, {
payload: JSON.stringify({
key: 'value',
key2: 'value2'
}),
topic: '1d6f237e609bed7c5d785f24d812354d/test'
});
};
ThingFabricMqttWebSocketService.connect($scope, {
username: CREDENTIAL_KEY,
password: CREDENTIAL_MD5_SECRET,
connectionId: connectionId
});
emittersToDestroy.push($scope.$on(getEmitTopic('onSuccess', connectionId), function(event, connection) {
ThingFabricMqttWebSocketService.subscribe(connectionId, {
topic: TOPIC
});
}));
emittersToDestroy.push($scope.$on(getEmitTopic('messageArrived', connectionId), function(event, message) {
var topic = message.destinationName;
var payload = message.payloadString;
$scope.$apply(function() {
$scope.stream.unshift({
timestamp: new Date().toISOString(),
thing: topic.split('/')[2],
payload: JSON.parse(payload)
});
_.first($scope.stream, 5);
});
}));
$scope.$on('$destroy', function() {
for (index in emittersToDestroy) {
emittersToDestroy[index]();
}
ThingFabricMqttWebSocketService.disconnect(connectionId);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment