MATLAB实现洪泛路由的模拟,采用DFS算法,直接上代码。
flooding.m
clear;clc;
%global ttl;
ttl=7;%设置最大传输跳数为7
%% 初始化无线传感网示意图
%.传感器节点区域界限
envSize=10;
%区域内传感器数量
global numOfNodes;
numOfNodes=100;
global radius;%作用范围
radius=1.5;
global xLocation;
global yLocation;
xLocation = rand(numOfNodes,1) * envSize;
yLocation = rand(numOfNodes,1) * envSize; %x,y坐标
global srcx;
global destx;
srcx = floor(rand(1,1) * numOfNodes)+1; %第srcx个节点作为源节点
destx = floor(rand(1,1) * numOfNodes)+1;%第destx个节点作为目的节点
global success;%标记是否成功访问到目的节点
success=0;
global visited;%标记节点是否被访问过
visited=zeros(1,100);%初始时都未被访问
global route;%记录传输路径
route=[];
%% 画图
figure(1);hold on;
plot(xLocation, yLocation, '.');
plot(xLocation(srcx),yLocation(srcx),'ko','Markerfacecolor','k','MarkerSize',3);
plot(xLocation(destx),yLocation(destx),'ko','Markerfacecolor','k','MarkerSize',3);
text(xLocation(srcx),yLocation(srcx), '源节点');
text(xLocation(destx),yLocation(destx), '目的节点');%标记源节点和目的节点
src=[xLocation(srcx),yLocation(srcx)]; dest=[xLocation(destx),yLocation(destx)];
%% 建立距离矩阵
global distMatrix;
distMatrix = zeros(numOfNodes);
for i=1:numOfNodes
for j=i+1:numOfNodes
distMatrix(i,j)=distance([xLocation(i),yLocation(i)],[xLocation(j),yLocation(j)]);
end
distMatrix(i,i)=10;%排除自身节点
end
distMatrix = distMatrix+distMatrix';
%% 开始查找
DFS(srcx,ttl);
%% 画出传输路径图
if(ismember(destx,route))
disp('传输成功')
j=length(route);
while(j~=1)
for i=1:j-1
if(distMatrix(route(i),route(j))<=radius&&i~=j-1)
route(i+1:1:j-1)=[];
break;
end
end
j=i;
end
else
route=[];
disp('传输失败');
end
plot(xLocation(route),yLocation(route),'ro','Markerfacecolor','r','MarkerSize',3);
DFS.m
function [] = DFS(r,ttl)% r:源节点 TTL:生存周期
%%
global success;
global visited;%标记节点是否被访问过
global distMatrix;%节点间的距离矩阵
global destx;%目的节点
global radius;%作用范围
global route;%记录传输路径
visited(r)=1;
if(success==1||ttl<0)
return;
end
if(~ismember(r,route))
route=[route,r];
else
temp=find(route==r);
route=[route,r];
route(temp+1:1:end)=[];
end
neighborNodes=find(distMatrix(r,:)<=radius);%查找在作用范围内的邻节点
neighborNodes=intersect(neighborNodes, find(visited(:) == 0));%找到可访问的 neighborNodes是列向量
if(ismember(destx,neighborNodes))%如果邻节点中含有目的节点
success=1;
route=[route destx];
return;
end
%% 递归程序的出口
if (isempty(neighborNodes))%邻节点为空
route(end)=[];%删除当前源节点,返回上一层
%route=[];
return;
end
%% 递归--当前节点的邻节点中不含有目的节点,从其邻节点开始查找
ttl=ttl-1;
for k = 1:length(neighborNodes)
% if (visited(neighborNodes(k)) == 0)
if(neighborNodes(k)==destx)%当传给中心点时结束
success=1;
break;
end;
DFS(neighborNodes(k),ttl);
%end;
end;
distance.m
%% 求两个节点之间的距离
function dis = distance(A,B)
dis = sqrt((A(1)-B(1))^2+(A(2)-B(2))^2);
end
传输成功后的示意图:红色节点表示传输路径,源节点和目的节点都是随机生成的
输出失败后的示意图:只标记出了源节点和目的节点,没有传输路径