Connect to AWS IoT from mqttcli

mqttcli that, to develop a MQTT client running in the CLI, to the public.

Let's connect to AWS IoT from this mqttcli.

Download mqttcli

mqttcli files from,

  • Linux (arm / amd64)
  • FreeBSD (arm / amd64)
  • Darwin (amd64)
  • Windows (amd64)

There are prepared, please download the binary suitable for your own architecture. Then, chmod u+x mqttcli and please grant execute permissions.

Make things with AWS IoT

  1. From AWS console AWS IoT Open.
  2. Create Resource from Create Thing select the
  3. Enter the Name, Create press
  4. Since the Thing of the name that you just entered in the list below comes out, select, from the right of the tag Connect a Device click.
  5. Connect a Device since coming out of the screen that, NodeJS press, Generate Certificate and Policy Press
  6. After about 10 seconds,
  • Download Public Key
  • Download Private Key
  • Download Certificate

You are instructed to download three files, so download them all.

  1. Confirm & Start Connecting press. Then, the following JSON is displayed, so copy it and save it in a file.

    Code-Block .. :: json

    {

    "Host" : "A3HVHEAALED.Iot.Ap-northeast-1.Amazonaws.Com", "Port" : 8883, "clientId" : "Something", "ThingName" : "Something", "CaCert" : "Root-CA .Crt "," ClientCert " : " 2A338xx2xxf-Certificate.Pem.Crt "," privateKey " : " Aad380efffx-Private.Pem.Key "

    }

  2. root-CA.crt というファイルを AWS IoT SDKのここ _ as it is written on, `こちらのSymantecのページ Authority-G5.pem> `_ please be obtained from.

  3. Please put the three files you downloaded earlier, the JSON file and root - CA.crt in the same directory.

This is the end of the preparation.

Connect to AWS IoT

Go to the directory containing the file and start mqttcli as follows. -t to specify the topic in but, $ you might need to escape. --conf is a JSON file that you just saved to specify in. -d is for debugging.

$ mqttcli sub -t "\$aws/things/something/shadow/update" --conf something.json -d
INFO[0000] Broker URI: ssl://A3HVHEAALED.iot.ap-northeast-1.amazonaws.com:8883
INFO[0000] Topic: $aws/things/something/shadow/update
INFO[0000] connecting...
INFO[0000] client connected

With success it is successful. I can connect with MQTT.

Update Thing Shadow

To update Thing Shadow send JSON as shown below.

{
  "state": {
    "reported": {
      "from": "mqttcli"
    }
  }
}

Let's send it with mqttcli

echo '{"state": {"reported": {"from": "mqttcli"} } }"' | mqttcli pub -t "\$aws/things/something/shadow/update" --conf something.json -d -s

Now, from the AWS Console, the state should be rewritten.

In this way, I was able to touch AWS IoT with mqttcli and. I also confirm that the same thing can be done by mosquitto_sub.

At last

Let's use AWS IoT's SDK instead of hitting MQTT directly. Then you do not have to be conscious of MQTT like this.

Awareness on AWS IoT and Thing Shadows

Note : This article contains assumptions.

AWS IoT has been announced. AWS IoT has prepared a Managed MQTT Server, and it seems to be appreciated that MQTT evaluates that it takes care of MQTT Server, which is difficult to operate.

But it is not. The essence of AWS IoT is the mechanism of Thing Shadows.

However, I have not used it properly yet, please point out if there is a mistake.

Thing Shadows

In IoT AWS, Things it has been defined that thing. There are two kinds of Things.

Things
Actual physical things. device
Thing Shadow
Things state on network (AWS)

Things is as it is. The new one is Thing Shadow. This is "a (virtual) mapping of physical devices onto the network".

Things and Thing Shadow are connected one to one. If there is any change in Things, a change will also occur in Thing Shadows. Inversely also. If you make a change to Thing Shadows, it also makes a change to Things.

That is,

  • Physical space
  • Virtual space

It is nothing other than that it was integrated.

Information on Thing Shadow

The implementation of Thing Shadow is just JSON.:

{
    "state" : {
        "desired" : {
          "color" : "RED",
          "sequence" : [ "RED", "GREEN", "BLUE" ]
        },
        "reported" : {
          "color" : "GREEN"
        }
    },
    "metadata" : {
        "desired" : {
            "color" : {
                "timestamp" : 12345
            },
            "sequence" : {
                "timestamp" : 12345
            }
        },
        "reported" : {
            "color" : {
                "timestamp" : 12345
            }
        }
    },
    "version" : 10,
    "clientToken" : "UniqueClientToken",
    "timestamp": 123456789
}

Here important is possessed by each state and the Metadata, desired and reported is.

1. When Thing is updated

When Thing is updated, which is a physical thing, the information is notified to Thing Shadow by MQTT or HTTPS.

Along with this, reported of state will be updated.

2. When Thing Shadow is updated

Thing Shadow can be updated in virtual space by MQTT or HTTP. In that case, desired information is updated.

In this case, desired and reported If there is a difference, the message is sent to the Thing (not necessarily the one) that subscribe to this Thing Shadow. Thing can receive this and update its own information. Then, when you can update, reported to update the Thing Shadow as.


With these actions, Thing and Thing Shadows can be synchronized. If, repoted and desired If you are different are not synchronized, it will be called.

More say, as API, update / get / delete are prepared for each accepted and rejected we are available. For this reason, I tried to update Things Shadows, but I can understand that I could not do it.

Difference from MQTT

So far, I have explained Things and Thing Shadows. By the way, AWS IoT does not have the following functions of MQTT.

  • Retain
  • Will
  • QoS 2

Why. That is because there is a Thing Shadow.

  • Retain is Shadow itself
  • Wll does not need to be in the first place as there is no offline state
  • Synchronization with QoS 2 can be realized using Shadow's desired / reported

Would not it be nice to emphasize that AWS IoT is not a message protocol called MQTT but is for handling "state"?

Summary

If you capture AWS IoT as just a Managed MQTT Server, you will miss the essence. It may be fun to look back at something about the fusion of virtual space and physical space, Internet of Things, and so on.

In addition, still this time Rule it does not depress respect. By combining Thing Shadows / Rule, you should be able to create a machine - to - machine, Things - to - Things world without human intervention.

It was a bit of an emotional story that I did not write in this blog so much. (Actually, I was doing this kind of research more than 10 years ago, I am glad that it expanded to this point, I decided to write it momentum)

I wrote an article on MQTT in WEB + DB PRESS vol 88

Released August 22, 2015 WEB+DB PRESS vol88 >` _ to 速習 MQTT titled allowed to write an article about MQTT I had you.

The contents are as follows.

  • What is MQTT
  • Usage scene of MQTT
  • Features of MQTT
  • Comparison with other protocols
  • Try using MQTT

As described in the title "Hayami," it is content that explains the contents of the protocol that MQTT is unable to hear, which is the main explanation of usage scenes and features. Although we try to implement try once using the MQTT, apps that use the MQTT at the point that in the python, eclipse paho thanks There is also a very Implementation is completed in a short row, and the amount is honestly high.

Recently it has become completely buzzword, and I have gradually come to see discourses such as "MQTT is the protagonist of the IoT era" and "MQTT can do all it". The contents of this time aimed to convey the actual situation of MQTT as accurately as possible. The use of MQTT is limited, and of course there are usage forms that are perfectly suitable, but I think that there are many cases where it is better to use other protocols. I hope to be able to communicate the neighborhood without excess or deficiency.

Sphinx InDesign Builder

Well, it is the main issue.

I wrote this in reStructuredText (rst) format. However, since in the rst form it knew that the variety is its work after the occurrence, Sphinx Indesign Builder has created a Spinx extension called.

% pip install sphinxcontrib_indesignbuilder

After installing with, in conf.py

extensions = ['sphinxcontrib.indesignbuilder']

The preparation is completed if it writes.

later,

% sphinx-build -b singlewebdb -d build/doctrees source build/singlewebdb

If, build/singlewebdb InDesign XML files for use with WEB + DB PRESS in will be created. The one marked with "single" can be put together in one xml file, it is possible to combine it into one. Editing WEB + DB PRESS will push this XML into InDesign, placing float elements such as diagrams, you will be ready to create PDF. It was a hassle that was almost the same as using md2inao. (However, note that among the functions that can be realized with md2inao, currently only functions required for this manuscript are implemented)

Actually, since we need human power to place the float elements, it is not a consistent flow from rst format file to PDF. For that, InDesgin power seems to be quite necessary.

It should be noted that, webdb as with the, is was created this time sphinx extension for WEB + DB PRESS. In other books and magazines, since the style naming convention is different, it can not be applied as it is. However, if you refer to the extension you created this time, it is fairly easy to implement another extension that conforms to other style naming conventions. Perhaps if you read a certain configuration file, it may be possible to export the XML according to that style naming convention by itself. If so, implementation is no longer necessary.

The reStructuredText (rst) format is also important in that it has high readability even in its original form, but its high extensibility is due to the extension point being decided. For example, we can flexibly respond to requests that "I want to express this part of this sentence specially". As a result, expressiveness is much higher than other description formats.

Summary

  • I wrote an article on MQTT in WEB + DB PRESS vol 88
    • It is contents to explain what MQTT can do and what I can not do
  • We implemented the Sphinx extension called Sphinx InDesign Builder
    • Drafted in reStructuredText (rst) format

WEB+DB PRESS vol88 >` _ the development of mobile development and LINE, please buy by all means because it also listed articles about Elixir.

Handle BLE from golang at Edison

Intel Edison is popular. In particular, it is very suitable for IoT that both WiFi and BLE can be used.

The Edison standard NodeJS you have a development environment that uses is mounted, but still here is where you want to handle in golang.

Paypal / gatt

To handle the BLE in Golang, github.com/paypal/gatt is the best. This library is implemented by golang all from the operation of BLE's peripheral etc. It works with pure golang.

The sample program is described below. In this example, the Main gatt.NewDevice create a device in, onStateChanged and onPeriphDiscovered only to register the two functions of the handler, you can the search for BLE equipment.

func onStateChanged(d gatt.Device, s gatt.State) {
     fmt.Println("State:", s)
     switch s {
     case gatt.StatePoweredOn:
             fmt.Println("scanning...")
             d.Scan([]gatt.UUID{}, false)
             return
     default:
             d.StopScanning()
     }
}
func onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int) {
     fmt.Printf("\nPeripheral ID:%s, NAME:(%s)\n", p.ID(), p.Name())
     fmt.Println("  Local Name        =", a.LocalName)
     fmt.Println("  TX Power Level    =", a.TxPowerLevel)
     fmt.Println("  Manufacturer Data =", a.ManufacturerData)
     fmt.Println("  Service Data      =", a.ServiceData)
}
func main() {
     d, err := gatt.NewDevice(option.DefaultClientOptions...)
     if err != nil {
             log.Fatalf("Failed to open device, err: %s\n", err)
     }
     // Register handlers.
     d.Handle(gatt.PeripheralDiscovered(onPeriphDiscovered))
     d.Init(onStateChanged)
     select {}
}

Using paypal / gatt makes it easy to handle BLE from golang, but there is one problem.

paypal / gatt is, HCI USER CHANNEL are based on the assumption, which are equipped only with Linux 3.14 or later. In other words, in Edison running on Linux 3.10, paypal / gatt will not work.

Noble

However, to work with NodeJS noble Do I work is, and I think examined go and noble is build during the installation of the following two small helper process, run I understood what I was using at the time.

When installing noble, the following two binaries are completed.

  • Node_modules / noble / build / Release / hci-ble
  • Node_modules / noble / build / Release / l2cap-ble

As its name implies, hci-ble deals with HCI and l2cap-ble deals with L2CAP. The two are Bluez for that link directly to the library and work with kernel 3.10.

Noblechild

I came up with the examination so far.

"If you use the noble helper process you can handle BLE in kernel 3.10 even in Pure golang"

That was made in that noblechild is.

Noblechild starts the helper process of noble and handles the helper process like noble, so that Pure golang can handle BLE from kernel 3.10 as well.

How to use

  1. Install noble.
  2. NOBLE_TOPDIR the environment variable, and set it to the top of the directory where you installed the noble.

that's all. After that, we provide almost the same interface as paypal / gatt, so you can use it as it is.

func main() {
     d, err := noblechild.NewDevice(DefaultClientOptions...)
     if err != nil {
             log.Fatalf("Failed to open device, err: %s\n", err)
     }
     d.Handle(noblechild.PeripheralDiscovered(onPeriphDiscovered))
     d.Init(onStateChanged)
}

Summary

To handle the BLE from golang in Edison Intel noblechild it has created a library called.

Since it is a huge hack, the line is not good. If Edison goes up to 3.14, we can directly use paypal / gatt, so we think that it is the position as a connection between the past.

It is useful to handle BLE with golang. We also MQTT gateways that are associated with fuji is also mounted on, so we work without a problem, I think you would like to publish them.

Looking for work

ツキノワ株式会社 In, BLE and MQTT, is looking for your work on Golang. Please feel free to contact us.

Create Go structure from C header file

I did not announce it at Gocon 2015.

Categories

r_rudi

#python, #postgres, #sphinx, #freebsd