ipaddress.txe

本文介绍Python的ipaddress模块,详细讲解如何创建、检查和操作IP地址、网络和接口对象,适用于不熟悉IP网络术语的用户及希望了解模块如何处理IP网络地址概念的网络工程师。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

An introduction to the ipaddress module
***************************************

author:
   Peter Moody

author:
   Nick Coghlan


Overview
^^^^^^^^

This document aims to provide a gentle introduction to the "ipaddress"
module. It is aimed primarily at users that aren't already familiar
with IP networking terminology(术语), but may also be useful to network
engineers wanting an overview(概述) of how "ipaddress" represents IP network
addressing concepts.
 aims to 旨意
本文旨在对“ipaddress”进行温和介绍
模块。 它主要针对尚不熟悉的用户
使用IP网络术语,但也可能对网络有用
工程师想要概述“ipaddress”如何代表IP网络
解决概念。

Creating Address/Network/Interface objects
==========================================

Since "ipaddress" is a module for inspecting(检查) and manipulating(操作) IP
addresses, the first thing you'll want to do is create some objects.
You can use "ipaddress" to create objects from strings and integers().


A Note on IP Versions  关于ip版本的说明
---------------------

For readers that aren't particularly(不怎么,不见得) familiar with IP addressing, it's
important to know that the Internet Protocol is currently(当前) in the
process(过程) of moving from version 4 of the protocol to version 6. This
transition(过度,转变) is occurring(发生) largely because version 4 of the protocol
doesn't provide enough addresses to handle the needs of the whole
world, especially given the increasing number of devices(设备,器件) with direct(直接)
connections to the internet.

Explaining(解释) the details(细节) of the differences between the two versions of
the protocol is beyond the scope(视野范围) of this introduction, but readers
need to at least be aware that these two versions exist, and it will
sometimes be necessary to force the use of one version or the other.
force 推动,促使


IP Host Addresses  ip主机地址 
-----------------

Addresses, often referred to as "host addresses" are the most basic
unit when working with IP addressing. The simplest way to create
addresses is to use the "ipaddress.ip_address()" factory function,
which automatically(自动的) determines(决心,确定) whether to create an IPv4 or IPv6
address based on the passed(通过) in value:

 referred to as 被称为
 referred  参考,提到

>>> ipaddress.ip_address('192.0.2.1')
IPv4Address('192.0.2.1')
>>> ipaddress.ip_address('2001:DB8::1')
IPv6Address('2001:db8::1')

Addresses can also be created directly from integers. Values that will
fit(适合) within(在...之内) 32 bits are assumed to be IPv4 addresses:
are assumed to 假设为

   >>> ipaddress.ip_address(3221225985)
   IPv4Address('192.0.2.1')
   >>> ipaddress.ip_address(42540766411282592856903984951653826561)
   IPv6Address('2001:db8::1')

To force(促使) the use of IPv4 or IPv6 addresses, the relevant(相关的,有关的) classes can
be invoked(调用) directly. This is particularly(特别的,尤其的) useful to force creation of
IPv6 addresses for small integers:

   >>> ipaddress.ip_address(1)
   IPv4Address('0.0.0.1')
   >>> ipaddress.IPv4Address(1)
   IPv4Address('0.0.0.1')
   >>> ipaddress.IPv6Address(1)
   IPv6Address('::1')


Defining Networks(网络)
-----------------

Host addresses are usually grouped together(grouped together 集合在一起) into IP networks, so
"ipaddress" provides a way to create, inspect and manipulate network
definitions. IP network objects are constructed from strings that
define the range(范围,幅度) of host addresses that are part of that network. The
simplest form for that information is a "network address/network
prefix(前缀)" pair(一对), where the prefix defines the number of leading bits that
are compared to determine whether or not an address is part of the
network and the network address defines the expected value of those
bits.

主机地址通常组合在一起(组合在一起在一起)到IP网络,所以
“ipaddress”提供了一种创建,检查和操作网络的方法
定义。 IP网络对象由字符串构成
定义属于该网络的主机地址的范围(范围,幅度)。该
该信息的最简单形式是“网络地址/网络
prefix(前缀)“pair(一对),其中前缀定义前导位数
比较以确定地址是否是其中的一部分
网络和网络地址定义了那些的预期值
位。
As for addresses, a factory function is provided that determines the
correct IP version automatically:
as for 关于,至于


   >>> ipaddress.ip_network('192.0.2.0/24')
   IPv4Network('192.0.2.0/24')
   >>> ipaddress.ip_network('2001:db8::0/96')
   IPv6Network('2001:db8::/96')

Network objects cannot have any host bits set.  The practical effect
of this is that "192.0.2.1/24" does not describe a network.  Such
definitions are referred to as interface objects since the ip-
on-a-network notation is commonly used to describe network interfaces
of a computer on a given network and are described further in the next
section.
网络对象不能设置任何主机位。 实际效果
这是“192.0.2.1/24”没有描述网络。 这样
自从ip-以来,定义被称为接口对象
网络上的表示法通常用于描述网络接口
在给定网络上的计算机,并在下面进一步描述
部分。

By default, attempting to create a network object with host bits set
will result in "ValueError" being raised. To request that the
additional bits instead be coerced to zero, the flag "strict=False"
can be passed to the constructor:
默认情况下,尝试创建具有主机位设置的网络对象
将导致“ValueError”被引发。 要求那个
附加位反而被强制为零,标志“strict = False”
可以传递给构造函数:

   >>> ipaddress.ip_network('192.0.2.1/24')
   Traceback (most recent call last):
      ...
   ValueError: 192.0.2.1/24 has host bits set
   >>> ipaddress.ip_network('192.0.2.1/24', strict=False)
   IPv4Network('192.0.2.0/24')

While the string form offers significantly more flexibility, networks
can also be defined with integers, just like host addresses. In this
case, the network is considered to contain only the single address
identified by the integer, so the network prefix includes the entire
network address:
虽然字符串形式提供了更大的灵活性,网络
也可以用整数定义,就像主机地址一样。 在这
在这种情况下,网络被认为只包含单个地址
由整数标识,因此网络前缀包括整个
网络地址:

   >>> ipaddress.ip_network(3221225984)
   IPv4Network('192.0.2.0/32')
   >>> ipaddress.ip_network(42540766411282592856903984951653826560)
   IPv6Network('2001:db8::/128')

As with addresses, creation of a particular kind of network can be
forced by calling the class constructor directly instead of using the
factory function.
与地址一样,可以创建特定类型的网络
通过直接调用类构造函数而不是使用
工厂功能。


Host Interfaces 主机接口
---------------

As mentioned just above, if you need to describe an address on a
particular network, neither the address nor the network classes are
sufficient(足够的,充分的). Notation like "192.0.2.1/24" is commonlyt(通常) used by network
engineers and the people who write tools for firewalls and routers as
shorthand for "the host "192.0.2.1" on the network "192.0.2.0/24"",
Accordingly, "ipaddress" provides a set of hybrid classes that
associate an address with a particular network. The interface for
creation is identical to that for defining network objects, except
that the address portion isn't constrained to being a network address.
如上所述,如果您需要描述一个地址
特定网络,地址和网络类都不是
足够。 网络通常使用“192.0.2.1/24”之类的符号
工程师和为防火墙和路由器编写工具的人
“主机”192.0.2.1“在网络上”192.0.2.0/24“”的简写,
因此,“ipaddress”提供了一组混合类
将地址与特定网络相关联。 接口为
创建与定义网络对象的创建相同,除外
地址部分不限于网络地址。

>>> ipaddress.ip_interface('192.0.2.1/24')
IPv4Interface('192.0.2.1/24')
>>> ipaddress.ip_interface('2001:db8::1/96')
IPv6Interface('2001:db8::1/96')

Integer inputs are accepted (as with networks), and use of a
particular IP version can be forced by calling the relevant
constructor directly.


Inspecting Address/Network/Interface Objects
============================================

You've gone to the trouble of creating an
IPv(4|6)(Address|Network|Interface) object, so you probably want to
get information about it.  "ipaddress" tries to make doing this easy
and intuitive.

Extracting the IP version:

   >>> addr4 = ipaddress.ip_address('192.0.2.1')
   >>> addr6 = ipaddress.ip_address('2001:db8::1')
   >>> addr6.version
   6
   >>> addr4.version
   4

Obtaining the network from an interface:

   >>> host4 = ipaddress.ip_interface('192.0.2.1/24')
   >>> host4.network
   IPv4Network('192.0.2.0/24')
   >>> host6 = ipaddress.ip_interface('2001:db8::1/96')
   >>> host6.network
   IPv6Network('2001:db8::/96')

Finding out how many individual addresses are in a network:

   >>> net4 = ipaddress.ip_network('192.0.2.0/24')
   >>> net4.num_addresses
   256
   >>> net6 = ipaddress.ip_network('2001:db8::0/96')
   >>> net6.num_addresses
   4294967296

Iterating through the "usable" addresses on a network:

   >>> net4 = ipaddress.ip_network('192.0.2.0/24')
   >>> for x in net4.hosts():
   ...     print(x)  # doctest: +ELLIPSIS
   192.0.2.1
   192.0.2.2
   192.0.2.3
   192.0.2.4
   ...
   192.0.2.252
   192.0.2.253
   192.0.2.254

Obtaining the netmask (i.e. set bits corresponding to the network
prefix) or the hostmask (any bits that are not part of the netmask):
获得网络掩码(即设置对应于网络的位)
前缀)或主机掩码(不属于网络掩码的任何位):

>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> net4.netmask
IPv4Address('255.255.255.0')
>>> net4.hostmask
IPv4Address('0.0.0.255')
>>> net6 = ipaddress.ip_network('2001:db8::0/96')
>>> net6.netmask
IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::')
>>> net6.hostmask
IPv6Address('::ffff:ffff')

Exploding or compressing the address:

   >>> addr6.exploded
   '2001:0db8:0000:0000:0000:0000:0000:0001'
   >>> addr6.compressed
   '2001:db8::1'
   >>> net6.exploded
   '2001:0db8:0000:0000:0000:0000:0000:0000/96'
   >>> net6.compressed
   '2001:db8::/96'

While IPv4 doesn't support explosion or compression, the associated
objects still provide the relevant properties so that version neutral
code can easily ensure the most concise or most verbose form is used
for IPv6 addresses while still correctly handling IPv4 addresses.

而IPv4不支持爆炸或压缩,相关联
对象仍然提供相关属性,以便版本中立
代码可以轻松确保使用最简洁或最详细的表单
用于IPv6地址,同时仍能正确处理IPv4地址。


Networks as lists of Addresses 网络作为地址列表
==============================

It's sometimes useful to treat networks as lists.  This means it is
possible to index them like this:
将网络视为列表有时很有用。 这意味着它
可以像这样索引它们:

   >>> net4[1]
   IPv4Address('192.0.2.1')
   >>> net4[-1]
   IPv4Address('192.0.2.255')
   >>> net6[1]
   IPv6Address('2001:db8::1')
   >>> net6[-1]
   IPv6Address('2001:db8::ffff:ffff')

It also means that network objects lend themselves to using the list
membership test syntax like this:
它还意味着网络对象适合使用列表
成员资格测试语法如下:

   if address in network:
       # do something

Containment testing is done efficiently based on the network prefix:

   >>> addr4 = ipaddress.ip_address('192.0.2.1')
   >>> addr4 in ipaddress.ip_network('192.0.2.0/24')
   True
   >>> addr4 in ipaddress.ip_network('192.0.3.0/24')
   False


Comparisons
===========

"ipaddress" provides some simple, hopefully intuitive ways to compare
objects, where it makes sense:

   >>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')
   True

A "TypeError" exception is raised if you try to compare objects of
different versions or different types.


Using IP Addresses with other modules
=====================================

Other modules that use IP addresses (such as "socket") usually won't
accept objects from this module directly. Instead, they must be
coerced to an integer or string that the other module will accept:

   >>> addr4 = ipaddress.ip_address('192.0.2.1')
   >>> str(addr4)
   '192.0.2.1'
   >>> int(addr4)
   3221225985


Getting more detail when instance creation fails
================================================

When creating address/network/interface objects using the version-
agnostic factory functions, any errors will be reported as
"ValueError" with a generic error message that simply says the passed
in value was not recognized as an object of that type. The lack of a
specific error is because it's necessary to know whether the value is
*supposed* to be IPv4 or IPv6 in order to provide more detail on why
it has been rejected.

To support use cases where it is useful to have access to this
additional detail, the individual class constructors actually raise
the "ValueError" subclasses "ipaddress.AddressValueError" and
"ipaddress.NetmaskValueError" to indicate exactly which part of the
definition failed to parse correctly.

The error messages are significantly more detailed when using the
class constructors directly. For example:

   >>> ipaddress.ip_address("192.168.0.256")
   Traceback (most recent call last):
     ...
   ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address
   >>> ipaddress.IPv4Address("192.168.0.256")
   Traceback (most recent call last):
     ...
   ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256'

   >>> ipaddress.ip_network("192.168.0.1/64")
   Traceback (most recent call last):
     ...
   ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network
   >>> ipaddress.IPv4Network("192.168.0.1/64")
   Traceback (most recent call last):
     ...
   ipaddress.NetmaskValueError: '64' is not a valid netmask

However, both of the module specific exceptions have "ValueError" as
their parent class, so if you're not concerned with the particular
type of error, you can still write code like the following:

   try:
       network = ipaddress.IPv4Network(address)
   except ValueError:
       print('address/netmask is invalid for IPv4:', address)
 

/********************************** (C) COPYRIGHT ******************************* * File Name : main.c * Author : WCH * Version : V1.2.0 * Date : 2025/07/23 * Description : ModbusTCP-RTU Gateway with bidirectional transmission ********************************************************************************* * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. * Attention: This software (modified or not) and binary are used for * microcontroller manufactured by Nanjing Qinheng Microelectronics. *******************************************************************************/ /* *@Note Fixed version with correct CRC calculation and frame conversion: - Fixed Modbus_CRC16 function to match standard Modbus RTU specification - Corrected frame conversion logic between TCP and RTU - Added detailed debug information for troubleshooting */ #include "string.h" #include "eth_driver.h" #include "ch32v20x_usart.h" #include "ch32v20x_rcc.h" #include "ch32v20x_gpio.h" #include <stdint.h> // Network byte order conversion function declarations extern uint16_t htons(uint16_t hostshort); extern uint16_t ntohs(uint16_t netshort); extern uint8_t WCHNET_GetSocketState(uint8_t socketid); // Socket state enumeration typedef enum { SOCK_STATE_CLOSED = 0, SOCK_STATE_INIT = 1, SOCK_STATE_LISTEN = 2, SOCK_STATE_SYNSENT = 3, SOCK_STATE_SYNRECV = 4, SOCK_STATE_ESTABLISHED = 5, SOCK_STATE_FIN_WAIT = 6, SOCK_STATE_CLOSING = 7, SOCK_STATE_TIME_WAIT = 8, SOCK_STATE_CLOSE_WAIT = 9, SOCK_STATE_LAST_ACK = 10 } SocketState; #define KEEPALIVE_ENABLE 1 // Enable keep alive function // Configuration options #define DEBUG_MODE 1 // Debug mode (1: enable, 0: disable) #define UART_RX_BUF_SIZE 256 // UART receive buffer size #define MODBUS_MAX_FRAME_LENGTH 256 // Maximum Modbus frame length #define MODE_SWITCH_KEY_PORT GPIOB #define MODE_SWITCH_KEY_PIN GPIO_Pin_12 // Mode switch key pin #define MODE_SWITCH_DEBOUNCE_MS 50 // Key debounce time (ms) // Modbus function codes typedef enum { MODBUS_FC_READ_COILS = 0x01, MODBUS_FC_READ_DISCRETE_INPUTS = 0x02, MODBUS_FC_READ_HOLDING_REGISTERS = 0x03, MODBUS_FC_READ_INPUT_REGISTERS = 0x04, MODBUS_FC_WRITE_SINGLE_COIL = 0x05, MODBUS_FC_WRITE_SINGLE_REGISTER = 0x06, MODBUS_FC_WRITE_MULTIPLE_COILS = 0x0F, MODBUS_FC_WRITE_MULTIPLE_REGISTERS = 0x10, } Modbus_FunctionCode; // Modbus exception codes异常码 typedef enum { MODBUS_EXCEPTION_OK = 0x00, MODBUS_EXCEPTION_ILLEGAL_FUNCTION = 0x01, MODBUS_EXCEPTION_ILLEGAL_ADDRESS = 0x02, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE = 0x03, MODBUS_EXCEPTION_SERVER_DEVICE_FAILURE = 0x04, } Modbus_ExceptionCode; // Gateway working mode typedef enum { GATEWAY_MODE_TCP_CLIENT = 0, // TCP client mode GATEWAY_MODE_TCP_SERVER = 1, // TCP server mode } GatewayMode; // ModbusTCP header structure typedef struct { uint16_t transaction_id; // Transaction identifier uint16_t protocol_id; // Protocol identifier (0x0000 for Modbus) uint16_t length; // Length of remaining data uint8_t unit_id; // Unit identifier } ModbusTCP_Header; // Global variables u8 MACAddr[6]; // MAC address u8 IPAddr[4] = { 192, 168, 3, 155 }; // IP address u8 GWIPAddr[4] = { 192, 168, 3, 1 }; // Gateway IP address u8 IPMask[4] = { 255, 255, 255, 0 }; // Subnet mask u8 DESIP[4] = { 192, 168, 3, 66 }; // Target IP address u16 desport = 502; // Target port u16 srcport = 504; // Source port GatewayMode current_mode = GATEWAY_MODE_TCP_CLIENT; // Current working mode u8 mode_switch_request = 0; // Mode switch request flag u8 SocketId; u8 socket[WCHNET_MAX_SOCKET_NUM]; // Connected socket IDs// 已连接的套接字ID u8 SocketRecvBuf[WCHNET_MAX_SOCKET_NUM][RECE_BUF_LEN]; // Socket receive buffers// 套接字接收缓冲区 u8 MyBuf[RECE_BUF_LEN]; // UART related variables volatile uint8_t uart_rx_buf[UART_RX_BUF_SIZE]; // UART接收缓冲区 volatile uint16_t uart_rx_len = 0; // UART接收长度 volatile uint8_t uart_frame_ready = 0; // UART帧就绪标志 // Function declarations uint16_t Modbus_CRC16(uint8_t *data, uint16_t len); void USART1_Init(uint32_t baudrate); void TIM2_Init_ForUartFrame(void); void WCHNET_DataToUart(uint8_t *data, uint16_t len); void UartDataToWCHNET(void); void ModbusTCPToRTU(uint8_t *tcp_data, uint16_t tcp_len); void ModbusRTUToTCP(uint8_t *rtu_data, uint16_t rtu_len); void SetGatewayMode(GatewayMode mode); void WCHNET_CreateTcpSocket(void); void KEY_Init(void); uint8_t KEY_Scan(void); void Delay_Ms(uint32_t n); /********************************************************************* * @fn Modbus_CRC16 * * @brief 修正后的Modbus CRC16计算函数,符合标准Modbus RTU规范 * 测试数据: 01 03 00 00 00 01 → 正确CRC应为0xD5CA *********************************************************************/ uint16_t Modbus_CRC16(uint8_t *data, uint16_t len) { uint16_t crc = 0xFFFF; // 初始值必须为 0xFFFF for (uint16_t i = 0; i < len; i++) { crc ^= data[i]; // 与当前字节异或 // 处理每个位(8 次循环) for (uint8_t j = 0; j < 8; j++) { if (crc & 0x0001) { // 最低位为 1 crc = (crc >> 1) ^ 0xA001; // 右移并异或多项式 } else { crc >>= 1; // 右移一位 } } } // 调换高低字节,符合 RTU 存储顺序(低字节在前) return crc; } /********************************************************************* * @fn mStopIfError * * @brief Check error code and print *********************************************************************/ void mStopIfError(u8 iError) { if (iError == WCHNET_ERR_SUCCESS) return; printf("Error: 0x%02X\r\n", (u16)iError); } /********************************************************************* * @fn USART1_Init * * @brief Initialize USART1 for Modbus RTU *********************************************************************/ void USART1_Init(uint32_t baudrate) { GPIO_InitTypeDef GPIO_InitStructure = {0}; USART_InitTypeDef USART_InitStructure = {0}; NVIC_InitTypeDef NVIC_InitStructure = {0}; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE); // PA9: TX, PA10: RX GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); USART_InitStructure.USART_BaudRate = baudrate; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART1, &USART_InitStructure); USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); USART_Cmd(USART1, ENABLE); } /********************************************************************* * @fn TIM2_Init_ForUartFrame * * @brief Initialize TIM2 for UART frame timeout detection *********************************************************************/ // 新增波特率定义(根据实际需求修改) #define UART_BAUDRATE 9600 // 计算 3.5 个字符时间(单位:ms,向上取整) #define CHAR_TIME_MS (11.0 / UART_BAUDRATE * 1000) // 1 字符时间(ms) #define RTU_FRAME_TIMEOUT_MS (uint32_t)(CHAR_TIME_MS * 3.5 + 0.5) // 向上取整 // 定时器初始化函数修改 void TIM2_Init_ForUartFrame(void) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; // 超时时间设置为计算值(RTU_FRAME_TIMEOUT_MS) TIM_TimeBaseStructure.TIM_Period = RTU_FRAME_TIMEOUT_MS - 1; // 0~n-1 共 n 个周期 TIM_TimeBaseStructure.TIM_Prescaler = (SystemCoreClock/1000) - 1; // 1ms 计数一次 TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); NVIC_EnableIRQ(TIM2_IRQn); TIM_Cmd(TIM2, DISABLE); } /********************************************************************* * @fn KEY_Init * * @brief Initialize mode switch key *********************************************************************/ void KEY_Init(void) { GPIO_InitTypeDef GPIO_InitStructure = {0}; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); GPIO_InitStructure.GPIO_Pin = MODE_SWITCH_KEY_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // Pull-up input GPIO_Init(MODE_SWITCH_KEY_PORT, &GPIO_InitStructure); } /********************************************************************* * @fn KEY_Scan * * @brief Scan mode switch key with debounce *********************************************************************/ uint8_t KEY_Scan(void) { static uint8_t key_up = 1; if(key_up && (GPIO_ReadInputDataBit(MODE_SWITCH_KEY_PORT, MODE_SWITCH_KEY_PIN) == 0)) { Delay_Ms(MODE_SWITCH_DEBOUNCE_MS); if(GPIO_ReadInputDataBit(MODE_SWITCH_KEY_PORT, MODE_SWITCH_KEY_PIN) == 0) { key_up = 0; return 1; } } else if(GPIO_ReadInputDataBit(MODE_SWITCH_KEY_PORT, MODE_SWITCH_KEY_PIN) == 1) { key_up = 1; } return 0; } /********************************************************************* * @fn WCHNET_DataToUart * * @brief Transmit Ethernet data to UART (Modbus RTU) *********************************************************************/ void WCHNET_DataToUart(uint8_t *data, uint16_t len) { if(len == 0 || len > MODBUS_MAX_FRAME_LENGTH) { if(DEBUG_MODE) printf("Invalid UART transmit length: %d\r\n", len); return; } for(uint16_t i = 0; i < len; i++) { while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); USART_SendData(USART1, data[i]); } if(DEBUG_MODE) printf("UART data sent, length: %d bytes\r\n", len); } /********************************************************************* * @fn UartDataToWCHNET * * @brief 增强调试信息的UART数据处理函数 *********************************************************************/ void UartDataToWCHNET(void) { if (uart_frame_ready && uart_rx_len > 0) { if(DEBUG_MODE) { printf("UART Frame Received, length: %d bytes\r\n", uart_rx_len); printf("UART Raw Data: "); for(int i = 0; i < uart_rx_len; i++) { printf("%02X ", uart_rx_buf[i]); } printf("\r\n"); } // Create temporary buffer to remove volatile attribute uint8_t temp_buf[UART_RX_BUF_SIZE]; uint16_t temp_len = uart_rx_len; // Safely copy data from volatile memory for (uint16_t i = 0; i < temp_len; i++) { temp_buf[i] = uart_rx_buf[i]; } ModbusRTUToTCP(temp_buf, temp_len); // Reset buffer after processing uart_rx_len = 0; uart_frame_ready = 0; } } /********************************************************************* * @fn ModbusTCPToRTU * * @brief 修正后的TCP转RTU函数,正确计算CRC *********************************************************************/ void ModbusTCPToRTU(uint8_t *tcp_data, uint16_t tcp_len) { if(tcp_data == NULL || tcp_len < sizeof(ModbusTCP_Header) + 1) { if(DEBUG_MODE) printf("Invalid ModbusTCP frame, length: %d\r\n", tcp_len); return; } ModbusTCP_Header *header = (ModbusTCP_Header *)tcp_data; // Check if it's a Modbus protocol frame (0x0000) if(ntohs(header->protocol_id) != 0) { if(DEBUG_MODE) printf("Not a ModbusTCP frame (Protocol ID: 0x%04X)\r\n", ntohs(header->protocol_id)); return; } // 解析TCP头信息 uint8_t unit_id = header->unit_id; uint8_t function_code = tcp_data[6]; // 功能码在第7字节(索引6) uint16_t tcp_payload_len = ntohs(header->length); // 校验TCP数据长度是否匹配 if(tcp_len != sizeof(ModbusTCP_Header) + tcp_payload_len) { if(DEBUG_MODE) printf("TCP data length mismatch: header=%d, actual=%d\r\n", tcp_payload_len, tcp_len - sizeof(ModbusTCP_Header)); return; } // 构建RTU数据部分(不包含CRC) uint8_t rtu_data[MODBUS_MAX_FRAME_LENGTH]; uint16_t rtu_data_len = 0; // 复制单元ID和功能码 rtu_data[rtu_data_len++] = unit_id; rtu_data[rtu_data_len++] = function_code; // 复制数据部分(TCP数据从第7字节开始,长度为tcp_payload_len-1) // 因为tcp_payload_len包含unit_id(1字节)+功能码(1字节)+数据(n字节) uint16_t data_part_len = tcp_payload_len - 2; if(data_part_len > 0) { memcpy(&rtu_data[rtu_data_len], &tcp_data[7], data_part_len); rtu_data_len += data_part_len; } // 计算并添加CRC uint16_t crc = Modbus_CRC16(rtu_data, rtu_data_len); rtu_data[rtu_data_len++] = crc & 0xFF; // CRC低字节 rtu_data[rtu_data_len++] = (crc >> 8) & 0xFF; // CRC高字节 // 调试信息 if(DEBUG_MODE) { printf("TCP->RTU Converted: "); for(int i = 0; i < rtu_data_len; i++) { printf("%02X ", rtu_data[i]); } printf(", CRC: 0x%04X\r\n", crc); } // 发送到UART WCHNET_DataToUart(rtu_data, rtu_data_len); } /********************************************************************* * @fn ModbusRTUToTCP * * @brief 修正后的RTU转TCP函数,正确校验CRC并构建TCP帧 *********************************************************************/ uint8_t WCHNET_GetSocketState(uint8_t socketid) { // Check if socket is in connected list for (uint8_t i = 0; i < WCHNET_MAX_SOCKET_NUM; i++) { if (socket[i] == socketid) { return SOCK_STATE_ESTABLISHED; // Connected } } return SOCK_STATE_CLOSED; // Not connected } void ModbusRTUToTCP(uint8_t *rtu_data, uint16_t rtu_len) { // 最小RTU帧: 地址(1) + 功能码(1) + 数据(n) + CRC(2) → 最小长度为4 if(rtu_data == NULL || rtu_len < 4) { if (DEBUG_MODE) printf("Invalid ModbusRTU frame length: %d (min 4)\r\n", rtu_len); return; } // 提取单元ID uint8_t unit_id = rtu_data[0]; // // 调试用:打印功能码信息 // if(DEBUG_MODE) { // uint8_t function_code = rtu_data[1]; // printf("RTU Function Code: 0x%02X\r\n", function_code); // } // 验证CRC uint16_t received_crc = (rtu_data[rtu_len - 1] << 8) | rtu_data[rtu_len - 2]; uint16_t calculated_crc = Modbus_CRC16(rtu_data, rtu_len - 2); // 详细的CRC调试信息 if (DEBUG_MODE) { printf("RTU CRC Check: Received=0x%04X, Calculated=0x%04X\r\n", received_crc, calculated_crc); } // CRC校验失败则丢弃帧 if(received_crc != calculated_crc) { if (DEBUG_MODE) printf("ModbusRTU CRC check failed - discarding frame\r\n"); return; } // 检查socket连接状态 uint8_t socket_connected = 0; for(int i = 0; i < WCHNET_MAX_SOCKET_NUM; i++) { if(socket[i] == SocketId) { socket_connected = 1; break; } } if(!socket_connected) { if(DEBUG_MODE) printf("Socket not connected! Cannot send data\r\n"); // 客户端模式下尝试重连 if(current_mode == GATEWAY_MODE_TCP_CLIENT) { printf("Reconnecting due to send failure...\r\n"); WCHNET_SocketClose(SocketId, 0); Delay_Ms(100); WCHNET_CreateTcpSocket(); } return; } // 构建TCP帧 uint8_t tcp_frame[MODBUS_MAX_FRAME_LENGTH]; ModbusTCP_Header *header = (ModbusTCP_Header *)tcp_frame; // 设置事务ID(自增) static uint16_t transaction_id = 0; header->transaction_id = htons(transaction_id++); header->protocol_id = htons(0); // Modbus协议 header->length = htons(rtu_len - 2); // RTU长度减去CRC字节 header->unit_id = unit_id; // 复制数据部分(排除CRC) memcpy(&tcp_frame[sizeof(ModbusTCP_Header)], rtu_data, rtu_len - 2); uint16_t tcp_len = sizeof(ModbusTCP_Header) + (rtu_len - 2); // 检查TCP帧长度 if(tcp_len > MODBUS_MAX_FRAME_LENGTH) { if(DEBUG_MODE) printf("TCP frame too long: %d > %d\r\n", tcp_len, MODBUS_MAX_FRAME_LENGTH); return; } // 调试信息 if(DEBUG_MODE) { printf("RTU->TCP Converted frame: "); for(int i = 0; i < tcp_len; i++) { printf("%02X ", tcp_frame[i]); } printf("\r\n"); } // 发送到TCP uint32_t send_len = tcp_len; uint8_t err = WCHNET_SocketSend(SocketId, tcp_frame, &send_len); if(err != WCHNET_ERR_SUCCESS) { if(DEBUG_MODE) printf("Failed to send TCP data: 0x%02X\r\n", err); } else { if(DEBUG_MODE) printf("TCP data sent, length: %d bytes\r\n", send_len); } } /********************************************************************* * @fn SetGatewayMode * * @brief Set gateway working mode (client/server) *********************************************************************/ void SetGatewayMode(GatewayMode mode) { // Close current connection if(SocketId < WCHNET_MAX_SOCKET_NUM) { WCHNET_SocketClose(SocketId, 0); Delay_Ms(100); // Wait for close completion } current_mode = mode; memset(socket, 0xff, WCHNET_MAX_SOCKET_NUM); // Clear socket list if(mode == GATEWAY_MODE_TCP_CLIENT) { printf("Gateway mode set to TCP Client\r\n"); printf("Target server: %d.%d.%d.%d:%d\r\n", DESIP[0], DESIP[1], DESIP[2], DESIP[3], desport); // Create TCP client connection WCHNET_CreateTcpSocket(); } else { printf("Gateway mode set to TCP Server\r\n"); printf("Listening port: %d\r\n", desport); // Create TCP server listener SOCK_INF TmpSocketInf; memset((void *)&TmpSocketInf, 0, sizeof(SOCK_INF)); TmpSocketInf.SourPort = desport; TmpSocketInf.ProtoType = PROTO_TYPE_TCP; TmpSocketInf.RecvBufLen = RECE_BUF_LEN; u8 err = WCHNET_SocketCreat(&SocketId, &TmpSocketInf); mStopIfError(err); if(err == WCHNET_ERR_SUCCESS) { err = WCHNET_SocketListen(SocketId); mStopIfError(err); if(err == WCHNET_ERR_SUCCESS) { printf("TCP Server started successfully\r\n"); } } } } /********************************************************************* * @fn WCHNET_CreateTcpSocket * * @brief Create TCP Socket (client mode) *********************************************************************/ void WCHNET_CreateTcpSocket(void) { u8 err; SOCK_INF TmpSocketInf; memset((void *) &TmpSocketInf, 0, sizeof(SOCK_INF)); memcpy((void *) TmpSocketInf.IPAddr, DESIP, 4); TmpSocketInf.DesPort = desport; TmpSocketInf.SourPort = srcport++; // Prevent port overflow if(srcport > 65530) srcport = 504; TmpSocketInf.ProtoType = PROTO_TYPE_TCP; TmpSocketInf.RecvBufLen = RECE_BUF_LEN; err = WCHNET_SocketCreat(&SocketId, &TmpSocketInf); printf("Creating socket %d...\r\n", SocketId); mStopIfError(err); if(err == WCHNET_ERR_SUCCESS) { err = WCHNET_SocketConnect(SocketId); mStopIfError(err); } } /********************************************************************* * @fn WCHNET_HandleSockInt * * @brief Handle Socket interrupt *********************************************************************/ void WCHNET_HandleSockInt(u8 socketid, u8 intstat) { u8 i; if (intstat & SINT_STAT_RECV) // Receive data { uint32_t len = WCHNET_SocketRecvLen(socketid, NULL); if (len > 0 && len < MODBUS_MAX_FRAME_LENGTH) { uint8_t buffer[MODBUS_MAX_FRAME_LENGTH]; WCHNET_SocketRecv(socketid, buffer, &len); if(DEBUG_MODE) { printf("TCP Data Received, length: %d bytes\r\n", len); printf("TCP Raw Data: "); for(int i = 0; i < len; i++) { printf("%02X ", buffer[i]); } printf("\r\n"); } // Convert ModbusTCP data to ModbusRTU and send to serial port ModbusTCPToRTU(buffer, len); } else if(len >= MODBUS_MAX_FRAME_LENGTH) { if(DEBUG_MODE) printf("TCP data too long: %d bytes\r\n", len); } } if (intstat & SINT_STAT_CONNECT) // Connect successfully { #if KEEPALIVE_ENABLE WCHNET_SocketSetKeepLive(socketid, ENABLE); #endif WCHNET_ModifyRecvBuf(socketid, (u32) SocketRecvBuf[socketid], RECE_BUF_LEN); for (i = 0; i < WCHNET_MAX_SOCKET_NUM; i++) { if (socket[i] == 0xff) { // Save connected socket id socket[i] = socketid; break; } } printf("TCP Connect Success\r\n"); printf("Socket id: %d\r\n", socket[i]); if(current_mode == GATEWAY_MODE_TCP_CLIENT) { printf("Connected to %d.%d.%d.%d:%d\r\n", DESIP[0], DESIP[1], DESIP[2], DESIP[3], desport); } else { printf("Client connected to server\r\n"); } } if (intstat & SINT_STAT_DISCONNECT) // Disconnect { for (i = 0; i < WCHNET_MAX_SOCKET_NUM; i++) { // Delete disconnected socket id if (socket[i] == socketid) { socket[i] = 0xff; break; } } printf("TCP Disconnect\r\n"); // Try to reconnect if in client mode if(current_mode == GATEWAY_MODE_TCP_CLIENT) { printf("Reconnecting in 1 second...\r\n"); Delay_Ms(1000); WCHNET_CreateTcpSocket(); } } if (intstat & SINT_STAT_TIM_OUT) // Timeout disconnect { for (i = 0; i < WCHNET_MAX_SOCKET_NUM; i++) { // Delete disconnected socket id if (socket[i] == socketid) { socket[i] = 0xff; break; } } printf("TCP Timeout\r\n"); // Try to reconnect if in client mode if(current_mode == GATEWAY_MODE_TCP_CLIENT) { printf("Reconnecting in 1 second...\r\n"); Delay_Ms(1000); WCHNET_CreateTcpSocket(); } } } /********************************************************************* * @fn WCHNET_HandleGlobalInt * * @brief Handle global interrupt *********************************************************************/ void WCHNET_HandleGlobalInt(void) { u8 intstat; u16 i; u8 socketint; intstat = WCHNET_GetGlobalInt(); // Get global interrupt flag if (intstat & GINT_STAT_UNREACH) // Unreachable interrupt { printf("GINT_STAT_UNREACH: Host unreachable\r\n"); } if (intstat & GINT_STAT_IP_CONFLI) // IP conflict { printf("GINT_STAT_IP_CONFLI: IP address conflict\r\n"); } if (intstat & GINT_STAT_PHY_CHANGE) // PHY status change { i = WCHNET_GetPHYStatus(); if (i & PHY_Linked_Status) printf("PHY Link Success: Ethernet connected\r\n"); else printf("PHY Link Lost: Ethernet disconnected\r\n"); } if (intstat & GINT_STAT_SOCKET) { // Socket related interrupt for (i = 0; i < WCHNET_MAX_SOCKET_NUM; i++) { socketint = WCHNET_GetSocketInt(i); if (socketint) WCHNET_HandleSockInt(i, socketint); } } } /********************************************************************* * @fn USART1_IRQHandler * * @brief USART1 interrupt service routine *********************************************************************/ // void USART1_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast"))); void USART1_IRQHandler(void) { if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) { USART_ClearITPendingBit(USART1, USART_IT_RXNE); // Receive one byte uint8_t data = USART_ReceiveData(USART1); // Store in buffer if(uart_rx_len < UART_RX_BUF_SIZE - 1) { uart_rx_buf[uart_rx_len++] = data; } else { // Buffer full, reset (prevent overflow) if(DEBUG_MODE) printf("UART buffer overflow, resetting\r\n"); uart_rx_len = 0; } // Reset timer (restart timeout when data received) TIM_SetCounter(TIM2, 0); TIM_Cmd(TIM2, ENABLE); } } /********************************************************************* * @fn main * * @brief Main program *********************************************************************/ int main(void) { u8 i; Delay_Init(); USART_Printf_Init(115200); // Initialize USART for printf USART1_Init(9600); // Initialize USART1 for Modbus RTU TIM2_Init_ForUartFrame(); // Initialize timer for UART frame detection KEY_Init(); // Initialize mode switch key printf("ModbusTCP-RTU Gateway\r\n"); printf("==================================\r\n"); if((SystemCoreClock == 60000000) || (SystemCoreClock == 120000000)) printf("System Clock: %d Hz\r\n", SystemCoreClock); else printf("Error: Please use 60MHz or 120MHz clock for Ethernet!\r\n"); // printf("Ethernet Library Version: 0x%x\r\n", WCHNET_GetVer()); //以太网存储库版本 // if (WCHNET_LIB_VER != WCHNET_GetVer()) { // printf("Warning: Library version mismatch!\r\n"); // } WCHNET_GetMacAddr(MACAddr); // Get MAC address printf("MAC Address: "); for(i = 0; i < 6; i++) printf("%02X ", MACAddr[i]); printf("\r\n"); printf("==================================\r\n"); printf("Network Configuration:\r\n"); printf("IP Address: %d.%d.%d.%d\r\n", IPAddr[0], IPAddr[1], IPAddr[2], IPAddr[3]); printf("Subnet Mask: %d.%d.%d.%d\r\n", IPMask[0], IPMask[1], IPMask[2], IPMask[3]); printf("Gateway: %d.%d.%d.%d\r\n", GWIPAddr[0], GWIPAddr[1], GWIPAddr[2], GWIPAddr[3]); printf("==================================\r\n"); // Initialize Ethernet library i = ETH_LibInit(IPAddr, GWIPAddr, IPMask, MACAddr); mStopIfError(i); if (i == WCHNET_ERR_SUCCESS) printf("Ethernet initialized successfully\r\n"); #if KEEPALIVE_ENABLE // Configure keep alive parameters { struct _KEEP_CFG cfg; cfg.KLIdle = 20000; // Keep-alive idle time: 20s cfg.KLIntvl = 15000; // Keep-alive interval: 15s cfg.KLCount = 9; // Keep-alive retry count: 9 WCHNET_ConfigKeepLive(&cfg); printf("TCP Keep-alive enabled\r\n"); } #endif memset(socket, 0xff, WCHNET_MAX_SOCKET_NUM); // Initialize network connection SetGatewayMode(current_mode); // printf("Press mode switch key (PB12) to toggle between client/server modes\r\n"); // printf("==================================\r\n"); while(1) { // Check mode switch key if(KEY_Scan()) { printf("\r\nMode switch requested\r\n"); GatewayMode new_mode = (current_mode == GATEWAY_MODE_TCP_CLIENT) ? GATEWAY_MODE_TCP_SERVER : GATEWAY_MODE_TCP_CLIENT; SetGatewayMode(new_mode); } // Ethernet library main task WCHNET_MainTask(); // Handle Ethernet interrupts if(WCHNET_QueryGlobalInt()) { WCHNET_HandleGlobalInt(); } // Process UART data and forward to Ethernet UartDataToWCHNET(); // Short delay to reduce CPU usage Delay_Ms(1); } } 这个代码串口为啥不能发数据帧
最新发布
07-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值