27,374
社区成员
发帖
与我相关
我的任务
分享
/**************** Device Structure *******************/
struct device {
u16 DeviceID; //Device Identifier
//char Name[10]; //Device Name which can be customized
u8 IsRS485; //Is this device using RS485 bus to send out data? 1:RS485 bus,0:nRF24L01 wireless 2.4G
u8 Address[5]; //Device address, for each nRF24L01 has a unique device address which consists of 5 bytes
};
typedef struct device DEVICE; //Define a new type replacing "struct device"
#define MAX_DEVICE_CNT 0x1E /* Maximum Devices Available */
u8 DEVICE_NBR=0; //全局变量保存已有的保存在AT24C04中的设备数量
DEVICE* ALL_DEVICE; //全局变量保存所有的设备信息
/*
* 函数名:Get_Devices
* 描述 :从AT24C02中得到全部的设备信息
* 输入 :无
* 输出 :无
* 调用 :外部调用
*/
void Get_Devices(void)
{
u8 dev_num=0; //从AT24C04读取设备数量
I2C_EE_BufferRead(&dev_num, EEPROM_BASE_ADDR_DEVICE, 1);
if (dev_num!=0xff && dev_num<=MAX_DEVICE_CNT){//判断是否超出最大数量
u8 * result;
u8 i=0, j=0;
DEVICE *device;
DEVICE_NBR = dev_num; //保存总的设备数量
//DEVICE_DATA_LEN是结构体的数据长度,应该就是sizeof(DEVICE)
//动态分配内存保存从AT24C04中读取出来的所有设备数据
result=(u8*)malloc(dev_num * DEVICE_DATA_LEN); //最大30个设备,每个8字节数据,就是DEVICE_DATA_LEN
//result=(u8*)calloc(dev_num, DEVICE_DATA_LEN); //为一维数分配dev_num个元素,每个元素占8个字节
//分配ALL_DEVICE所需要的内存空间
ALL_DEVICE=(DEVICE*)malloc(dev_num * sizeof(DEVICE));
device=ALL_DEVICE;
//根据设备数量从AT24C04读取指定长度的数据并保存在result中
I2C_EE_BufferRead(result, EEPROM_BASE_ADDR_DEVICE+1, dev_num*DEVICE_DATA_LEN);
for(i=0;i<dev_num * DEVICE_DATA_LEN;i=i+DEVICE_DATA_LEN){
device->DeviceID=((result[i+1]&0x00FF)<<8)|(result[i]&0x00FF); //设备序号
device->IsRS485=result[i+2]; //通讯方式
for(j=0;j<5;j++){ //无线2.4G通道地址,5个字节
device->Address[j]=result[i+3+j];
}
device++;
}
free(result); //释放分配的空间
free(ALL_DEVICE);
}
}
u8 i=0; //循环计数器
u8 rs485=0; //设备通信方式1:RS485总线,0:nRF24L01无线2.4G
u8 *addr=NULL; //保存设备地址
u16 device_id=0; //保存网络传来的设备信息
DEVICE * d=ALL_DEVICE; //根据网络传来的设备信息从列备列表中查找
device_id=((arg[2]&0x00FF)<<8)|(arg[1]&0x00FF); //得到要操作的设备ID
//for(d=ALL_DEVICE;d<ALL_DEVICE+DEVICE_NBR;d++)
for(i=0;i<DEVICE_NBR;i++)
{
if (device_id==d->DeviceID) //如果找到匹配的设备信息
{
rs485=d->IsRS485; //得到当前设备的数据传输方式
addr=d->Address; //得到当前设备的nRF24L01无线2.4G模块地址
break;
}
d++;
}
if (rs485==1)//使用RS485方式通信
{
//服务端处理
}
else //无线2.4G方式
{
//服务端 处理
}