Skip to content

Instantly share code, notes, and snippets.

@spietika
Created July 31, 2017 17:03
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 spietika/0eab944e564722794e9dc559dc1cec21 to your computer and use it in GitHub Desktop.
Save spietika/0eab944e564722794e9dc559dc1cec21 to your computer and use it in GitHub Desktop.
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