树莓派接入阿里云IOT平台2(搭载DS18B20温度模块数据上云)

树莓派接入阿里云IOT平台2(搭载DS18B20温度模块数据上云)

再此之前说明一下,如果没有了解过阿里云和DS18B20温度模块的小伙伴,建议回去了解一下我的上两篇文章树莓派接入阿里云IOT平台1(Python模拟数据上传)树莓派与DS18B20温度传感器模块的使用,因为这篇文章是根据上两篇延伸开发的,所以小白最好去了解实践一下,看明白了以上两篇文章,想弄明白此文章就是水到渠成的事了。

云端开发

1.注册产品与设备,这一步我就不详解了,要了解的回到树莓派接入阿里云IOT平台1(Python模拟数据上传)这篇文章了解,很详细,应该看得懂的,在这里我们根据上一篇文章内容做一些更改即可。
产品功能定义留下温度即可,湿度删除。
在这里插入图片描述

树莓派端开发

1.DS18B20接线,想详细了解请看此文章树莓派与DS18B20温度传感器模块的使用
在这里插入图片描述
2.代码

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json
#这个就是我们在阿里云注册产品和设备时的三元组啦
#把我们自己对应的三元组填进去即可
options = {
    'productKey':'你的productKey',
    'deviceName':'你的deviceName',
    'deviceSecret':'你的deviceSecret',
    'regionId':'cn-shanghai'
}

HOST = options['productKey'] + '.iot-as-mqtt.'+options['regionId']+'.aliyuncs.com'
PORT = 1883 
PUB_TOPIC = "/sys/" + options['productKey'] + "/" + options['deviceName'] + "/thing/event/property/post";


# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    # client.subscribe("the/topic")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

def hmacsha1(key, msg):
    return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()

def getAliyunIoTClient():
	timestamp = str(int(time.time()))
	CLIENT_ID = "paho.py|securemode=3,signmethod=hmacsha1,timestamp="+timestamp+"|"
	CONTENT_STR_FORMAT = "clientIdpaho.pydeviceName"+options['deviceName']+"productKey"+options['productKey']+"timestamp"+timestamp
	# set username/password.
	USER_NAME = options['deviceName']+"&"+options['productKey']
	PWD = hmacsha1(options['deviceSecret'],CONTENT_STR_FORMAT)
	client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
	client.username_pw_set(USER_NAME, PWD)
	return client
def DS18B20():   #温度模块函数,返回温度数据
	tfile = open("/sys/bus/w1/devices/28-		0316a279a3e8/w1_slave")
	text =  tfile.read()
	tfile.close()
	secondline=text.split("\n")[1]
	temperaturedata = secondline.split(" ")[9]
	temperature = float(temperaturedata[2:])
	temperature = temperature / 1000
	return temperature
	print (temperature)
		
	
if __name__ == '__main__':

	client = getAliyunIoTClient()
	client.on_connect = on_connect
	client.on_message = on_message
	
	client.connect(HOST, 1883, 300)
    	DS18B20()#调用温度模块函数,返回temperature值
	payload_json = {
		'id': int(time.time()),
		'params': {
			'temperature': temperature#将DS18B20的函数返回值上传云端

		},
	    'method': "thing.event.property.post"
	}
	print('send data to iot server: ' + str(payload_json))

	client.publish(PUB_TOPIC,payload=str(payload_json),qos=1)
	client.loop_forever()
	

最后运行脚本,再去阿里云看一下,完全OK。
在这里插入图片描述
有问题的小伙伴下方留言,喜欢了解树莓派的小伙伴请关注一下喔,持续更新。

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
以下是基于Arduino平台,使用Arduino IDE编写的NB-IoT接入阿里云平台MQTT协议实现数据传输的示例代码。在使用前需要先在阿里云平台创建设备和Topic,并且获取对应的设备信息和证书。 ```C++ #include <SoftwareSerial.h> #include <PubSubClient.h> #include <ArduinoJson.h> #include <OneWire.h> #include <DallasTemperature.h> #include <DFRobot_SIM808.h> //定义NB-IoT模块相关参数 #define PIN_TX 7 #define PIN_RX 8 #define BAUDRATE 9600 //定义DS18B20温度传感器相关参数 #define ONE_WIRE_BUS 2 #define TEMPERATURE_PRECISION 9 //定义阿里云MQTT平台相关参数 #define MQTT_SERVER "xxx.mqtt.aliyuncs.com" //MQTT服务器地址 #define MQTT_PORT 1883 //MQTT服务器端口 #define MQTT_CLIENT_ID "GID_xxxxxxxxxxxxxx" //客户端ID #define MQTT_USERNAME "xxxxxxxxxxxxx" //MQTT用户名 #define MQTT_PASSWORD "xxxxxxxxxxxxx" //MQTT密码 #define MQTT_TOPIC "/xxxxxxxxxxxxx/xxxxxxxxxxxxx" //MQTT Topic SoftwareSerial mySerial(PIN_RX, PIN_TX); DFRobot_SIM808 sim808(&mySerial);//创建NB-IoT模块对象 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); WiFiClient wifiClient; PubSubClient mqttClient(MQTT_SERVER, MQTT_PORT, wifiClient); void setup() { Serial.begin(9600); mySerial.begin(BAUDRATE); while(!sim808.init());//等待模块初始化完成 delay(2000); Serial.println("SIM808 init success!"); sensors.begin(); } void loop() { sim808.checkPowerUp();//检查模块是否开机 if (sim808.isNetworkRegistered()) { Serial.println("Network is registered."); if (sim808.isGprsActived()) { Serial.println("GPRS is actived."); if (!mqttClient.connected()) { Serial.println("MQTT client is not connected."); connectMqttServer(); } mqttClient.loop(); float temperature = readTemperature(); publishMqttMessage(temperature); } else { Serial.println("GPRS is not actived, trying to activate..."); sim808.activeGprs("CMNET");//激活GPRS } } else { Serial.println("Network is not registered, trying to register..."); sim808.waitForNetworkRegistered();//等待网络注册 } } float readTemperature() { sensors.requestTemperatures(); float temperature = sensors.getTempCByIndex(0); return temperature; } void connectMqttServer() { Serial.println("Connecting to MQTT server..."); if (mqttClient.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)) { Serial.println("MQTT server connected."); mqttClient.subscribe(MQTT_TOPIC);//订阅MQTT Topic } else { Serial.print("Failed to connect MQTT server, rc="); Serial.println(mqttClient.state()); } } void publishMqttMessage(float temperature) { StaticJsonDocument<200> jsonDoc; jsonDoc["temperature"] = temperature; char message[200]; serializeJson(jsonDoc, message, sizeof(message)); mqttClient.publish(MQTT_TOPIC, message);//发布MQTT消息 } ``` 此代码实现了以下功能: 1. 连接NB-IoT模块DS18B20温度传感器; 2. 检查NB-IoT网络状态; 3. 激活GPRS连接; 4. 连接阿里云MQTT平台; 5. 订阅指定的MQTT Topic; 6. 读取DS18B20传感器数据; 7. 将温度数据以JSON格式发布到MQTT Topic。 注意:由于NB-IoT网络和阿里云MQTT平台的连接较为复杂,上述代码仅供参考,具体实现需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值