BLE and Slack Notification

このエントリーをはてなブックマークに追加

How it works

HandsFree, Send message “in home” or “leaving” on slack.

obniz is monitoring BLE advertisements.
When people who has BLE ad App, obniz found it and notify it to program.
Then program calls SlackAPI.

Program

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://unpkg.com/obniz@2.0.2/obniz.js"></script>
</head>
<body>

<div id="obniz-debug"></div>

<button id=startbutton >start</button>
<button id=stopbutton >stop</button>
<h1><div id=results >Leaving</div></h1>

<script>
var status = "undefined";
var scanTime = 1;

var obniz = new Obniz("OBNIZ ID HERE");
 obniz.onconnect = async function () {
    obniz.ble.scan.onfinish = ((results) => {
        var find = "Leaving";
        for (key in results){
          var beacon = results[key].iBeacon();
          if (beacon){
            if (beacon.uuid === "10f86430-1346-11e4-9191-0800200c9a66"){
              find = "In home now";
            }
        }
     }
     
     $("#results").html(find);
     
     if(status === "undefined" || status !== find){
        var t = new Date();
        sendToSlack("" +  t.getHours() + ":" +( "00" + t.getMinutes()).slice(-2) + ":" + ("00"+t.getSeconds()).slice(-2) + "  " + find);
     }
     status = find;
     obniz.ble.scan.start({duration:scanTime});
   })
   
   $("#startbutton").click(()=>{
     $("#results").html("");
     obniz.ble.scan.start({duration:scanTime});
   });
   
   $("#stopbutton").click(()=>{
     obniz.ble.scan.end();
   });
   
  function sendToSlack(msg){
    var url = 'https://slack.com/api/chat.postMessage'; ;
    var data = {
      token: 'SLACK TOKEN HERE',
      channel: '#general',
      username: 'bot',
      text: msg
    };

    $.ajax({
      type: 'GET',
      url: url,
      data: data,
      success: function (data) {
      }
    });
   }
 }
</script>
</body>
</html>