项目初始化
This commit is contained in:
8
.idea/.gitignore
generated
vendored
Normal file
8
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# Editor-based HTTP Client requests
|
||||||
|
/httpRequests/
|
||||||
|
# Datasource local storage ignored files
|
||||||
|
/dataSources/
|
||||||
|
/dataSources.local.xml
|
8
.idea/hvac_end_python.iml
generated
Normal file
8
.idea/hvac_end_python.iml
generated
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="PYTHON_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager">
|
||||||
|
<content url="file://$MODULE_DIR$" />
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
13
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
13
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<component name="InspectionProjectProfileManager">
|
||||||
|
<profile version="1.0">
|
||||||
|
<option name="myName" value="Project Default" />
|
||||||
|
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||||
|
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||||
|
<option name="ignoredErrors">
|
||||||
|
<list>
|
||||||
|
<option value="N803" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</inspection_tool>
|
||||||
|
</profile>
|
||||||
|
</component>
|
6
.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
6
.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<component name="InspectionProjectProfileManager">
|
||||||
|
<settings>
|
||||||
|
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||||
|
<version value="1.0" />
|
||||||
|
</settings>
|
||||||
|
</component>
|
4
.idea/misc.xml
generated
Normal file
4
.idea/misc.xml
generated
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (hvac_end)" project-jdk-type="Python SDK" />
|
||||||
|
</project>
|
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectModuleManager">
|
||||||
|
<modules>
|
||||||
|
<module fileurl="file://$PROJECT_DIR$/.idea/hvac_end_python.iml" filepath="$PROJECT_DIR$/.idea/hvac_end_python.iml" />
|
||||||
|
</modules>
|
||||||
|
</component>
|
||||||
|
</project>
|
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
32
api/modbus_api.py
Normal file
32
api/modbus_api.py
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
from api.schemas.modbus_schemas import ModbusIn, ModbusOut
|
||||||
|
from common import reponse_code as rc
|
||||||
|
from modbus.modbus_util import write_register, read_register_float_value
|
||||||
|
|
||||||
|
|
||||||
|
modbus = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@modbus.post("/write")
|
||||||
|
def write_float_value(modbusIn: ModbusIn):
|
||||||
|
if modbusIn.type == 'float':
|
||||||
|
value = float(modbusIn.value)
|
||||||
|
elif modbusIn.type == 'short':
|
||||||
|
value = int(modbusIn.value)
|
||||||
|
success, msg = write_register(host=modbusIn.host, port=modbusIn.port,
|
||||||
|
address=modbusIn.address, value=value)
|
||||||
|
if success:
|
||||||
|
return rc.response_success("修改成功")
|
||||||
|
else:
|
||||||
|
return rc.response_error(msg)
|
||||||
|
|
||||||
|
|
||||||
|
@modbus.post("/read")
|
||||||
|
def write_float_value(modbusOut: ModbusOut):
|
||||||
|
success, result_dict = read_register_float_value(host=modbusOut.host, port=modbusOut.port, address=modbusOut.address)
|
||||||
|
if success:
|
||||||
|
return rc.response_success(msg="读取成功", data=result_dict)
|
||||||
|
else:
|
||||||
|
return rc.response_error('读取失败')
|
||||||
|
|
||||||
|
|
16
api/schemas/modbus_schemas.py
Normal file
16
api/schemas/modbus_schemas.py
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class ModbusIn(BaseModel):
|
||||||
|
host: Optional[str] = Field(..., description="地址")
|
||||||
|
port: Optional[int] = Field(..., description="端口")
|
||||||
|
address: Optional[int] = Field(..., description="内存地址")
|
||||||
|
value: Optional[str] = Field(..., description="写入的值")
|
||||||
|
type: Optional[str] = Field(..., description="写入值的类型")
|
||||||
|
|
||||||
|
|
||||||
|
class ModbusOut(BaseModel):
|
||||||
|
host: Optional[str] = Field(..., description="地址")
|
||||||
|
port: Optional[int] = Field(..., description="端口")
|
||||||
|
address: Optional[list[int]] = Field(..., description="内存地址")
|
20
app/app_config.py
Normal file
20
app/app_config.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from api.modbus_api import modbus
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
添加CORS中间件,允许跨域请求
|
||||||
|
'''
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(modbus, prefix="/modbus", tags=["modbus的api"])
|
34
common/reponse_code.py
Normal file
34
common/reponse_code.py
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
from fastapi.responses import JSONResponse, Response
|
||||||
|
from fastapi import status
|
||||||
|
|
||||||
|
|
||||||
|
def response_code_view(code: int,msg: str) -> Response:
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=code,
|
||||||
|
content={
|
||||||
|
'code': code,
|
||||||
|
'msg': msg
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def response_success(msg: str = "查询成功", data: object = None):
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status.HTTP_200_OK,
|
||||||
|
content={
|
||||||
|
'code': 200,
|
||||||
|
'msg': msg,
|
||||||
|
'data': data,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def response_error(msg:str):
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status.HTTP_200_OK,
|
||||||
|
content={
|
||||||
|
'code': 500,
|
||||||
|
'msg': msg,
|
||||||
|
'data': None,
|
||||||
|
}
|
||||||
|
)
|
5
main.py
Normal file
5
main.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import uvicorn
|
||||||
|
from app.app_config import app
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
uvicorn.run("main:app", port=8991, reload=True, host="0.0.0.0")
|
77
modbus/modbus_util.py
Normal file
77
modbus/modbus_util.py
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
from pymodbus.client.tcp import ModbusTcpClient
|
||||||
|
from pymodbus.exceptions import ModbusException
|
||||||
|
import struct
|
||||||
|
|
||||||
|
|
||||||
|
def read_register_float_value(host: str, port: int, address: list[int]):
|
||||||
|
"""
|
||||||
|
从modbus 读取数据
|
||||||
|
:param port: 端口
|
||||||
|
:param host: 地址
|
||||||
|
:param address: 减去40000的偏移量
|
||||||
|
:return: float值
|
||||||
|
"""
|
||||||
|
result_dict = {}
|
||||||
|
client = ModbusTcpClient(host=host, port=port)
|
||||||
|
try:
|
||||||
|
# 连接到 Modbus 设备
|
||||||
|
if client.connect():
|
||||||
|
for add in address:
|
||||||
|
# 从起始地址为 40002 的寄存器读取数据(Modbus 地址从 0 开始,所以 40003 对应 40002)
|
||||||
|
result = client.read_holding_registers(address=add, count=2) # 读取 2 个寄存器,因为一个 float 占用 2 个寄存器
|
||||||
|
if not result.isError():
|
||||||
|
# 获取寄存器值列表
|
||||||
|
register_values = result.registers
|
||||||
|
# 将寄存器值转换为字节表示
|
||||||
|
packed_bytes = bytes()
|
||||||
|
for value in register_values:
|
||||||
|
packed_bytes += value.to_bytes(2, byteorder='big')
|
||||||
|
# 将字节表示转换为浮点数
|
||||||
|
float_value = struct.unpack('>f', packed_bytes)[0] # 使用大端序
|
||||||
|
result_dict[add] = float_value
|
||||||
|
else:
|
||||||
|
print("读取数据失败:", result)
|
||||||
|
return False, None
|
||||||
|
return True, result_dict
|
||||||
|
else:
|
||||||
|
print("无法连接到 Modbus 设备")
|
||||||
|
return False, None
|
||||||
|
except ModbusException as e:
|
||||||
|
print("发生 Modbus 异常:", e)
|
||||||
|
return False, None
|
||||||
|
finally:
|
||||||
|
# 关闭连接
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
def write_register(host: str, port: int, address: int, value):
|
||||||
|
"""
|
||||||
|
写数据
|
||||||
|
:param host: 地址
|
||||||
|
:param port: 端口
|
||||||
|
:param address: 地址
|
||||||
|
:param value: 值
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
|
client = ModbusTcpClient(host=host, port=port)
|
||||||
|
try:
|
||||||
|
# 连接到 Modbus 设备
|
||||||
|
if client.connect():
|
||||||
|
# 将浮点数转换为字节表示
|
||||||
|
packed_float = struct.pack('>f', value)
|
||||||
|
# 将字节转换为 16 位整数列表,因为每个寄存器是 16 位
|
||||||
|
registers = [int.from_bytes(packed_float[i:i + 2], byteorder='big', signed=False) for i in
|
||||||
|
range(0, len(packed_float), 2)]
|
||||||
|
# 向起始地址为 40000 的寄存器写入数据(Modbus 地址从 0 开始,所以 40001 对应 40000)
|
||||||
|
result = client.write_registers(address=address, values=registers)
|
||||||
|
if not result.isError():
|
||||||
|
return True, "浮点数写入成功"
|
||||||
|
else:
|
||||||
|
return False, "浮点数写入失败:" + result
|
||||||
|
else:
|
||||||
|
return False, "无法连接到 Modbus 设备"
|
||||||
|
except ModbusException as e:
|
||||||
|
return False, "发生 Modbus 异常:" + e
|
||||||
|
finally:
|
||||||
|
# 关闭连接
|
||||||
|
client.close()
|
3
requirement.txt
Normal file
3
requirement.txt
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
fastapi==0.112.2
|
||||||
|
uvicorn==0.32.1
|
||||||
|
pymodbus==3.8.3
|
Reference in New Issue
Block a user