Instantly share code, notes, and snippets.

Embed
What would you like to do?
Minimal example to interact with Sonoff S20 using MQTT and JavaScript
<!-- Minimal example to interact with Sonoff S20 device with MQTT
for a blog post (https://pagefault.blog)
-->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sonoff example</title>
<link rel="stylesheet" href="https://bootswatch.com/paper/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- Here is the interesting part -->
<script >
// Connect to MQTT broker
// Note. this example uses web-sockets (port 1884)
mqtt = new Paho.MQTT.Client("192.168.0.19", Number(1884), "sonoff-example-client");
mqtt.connect({onSuccess: function() {
console.log("connected!");
}});
function toggleSonoff() {
console.log("toggleSonoff");
// Send 'toggle' message to command topic
message = new Paho.MQTT.Message("toggle");
message.destinationName = "cmnd/sonoff1/power";
mqtt.send(message);
};
</script>
</head>
<body>
<div class="container">
<div class="row text-center span2">
<div class="page-header">
<h2>Sonoff example</h2>
</div>
<button type="submit" class="btn btn-primary btn-lg" onclick="toggleSonoff()">Toggle</button>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment