• Business process description:

Mobile terminal -> Business server -> Aliyun Internet of Things platform -> Raspberry PI -> local device (such as printer service)-> Raspberry PI -> Business server In this process, the data obtained can be uploaded to the server after controlling the corresponding device through mobile phone for operation

  • Things to prepare:
  1. Raspberry pie (3 b)

  2. Ali Cloud account (open Internet of Things platform and public instance)

  3. Business server, which can be tested with local services (this article uses GO to turn on business services)

  4. Documents for Aliyun Iot platform

    ① Device access: help.aliyun.com/document_de…

    ② Cloud API: help.aliyun.com/document_de…

  • Platform configuration
  1. Let’s go to the public instance

  1. Create a product

  1. Create a device

  1. Add object model property configuration

  1. Online debugging; If the first setting is selected, all current attributes will be sent. If the second setting is selected, the command will send the current attribute. The data received by the device is in a key-value JSON format. For example, the first setting is {“color”:”red”,”size”:5}, and the second setting is {“color”:”red”}.

  1. Configure the Python SDK on Raspberry PI, using Aliyun-iot-LinkKit (note: Python 3.6 must be installed on Raspberry PI, as it is officially recommended, and I started with a higher version, which had problems and had to be resolved by Ali engineers). Here, raspberry PI environment configuration and Ali Cloud SDK installation of the Internet of things and encountered some pits will not be described, you can see other articles.
pip install aliyun-iot-linkkit
Copy the code
  1. Python (Raspberry PI)
# subsequent change from the server options = {' regionId ':' XXXX '#' productKey 'check here: https://developer.aliyun.com/article/775321 "XXXXXX ", # product key 'deviceName':" XXX ", # deviceName' deviceSecret': Linkkit (host_name=options['regionId'], product_key=options['productKey'], Device_name =options['deviceSecret'], device_secret=options['deviceSecret'], # rc, userdata): print("on_connect:%d,rc:%d,userdata:" % (session_flag, rc)) if rc == 0: Print ("Connection successful") elif rc == 1: print("Protocol version error") elif rc == 2: Print ("Invalid client identity") elif rc == 4: Print ("Wrong user name or password") elif rc == 5: Def on_disconnect(rc, userdata) def on_disconnect(rc, userdata): print("on_disconnect:rc:%d,userdata:" % rc) if rc ! = 0: print("Unexpected disconnection %s" % rc) def on_topic_message(topic, payload, qos, userdata): print("on_topic_message,topic=%s; qos=%s; payload=%s; userdata=%s" % (topic, str(payload), str(qos), str(userdata))) try: S = payload.decode(' utF-8 ', errors='ignore') print(" received message :", s) pass except Exception as e: Print ('No this moType', e) # def on_subscribe (mid, qos, userdata): print("on_subscribe_topic mid:%d, granted_qos:%s" % (mid, str(','.join('%s' % it for it in qos)))) print(qos) if qos == 128: Def on_unsubscribe_topic(mid, userdata): Def on_publish_topic(mid, userdata) def on_publish_topic(mid, userdata) def on_publish_topic(mid, userdata) Def mqtt_publish(sensor_data, topic='defult', qos=0): print("on_publish_topic mid:%d" % mid) Rc, mid = lk.publish_topic(lk.to_full_topic("user/update"), sensor_data) print("mqtt_publish: publish..." , "user/update", sensor_data) return except KeyboardInterrupt: print("EXIT") # This is a blocking form of the network loop that is not returned until the client calls Disconnect (). It handles the reconnection automatically. Lk.on_disconnect () sys.exit(0) def on_thing_enable(userdata): Def on_thing_disable: print("on_thing_enable") def on_thing_disable(userdata): Def on_thing_prop_post(request_id, code, data, message, userdata): print("on_thing_disable") print("on_thing_prop_post request id:%s, code:%d, data:%s message:%s" % (request_id, code, str(data), Def on_thing_prop_changed(params, userdata): Realistic use of direct read pins is recommended. Print ('on_thing_prop_changed', params, userdata) def on_thing_event_post(event, request_id, code, data) message, userdata): print("on_thing_event_post event:%s,request id:%s, code:%d, data:%s, message:%s" % (event, request_id, code, str(data), Def on_thing_call_service(identifier, request_id, params, userdata): print("on_thing_call_service identifier:%s, request id:%s, params:%s" % (identifier, request_id, Def mqtt_run(): Lk.enable_logger (level= logging.debug) # Register the method for receiving cloud data lK.on_connect = on_connect Lk. On_disconnect = on_disconnect # If a triplet is mistakenly written to multiple devices during the production of the product, the multiple devices will be considered as the same device by the Internet of Things platform, so that one device goes online and disconnects the connection of another device. Users can upload their interface information to the cloud center, so that the cloud center can locate problems based on the interface information. Lk. Config_device_info (" Eth | 03 acdeff0032 | Eth | 03 acdeff0031 ") # enterprise instance domain configuration changes Lk. Config_mqtt # (the endpoint = "iot-06z00ftnh9vq6fq.mqtt.iothub.aliyuncs.com") registered in the cloud subscription method of lk. On_subscribe_topic = Lk.on_topic_message = on_topic_message # Registers methods that are called when data is published to the cloud Lk.on_publish_topic = on_publish_topic # Register methods to cancel cloud subscriptions lK.on_unsubscribe_topic = on_unsubscribe_topic # object model lk.on_thing_enable = on_thing_enable lk.on_thing_disable = on_thing_disable lk.on_thing_prop_post = on_thing_prop_post lk.on_thing_prop_changed = on_thing_prop_changed lk.on_thing_event_post = on_thing_event_post lk.on_thing_call_service = Lk.connect_async () # Since it is an asynchronous call it takes time so if there is no delay function, Time.sleep (2) # subscribe to this topic RC, mid = lk.subscribe_topic(lk.to_full_topic("user/get")) if rc == 0: print("subscribe multiple topics success:%r, mid:%r" % (rc, mid)) else: print("subscribe multiple topics fail:%d" % rc) pass input() if __name__ == '__main__': thread_mqtt_run = threading.Thread(target=mqtt_run) thread_mqtt_run.start()Copy the code
  1. Golang Business Services (here)
package main import ( "encoding/base64" "net/http" openapi "github.com/alibabacloud-go/darabonba-openapi/client" "github.com/alibabacloud-go/iot-20180120/v2/client" "github.com/alibabacloud-go/tea/tea" "github.com/gin-gonic/gin" Jsoniter "github.com/json-iterator/go") /** accessKey,accessSecret Key ID issued by Ali Cloud to users to access the service. Log in to the Ali Cloud Console, move the cursor to the profile picture of the account, and click AccessKeys to go to the user information management page to create and view accessKeys. */ const (accessKey = "XXXX" accessSecret = "XXXXX") endPoint = "iot.cn-shanghai.aliyuncs.com" ) var iotClient *client.Client func init() { iotClient, _ = CreateClient(tea.String(accessKey), tea.String(accessSecret)) } func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *client.Client, _err error) { config := &openapi.Config{ AccessKeyId: accessKeyId, AccessKeySecret: AccessKeySecret,} // Access domain config.endpoint = tea.String(Endpoint) _result = &client.client {} _result, _err = client.NewClient(config) return _result, _err } func Publish(c *gin.Context) { json := make(map[string]interface{}) err := c.BindJSON(&json) if err ! = nil { c.Status(http.StatusBadRequest) c.Abort() } data, _ := jsoniter.Marshal(json) pubRequest := &client.PubRequest{ ProductKey: tea.String("gg2xYGJC3qi"), TopicFullName: tea.String("/gg2xYGJC3qi/scanner/user/get"), IotInstanceId: tea.String("iot-06z00ftnh9vq6fq"), Qos: tea.Int32(0), } pubRequest.MessageContent = tea.String(base64.StdEncoding.EncodeToString(data)) resp, err := iotClient.Pub(pubRequest) if err ! = nil { c.Status(http.StatusBadRequest) } else { c.String(http.StatusOK, resp.GoString()) } } func SetDeviceProperty(c *gin.Context) { json := make(map[string]interface{}) err := c.BindJSON(&json) if err ! = nil { c.Status(http.StatusBadRequest) c.Abort() } data, _ := jsoniter.Marshal(json) setDevicePropertyRequest := &client.SetDevicePropertyRequest{ IotInstanceId: tea.String("iot-06z00ftnh9vq6fq"), ProductKey: tea.String("gg2xYGJC3qi"), DeviceName: tea.String("scanner"), Items: tea.String(string(data)), } resp, err := iotClient.SetDeviceProperty(setDevicePropertyRequest) if err ! = nil { c.Status(http.StatusBadRequest) } else { c.String(http.StatusOK, resp.GoString()) } } func main() { gin.SetMode(gin.DebugMode) router := gin.Default() router.POST("/lulu/publish", Publish) router.POST("/lulu/setDeviceProperty", SetDeviceProperty) _ = http.ListenAndServe(":8080", router) }Copy the code

Two interfaces are defined here, one for the way messages are published and the other for the way attributes are reported.