python实现:把一个变量值存入redis,下次启动程序时作为初始值使用

# -*- coding:utf-8 -*-
"""
__project_ = 'mqttclient'
__file_name__ = 'MqttClient_dev'
__author__ = 'xbxia'
__time__ = '2020/12/23 9:24'
__product_name = PyCharm
# code is far away from bugs with the god animal protecting

"""
# 使用定时器
import threading
import datetime as dt
import binascii # ascii编码

# 生成随机数
import random

# mqtt客户端
import paho.mqtt.client as mqtt
import json
import redis

# redis连接
class RedisTT(object):
def __init__(self):
self.host = '47.101.151.35'
self.port = 63791
self.password = 123456
self.db = 2

self.r = redis.StrictRedis(host=self.host,password=self.password,port=self.port,db=self.db)

def insertRedis(self, keyName, attr_dict): #存入到redis中
self.r.hmset(keyName, attr_dict) #批量添加属性

def getRedis(self, keyName, key): #取出所有数据
#h_data = self.r.hget(keyName, key)
return(self.r.hget(keyName, key))





def saveTopic(content):
with open(r'topic.txt', 'a+', encoding='utf-8') as fs:
fs.writelines(content + '\n')


# 一旦连接成功,回调此方法
def on_connect(mqttc, userdata, flags, rc):
print("rc: " + str(rc))


# 一旦订阅到消息,回调此方法
def on_message(mqttc, userdata, msg):
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
# save(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))


# 一旦订阅成功,回调此方法
def on_subscribe(mqttc, userdata, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))


# 一旦有log,回调此方法
def on_log(mqttc, userdata, level, string):
print(string)


# 创建mqtt客户端,带有鉴权

client_id = "X1XXXQ2007060017|productid=a1s2d3|" # walle平台
mqttc = mqtt.Client(client_id)
mqttc.username_pw_set("hd", "hdcloud890!")
# mqttc.username_pw_set("iotwedora", "cloud")
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_log = on_log


# 连接broker,心跳时间为60s
mqttc.connect("172.16.22.170", 41564, 60) #基站平台
#mqttc.connect("mapall.cn", 6811, 60) # walle平台
#mqttc.connect("192.168.80.21", 50210, 60)
#mqttc.connect("mdtu.com", 50210, 60)
#mqttc.connect("172.16.22.155", 51553, 60) #ops开发测试环境
#mqttc.connect("www.xindny-ie.com", 51553, 60)
print('***2连接建立**')


# 定时发布主题
def fun_timer():
global decimal
now_time = dt.datetime.now().strftime('%F %T')
print(now_time)

  # 内嵌累计数据发生器函数
def count1():
num = float(RedisTT().getRedis(keyName='202103261354', key='energy')) # 初始上报量
print('重启后读取的初始值:%s' % num)
decimal = 3 # 默认两位小数点
num += 0.2
nu = format(num, '.{}f'.format(decimal))
return nu


# 发布消息
content_dic1 = {
"data": {
"device": "202103261354",
"timestamp": dt.datetime.now().strftime('%F %T'),
"frequency": random.randrange(48, 50, 1), #频率
#"energy": count1()
# "VD8": random.randint(0, 1),
#"VD1": random.uniform(30, 40) #温度
"energy": count1()
}
}
content1 = json.dumps(content_dic1)

# 读取设备的 energy值,存到redis中
keyName = content_dic1['data']['device']
attr_dict = content_dic1['data']['energy']

# 把设备的energy值存入redis
RedisTT().insertRedis(keyName=keyName, attr_dict={'energy': attr_dict})
print('存入的值:%s' % attr_dict)


# 发布主题
mqttc.publish("/UL/X1XXXQ2007060017/DPU/data", payload=content1, qos=0)

global timer
timer = threading.Timer(60, fun_timer)
timer.start()
print('&&&&&&&&&')

mqttc.subscribe("/UL/X1XXXQ2007060017/DPU/data", 0)

timer = threading.Timer(1, fun_timer)
timer.start()
#mqttc.loop_start()
mqttc.loop_forever()
posted @ 2021-09-03 09:44  ReluStarry  阅读(194)  评论(0编辑  收藏  举报