实验环境:PT8.2
实验目标:通过实验基于http协议实现互联网的PT中设备之间的连接,http协议的使用
实验拓扑:
实验过程:
-
设备连接
(1)如图创建文件左边为客户端client
(2)如图创建右边为服务端Server
-
程序设计
(1)client端mcu中的程序设计如下
在programing中选择“RealHTTP Client Python ”
程序代码为:
from realhttp import *
from time import *
from gpio import *
url = "http://127.0.0.1:8765/garage" #127.0.0.1本机地址,是在同一台电脑上的连额吉;若两台电脑,127.0.0.1替换为服务端的ip地址就可以;8765是通信的端口
def onHTTPDone(status, data):
print("status: " + str(status))
print("data: " + data)
def main():
http = RealHTTPClient()
http.onDone(onHTTPDone)
# http.get(url)
# don't let it finish
while True:
garageStatus=customRead(0) #读取门的状态
print garageStatus
json={'garageStatus':garageStatus} #组成门状态的数据
http.postWithHeader(url,json,{"content-type":"application/json"}) #提交
sleep(1)
if __name__ == "__main__":
main()
(2)服务端中mcu的程序设计
程序代码为:
from gpio import *
from time import *
from realhttp import *
from json import *
port = 8765
#server = RealTCPServer()
def onTCPNewClient(client):
def onTCPConnectionChange(type):
print("connection to " + client.remoteIP() + " changed to state " + str(type))
def onTCPReceive(data):
print("received from " + client.remoteIP() + " with data: " + data)
# send back same data
client.send(data)
client.onConnectionChange(onTCPConnectionChange)
client.onReceive(onTCPReceive)
def main():
server=RealHTTPServer()
print( "Server started:%s"%(server.start(8765))) #打印服务端的监听
print("server listening:%s"%(server.isListening()))
server.route("/garage",["POST"],garage_posts)
while True:
sleep(1)
def garage_posts(context,request,reply): #客户端提交信息分析
garage=request.body()
garageStauts=loads(garage)['garageStatus'] #门的状态
print garageStauts
if int(garageStauts)==0:
customWrite(0,'Door is close!')
reply.setContent("Door is closed!")
if int(garageStauts)==1:
customWrite(0,'Door is open')
reply.setContent('Door is open!')
reply.setStatus(2000)
reply.end()
if __name__ == "__main__":
main()
3.设备调试
程序运行,观察LCD灯的变化。
2023年6月23日 于青海建院
实验验证:普大通信222班马盈玲