基于Python3的远程访问温湿度传感器并将获取的数据传入数据库之一(数据采集)

说明:一个完成版温湿度采集过程

(1)创建套接字,绑定套接字到本地IP与端口

sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

(2)远程访问ip,端口及指令

sk.connect(('10.1.156.82', 8001))//温湿度传感器的IP:10.1.156.82,端口:8001
inp = '030300000002c5e9'//十六进制

(3)源代码

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
u'''
Created on 2018年5月7日

@author: lenovo
'''
__author__ = 'lxd '
__version__ = '1.0.0'
__company__ = u'重庆交大'
__updated__ = '2018-05-09'

import socket
import codecs
import time
"""
client
    connect()
    recv()
    send()
    sendall()
"""
# 创建套接字,绑定套接字到本地IP与端口
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#address = ('10.1.156.82', 8001)
sk.connect(('10.1.156.82', 8001))
inp = '030300000002c5e9'
while True:
    if inp == 'exit':
        print("exit")
        break
    #默认编码为十六进制编码
    sk.send(codecs.decode(inp, 'hex'))
    #每2秒读取以此数据
    time.sleep(2)
    #每次接受1024字节的数据
    result = sk.recv(1024)
    result = codecs.encode(result, 'hex')
    r = bytes(result).decode('utf-8')
    shidu = int(r[6:10], 16) / 100
    wendu = int(r[10:14], 16) / 100
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    print("温度:%s,湿度:%s\n" % (wendu, shidu))
sk.close()

(4)结果显示:


注:本文的由于温湿度传感器IP采用的是局域网,所以要想成功连接需要连接校网(现在只完成了数据采集,后续将数据传入数据库)

连接数据库的实际过程见:https://blog.csdn.net/myclass1312/article/details/80485257

猜你喜欢

转载自blog.csdn.net/myclass1312/article/details/80456746
今日推荐