当前位置:网站首页>Alibaba cloud IOT transfer to PostgreSQL database scheme
Alibaba cloud IOT transfer to PostgreSQL database scheme
2022-04-23 03:56:00 【Illusory private school】
High quality resource sharing
| Learning route guidance ( Click unlock ) | Knowledge orientation | Crowd positioning |
|---|---|---|
| 🧡 Python Actual wechat ordering applet 🧡 | Progressive class | This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system . |
| Python Quantitative trading practice | beginner | Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system |
I wrote an article before, such as deploying on Alibaba cloud .NET 3.1 Custom runtime article , Make complaints about it , Although it is now 2022 Years. , However, Alibaba cloud's support for functional computing still remains .NET Core 2.1, Update slow , Due to the limitation of unpacking size , You can't put too complicated things on it , Although now .NET 6 Cutting the bag can solve this problem very well , But I'm still upset .
demand
Get down to business , There is such a scene : Send data to Alibaba cloud IoT platform , And then insert it directly into postgresQL In the database . Normally , As long as the data is sent to IoT platform , Then define forwarding to RDS That's all right. , However, Alibaba cloud has several limitations :
- Data flow to RDS database , Can only support
mysqlAndsql server - Data flow only supports
jsonForm of data flow , If you send transparent data , Then it can't be sent ( to update : Now the new version of data flow has supported .)
focused , Maybe we can only take out Alibaba cloud's function computing service , Use function calculation as a transfer function , Transfer the transmitted data to function calculation , Then perform... In the function calculation sql sentence .
IoT Platform reception settings
Alibaba cloud's Internet of things platform , After setting up the basic products and equipment , If it's a physical model , Then set the corresponding object model by yourself . It's easier to pass through , Support MQTT The device side only needs to define :
- Send a transparent message to /{productKey}/{deviceName}/user/update
- Subscribe to Alibaba cloud /{productKey}/{deviceName}/user/get
- Set alicloud's Mqtt IoT Instance terminal node :({YourProductKey}.iot-as-mqtt.{YourRegionId}.aliyuncs.com:1883
- Set the device's ProductKey and ProductSecret
Once you set it up , Data can be transferred to Alibaba cloud IoT End , Data transmission , Look at the log , If you can see it :
That means it has been sent OK 了 , Received an ordinary string ( No json), Further analysis is required .
IoT Circulation settings
stay Cloud product flow in , New parser , Set up the data source , Data destination selection function calculation :

The parser script is relatively simple :
var data = payload();
writeFc(1000, data);
Be careful ,payload function payload(textEncoding) Is a built-in function :
- No parameter passed in : The default in accordance with the UTF-8 The encoding is converted to a string , namely payload() Equivalent to payload(‘utf-8’).
- ‘json’: take payload Data to Map Format variable . If payload No JSON Format , Then return an exception .
- ‘binary’: take payload Data is converted into binary variables for transparent transmission .
Here I use the form of text transmission , Turn the data into UTF8 Text transfer .writeFc It refers to passing the converted content to 1000 Numbered objective function . For details, see file .
Of course, you can also use more complex Script , Realize the preliminary processing of script data , Because I have function calculation behind here , I'll just move the data directly to the next node .
Function calculation configuration
Create a new function according to the official document , Please note that Unwanted New trigger ! Our function here uses python Language , adopt psycopg2 Insert data into postgres In the database .
Because in function calculation , There is no such package by default , You need to add references manually , Official recommended use Serverless Devs Tool installation deployment , This thing is very difficult to use , Um. , I don't accept his suggestion . I recommend you to use vscode, Install alicloud serverless Plug in for , This is actually more convenient .
Follow the plug-in documentation , Build your own services and functions , By default, it will give a function entry :
# To enable the initializer feature (https://help.aliyun.com/document\_detail/158208.html)
# please implement the initializer function as below:
# def initializer(context):
# logger = logging.getLogger()
# logger.info('initializing')
def handler(event, context):
logger = logging.getLogger()
logger.info(event)
return 'hello world'
Let's first right-click on the function , And then choose Install Package, choice pip install psycopg2, Dependencies are automatically installed , This is very convenient .
Please note that , adopt IOT The flowing string , yes b'data' The form of such a form , It needs to be done first decode once , And then we're dealing with it , Change the function to :
# -*- coding: utf-8 -*-
import logging
import psycopg2
import uuid
import time
def insert\_database(device\_id,data):
timest = int(time.time()*1000)
guid = str(uuid.uuid1())
conn = psycopg2.connect(database="", user="", password="", host="", port="")
cur = conn.cursor()
sql = 'INSERT INTO "data"("Id","DeviceId","Timestamp", "DataArray") VALUES (\'{id}\', \'{deviceid}\', \'{timestamp}\', array{data})'
sql = sql.format(id= guid, deviceid= device_id, timestamp= timest, data= data)
cur.execute(sql)
conn.commit()
print(" Records inserted successfully")
conn.close()
def extract\_string\_array(data: bytes):
arr = data.decode().strip().split(' ')
# Write your own logic
return deviceid, resu
def handler(event, context):
logger = logging.getLogger()
logger.info(event)
device_id, result = extract_string_array(event)
insert_database(device_id, result)
return 'OK'
preservation , And then in vscode in deploy that will do .
Tips :vscode You can also perform local debug, It's more convenient , But these functions depend on docker, So it's better to install it in advance .
When it's done , Should be able to see such a picture :
thus , The data will flow normally and successfully .
The main points of
- Do not set the trigger , It took a long time to configure this trigger
- Function calculation and database VPC It should be the same , And give authority , Otherwise it can't be accessed .
- Function evaluation cannot be maintained by default , If there is such a need , Better try something else , Or take a look at the reserved instance of function calculation ( Resident instance )
- Install locally in advance Docker, If there were not all kinds of problems .
- Postgresql Insert data in array format , Pay attention to the format , You can refer to this one file
- If not for a long time docker, Lead to docker Can't start , You can refer to this one article
版权声明
本文为[Illusory private school]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230351485073.html
边栏推荐
- Vscode delete uninstall residue
- Vscode download and installation + running C language
- Who will answer the question?
- 什么是软件验收测试,第三方软件检测机构进行验收测试有什么好处?
- As a code farmer, what kind of experience is it that a girlfriend can code better than herself?
- What is software acceptance testing? What are the benefits of acceptance testing conducted by third-party software testing institutions?
- 知乎有问题,谁来解答?
- STM32 advanced timer com event
- Laboratory safety examination
- Basic usage of Google colab (I)
猜你喜欢

【BIM入门实战】Revit建筑墙体:构造、包络、叠层图文详解

【NeurIPS 2019】Self-Supervised Deep Learning on Point Clouds by Reconstructing Space

Retrieval question answering system baseline

(valid for personal testing) compilation guide of paddedetection on Jetson

【BIM入门实战】Revit中的墙体层次以及常见问题解答

LabVIEW 小端序和大端序区别

Qt程序集成EasyPlayer-RTSP流媒体播放器出现画面闪烁是什么原因?

OpenCV----YOLACT实例分割模型推理

ROS series (IV): ROS communication mechanism series (6): parameter server operation

变量、常量、运算符
随机推荐
The difference between lists, tuples, dictionaries and collections
Nel ASA:挪威Herøya设施正式启用
【BIM+GIS】ArcGIS Pro2.8如何打开Revit模型,BIM和GIS融合?
How to introduce opencv into cmake project
UDP protocol and TCP protocol
51 single chip microcomputer: D / a digital to analog conversion experiment
使用大华设备开发行AI人流量统计出现时间不正确的原因分析
Hard core chip removal
創下國產手機在海外市場銷量最高紀錄的小米,重新關注國內市場
Openvino only supports Intel CPUs of generation 6 and above
Detailed explanation on the use of annotation tool via (VGg image annotator) in mask RCNN
SQL learning record
Basic introduction to spot gold
ROS series (IV): ROS communication mechanism series (1): topic communication
ROS series (4): ROS communication mechanism series (4): topic communication practice
Websites frequented by old programmers (continuously updated)
现货黄金操作技巧_估波曲线
【BIM入门实战】Revit建筑墙体:构造、包络、叠层图文详解
UDP协议与TCP协议
减治思想——二分查找详细总结

