In 1995, when Brendan Eich, who worked at Netscape, set out to develop a scripting language called LiveScript for Netscape Navigator 2.0, No one could have imagined that AVAScript would play a major role in Internet software development today. Nowadays, Javascript has conquered more and more fields, such as Web engineering construction, back-end server development, 3D graphics, AR, VR, etc. Even, in recent years we have been pleasantly surprised to find that JS can be used to develop hardware devices. Today, I will talk to you about the simple development of the Internet of things with JS experience and experience.

Any application that can be written in JavaScript will eventually be written in JavaScript — Atwood’s Law

What is a IOT

We always talk about IOT, but what exactly is IOT? IOT stands for Internet of Things, which literally translates as “The Internet of Things”. The correct translation is “Internet of Things”. The Internet of Things (Internet of Things), also known as the sensor network, is simply the extension of the Internet from people to Things.

The physical networking can be split in two directions, from “things” to “net” or from “net” to “things”. From object to net can be understood as the process that people perceive objects beyond the limitations of space and their own conditions. From “net” to “object” is the process of controlling objects across space.

Introduction to IoT application development platform

In the field of IoT application development, there are several well-known development platforms:

  • Embedded operating system, including VxWorks, FreeRTOS, LiteOS, etc.
  • Geek hardware platforms, including Raspberry PI, Arduino, etc.;
  • JavaScript IoT application development platform, including Ruff, Tessel, JerryScript, Johnny-Five, etc.

Embedded operating system, from the functional point of view, can meet the vast majority of current requirements. But:

  • The threshold of entry is very high, developers want to become an excellent embedded development engineer, need to learn a lot of software and hardware knowledge. The amount of talent in the embedded space is limited compared to the software industry.
  • The development method of embedded technology has fallen behind the development of the whole industry. Agile software development methods, as well as lean startup concepts, are limited by tools and rarely applied in the embedded space, so the field is slow to develop in engineering methods.
  • The programming concepts of these operating systems are often in proprietary domains, so knowledge is difficult to share and developers are less mobile within the industry. As a result, the embedded community generally lags behind the software industry in understanding modern software development concepts.

The geek hardware platform is intended to lower the barriers to development and allow more developers to enter the hardware development space. But:

  • It only struggles at the introductory level on the operational side, while the really hard part of developing is programming concepts. For most software developers, the difficulty lies in the concept of programming in hardware. A variety of interfaces and parameters, which is difficult for software developers to understand and master.
  • More critically, these platforms only solve the problem of prototyping. Even if a developer is able to implement a prototype, it’s hard to use it in a real product. When applied to products, the hardware is often redesigned, and the advantages of these platforms are lost.

The essential complexity of both lies in their programming models. For software developers, hardware interfaces such as GPIO and I2C are completely different languages. In addition to understanding the programming methods of interfaces, they also need to read their data manuals and understand the details of parameters for each hardware.

By now, you might think that the IoT industry is another world to software engineers. Yes, a lot of people think that way, and there are people who want to change the world with higher-level languages, and the JavaScript community is the most active one.

JavaScript IoT application development platform

The JavaScript IoT application development platform is designed to enable developers to use JavaScript to develop IoT applications. On the one hand, it can better build abstractions. On the other hand, it can introduce more modern development methods into hardware development. Currently, JavaScript IoT application development platforms are mainly divided into several categories:

  • Running JavaScript on hardware, such as JerryScript, Espruino, etc.
  • Hardware abstraction capabilities such as Tessel, Johnny-Five, Cylon.js, etc.
  • Production-oriented capabilities, such as Ruff.

The advantage of the Ruff

Compared with Arduino, Ruff is closer to the network. Since Arduino was born earlier, the standard development board does not have network communication mode. Although it can be added in the form of extension, it is slightly complicated to get started. Ruff naturally supports Wifi communication, and using Ruff for HTTP communication is no different from using normal NodeJS for HTTP communication. It is extremely easy to get started. Of course, due to the early release of Arduino, and the design of modular development from the very beginning, the third generation of Arduino module is relatively simple, just like building blocks layer by layer installation, while the hardware modules of RUFF are relatively few, so the ecology is not so mature and perfect compared with Arduino.

Ruff is closer to iot development than Raspberry PI. At its core, the Raspberry PI is a condensed but relatively complete operating system that allows you to do everything from browse the Web to write Web server programs to write the I/O interface to the Raspberry PI (timing the coffee machine, feeding the dog…). The simple function of Ruff can be considered as single chip microcomputer. It is possible to deploy various Web servers, but it is impossible to access graphical interfaces such as browsers. However, its core goal is to program for hardware, which has lower power consumption and higher efficiency. All in all, it is the difference between their original design intentions. Raspberry PI is supposed to be a computer, and if it’s too weak, it can’t do a lot of things. Ruff development kit is meant to be a hardware application, and if it’s too strong, it doesn’t really work.

Ruff to fit

Ruff is extremely easy to get started with. Through the official website tutorial we can quickly use Javascript to write a simple lighting LED light program.

'use strict';

$.ready(function (error) {
    if (error) {
        console.log(error);
        return;
    }

    $('#led-r').turnOn(a);  // Turn on the light
});

$.end(function (a) {
    $('#led-r').turnOff(a);
});
Copy the code

Then connect to Ruff’s own wifi hotspot.

Over a wireless network, run the rap deploy-s command to download the program to the development board. The whole process is extremely simple and natural. It’s not much more complicated than configuring front-end engineering.

Ruff embrace the Internet

If Ruff can only develop simple programs such as small light off, it can only be a toy. The true “Internet of things” can only be achieved by truly connecting to the vast Internet. Later, it will introduce how to connect RUFF to Aliyun Iot suite to realize information reporting and acquisition, information perception from “things” to “net” and remote control from “net” to “things”.

Ali Cloud iot Suite is specially launched by Ali Cloud for developers in the field of Internet of Things. Its purpose is to help developers build data channels with strong security performance to facilitate two-way communication between terminals (such as sensors, actuators, embedded devices or smart home appliances, etc.) and the cloud. Global multi-node deployment enables massive devices around the world to access Ali Cloud IoT Hub safely and with low delay. Multiple protection is provided to ensure device cloud security, and performance can support long-term connections of hundreds of millions of devices and concurrent messages. Iot suite also provides one-stop hosting services, from data collection to calculation to storage. Users do not need to purchase a server to deploy a distributed architecture, and users only need to configure rules on the Web to realize full stack services such as collection, calculation and storage. In short, iot developers can quickly build stable and reliable iot platforms based on the services provided by iot suite.

Of course, you can visit the product details page of Ali Cloud iot Suite to explore the powerful functions of the Iot suite, Ali Cloud – iot Suite – product details

It can also be seen from the architecture diagram that the red message publishing channel is the perception process from “thing” to “network” mentioned above, while the blue subscription message service is the control process from “network” to “thing” mentioned above.

There is currently no official JS SDK for Aliyun iot Suite. However, MQTT protocol used by Internet of Things suite is a general Internet of Things communication protocol. We can access the general Openapi of Aliyun products according to the SDK of Java.

Examples of ruFF program code:

'use strict';

var fs = require('fs');
var os = require('os')
var mqtt = require('mqtt')

var productKey = 'Fill in the productKey applied in the Iot suite of Ali Cloud'
var deviceName = 'Fill in deviceName applied in Alibaba Cloud Iot Suite'
var deviceSecret = 'Fill in deviceSecret applied in Alibaba Cloud iot Suite'
var targetServer = "tcp://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com:1883"
var port = 1883
var host = productKey + '.iot-as-mqtt.cn-shanghai.aliyuncs.com'

var clientId = os.hostname(a);
var timestamp = (new Date()).valueOf(a)
var mqttClientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
var mqttUsername = deviceName + "&" + productKey
var content = 'clientId' + clientId + 'deviceName' + deviceName + 'productKey' + productKey + 'timestamp' + timestamp

// var forge = require('forge')
// var hmac = forge.hmac.create();
// hmac.start('sha1', deviceSecret);
// hmac.update(content);
// var mqttPassword = hmac.digest().toHex();
// console.log(mqttPassword)
// RuFF can not use crypto and other packages, can implement hMAC SHA1 encryption
var mqttPassword = 'Generated Secret Text';

var puburl = "/" + productKey + "/" + deviceName + "/update"
var suburl = "/" + productKey + "/" + deviceName + "/get"

var tsl_options = {
  port: port.
  host: host.
  rejectUnauthorized: false.
  keepalive: 100.
  clientId: mqttClientId.
  username: mqttUsername.
  password: mqttPassword
}


$.ready(function (error) {
  if (error) {
    console.log(error);
    return;
  }

  var mqttClient = mqtt.connect(targetServer. tsl_options)

   mqttClient.on('connect'. function (a) {
    console.log('********** Connected **********')
    // When the button is pressed, messages are sent to Ali Cloud MNS service through MQTT protocol
    
    $('#button').on('push'. function (a) {
      var data = { ts: (new Date()).valueOf(), deviceName: deviceName }
      mqttClient.publish(puburl. JSON.stringify(data))
      console.log(JSON.stringify(data))
    });
    //level 0: indicates a maximum of one transmission
    // Level 1: at least one transfer
    // Level 2: only one transfer
    mqttClient.subscribe(suburl. {qos:1})
   
    // When a message is received, the red light is on and off
    mqttClient.on('message'. function (topic. message) {
      var msg = message.toString(a)
      console.log('The message you received was:' + msg)
      if(msg= ='turn_on_led') {
        $('#led-r').turnOn(a);
        setTimeout(function() {
          $('#led-r').turnOff(a);
        }, 500)
      }
    })
  })
  mqttClient.on('error'. function (error) {
    console.log(error)
  })

});
Copy the code

Examples of server-side code:

const RPCClient = require('@alicloud/pop-core').RPCClient;
const MNSClient = require('@alicloud/mns');
const Base64 = require('js-base64').Base64;

var iotClient = new RPCClient({
  accessKeyId: 'Aliyun accessKeyId'.
  secretAccessKey: 'Aliyun accessKeySecret'.
  endpoint: 'https://iot.cn-shanghai.aliyuncs.com'.
  apiVersion: '2017-04-20'
});

var mnsClient = new MNSClient('Ali Cloud Account ID'. {
  region: 'cn-shanghai'.
  accessKeyId: 'Aliyun accessKeyId'.
  accessKeySecret: 'Aliyun accessKeySecret'.
});

const queueName = 'aliyun-iot-xGEDKBE*****' // Open Ali Cloud iot suite to generate MNS message queue
Consume messages from the queue
setInterval(async (a)= >{
  try{
    var receiveRes = await mnsClient.receiveMessage(queueName)
    var deleteRes = await mnsClient.deleteMessage(queueName. receiveRes.body.ReceiptHandle);
    var payload = JSON.parse(Base64.decode(receiveRes.body.MessageBody))
    var data = Base64.decode(payload.payload)
    console.log('Data received from the IoT device is:' + data)
  } catch(err) {
    console.log(err)
  }
}, 500)


const productKey = '* * * * * * * * * *'    // productKey of alibaba Cloud iot suite
const deviceName = '* * * * * * * * * *'    // Alibaba Cloud iot suite deviceName

const iotClientParams = {
  ProductKey: productKey.
  TopicFullName: ` /The ${productKey}/The ${deviceName}/get`.
  MessageContent: Base64.encode('turn_on_led'),
}

// Send a message to ruFF
setInterval(async (a)= >{
  try{
    var sedRes = await iotClient.request('Pub'. iotClientParams)
  }catch(err) {
    console.log(err)
  }
}, 2000)
  
Copy the code

* Note: The server program does not need to purchase ECS of Aliyun, and can be tested locally. The Internet of Things suite and MNS on-demand service will almost not cost in non-production environment, and you can use it by registering an Aliyun account. The above code examples are relatively simple to write, which can realize the two-way communication between the simple Internet of Things devices and the server program. We look forward to practicing together!

Finally, also send an advertisement, Ali cloud front end team is not just front end! Join us and explore the sea of stars with JS in your hands!