[PYTHON] Easy IoT to start with Raspberry Pi and MESH

Ubiregi Advent Calendar 2019 Day 4 introduces easy IoT using Raspberry Pi and MESH.

What to make

When you press the "button" on the MESH block, a fixed message will be posted to Slack, which is very simple. As an application, I attach a monitor to the Raspberry Pi and use it as a doorphone, I think that I want to see it. If you live alone, there is a problem that you do not know if people are visiting while you are away, and if you place a MESH button instead, you can do something like notify your smartphone that a person has arrived.

What to prepare (the one used this time)

Prerequisites

procedure

Make Raspberry Pi a "MESH Hub"

The formula is very generous in this regard, so you should refer to it.

[Tell me how to install the "MESH Hub" app on my Raspberry Pi – MESH Support \ | Block-shaped electronic tags that connect to the app for playfulness](https://support.meshprj.com/hc/ ja / articles / 115002125554)

Supplement

The Raspberry Pi I used this time is Zero, so it's very heavy when I launch the browser. So, the part to access with the browser in the above procedure is done with a normal PC, ② How to log in to Raspberry Pi and execute the download command I think it's easy to copy the command and download it via SSH.

Get the URL of the Incoming Webhook

Decide / create a notification channel in advance.

next, Use Slack's Incoming Webhooks -Qiita Let's add the Incoming Webhook and copy the URL by referring to. It is recommended to save the URL (we will use it next time) because you can use Notepad or anything.

Write Server in Python

I'm using Python simply because I use Python a lot, so it doesn't matter what language you use, as long as you can do the same. By the way, Rasbian has Python installed by default, so you don't need to install Python itself. The version of Python used this time is Python 2.7.13.

Create a simple HTTP Server for hitting Raspberry Pi programs from MESH. This time I used a lightweight micro web framework called bottle.

Advance preparation

Install the library used in the source code with pip. (Requests is used when going to hit Slack)

$ pip install bottle requests

Source code

The location can be anywhere, so create a file in a suitable place and write the following source code. The name can be anything, but this time I chose server.py. (Refer to "Making a chat robot operated by Apple Watch using the Raspberry Pi version MESH -Qiita")

server.py


# -*- coding: utf-8 -*-

from bottle import route, run, template
import json
import requests

slack_settings = {
    # channel_Let's change the name arbitrarily
    #This is because it is easy to increase the setting when you want to notify other channels as well.
    'channel_name': {
        'url'    : '{URL obtained in the process of "Getting URL of Incoming Webhook"}',
        'botname': 'test',
        'icon'   : ':muscle:',
        'message': '<!here>\Notification from nMESH'
    }
}

def push(setting):
    datas = {
        'username'   : setting['botname'],
        'icon_emoji' : setting['icon'],
        'text'       : setting['message'],
        'contentType': 'application/json'
    }
    payload = json.dumps(datas)
    result  = requests.post(setting['url'], payload)
    print(result)

@route('/post/slack/<command>')
def mesh_button(command):
    if command == 'channel_name':
        push(slack_settings['channel_name'])
    else:
        raise Error

run(host='localhost', port=8080, reloader=True)

Start the server

Start the server with the following command. I don't think it's particularly difficult.

$ python server.py

If you start it well, you will see this display.

Bottle v0.12.17 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.

Try hitting it with curl. If you close the console running python server.py, the server will stop, so let's open another console (even if you have an SSH connection).

$ curl http://localhost:8080/post/slack/channel_name

On the side running the server

<Response [200]>
127.0.0.1 - - [04/Dec/2019 13:46:15] "GET /post/slack/channel_name HTTP/1.1" 200 0

I think that a log will appear, so if it does, it is a success.

Create a custom block from the MESH SDK

In MESH, processing is created by connecting standard processing called blocks with lines. (Set later) So, you need to create a block that hits the URL of server.py created earlier. So, first make it.

Access the custom block creation page

Access SDK \ _TOP \ _JP. You can go to the custom block management screen from "Use MESH SDK". FireShot Capture 005 - SDK_TOP_JP - meshprj.com.png

Create a custom block

Click Create New Block to display the custom block creation screen, so set it. The settings are as follows. Once you have set everything, click "Save" in the upper left to save.

FireShot Capture 010 - MESH SDK - meshprj.com.png FireShot Capture 011 - MESH SDK - meshprj.com.png

Source code set in Code


var localhost = 'http://localhost:8080' + properties.path;

ajax({
  url    : localhost,
  type   : 'get',
  timeout: 5000,
  success: function (data) {
    callbackSuccess({
      resultType : 'continue'
    });
  },
  error: function(request, errorMessage) {
    log('ERROR: ' + errorMessage);
    callbackSuccess({
      resultType: 'continue'
    });
  }
});

return {
  resultType: 'pause'
}

A brief description of the settings

For the settings in this area, I referred to "Making a chat robot operated by Apple Watch using the Raspberry Pi version MESH -Qiita".

Connector This set only the Input Connector. As you will see later by touching the MESH app, there are Input and Output in the MESH block. This time, after pressing the button, the processing of this custom block is started and it feels like the end, so there is no setting in the Output Connector. If you want to do something else after this custom block works, the Output Connector also needs to be configured.

Property This will allow you to create properties that you can reference in your code. You can tweak the property values when placing custom blocks. So, for example, even if you want to notify another channel, you do not need to create a new block, you can just change the property value when arranging it and it will be OK.

Code This will be the JavaScript code that will be executed when the custom block is kicked. Once the code is kicked, I'm going to hit the server I wrote earlier in Python with Ajax.

Create a recipe with the MESH app

A brief description of the MESH app

To make a process using MESH, you need to make a "recipe" with the MESH app. ** This recipe can only be made from the MESH app. ** The recipe to run on Raspberry Pi will also be created from the MESH app.

MESH hub registration

As a preliminary preparation, let's turn on Bluetooth on your smartphone and Raspberry Pi. Launch the MESH app from your smartphone. There is a smartphone mark on the upper right, but if you tap this, you will see the following "Change to another terminal", so tap this.

IMG_5206.PNG

Then, the "Select device" screen will appear. Sign in and tap "Add hub". IMG_5208.PNG

Tap "Add Hub" to display the next screen. Tap "Start Setup" to continue. IMG_5210.PNG

This screen also proceeds with "Next". IMG_5211.PNG

If the connection between the smartphone and Raspberry Pi is successful, the following screen will be displayed. If you can't wait a few minutes, check Bluetooth or see if the Raspberry Pi is ready to set up (tap the link on the screen and you'll see how to do it) .. IMG_5213.PNG

This screen is a screen as to whether or not to set the Wi-Fi of Raspberry Pi. Unless you have connected by wire, basically the Wi-Fi connection should be finished, so skip it. IMG_5215.PNG

Decide the name of the hub appropriately and proceed to the next. IMG_5218.PNG

If all goes well, you will end up with this screen, so select the Raspberry Pi MESH hub you just added and tap "Select" at the bottom of the screen. IMG_5220.PNG

Add block / custom block / create recipe

Tap "New Recipe" on the top screen of the app to display this screen. First, let's add a MESH block. Turn on the MESH block and tap the "Add Block" plus mark at the bottom left. (The power can be turned on by pressing and holding the silicon material part of the MESH block. If it does not turn on, charge it.) IMG_5222.PNG

If you can add it successfully, a "button block" will be displayed in the lower left block, so tap it and drag it to place it. It should look like the screen below. IMG_5226.PNG

Then add a custom block. I just registered the JavaScript code on the web screen. Although it is reflected on the upper screen, you can go to the addition screen by tapping the plus mark of "Custom addition". Then, the custom block you registered earlier will be displayed as shown below, so tap it and tap the "Add" button. IMG_5227.PNG

I think I was able to add it safely, so place the custom block in the same way as the "button block" was placed earlier, and connect the end of the button block and the end of the custom block as shown below. You can connect with a line by dragging from the placed button block to the custom block. IMG_5230.PNG

Supplement

If you tap the placed custom block, you will see a screen like this. You can change the value of the property here. If you change the server side program of Python, you can change the behavior by changing the Path here in the same custom block. IMG_5231.PNG

Operation check

Now that the settings are complete, let's press the MESH button. If you post to Slack, you're successful. 無題.png

Summary

This completes the notification (via Raspberry Pi) on Slack when you press the MESH button. There are quite a lot of steps, but as you may have noticed, the source code I wrote is very small. In the first place, there is a hurdle that you have to install Raspberry Pi, but if you exceed it, you can do it relatively quickly. In addition to buttons, MESH has various blocks such as LED, motion sensor, motion sensor, temperature / humidity sensor, brightness sensor, and GPIO. One of its strengths is that you can make your own IoT even if you can't do electronic work at all (except for GPIO). When it comes to electronic work, some knowledge of electricity and electronics is absolutely necessary, so for those who have been software engineers, the hurdles are a little high. However, MESH tags require almost no knowledge of electronic work and are recommended because most things can be done with software. By the way, if you want to do something physically but don't have knowledge of electronic work, you may want to try using the Eject command, which is very convenient (Reference: Eject command is Raspberry). Let's play with Pi ~ Easy work with CD \ -ROM drive ~).

Recommended Posts

Easy IoT to start with Raspberry Pi and MESH
Easy introduction to home hack with Raspberry Pi and discord.py
Easy connection between Raspberry Pi and AWS IoT
Connect Raspberry Pi to Alibaba Cloud IoT Platform with Python
Pet monitoring with Rekognition and Raspberry pi
Raspberry Pi + python + IoT device, environment construction procedure to start image processing and machine learning
MQTT RC car with Arduino and Raspberry Pi
Get temperature and humidity with DHT11 and Raspberry Pi
Raspberry Pi and AWS IoT connection program example
Connect to MySQL with Python on Raspberry Pi
GPGPU with Raspberry Pi
DigitalSignage with Raspberry Pi
Record temperature and humidity with systemd on Raspberry Pi
Machine learning with Raspberry Pi 4 and Coral USB Accelerator
Try to visualize the room with Raspberry Pi, part 1
Detect mask wearing status with OpenCV and Raspberry Pi
Measure temperature and humidity with Raspberry Pi3 and visualize with Ambient
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Getting Started with Yocto Project with Raspberry Pi 4 and WSL2
Troubleshoot with installing OpenCV on Raspberry Pi and capturing
Control music playback on a smartphone connected to Raspberry Pi 3 and bluetooth with AVRCP
Introduced python3-OpenCV3 to Raspberry Pi
Mutter plants with Raspberry Pi
I talked to Raspberry Pi
Easy to make with syntax
Introducing PyMySQL to raspberry pi3
Easy to use Nifty Cloud API with botocore and python
Update Python for Raspberry Pi to 3.7 or later with pyenv
Create a web surveillance camera with Raspberry Pi and OpenCV
Python beginner opens and closes interlocking camera with Raspberry Pi
Create an LCD (16x2) game with Raspberry Pi and Python
I tried connecting Raspberry Pi and conect + with Web API
Production of temperature control system with Raspberry Pi and ESP32 (1)
Measure and compare temperature with Raspberry Pi and automatically generate graph
[Raspberry Pi] How to continuously monitor directories and run arbitrary shells with hooks for changes
Port FreeRTOS to Raspberry Pi 4B
Log in to Raspberry PI with ssh without password (key authentication)
Use vl53l0x with Raspberry Pi (python)
Servo motor control with Raspberry Pi
MQTT on Raspberry Pi and Mac
Easy Slackbot with Docker and Errbot
I tried to automate the watering of the planter with Raspberry Pi
Serial communication with Raspberry Pi + PySerial
I made a web server with Raspberry Pi to watch anime
Home hack to buy automatically when it gets cheaper with Amazon Dash Button and Raspberry Pi
Output from Raspberry Pi to Line
Christmas classic (?) Lighting a Christmas tree with Raspberry Pi and Philips Hue
OS setup with Raspberry Pi Imager
Easy to install pyspark with conda
Make a thermometer with Raspberry Pi and make it viewable with a browser Part 4
Try L Chika with raspberry pi
Make a Kanji display compass with Raspberry Pi and Sense Hat
Programd automatic start at startup with Raspberry Pi 3B + systemd Summary
VPN server construction with Raspberry Pi
Graph display of household power consumption with 3GPI and Raspberry Pi
Easy and easy IoT life using Micropython!
Create your own IoT platform using raspberry pi and ESP32 (Part 1)
Try moving 3 servos with Raspberry Pi
Measure temperature, humidity, etc. with SensorTag and send it to Ambient via Raspberry Pi 3 to graph it Part 2
Easy to draw graphs with matplotlib
Easy modeling with Blender and Python