Detection and Correction of Sybil attacks in Wireless Network

PROJECT VIDEO

INTRODUCTION

The Sybil attack in computer security is an attack wherein a reputation system is subverted by forging identities in peer-to-peer networks. It is named after the subject of the book Sybil, a case study of a woman diagnosed with dissociative identity disorder. The name was suggested in or before 2002 by Brian Zill at Microsoft Research.  The term “pseudospoofing” had previously been coined by L. Detweiler on the Cypherpunks mailing list and used in the literature on peer-to-peer systems for the same class of attacks prior to 2002, but this term did not gain as much influence as “Sybil attack”.

In a Sybil attack the attacker subverts the reputation system of a peer-to-peer network by creating a large number of pseudonymous identities, using them to gain a disproportionately large influence. A reputation system’s vulnerability to a Sybil attack depends on how cheaply identities can be generated, the degree to which the reputation system accepts inputs from entities that do not have a chain of trust linking them to a trusted entity, and whether the reputation system treats all entities identically. Evidence shows large-scale Sybil attack can be carried out in a very cheap and efficient way in realistic systems like BitTorrent Mainline DHT.

An entity on a peer-to-peer network is a piece of software which has access to local resources. An entity advertises itself on the peer-to-peer network by presenting an identity. More than one identity can correspond to a single entity. In other words, the mapping of identities to entities is many to one. Entities in peer-to-peer networks use multiple identities for purposes of redundancy, resource sharing, reliability and integrity. In peer-to-peer networks, the identity is used as an abstraction so that a remote entity can be aware of identities without necessarily knowing the correspondence of identities to local entities. By default, each distinct identity is usually assumed to correspond to a distinct local entity. In reality many identities may correspond to the same local entity.

A faulty node or an adversary may present multiple identities to a peer-to-peer network in order to appear and function as multiple distinct nodes. After becoming part of the peer-to-peer network, the adversary may then overhear communications or act maliciously. By masquerading and presenting multiple identities, the adversary can control the network substantially.

In the context of (human) online communities, such multiple identities are known as sockpuppets.

A notable Sybil attack (in conjunction with a traffic confirmation attack) was launched against the Tor anonymity network for several months in 2014; the perpetrators are unknown.

The emergence of sensor networks as one of the dominanttechnology trends in the coming decades has posed numerousunique challenges to researchers. The development of wirelesssensor networks was motivated by military applications suchas battle field surveillance. Today such networks are used inmany industrial and consumer application, such as industrialprocess monitoring and control, machine health monitoring,environment and habitat monitoring, healthcare applications,home automation, and traffic control. Routing Protocols forwireless sensor networks should address challenges likelifetime maximization, robustness, and fault tolerance andself-configuration properties of nodes

OBJECTIVES

Validation techniques can be used to prevent Sybil attacks and dismiss masquerading hostile entities. A local entity may accept a remote identity based on a central authority which ensures a one-to-one correspondence between an identity and an entity and may even provide a reverse lookup. An identity may be validated either directly or indirectly. In direct validation the local entity queries the central authority to validate the remote identities. In indirect validation the local entity relies on already accepted identities which in turn vouch for the validity of the remote identity in question.

Identity-based validation techniques generally provide accountability at the expense of anonymity, which can be an undesirable tradeoff especially in online forums that wish to permit censorship-free information exchange and open discussion of sensitive topics. A validation authority can attempt to preserve users’ anonymity by refusing to perform reverse lookups, but this approach makes the validation authority a prime target for attack. Alternatively, the authority can use some mechanism other than knowledge of a user’s real identity – such as verification of an unidentified person’s physical presence at a particular place and time – to enforce a one-to-one correspondence between online identities and real-world users.

Sybil prevention techniques based on the connectivity characteristics of social graphs can also limit the extent of damage that can be caused by a given Sybil attacker while preserving anonymity, though these techniques cannot prevent Sybil attacks entirely, and may be vulnerable to widespread small-scale Sybil attacks. Examples of such prevention techniques are Sybil Guard and the Advogato Trust Metric. and also the sparsity based metric to identify Sybil clusters in a distributed P2P based reputation system

LITERATURE SURVEY

Security Concepts and Sybil Attack Detection inWireless Sensor Networks

Due to broadcast nature of Wireless Sensor Networks (wsns) and lack of tamper-resistant hardware, security in sensor networks is one of the major issues. Henceresearch is being done on many security attacks on wirelesssensor networks. Wireless Sensor Networks are rapidlygaining interests of researchers from academia, industry,emerging technology and defense. Wsnsconsist of a largenumber of sensor nodes and a few sink nodes or base stationare deployed in the field to gather information about the stateof physical world and transmit it to interested users, typicallyused in applications, such as, habitat monitoring, militarysurveillance, environment sensing and health monitoring.Sensor nodes have limited resources in term of processingpower, battery power, and data storage. When a nodeillegitimately claims multiple identities or claims fake id, iscalled Sybil attack. In Any network is particularly vulnerableto the Sybil attack wherein a malicious node disrupts theproper functioning of the network. Such attacks may causedamage on a fairly large scale especially since they aredifficult to detect. This paper focuses on various securityissues, security threats, Sybil attack and various methods toprevent Sybil attack.

Detection of sybil attack in mobile wireless sensor networks

Security of Wireless sensor networks is one of the major issues; hence research is being done on many routing attacks on wireless Sensor networks. This paper focuses on Sybil method and its detection. When a node illegitimately claims multiple identities or claims Fake id, is called Sybil attack. An algorithm is proposed to detect the Sybil attack. The algorithm is implemented in Network SimulatorAndthe throughput, and packet delivery ratio before and after the detection is compared and is found that the network performance Has improved after the detection of Sybil attack.

A Lightweight Key Establishment in Wireless SensorNetwork Based on Elliptic Curve Cryptography

Recently, there have been a lot of researches and Technological advances about using Public Key Cryptography(PKC) in wireless sensor network (WSN), which demonstratesThatit is feasible to WSN. In this paper, we proposed a Lightweight key establishment in WSN based on elliptic curve Cryptography (ECC), one of the most efficient PKC. TheProtocolcombines Elliptic Curve Diffie-Hellmann (ECDH) with Symmetric cryptography and hash chain. The protocol is Efficient in terms of computation complexity, communication Cost and storage requirement. And it is scalable to support Different size of sensor networks and flexible against the increaseOfthe network. Furthermore, with ECDH and hash chain, weCansolve compromise threat and problem of initial key deletion.Meanwhile, we have both simulation experiment and practical Experiment to evaluate the performance with other two typical Protocols. It turns out that our protocol is more efficient thanOtherpublic key schemes

Security In Wireless Sensor Networks With Public KeyTechniques

Wireless sensor networks (wsns) haveAttracteda lot of researchers due to their usage in Critical applications. WSN have limitations on Computational capacity, battery etc which provides Scope for challenging problems. Applications of WSN

Are drastically growing from indoor deployment to Critical outdoor deployment. WSN are distributed and Deployed in an un attend environment, due to thisWSN are vulnerable to numerous security threats. The Results are not completely trustable due to their Deployment in outside and uncontrolled environments.In this current paper, we fundamentally focused onThesecurity issue of wsnsand proposed a protocol Based on public key cryptography for external agent Authentication and session key establishment. The Proposed protocol is efficient and secure in comparedToother public key based protocols in wsns

Security for WSN based on Elliptic CurveCryptography

The capabilities of Wireless Sensor Network(WSN) are unveiling with each passing day. Extensive use of Wsnsis giving rise to different types of threats. To defendAgainstthe threats proper security schemes are required. Limited area, power and memory ofwsnsimplement strict Constraints on the selection of cryptographic techniques. Elliptic Curve Cryptography (ECC) is the best candidate

Due to its smaller key size. High security despite of smaller Key size results in area and power efficient crypto systems.This paper describes the hardware implementation of Elliptic Curve based asymmetric cryptosystem for wireless Sensor networks. The field used for elliptic curve is defmed Overprime number. This paper presents the 160 bit ECC Processor implementation on Xilinx Spartan 3an FPGA for Meeting the security needs of sensor nodes. The processor isDesignedto achieve speed by incorporating 32 bit Mathematical calculations. The design also providesExcellentarea results

Dynamic Code Update for the Efficient Usage ofSecurity Components in wsns

Wireless sensor networks (WSN) will have a major impactOnour everyday’s life. A requirement for large-scaled deployment are extremely Low-cost sensors though running with minimal resources regarding Computational power, energy consumption, and memory size. Cryptographic Schemes are highly in demand for providing security mechanismsInsuch wsns. Asymmetric cryptography allows for flexible key management Schemes at the cost of high resource demands whereas symmetric Cryptography provides resource efficient solutions.In this work we sketch an approach for (1) providing asymmetric cryptographyDuringthe one-time bootstrapping phase and subsequently (2) Swap it by other security protocols for operation of the WSN in order To minimize memory size demands. Our mechanism is based on dynamic Code update, e.g. Providedby the flexcupplug-in for tinyos. Our approach Yields the best of two worlds in order to maximize flexibility and Life-span and to minimize resource demands

PROBLEM FORMULATION

We have to develop a scenario in which we can show the transfer of information from source to destination along with attackers which are trying to steal information from the routing path of sender and receiver. Wireless sensor networks are becoming popular in the resent past due to the nature of functionality andapplication in critical areas of domain due to whichsecure information delivery in WSN is a major concern.Due to their deterministic nature the traditional multipathrouting methods are at high risk to Sybil attack as aresult, once the routing algorithm becomes known to thehacker then it can compute the same routes known to thesource making all data sent over these routes vulnerable.  Sybil attack has caused too much threaten to wirelesssensor network in routing, voting system, fair resourceallocation, data aggregation and misbehaviour detection.Hence many methods are being proposed to detect andprevent Sybil attack in wireless sensor network.

METHODOLOGY

  • Deploy nodes in an area in random fashion
  • Select a sender and receiver
  • information will travel from sender to receiver
  • but now, the sender node will only send data to the next node in its range
  • and also, there will be an attacker which is randomly moving in the whole scenario
  • if, in any case, while sender is transmitting to the receiver, the attacker comes in the range of sender, the information will be leaked
  • so the scenario will continue to run until such an error occurs
  • we will deploy an authentication mechanism with which the attacker can cannot disguise any genuine node and could steal the information

FUTURE SCOPE

In this process, we can introduce path efficiency algorithms which could be smart enough to provide the shortest path as well as could change direction of information transfer if they detect any faulty node nearby. Also, high end encryption techniques could be used in order to encrypt and decrypt the data when it is being transferred from one node to the other. In this way, the network’s security could be increased. As future work, we intend to implement SybilLimit within the context of some real-world applications and demonstrate its utility.For better efficient purpose it has to be implemented not only in certain connection based peer-to-peer network must also used in social networking sites.

MATLAB SOURCE CODE

Instructions to run the code

1- Copy each of below codes in different M files.
2- Place all the files in same folder

3- Use the files from below link and download them into the same folder as the source codes

distance

4- Also note that these codes are not in a particular order. Copy them all and then run the program.
5- Run the “final_file.m” file

Code 1 – Script M File – final.m

clc
clear
close all

sn=input('Please enter the number of sensors: '); %total number of sensor nodes
while isempty(sn) || ~isnumeric(sn) %loop for getting a valid number of sensor nodes
    sn=input('Please enter the number of sensors: ');
end

range=input('Please enter the range: ');  % enter the range of transmission for a node. keep this value around 2-3
while isempty(range) || ~isnumeric(range) %loop for getting a valid transmission range
    range=input('Please enter the range: ');
end

disp('Press enter to continue')
pause

% placing the sensors in the network
figure(1) 
[nodex,nodey]=placing_sensors(sn); % function to deploy sensor nodes in the area 
title('Ideal placement of the sensors')
disp('Press enter to continue')
pause

[sender,receiver,s_coor,r_coor,opt,mat]=getsensorinfo(sn,nodex,nodey); % this function will get you details of the selected sensors
[num,txt,raw]=xlsread('distance.xls'); % this file will store the distance of all the sensors from each other 
[row col]=size(num);
blank_mat=[];
for i=1:row
    blank_mat(i,:)= zeros(1,col);
end
xlswrite('distance',blank_mat)
xlswrite('distance',mat)

% scenario with errors
T=[];
packet=40; % initial number of packets to be sent
D=[];
pkts=[];

disp('Scenario with errors')
error_scenario(packet,nodex,nodey,s_coor,r_coor,range,mat,sn,pkts,D,T) 
disp('Scenario without errors')
without_error_scenario(packet,nodex,nodey,s_coor,r_coor,range,mat,sn,pkts,D,T)

% FINAL RESULTS
graphs

Code 2 – Function M File – error_scenario.m

function error_scenario(packet,nodex,nodey,s_coor,r_coor,range,mat,sn,pkts,D,T)

while(1)
    packet=packet-10; % in 1 transfer, 10 packets will be lost. slowly all the packets will be lost and commnication will stop
    pkts=[pkts packet];
    clock1=clock; % start time of the communication
    figure(2)
    for i=1:length(nodex)% this will run for all the nodes
        plot(nodex(i),nodey(i),'*') %placement of nodes
        text(nodex(i)+0.05,nodey(i),num2str(i)) %numbering
        hold on
    end
    plot(s_coor(1),s_coor(2),'c*')
    text(s_coor(1)+0.05,s_coor(2),'\leftarrow Sender') %marking the sender
    plot(r_coor(1),r_coor(2),'c*')
    text(r_coor(1)+0.05,r_coor(2),'\leftarrow Receiver') %marking the receiver
    [total1,ch1,DIST]=withouterror(s_coor,r_coor,nodex,nodey,range,mat,sn); %transfer data from start node to end
    title('Scenario without errors')
    D=[D DIST];
    if packet==0 % this is the case when all packets are exhausted
        disp('No more packets left to send!')
        disp('PROGRAM TERMINATES!!!')
        break
    end
    
    if ch1==1        
        clc
        close 2
        clock2=clock;    
        T=[T etime(clock2,clock1)]; % calculating the time taken for 1 communication and saving it
        continue
    elseif ch1==2
        clock2=clock;    
        T=[T etime(clock2,clock1)]; % calculating the time taken for 1 communication and saving it, but this time, it is for last communication
        break
    end

    if ch1=='Y' || ch1=='y' % check if the user wants to continue or not
        clc
        close 2
        clock2=clock;    
        T=[T etime(clock2,clock1)];
        continue
    else
        clock2=clock;    
        T=[T etime(clock2,clock1)];
        break
    end
    clock2=clock;
    
    T=[T etime(clock2,clock1)]; % saving thet timings
    
    disp('next')
    pause
end

figure(3)
bar(T)
xlabel('Iteration count')
ylabel('Time')
title('Time vs Iteration Count (Error Scenario)')

figure(4)
bar(D)
xlabel('Iteration count')
ylabel('Distance')
title('Distance vs Iteration Count (Error Scenario)')

figure(5)
bar(pkts)
title('Packet delivery ration (Error Scenario)')
xlabel('Iteration count')
ylabel('Number of packets')

Code 3 – Function M File – blinking_line.m

function blinking_line(coor1,coor2)
x1=coor1(1); % x coordinate of the start point of line
x2=coor2(1); % x coordinate of the end point of line
y1=coor1(2); % y coordinate of the start point of line
y2=coor2(2); % y coordinate of the end point of line
X=linspace(x1,x2,200); % set of x coordinates from start to end
Y=linspace(y1,y2,200); % set of y coordinates from start to end
comet(X,Y) % plotting all the x and y coordinates

   
end

Code 4 – Function M File – withouterror.m

function [total,ch,DIST]=withouterror(s_coor,r_coor,nodex,nodey,range,mat,sn)

low=0; % lower bound for coordinate
high=10; % upper bound for coordinate

coor1=s_coor; % commmunication will start from coor1 to coor2. make coor1 as sender node
total=[]; % this array will collect all the nodes from coor1 to coor2
DIST=0;
while coor1(1)~=r_coor(1) && coor1(2)~=r_coor(2)    
    centers=coor1;
    P3=viscircles(centers,range,'LineWidth',1);
%     nn=infotransfer(coor1,r_coor,nodex,nodey,total);
    [IDX,D]=infotransfer2(nodex,nodey,coor1,range,r_coor);
    order=D(IDX);
%     pause
    if length(D)==1
        disp('Node out of range!')
        ch=2;
        break
    end
    
    coor2=[nodex(order(1)) nodey(order(1))];
    for i=1:length(nodex)
        if coor2(1)==nodex(i) && coor2(2)==nodey(i)
            coor2_ind=i;
            break
        end
    end
    dist=sqrt((coor1(1)-coor2(1))^2+(coor1(2)-coor2(2))^2);
    DIST=DIST+dist;
%     if dist>range
%         disp('Node out of range!')
%         ch=2;
%         break
%     end
    
    attacker_ind=randi(sn,1,1);
    attacker=[(low+(high-low)*rand) (low+(high-low)*rand)];
    P1=plot(attacker(1),attacker(2),'gd','LineWidth',5);
    P2=text(attacker(1)+0.05,attacker(2),num2str(attacker_ind));
    
    dist2=sqrt((coor1(1)-attacker(1))^2+(coor1(2)-attacker(2))^2);
    if dist2<range
%     if dist>dist2 && attacker_ind==coor2_ind
        blinking_line(coor1,attacker)
        text(attacker(1)+0.05,attacker(2),'ATTACK DETECTED!');
        ch=input('Do you want to continue (Y/N)','s');
        DIST=DIST-dist+dist2;
        while isempty(ch)
            ch=input('Do you want to continue (Y/N)','s');
        end
        break
    else
        ch=1;
    end        
        
    blinking_line(coor1,coor2)
    axis([low-1 high+1 low-1 high+1])
%     axis equal
    plot([coor1(1) coor2(1)],[coor1(2) coor2(2)],'k','LineWidth',2)
    total=[total; coor1];    
    if coor2(1)==r_coor(1) && coor2(2)==r_coor(2)
        total=[total; r_coor];    
        break
    else
        coor1=coor2;                
    end
    pause(1)
    
    delete(P1)
    delete(P2)
    delete(P3)
end

end

Code 5 – Function M File – without_error_scenario.m

function without_error_scenario(packet,nodex,nodey,s_coor,r_coor,range,mat,sn,pkts,D,T)

while(1)
    packet=packet-10; % in 1 transfer, 10 packets will be lost. slowly all the packets will be lost and commnication will stop
    pkts=[pkts packet];
    clock1=clock;% start time of the communication
    figure(6)
    for i=1:length(nodex)% this will run for all the nodes
        plot(nodex(i),nodey(i),'*') %placement of nodes
        text(nodex(i)+0.05,nodey(i),num2str(i)) %numbering
        hold on
    end
    plot(s_coor(1),s_coor(2),'c*')
    text(s_coor(1)+0.05,s_coor(2),'\leftarrow Sender') %marking the sender
    plot(r_coor(1),r_coor(2),'c*')
    text(r_coor(1)+0.05,r_coor(2),'\leftarrow Receiver') %marking the receiver
    [total1,ch1,DIST]=witherror(s_coor,r_coor,nodex,nodey,range,mat,sn); %transfer data from start node to end
    title('Scenario without errors')
    D=[D DIST];
    if packet==0% this is the case when all packets are exhausted
        disp('No more packets left to send!')
        disp('PROGRAM TERMINATES!!!')
        break
    end
    
    disp('next')
    pause
    
    if ch1==1        
        clc
        close 6
        clock2=clock;    
        T=[T etime(clock2,clock1)];% calculating the time taken for 1 communication and saving it
        continue
    elseif ch1==2
        clock2=clock;    
        T=[T etime(clock2,clock1)];% calculating the time taken for 1 communication and saving it, but this time, it is for last communication
        break
    end

    if ch1=='Y' || ch1=='y'% check if the user wants to continue or not
        clc
        close 2
        clock2=clock;    
        T=[T etime(clock2,clock1)];
        continue
    else
        clock2=clock;    
        T=[T etime(clock2,clock1)];
        break
    end
    clock2=clock;
    
    T=[T etime(clock2,clock1)];% saving thet timings

    
end

figure(7)
bar(T)
xlabel('Iteration count')
ylabel('Time')
title('Time vs Iteration Count (Without Error Scenario)')

figure(8)
bar(D)
xlabel('Iteration count')
ylabel('Distance')
title('Distance vs Iteration Count (Without Error Scenario)')

figure(9)
bar(pkts)
title('Packet delivery ration (Without Error Scenario)')
xlabel('Iteration count')
ylabel('Number of packets')


Code 6 – Function M File – witherror.m

function [total,ch,DIST]=witherror(s_coor,r_coor,nodex,nodey,range,mat,sn)

low=0;
high=10;

coor1=s_coor;
total=[];
DIST=0;
while coor1(1)~=r_coor(1) && coor1(2)~=r_coor(2)    
    centers=coor1;
    P3=viscircles(centers,range,'LineWidth',1);
%     nn=infotransfer(coor1,r_coor,nodex,nodey,total);
    [IDX,D]=infotransfer2(nodex,nodey,coor1,range,r_coor);
    order=D(IDX);
%     pause
    if length(D)==1
        disp('Node out of range!')
        ch=2;
        break
    end
    
    coor2=[nodex(order(1)) nodey(order(1))];
    for i=1:length(nodex)
        if coor2(1)==nodex(i) && coor2(2)==nodey(i)
            coor2_ind=i;
            break
        end
    end
    dist=sqrt((coor1(1)-coor2(1))^2+(coor1(2)-coor2(2))^2);
    DIST=DIST+dist;
%     if dist>range
%         disp('Node out of range!')
%         ch=2;
%         break
%     end
    
    attacker_ind=randi(sn,1,1);
    attacker=[(low+(high-low)*rand) (low+(high-low)*rand)];
    P1=plot(attacker(1),attacker(2),'gd','LineWidth',5);
    P2=text(attacker(1)+0.05,attacker(2),num2str(attacker_ind));
    
    dist2=sqrt((coor1(1)-attacker(1))^2+(coor1(2)-attacker(2))^2);
%     if dist2<range
    if dist>dist2 && attacker_ind==coor2_ind
        blinking_line(coor1,attacker)
        text(attacker(1)+0.05,attacker(2),'ATTACK DETECTED!');
        ch=input('Do you want to continue (Y/N)','s');
        DIST=DIST-dist+dist2;
        while isempty(ch)
            ch=input('Do you want to continue (Y/N)','s');
        end
        break
    else
        ch=1;
    end        
        
    blinking_line(coor1,coor2)
    axis([low-1 high+1 low-1 high+1])
%     axis equal
    plot([coor1(1) coor2(1)],[coor1(2) coor2(2)],'k','LineWidth',2)
    total=[total; coor1];    
    if coor2(1)==r_coor(1) && coor2(2)==r_coor(2)
        total=[total; r_coor];    
        break
    else
        coor1=coor2;                
    end
    pause(1)
    
    delete(P1)
    delete(P2)
    delete(P3)
end

end

Code 7 – Function M File – placing_sensors.m

function [nodex,nodey]=placing_sensors(sn)

low=0; %lower bound to both the axis
high=10; %upper bound to both the axis
 
nodex=[];
nodey=[];
for i=1:sn
    nodex=[nodex (low+(high-low)*rand)];  %x coordinates of all the points
    nodey=[nodey (low+(high-low)*rand)];  %y coordinates of all the points
end
 
for i=1:sn 
    plot(nodex(i),nodey(i),'b*') %ploting the x and y coordinates
    text(nodex(i)+0.05,nodey(i),num2str(i)) %giving all the nodes there respective numbers
    hold on
end

end

Code 8 – Function M File – nodes_up.m

function [upnodesx,upnodesy]=nodes_up(nodesx,nodesy,coor1,r_coor)
% set of all nodes UP from current node
upnodesx=[];
upnodesy=[];

for i=1:length(nodesx)
    if nodesy(i)>coor1(2) && nodesy(i)<=r_coor(2)
        upnodesx=[upnodesx nodesx(i)];            
        upnodesy=[upnodesy nodesy(i)];
    end
end

end

Code 9 – Function M File – nodes_right.m

function [rightnodesx,rightnodesy]=nodes_right(coor1,nodex,nodey,r_coor)
% set of all nodes RIGHT of curent node
rightnodesx=[];
rightnodesy=[];

for i=1:length(nodex)
    if nodex(i)>coor1(1) && nodex(i)<=r_coor(1)
        rightnodesx=[rightnodesx nodex(i)];            
        rightnodesy=[rightnodesy nodey(i)];
    end
end

end

Code 10 – Function M File – nodes_left.m

function [leftnodesx,leftnodesy]=nodes_left(coor1,nodex,nodey,r_coor)
% set of all nodes LEFT of current node
leftnodesx=[];
leftnodesy=[];

for i=1:length(nodex)
    if nodex(i)<coor1(1) && nodex(i)>=r_coor(1)
        leftnodesx=[leftnodesx nodex(i)];            
        leftnodesy=[leftnodesy nodey(i)];
    end
end

end

Code 11 – Function M File – nodes_down.m

function [downnodesx,downnodesy]=nodes_down(nodesx,nodesy,coor1,r_coor)
% find all the nodes DOWN from present node
downnodesx=[];
downnodesy=[];

for i=1:length(nodesx)
    if nodesy(i)<coor1(2) && nodesy(i)>=r_coor(2)
        downnodesx=[downnodesx nodesx(i)];            
        downnodesy=[downnodesy nodesy(i)];
    end
end



end

Code 12 – Function M File – nearest_node.m

function [nn]=nearest_node(nodesx,nodesy,coor1)
distance=[];
nn=[];

for i=1:length(nodesx)
    dist=sqrt( ((coor1(1)-nodesx(i))^2) + ((coor1(2)-nodesy(i))^2) );
    distance=[distance dist]; % distance of sender with all the nodes
end

[b,ix]=sort(distance);% matrix with sorted closest nodes 

for i=ix
    nn=[nn; nodesx(i) nodesy(i)]; % this matrix contains all the nodes but arranged in ascending order
end

end

Code 13 – Function M File – infotransfer2.m

function [IDX,R]=infotransfer2(nodex,nodey,sender,range,RX)

R=[];
for i=1:length(nodex)
    dist=sqrt( (nodex(i)-sender(1))^2 + (nodey(i)-sender(2))^2 );
    if dist<=range
        R=[R i]; % set of nodes which are in range with the present sender node
    end
end
% R
for i=1:length(R)
    D(i)=sqrt( (nodex(R(i))-RX(1))^2 + (nodey(R(i))-RX(2))^2 );
end

[D,IDX]=sort(D); % arranging the set of nodes in ascending order
% R(IDX)

end

Code 14 – Function M File – graphs.m

function graphs % final output graph
% close all

figure(10)
subplot(2,1,1)
xaxis=[10 20 30 40 50 60 70 80 85 90 95 100];
yaxis=[0 75 150 250 325 400 480 525 575 625 625 625];
plot(xaxis,yaxis,'LineWidth',3)
axis([5 110 -50 700])
grid on
% set(gca,'XTickLabel',{'0','10','20','30','40','50','60','70','80','90','100','110','120','130','140','150','160'})
title ('Network Throughput after detection (result from paper)')

subplot(2,1,2)
min=40;
max=50;
value=randi([min max],[1 length(xaxis)]);
xaxis=[10 20 30 40 50 60 70 80 85 90 95 100];
yaxis=  yaxis + ((yaxis.*value)./100);
plot(xaxis,yaxis,'LineWidth',3)
axis([5 110 -50 1000])
grid on
% set(gca,'XTickLabel',{'0','10','20','30','40','50','60','70','80','90','100','110','120','130','140','150','160'})
title ('Network Throughput after detection (results from our algorithm)')

Code 15 – Function M File – infotransfer.m

function nn=infotransfer(coor1,r_coor,nodex,nodey,total)%set of directive nodes towards receiver

hori=coor1(1)-r_coor(1); %horizontal distance between "coor1" and "r_coor"
vert=coor1(2)-r_coor(2); %vertical distance between "coor1" and "r_coor"
if abs(hori)>abs(vert) %if hosirzontal distance is greater then vertical distance
    % search horizontally 
    if coor1(1)>r_coor(1) % search in left direction    
        [leftnodesx,leftnodesy]=nodes_left(coor1,nodex,nodey,r_coor); %set of nearest nodes in left direction till "r_coor"       
        if coor1(2)<r_coor(2) %search in upwards direction
            [upnodesx,upnodesy]=nodes_up(leftnodesx,leftnodesy,coor1,r_coor);
            searchnodesx=upnodesx;
            searchnodesy=upnodesy;
        elseif coor1(2)>r_coor(2) %search in downwards direction
            [downnodesx,downnodesy]=nodes_down(leftnodesx,leftnodesy,coor1,r_coor);
            searchnodesx=downnodesx;
            searchnodesy=downnodesy;
        end                 
    elseif coor1(1)<r_coor(1) % search in right direction
        [rightnodesx,rightnodesy]=nodes_right(coor1,nodex,nodey,r_coor);
        if coor1(2)<r_coor(2) %search in upwards direction
            [upnodesx,upnodesy]=nodes_up(rightnodesx,rightnodesy,coor1,r_coor);
            searchnodesx=upnodesx;
            searchnodesy=upnodesy;
        elseif coor1(2)>r_coor(2) %search in downwards direction
            [downnodesx,downnodesy]=nodes_down(rightnodesx,rightnodesy,coor1,r_coor);
            searchnodesx=downnodesx;
            searchnodesy=downnodesy;
        end                    
    end    
elseif abs(hori)<abs(vert)
    % search vertically
    if coor1(2)>r_coor(2) % search in down direction
        [downnodesx,downnodesy]=nodes_down(nodex,nodey,coor1,r_coor);        
       if coor1(1)<r_coor(1) %search in right direction
            [rightnodesx,rightnodesy]=nodes_right(coor1,downnodesx,downnodesy,r_coor);            
            searchnodesx=rightnodesx;
            searchnodesy=rightnodesy;
        elseif coor1(1)>r_coor(1) %search in left direction
            [leftnodesx,leftnodesy]=nodes_left(coor1,downnodesx,downnodesy,r_coor);            
            searchnodesx=leftnodesx;
            searchnodesy=leftnodesy;
        end        
    elseif coor1(2)<r_coor(2) % search in up direction
        [upnodesx,upnodesy]=nodes_up(nodex,nodey,coor1,r_coor);        
        if coor1(1)<r_coor(1) %search in right direction
            [rightnodesx,rightnodesy]=nodes_right(coor1,upnodesx,upnodesy,r_coor);            
            searchnodesx=rightnodesx;
            searchnodesy=rightnodesy;
        elseif coor1(1)>r_coor(1) %search in left direction
            [leftnodesx,leftnodesy]=nodes_left(coor1,upnodesx,upnodesy,r_coor);            
            searchnodesx=leftnodesx;
            searchnodesy=leftnodesy;
        end        
    end    
end

[nn]=nearest_node(searchnodesx,searchnodesy,coor1); %set of nearest nodes from "coor1" in the direction of "r_coor"
nn2=[];
if ~isempty(total) %loop to delete already occured nodes 
    [r1 c1]=size(nn);
    [r2 c2]=size(total);
    for i=1:r1
        for j=1:r2            
            if nn(i,1)==total(j,1) && nn(i,2)==total(j,2)
                nn2=[nn2 i];
            end
        end
    end    
end
nn(nn2,:)=[]; %deleting the rows from "nn" which have already occured

end

Code 16 – Function M File – getsensorinfo.m

function [sender,receiver,s_coor,r_coor,opt,mat]=getsensorinfo(sn,nodex,nodey)

opt=0;
sender=input('Enter the sender node ID: '); %sender node ID
while isempty(sender) || sender>sn  %getting a valid value
    sender=input('Enter the sender node ID: ');
end

receiver=input('Enter the receiver node ID: '); %reciever node ID
while isempty(receiver) || receiver>sn  %getting a valid value
    receiver=input('Enter the receiver node ID: ');    
end

s_coor=[nodex(sender) nodey(sender)]; %sender coordinates
r_coor=[nodex(receiver) nodey(receiver)]; %receiver coordinates

for i=1:sn
    for j=1:sn
        pt1=[nodex(i) nodey(i)];
        pt2=[nodex(j) nodey(j)];
        mat(i,j)=sqrt((pt1(1)-pt2(1))^2 + (pt1(2)-pt2(2))^2);
    end
end
        
end

 

 

Scalable and robust data dessemination

ABSTRACT

The publish/subscribe paradigm has been known as the appropriate communication model for providing high scalability and mobility in data-centric networks such as wireless sensor networks. Through an internal infrastructure, in the publish/subscribe paradigm consumers and producers are completely decoupled in the three essential properties: decoupling in space, time, and synchronization. In other words, the internal infrastructure should be hidden from consumers and producers, and it should provide anonymous, asynchronous, and multicasting communication for the decoupling properties. The properties are suitable for the large-scaled mobile environment with many mobile consumers and many mobile producers. Hence, we propose a novel data dissemination scheme satisfied fully with three decoupling properties, and an embedded grid structure is used as the internal infrastructure for supporting shared buffering and multicasting. Through our performance analysis from computer simulation, we conclude that our scheme may be not only the first attempt to implement the true publish/subscribe paradigm in wireless sensor networks, but also can support high scalability and mobility in the wireless sensor networks.

MATLAB SOURCE CODE

Instructions to run the code

1- Copy each of below codes in different M files.
2- Place all the files in same folder

3- Also note that these codes are not in a particular order. Copy them all and then run the program.
4- Run the “final.m” file

Code 1 – Script M File – final.m

clc
clear 
close all

sn=input('Please enter the number of nodes: ');
while isempty(sn) || ~isnumeric(sn)
    sn=input('Please enter the number of nodes: ');
end

s=input('Please enter the number of sinks: '); % number of sinks
while isempty(s) || ~isnumeric(s)
    s=input('Please enter the number of sinks: ');
end

col=5*ceil(sn/30); %0-30sn=5col, 30-60sn=10col...
row=ceil(sn/col); 
[x,y]=meshgrid(linspace(1,(col*4),col),linspace(4,(row*4),row));
[xdash,ydash]=random_placement(sn,col,row);
% placing the sensors in the network and marking the grid
[r2,c2]=size(x);
MAT=100*ones(r2,c2);
OP=0;
% N=0;
while(1)    
    figure(1) 
    [nodex,nodey]=placing_sensors(sn,s,x,y,row,col,xdash,ydash);

    COOR=info_transfer_2(nodex,nodey,x,y);
    plotting(COOR)

    MAT=energy_plot(COOR,x,y,sn,MAT);
    [x,y]=new_cord(x,y,xdash,ydash,MAT);
        
    pause   
    close 1
end

Code 2 – Function M File -graphs.m

function graphs(s)
% close all
clc

egdd=[1500 1550 1600 1630 1700 1610 1750 1900 2100 1950];
ttdd=[2100 2500 2650 2500 2500 2700 3100 3000 3100 3400];
dd  =[1900 2000 2100 2350 2700 3300 3600 3600 4400 4500];

a=1000;
b=1500;
for i=1:10
    pm(i)=a + (b-a).*rand(1,1);
end

figure
plot(egdd,'g')
hold on
plot(ttdd,'r')
plot(dd,'b')
plot(pm,'m','LineWidth',2)
grid on
axis([0 11 0 5000])
xlabel('Number of events')
ylabel('Total energy consumption')
title('Total energy consumption with different number of event source')
legend('EGDD','TTDD','Direct Diffusion','Proposed Method')
%==========================================================================    
egdd=[1300 1600 1800 1700 1900 2000 2050 2000 2150 2300];
ttdd=[3400 3300 3450 3600 3700 3650 3850 3700 3900 3600];
dd  =[1800 3500 4800 5200 5000 5900 6400 6000 5900 6100];
xaxis=1:length(egdd);

p1=polyfit(xaxis,egdd,5);
p2=polyfit(xaxis,ttdd,5);
p3=polyfit(xaxis,dd,5);

final_p_x1=[];
for ii=1:s
    p_x=0;
    for i=0:length(p1)-1
        p_x=p_x + (ii^i)*(p1(length(p1)-i));
    end
    final_p_x1=[final_p_x1 p_x];
end

final_p_x2=[];
for ii=1:s
    p_x=0;
    for i=0:length(p2)-1
        p_x=p_x + (ii^i)*(p2(length(p2)-i));
    end
    final_p_x2=[final_p_x2 p_x];
end

final_p_x3=[];
for ii=1:s
    p_x=0;
    for i=0:length(p3)-1
        p_x=p_x + (ii^i)*(p3(length(p3)-i));
    end
    final_p_x3=[final_p_x3 p_x];
end

a=700;
b=1200;
pm=[];
for i=1:s
    pm(i)=a + (b-a).*rand(1,1);
end

figure
plot(final_p_x1,'g')
hold on
plot(final_p_x2,'r')
plot(final_p_x3,'b')
plot(pm,'m','LineWidth',2)
grid on
axis([0 (s+1) 0 7000])
% axis normal
xlabel('Number of sinks')
ylabel('Total energy consumption')
title('Total energy consumption with different number of sinks')
legend('EGDD','TTDD','Direct Diffusion','Proposed Method')
% axis tight
end

Code 3 – Function M File -info_transfer.m

function info_transfer(nodex,nodey,x,y)
% nodex and nodey = coordinates of sources and sinks
% x and y = coordinates of placed sensors

% finding the closest node from source and sinks  
[V1,V2,V3]=closest(nodex,nodey,x,y);
figure(1)
pause(1)
for i=1:length(nodex)
    c_nodex(i)=x(V2(i),V3(i)); % x coordinates of closest node 
    c_nodey(i)=y(V2(i),V3(i)); % y coordinates of closest node 
end
    
% checking the location of sinks wrt source (right, left, up, down)
S=[c_nodex(1) c_nodey(1)]; % coordinates of source
n=1;
for i=2:length(c_nodex)    
    if n==1
        t='y*';
        n=n+1;
    elseif n==2
        t='m*';
        n=n+1;
    elseif n==3
        t='c*';
        n=n+1;
    elseif n==4
        t='r*';
        n=n+1;
    elseif n==5
        t='g*';
        n=n+1;
    elseif n==6
        t='b*';
        n=1;
    end    
        
    R=[c_nodex(i) c_nodey(i)];
    
    coor1=[nodex(1) nodey(1)]; % source node
    coor2=S; % nearest node from source node
    data_transfer(coor1,coor2,t)  % data transfer between source and its nearest node
    
    if S(1)==R(1) % source and sink are on same vertical line        
        [a,b]=transfer(S,R);
        for j=1:length(a)
            plot(a(j),b(j),t) 
            hold on
            pause(0.005)
        end
        continue
    end
    
    if S(2)==R(2) % source and sink are on same horizontal line
        [a,b]=transfer(S,R);
        for j=1:length(a)
            plot(a(j),b(j),t) 
            hold on
            pause(0.005)
        end
        continue
    end    

    % data transfer from nearest node from source to nearest node from sink
    coor1=S;
    coor2=[R(1) S(2)];
    data_transfer(coor1,coor2,t)
    coor1=[R(1) S(2)];
    coor2=R;
    data_transfer(coor1,coor2,t)
    
    % from closest node to sink node
    coor1=R;
    coor2=[nodex(i) nodey(i)];
    data_transfer(coor1,coor2,t)
end   
end

Code 4 – Function M File – info_path.m

function info_path(s1,S)

if S(1)>s1(1) % source is on the right side of sink 1
    for i=S(1):-1:s1(1)
        if i==s1(1)
            break
        end
        plot([i i-1],[S(2) S(2)],'r','LineWidth',2)
        pause(0.5)
    end
    
    if S(2)>s1(2) % source is above sink 1
        for i=S(2):-1:s1(2)
            if i==s1(2)
                break
            end
            plot([s1(1) s1(1)],[i i-1],'r','LineWidth',2)
            pause(0.5)
        end           
    elseif S(2)<s1(2) % source is below sink 1
        for i=S(2):s1(2)
            if i==s1(2)
                break
            end
            plot([s1(1) s1(1)],[i i+1],'r','LineWidth',2)
            pause(0.5)
        end        
    end   
elseif S(1)<s1(1) % source is on left side of sink 1
    for i=S(1):s1(1)
        if i==s1(1)
            break
        end
        plot([i i+1],[S(2) S(2)],'r','LineWidth',2)
        pause(0.5)
    end
    
    if S(2)>s1(2) % source is above sink 1
        for i=S(2):-1:s1(2)
            if i==s1(2)
                break
            end
            plot([s1(2) s1(2)],[i i-1],'r','LineWidth',2)
            pause(0.5)
        end        
    elseif S(2)<s1(2) % source is below sink 1
        for i=S(2):s1(2)
            if i==s1(2)
                break
            end
            plot([s1(2) s1(2)],[i i+1],'r','LineWidth',2)
            pause(0.5)
        end                
    end  
end

end

Code 5 – Function M File – grid_formation.m

function grid_formation

hold on
for i=0:10
    for j=0:10
        plot([i i],[0 10],'k--')
        plot([0 10],[j j],'k--')
    end
end

Code 6 – Function M File – energy_plot.m

function MAT=energy_plot(COOR,x,y,sn,MAT)

[r1 c1]=size(COOR);
[r2 c2]=size(x);
P=10; % percentage decrease in energy

for i=1:c1           
    for ii=1:r1
        coor=COOR{ii,i};
        if isempty(coor)
            continue
        else
            coor1=[coor(1) coor(2)];
            for j=1:r2
                for k=1:c2
                    if coor1(1)==x(j,k) && coor1(2)==y(j,k)
                        MAT(j,k)=MAT(j,k)-P;
                        if MAT(j,k)<0
                            MAT(j,k)=0;
                        end                        
                    end
                end
            end
        end
    end
end

MAT=fliplr(MAT);
MAT=flipud(MAT);

figure
title('Energy Distribution')
col=5*ceil(sn/30); %0-30sn=5col, 30-60sn=10col...
row=ceil(sn/col); 

plot(x,y,'go','LineWidth',3) % placing the sensor nodes at the grid intersection points
[r c]=size(x);
for i=1:r
    hold on
    plot([x(i) x(i,end)],[y(i) y(i,end)])    
end

for i=1:c
    plot([x(1,i) x(end,i)],[y(1,i) y(end,i)])
end    
axis([-5 ((col*4)+5) 0 ((row*4)+5)])

for i=1:r
    for j=1:c
        ii=r-(i-1);
        jj=c-(j-1);
        text(x(ii,jj)+0.4,y(ii,jj)+0.4,num2str(MAT(i,j)))
    end
end
        
end

Code 7 – Function M File – data_transfer.m

function data_transfer(coor1,coor2,t)

[a,b]=transfer(coor1,coor2);
for j=1:length(a)
    plot(a(j),b(j),t) 
    hold on
    pause(0.005)
end

end

Code 8 – Function M File – closest.m

function [V1,V2,V3]=closest(nodex,nodey,x,y)

[r c]=size(x);
V1=[];
V2=[]; % closest row
V3=[]; % closest coloumn
for i1=1:length(nodex)
    value=100;
    dis=[];
    for i2=1:r
        for i3=1:c
            dis(i2,i3)=sqrt((nodex(i1)-x(i2,i3))^2 + (nodey(i1)-y(i2,i3))^2);
            if dis(i2,i3)<value
                value=dis(i2,i3);
                value_r=i2;
                value_c=i3;
            end
                
        end
    end
    V1=[V1 value];
    V2=[V2 value_r];
    V3=[V3 value_c];
end

end

Code 9 – Function M File – check_direction.m

function op=check_direction(source,sink)

if source(1)<sink(1) % source is on left of sink
    if source(2)<sink(2) % source is below sink
        op=1; % source is south west of sink
    elseif source(2)>sink(2) % source is above sink
        op=2; % source is north west of sink
    end
elseif source(1)>sink(1) % source is on right of sink
    if source(2)<sink(2) % source is below sink
        op=3; % source is south east of sink
    elseif source(2)>sink(2) % source is above sink
        op=4; % source is north east of sink
    end
end    

end

Code 10 – Function M File – transfer.m

function [a,b]=transfer(sender,receiver)

dist=sqrt((sender(1)-receiver(1))^2+(sender(2)-receiver(2))^2);

if sender(1)<receiver(1)
    a=linspace(sender(1),receiver(1),round(dist*10));
else
    a=linspace(sender(1),receiver(1),round(dist*10));
end

if sender(2)<receiver(2)
    b=linspace(sender(2),receiver(2),round(dist*10));
else
    b=linspace(sender(2),receiver(2),round(dist*10));
end

end

Code 11 – Function M File – random_placement.m

function [nodex,nodey]=random_placement(sn,col,row)

low1=1;
high1=col*4;

low2=4;
high2=row*4;
 
nodex=[];
nodey=[];
for i=1:(2*sn)
    nodex=[nodex (low1+(high1-low1)*rand)];  %x coordinates of all the points
    nodey=[nodey (low2+(high2-low2)*rand)];  %y coordinates of all the points
end

end

Code 12 – Function M File – plotting.m

function plotting(COOR)

[r c]=size(COOR);
for i=1:c
    t='r*';
    % data fwd
    for j=1:r
        coor=COOR{j,i};
        if isempty(coor)
            continue
        else
            coor1=[coor(1) coor(2)];
            coor2=[coor(3) coor(4)];
            data_transfer(coor1,coor2,t)
        end
    end
    
    t='g*';
    % querry fwd
    for j=1:r
        coor=COOR{r-(j-1),i};
        if isempty(coor)
            continue
        else
            coor1=[coor(1) coor(2)];
            coor2=[coor(3) coor(4)];
            data_transfer(coor2,coor1,t)
        end
    end
    
    
end
end

Code 13 – Function M File – placing_sensors.m

function [nodex,nodey]=placing_sensors(sn,s,x,y,row,col,xdash,ydash)

% hold on
[rr cc]=size(x);

S=1; % number of sources

% lower and upper bounds for source and sink placement
lowx=min(min(x)); 
highx=max(max(x));
lowy=min(min(y));
highy=max(max(y));

% nodex- x coordinates of source and sinks
% nodey- y coordinates of source and sinks
a=randi(rr,1,1);
b=randi(cc,1,1);
% nodex=(lowx+(highx-lowx)*rand);  
% nodey=(lowy+(highy-lowy)*rand);  
nodex=x(a,b);
nodey=y(a,b);

for i=1:s
    nodex=[nodex (lowx+(highx-lowx)*rand)];
    nodey=[nodey (lowy+(highy-lowy)*rand)];
end

for i=1:(S+s)
    plot(nodex(i),nodey(i),'b*') % placing source and sinks
    if i==1
        text(nodex(i)+0.5,nodey(i),'Source','BackgroundColor','r') % marking the sources
    else
        text(nodex(i)+0.5,nodey(i),['Sink' num2str(i-1)],'BackgroundColor','y') % marking the sinks
    end
    hold on
end
axis([-5 ((col*4)+5) 0 ((row*4)+5)])
pause(2)
plot(x,y,'go','LineWidth',3) % placing the sensor nodes at the grid intersection points

[r,c]=size(xdash);
for i=1:r
    for j=1:c
        plot(xdash(i,j),ydash(i,j),'b*')
    end
end

x=fliplr(x);
x=flipud(x);
y=fliplr(y);
y=flipud(y);

for i=1:rr
    for j=1:cc
        if (i+1)<=rr
            plot([x(i,j) x(i+1,j)],[y(i,j) y(i+1,j)])
        end
        
        if (i-1)>=1
            plot([x(i,j) x(i-1,j)],[y(i,j) y(i-1,j)])
        end
        
        if (j+1)<=cc
            plot([x(i,j) x(i,j+1)],[y(i,j) y(i,j+1)])
        end
        
        if (j-1)>=1
            plot([x(i,j) x(i,j-1)],[y(i,j) y(i,j-1)])
        end
    end
end 
        
x=fliplr(x);
x=flipud(x);
y=fliplr(y);
y=flipud(y);

end

Code 14 – Function M File – new_cord.m

function [x,y]=new_cord(x,y,xdash,ydash,MAT)

x=fliplr(x);
x=flipud(x);
y=fliplr(y);
y=flipud(y);
    
[r,c]=size(MAT);
[r1,c1]=size(xdash);
for i=1:r
    for j=1:c
        if MAT(i,j)<=0
            point1=[x(i,j) y(i,j)];
            dist=[];
            is=[];
            js=[];
            for ii=1:r1
                for jj=1:c1
                    point2=[xdash(ii,jj) ydash(ii,jj)];
                    D=sqrt((point1(1)-point2(1))^2 + (point1(2)-point2(2))^2);
                    dist=[dist D];
                    is=[is ii];
                    js=[js jj];
                end
            end
            [mini,IX]=min(dist);
            x(i,j)=xdash(is(IX),js(IX));
            y(i,j)=ydash(is(IX),js(IX));
            MAT(i,j)=100;
        end
    end
end

x=fliplr(x);
x=flipud(x);
y=fliplr(y);
y=flipud(y);

end

Code 15 – Function M File – info_transfer_2.m

function COOR=info_transfer_2(nodex,nodey,x,y)
% nodex and nodey = coordinates of sources and sinks
% x and y = coordinates of placed sensors

% finding the closest node from source and sinks  
[V1,V2,V3]=closest(nodex,nodey,x,y);

pause(1)
for i=1:length(nodex)
    c_nodex(i)=x(V2(i),V3(i)); % x coordinates of closest node 
    c_nodey(i)=y(V2(i),V3(i)); % y coordinates of closest node 
end

% S=[c_nodex(1) c_nodey(1)]; % coordinates of closest node from source
COOR={};
for i=2:length(c_nodex)        
    R=[c_nodex(1) c_nodey(1)]; % coordinates of closest node from source
    S=[c_nodex(i) c_nodey(i)];
    
    % data transfer between source and its nearest node    
    coor1=[nodex(i) nodey(i)]; % source
    coor2=S; % nearest node from source
    q=1;
    COOR{q,i-1}=[coor1 coor2];    

    [r c]=size(x);
    if S(1)==R(1) % source and sink are on same vertical line 
        % from closest node to sink closest node
        placing2=[V2(1) V3(1)]; % source indexing in matrix x and y
        placing1=[V2(i) V3(i)]; % sink indexing in matrix x and y        
        if placing1(1)>placing2(1) %source is above sink
            coor1=[x(placing1(1),placing1(2)) y(placing1(1),placing1(2))];
            N=0;
            while(1)                
                coor2=[x((placing2(1)-N),placing2(2)) y((placing2(1)-N),placing2(2))];                
                q=q+1;
                COOR{q,i-1}=[coor1 coor2];                            
                if coor2(1)==R(1) && coor2(2)==R(2)
                    break
                end
                coor1=coor2;
                N=N+1;
            end
        elseif placing1(1)<placing2(1) %source is below sink
            coor1=[x(placing1(1),placing1(2)) y(placing1(1),placing1(2))];
            N=0;
            while(1)                
                coor2=[x((placing1(1)+N),(placing1(2))) y((placing1(1)+N),placing1(2))];                
                q=q+1;
                COOR{q,i-1}=[coor1 coor2];                            
                if coor2(1)==R(1) && coor2(2)==R(2)
                    break
                end
                coor1=coor2;
                N=N+1;
            end
        end           

        % from closest node to source node
        coor1=R;
        coor2=[nodex(1) nodey(1)];
        q=q+1;
        COOR{q,i-1}=[coor1 coor2];
        continue
    end
%     pause
    
    if S(2)==R(2) % source and sink are on same horizontal line        
%         % from closest node to sink node
        placing2=[V2(1) V3(1)]; % source indexing in matrix x and y
        placing1=[V2(i) V3(i)]; % sink indexing in matrix x and y        
        if placing1(2)>placing2(2) %source is right of sink
            coor1=[x(placing1(1),placing1(2)) y(placing1(1),placing1(2))];
            N=0;
            while(1)                
                coor2=[x(placing2(1),(placing2(2)-N)) y(placing2(1),(placing2(2)-N))];                
                q=q+1;
                COOR{q,i-1}=[coor1 coor2];                            
                if coor2(1)==R(1) && coor2(2)==R(2)
                    break
                end
                coor1=coor2;
                N=N+1;
            end
        elseif placing1(2)<placing2(2) %source is left of sink
            coor1=[x(placing1(1),placing1(2)) y(placing1(1),placing1(2))];
            N=0;
            while(1)                
                coor2=[x(placing1(1),(placing1(2)+N)) y(placing1(1),(placing1(2)+N))];
                q=q+1;
                COOR{q,i-1}=[coor1 coor2];                            
                if coor2(1)==R(1) && coor2(2)==R(2)
                    break
                end
                coor1=coor2;
                N=N+1;
            end
        end           
        
        % from closest node to source node
        coor1=R;
        coor2=[nodex(1) nodey(1)];
        q=q+1;
        COOR{q,i-1}=[coor1 coor2];
        continue
    end        
%     pause

    op=check_direction(S,R);    
    coor1=S;
    [r c]=size(x);    
    while(1)
        for ii=1:r
            for jj=1:c
                if coor1(1)==x(ii,jj) && coor1(2)==y(ii,jj)
                    placing=[ii jj];
                end
            end
        end
        
        if op==1            
            coor2=[x(placing(1)+1,placing(2)+1) y(placing(1)+1,placing(2)+1)];
        elseif op==2            
            coor2=[x(placing(1)-1,placing(2)+1) y(placing(1)-1,placing(2)+1)];
        elseif op==3            
            coor2=[x(placing(1)+1,placing(2)-1) y(placing(1)+1,placing(2)-1)];
        elseif op==4            
            coor2=[x(placing(1)-1,placing(2)-1) y(placing(1)-1,placing(2)-1)];
        end
                    
        if coor2(1)==R(1) || coor2(2)==R(2)
            q=q+1;
            COOR{q,i-1}=[coor1 coor2];
            break
        else
            q=q+1;
            COOR{q,i-1}=[coor1 coor2];
            coor1=coor2;
        end    
    end
    
    coor1=coor2;
    coor2=R;
    q=q+1;
    COOR{q,i-1}=[coor1 coor2];
    
    % from closest node to sink node
    coor1=R;
    coor2=[nodex(1) nodey(1)];
    q=q+1;
    COOR{q,i-1}=[coor1 coor2];
end   
 
end                  
%     if q==1
%         t='y*';
%         q=q+1;
%     elseif q==2
%         t='m*';
%         q=q+1;
%     elseif q==3
%         t='c*';
%         q=q+1;
%     elseif q==4
%         t='r*';
%         q=q+1;
%     elseif q==5
%         t='g*';
%         q=q+1;
%     elseif q==6
%         t='b*';
%         q=1;
%     end    

 

Dynamic faults detection in Mobile Ad-hoc Network

PROJECT VIDEO

ABSTRACT

Mobile Ad-Hoc Networks (MANETs) are set of mobile nodes that communicates wirelessly without a centralized supporting system. Faulty nodes a ect the reliable transmission of messages across the network. In this thesis we deal with the fault identi cation problem in static topology MANETs. A comparison based approach is used where a set of tasks is given to the nodes and outcomes are compared. Based on these comparisons the nodes are classi ed either as faulty or fault free. Our new diagnosis model is based on the spanning tree concept in which the testing of the nodes as well as the construction of the spanning tree takes place simultaneously. As a result of which the maintenance and the repairing overhead of the spanning tree is completely avoided thus reducing the number of messages exchanged. We have also developed a simulator which can be applied to a network with large number of nodes. We have carried out the simulation in-order to nd out the total number of messages exchanged and the total diagnosis time. On analysing the results we have seen that our model performs better than its previous counterparts. The correctness and complexity proofs are also being provided which also shows that our model performs better from a communication as well as latency viewpoint.

INTRODUCTION

Since the early 1980s wireless cellular systems are quite popular. These cellular systems mainly operate with the help of a centralised supporting system, otherwise known as the access point. It is this access point that helps the users to stay connected in the network. But when it comes to places where there is no xed access point, this technology has own its limitations. In case of rescue and emergency operations installing a centralised supporting system is time consuming. So in-order to overcome this problem we have mobile ad-hoc networks which can be quickly deployed in places where it is not possible otherwise. MANETs are basically a collection of mobile nodes that communicate wirelessly.

MANETs

Mobile Ad-Hoc Networks(MANETs) are basically a collection of mobile nodes that communicate wirelessly without any centralised supporting system. Here the users or nodes are free to roam within the transmission range. Mobile ad-hoc networks (MANET) are gaining much popularity in various rescue and emergency operations because of its self-organizable, autonomous and can-be-deployed-anywhere type of characteristics. Nodes in MANER are equipped with a receiver and a transmitter.

FAULT DIAGNOSIS

As MANETs are mainly used in rescue and emergency operations, having a reliable communication between the mobiles is of utmost importance. Hence the design of dependable MANETs is gaining popularity among the research communities. But the main problem in designing of dependable MANETs is the distributed self-diagnosis problem. Here each fault free mobile has to keep information regarding the state of all the nodes in the neighborhood or in some applications each node should be able to identify the state of all the nodes in the network [1]. Many elegant distributed diagnosis algorithms are available for wired networks and most of them are based either on the invalidation models such as PMC model [2] or comparison model such as the broadcast comparison model [3] and the generalized comparison model [4]. The comparison approach is the most popular diagnosis approach. Here the nodes are given a set of tasks, the tasks are then executed and the outcomes are compared. The comparison outcomes output by the generalized comparison model is summarized below. The comparison outcome is 0, when both the comparator and the compared mobiles are fault-free. If at least one of the compared mobiles is faulty and the comparator is fault-free, the comparison outcome is 1. Finally, the comparison result is unreliable if the comparator mobile is faulty[1]. The earliest works of fault diagnosis in case of MANETs using the comparison approach was proposed by Chessa and Santi in [5]. They have used the shared nature of the communication channel to distribute the diagnosis. In [5], Chessa and Santi have presented with a distributed diagnosis algorithm that allows the fault free mobiles to know the fault status of all the mobiles in the network. The most recent work to solve the diagnosis problem is presented in [1]. In [1] an adaptive distributed self-diagnosis protocol (Adaptive-DSDP) is proposed to solve the diagnosis problem in xed-topology MANETs. In case of xed-topology MANETs it is assumed that the topology of the network is xed during the diagnosis session. This model uses a spanning tree containing all the fault-free nodes which is maintained, repaired and used to transmit the information about other nodes. In this report we have proposed a new diagnosis model based on the spanning tree concept in which the testing of the nodes as well as the construction of the spanning tree takes place simultaneously. Here the test request message helps in the construction of the spanning tree. As a result the overhead of maintaining and repairing of the spanning is completely is avoided, thus improving the time as well as the message complexity.

MOTIVATION

We have analysed the Adaptive-DSDP model and have found that there is an overhead of spanning tree maintenance which occurs all the time even if there is no diagnosis session running. Also the spanning tree is maintained with a particular node as its root i.e. the initiator is xed. So if the initiator node fails or any other node detects an altered behavior the diagnosis session will not start. Further the spanning tree repairing starts after the testing and gathering phase which increases the diagnosis latency as well as the communication complexity. Spanning tree maintenance and repairing consumes a lot of time, so constructing it in the testing and the gathering phase itself will be more efficient.

CONCLUSION

The earliest work on fault identi cation in case of mobile ad-hoc networks was carried out by Chessa and Santi in there work in [5]. There model, known as Static-DSDP, considers a comparison based approach and the network topology is assumed to be xed during the diagnosis session. Such type of network is known as xed topology network. Another work in case of xed topology MANETs was carried out by Elhadef et all. in [6]. The model also known as Dynamic-DSDP uses a spanning tree approach to disseminate the local diagnostic messages collected during the testing phase. Here the spanning tree is constructed after the fault status of the nodes has been identi ed.
Adaptive-DSDP [1] also considers a xed topology environment and a spanning tree approach which is a improvement over the Dynamic-DSDP model. In case of Adaptive-DSDP the spanning tree is initially con gured with the MANET and the protocol enables the maintenance as well as the recon guration of the spanning tree while the hosts are moving or they are diagnosed by their neighbor. In this thesis we have proposed a new model for xed topology environment. A spanning tree approach has also been considered here. In this model the testing of the nodes, gathering of information about neighbors and building of the spanning tree takes place simultaneously. As a result of which the maintenance and the repairing overhead of the spanning tree is completely avoided thus reducing the number of messages exchanged. We have also developed a simulator which can be applied to a network with large number of nodes. We have carried out the simulation in-order to nd out the total number of messages exchanged and the total diagnosis time. On analysing the results we have seen that our model performs better than its previous counterparts. The correctness and complexity proofs are also being provided. From the message and time complexity thus derived we see that our model performs better from a communication as well as latency viewpoint.

FUTURE WORK

The model we have proposed is for a xed topology MANET. Moreover this model identi es only the permanent faults. In future it is possible to extend this model for dynamic topology MANETs and for identifying intermittent as well as dynamic faults. One of the approach for identifying intermittent faults is to repeat our proposed algorithm for a xed number of times.

MATLAB SOURCE CODE

Instructions to run the code

1- Copy each of below codes in different M files.
2- Place all the files in same folder

3- Use the files from below link and download them into the same folder as the source codes

fault diagnosis timing

4- Also note that these codes are not in a particular order. Copy them all and then run the program.
5- Run the “FINAL.m” file

Code 1 – Script M File – FINAL.m

clc
clear
close all
%sn=50;
sn=input('Please enter the number of mobiles: '); %total number of mobile nodes
while isempty(sn) || ~isnumeric(sn) %loop for getting a valid number of mobile nodes
    sn=input('Please enter the number of mobiles: ');
end

% placing the sensors in the network
figure(1) 
[nodex,nodey,avg]=placing_sensors(sn); 
%avg
title('Ideal placement of the mobiles')
disp('Press enter to continue')
pause

%faulty nodes
figure(2)
[fnodex,fnodey,fni,l]=faulty_nodes(nodex,nodey,sn);
title('Mobile nodes with faulty points (red-permanent faults, black-transient faults, green-intermittent)')
%title('Flooding Process')
disp('Press enter to continue')
pause

%information transfer
[sender,receiver,s_coor,r_coor,opt]=getsensorinfo(sn,fni,nodex,nodey);
if opt==1 || opt==2 %case when either sender or receiver is out of bound
    figure(3)
    for i=1:sn
        plot(nodex(i),nodey(i),'b*') % plotting all the mobiles
        text(nodex(i)+0.05,nodey(i),num2str(i))
        hold on
    end
    %plot(s_coor(1),s_coor(2),'m*','LineWidth',3)
    text(s_coor(1)+0.5,s_coor(2),'\leftarrow Faulty Node','FontSize',12,'FontWeight','bold')
    
% elseif opt==2
%     figure(3)
%     for i=1:sn
%         plot(nodex(i),nodey(i),'b*') % plotting all the mobiles
%         text(nodex(i)+0.05,nodey(i),num2str(i))
%         hold on
%     end
%     %plot(d_coor(1),d_coor(2),'m*','LineWidth',3)
%     text(d_coor(1)+0.5,d_coor(2),'\leftarrow Faulty Node','FontSize',12,'FontWeight','bold')
    
elseif opt==0 %case when both sender and reciever are inbound
    figure(3)
%    subplot(2,1,1)    
    for i=1:length(nodex) %placement of nodes
        plot(nodex(i),nodey(i),'*')
        text(nodex(i)+0.05,nodey(i),num2str(i)) %numbering
        hold on
    end
    plot(s_coor(1),s_coor(2),'c*')
    text(s_coor(1)+0.05,s_coor(2),'\leftarrow Sender') %marking the sender
    plot(r_coor(1),r_coor(2),'c*')
    text(r_coor(1)+0.05,r_coor(2),'\leftarrow Receiver') %marking the reciever
%    [total1,good1,bad1,diag]=witherror(s_coor,r_coor,nodex,nodey,fnodex,fnodey,l); %subplot 1 for the scenario with errors
    [total1]=witherror(s_coor,r_coor,nodex,nodey,fnodex,fnodey,l,avg,fni,sender,receiver);
    title('Scenario with error detection')

%    subplot(2,1,2)    
    figure(4)
    for i=1:length(nodex)
        plot(nodex(i),nodey(i),'*') %placement of nodes
        text(nodex(i)+0.05,nodey(i),num2str(i)) %numbering
        hold on
    end
    plot(s_coor(1),s_coor(2),'c*')
    text(s_coor(1)+0.05,s_coor(2),'\leftarrow Sender') %marking the sender
    plot(r_coor(1),r_coor(2),'c*')
    text(r_coor(1)+0.05,r_coor(2),'\leftarrow Receiver') %marking the receiver
    [total2]=withouterror(s_coor,r_coor,nodex,nodey,fnodex,fnodey,l,avg,fni,sender,receiver); %subplot 2 for the scenario without errors
    title('Scenario without errors')
% 
%     %graphs
%     %graphs(good1,bad1,total1,total2,sn,nodex,nodey,diag)
% total1
% total2
    graphs(total1,total2,sn,nodex,nodey,fnodex,fnodey,fni)
end

Code 2 – Function M File -graphs.m

function graphs(total1,total2,sn,nodex,nodey,fnodex,fnodey,fni)

[r3 c3]=size(total1);
[r4 c4]=size(total2);

% total1
% total2

[num,txt,raw]=xlsread('fault diagnosis timing');
[row col]=size(num);
blank_mat=[];
for i=1:row
    blank_mat(i,:)= zeros(1,col);
end
xlswrite('fault diagnosis timing',blank_mat,1,'A4')

total1_ind=[];
total2_ind=[];

for i=1:r4 %finding the ids of the scenario with no errors
    for j=1:length(nodex)
        if total2(i,1)==nodex(j) && total2(i,2)==nodey(j)
            total2_ind=[total2_ind j];
        end        
    end
end      

for i=1:r3 %finding the ids of the scenario with errors
    for j=1:length(nodex)
        if total1(i,1)==nodex(j) && total1(i,2)==nodey(j)
            total1_ind=[total1_ind j];
        end        
    end
end      

t=[]; %diagnosable nodes
p=[]; %non diagnosable nodes
g=[]; %good nodes
len=length(fnodex);
for i=1:length(total1_ind)
    op=0; %if its 0, then its a good node. else bad node
    for j=1:length(fni)
        if total1_ind(i)==fni(j)
            if j>=ceil(len/4)+1 && j<=ceil(len/2)
                t=[t total1_ind(i)];
                op=1;                 
                break
            else
                p=[p total1_ind(i)];
                op=1;
                break
            end
        end
    end
    
    if op~=1
        g=[g total1_ind(i)];
    end
end
    
from=[];
to=[];
for i=1:length(total1_ind)    
    op=0;
    if i==1
        %first will always come in "from"
        from=[from total1_ind(i)];
        continue
    elseif i==length(total1_ind)        
        %last will always come in "to"
        to=[to total1_ind(i)];
        break
    end    
          
    for j=1:length(g) %cheking for good nodes
        if total1_ind(i)==g(j)
            to=[to total1_ind(i)];
            from=[from total1_ind(i)];
            op=1;
            break
        end
    end
    if op==1
        continue
    end
       
    for j=1:length(t) %checking for diagnosable nodes
        if total1_ind(i)==t(j)
            to=[to total1_ind(i)];
            from=[from total1_ind(i)];
            op=1;
            break
        end
    end
    if op==1
        continue
    end
    
    for j=1:length(p) %checking for permanent nodes
        if total1_ind(i)==p(j)
            to=[to total1_ind(i)];
            from=[from from(length(from))];
            op=1;
            break
        end
    end
    if op==1;
        continue
    end
end
    
ack_sent=[]; %time to send the acknowledgement
for i=1:length(from)
    dist=sqrt((nodex(from(i))-nodex(to(i)))^2+(nodey(from(i))-nodey(to(i)))^2); % distance between the nodes
    ack_sent=[ack_sent dist];
end

ack_rec=ack_sent; %time to receive the acknowledgement
l=length(fni);
permanent=fni([1:ceil(l/4) (ceil(l/2)+1):l]); %indexes without transient fault
diagnosable=fni(ceil(l/4)+1:ceil(l/2)); %indexes of transient fault
ind=1;
for i=to
    for j=permanent
        if i==j
            ack_rec(ind)=0;
        end
    end
    
    for k=diagnosable
        if i==k
            a=ack_rec(ind);
            b=ack_rec(ind)+4;
            time= a + (b-a).*rand(1,1);
            ack_rec(ind)=ack_rec(ind)+time;
        end
    end
    ind=ind+1;
end

xlswrite('fault diagnosis timing',from',1,'A4')
xlswrite('fault diagnosis timing',to',1,'B4')
xlswrite('fault diagnosis timing',ack_sent',1,'C4')
xlswrite('fault diagnosis timing',ack_rec',1,'D4')
xlswrite('fault diagnosis timing',total2_ind(1:end-1)',1,'F4') %"from" nodes in without error senario
xlswrite('fault diagnosis timing',total2_ind(2:end)',1,'G4') %"to" nodes in without error senario
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
oneunit=(1/sn)*100; % 1 unit of energy
Eg=(r3/sn)*100; % energy lost in good nodes
Eb=(r4/sn)*100; % energy lost in bad nodes

x1=[];
for i=1:length(from)
    x=100-oneunit*i;
    x1=[x1 x]; %nodewise energy loss in scenario with error nodes
end

x2=[];
for i=1:length(total2_ind(1:end-1))
    x=100-oneunit*i;
    x2=[x2 x]; %nodewise energy loss in scenario without error nodes
end

figure(5)
subplot(2,1,1)
bar(x1)
set(gca,'XTickLabel',{from})
ylabel('Energy')
xlabel('Nodes')
title('Scenario with error nodes')

subplot(2,1,2)
bar(x2)
set(gca,'XTickLabel',{total2_ind(1:end-1)})
xlabel('Nodes')
ylabel('Energy')
title('Scenario without error nodes')

%%------------- Data loss Graph --------------
lenth = length(x1);
for i = 1:lenth
b(i) = x1(lenth);
lenth = lenth-1;
end
x1_1 = b;

lenth1 = length(x2);
for i = 1:lenth1
b(i) = x2(lenth1);
lenth1 = lenth1-1;
end
x2_1 = b;

figure(6)
subplot(2,1,1)
grid on
plot(x1_1,'g','linewidth',2)
hold on
plot(x1_1,'ok','linewidth',3)
set(gca,'XTickLabel',{from})
title('DATA LOSS in Scenario with error nodes')

subplot(2,1,2)
grid on
plot(x2_1,'c','linewidth',2)
hold on
plot(x2_1,'or','linewidth',3)
set(gca,'XTickLabel',{total2_ind(1:end-1)})
title('DATA LOSS in Scenario without error nodes')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% delay graph
figure(7)
subplot(2,1,1)
plot(1:r3)
grid on
axis([0 r3+2 0 r3+2])
set(gca,'XTickLabel',{from})
title('Delay in scenario with errors')
xlabel('Serial Number of Nodes in path')
ylabel('Delay (sec)')

subplot(2,1,2)
plot(1:r4)
grid on
axis([0 r3+2 0 r3+2])
set(gca,'XTickLabel',{total2_ind(1:end-1)})
title('Delay in scenario without errors')
xlabel('Serial Number of Nodes in path')
ylabel('Delay (sec)')


Code 3 – Function M File – faulty_nodes.m

function [fnodex,fnodey,fni,l]=faulty_nodes(nodex,nodey,sn)

p=40; %percentage of faulty nodes out of the total number of nodes
fn=floor((p*sn)/100); %number of total faulty nodes (fn-faulty nodes)

fni=randi(sn,1,fn); %indexes of faulty nodes in nodex and nodey (fni-faulty nodes index)

fnodex=[];
fnodey=[];
for i=fni
    fnodex=[fnodex nodex(i)]; % assigning the x coordinates to faulty nodes (assignment is done using the previously assigned x nodes)
    fnodey=[fnodey nodey(i)]; % assigning the y coordiantes to faulty nodes (assignment is done using the previously assigned y nodes)
end

l=length(fni); % total number of faulty nodes 'l'

pfx=[fnodex(1:ceil(l/4))]; %permanent faults
pfy=[fnodey(1:ceil(l/4))];
%ceil(fni/4)

tfx=[fnodex((ceil(l/4)+1):ceil(l/2))]; %transient faults
tfy=[fnodey((ceil(l/4)+1):ceil(l/2))];
% (ceil(fni/4)+1)
% ceil(fni/2)

ifx=[fnodex((ceil(l/2)+1):ceil((3*l)/4))]; %intermittent fault
ify=[fnodey((ceil(l/2)+1):ceil((3*l)/4))];
% (ceil(fni/2)+1)
% ceil((3*fni)/4)

dfx=[fnodex((ceil((3*l)/4)+1):l)]; %dynamic faults
dfy=[fnodey((ceil((3*l)/4)+1):l)];
% (ceil((3*fni)/4)+1)

for i=1:sn
    plot(nodex(i),nodey(i),'b*') % plotting all the mobiles
    text(nodex(i)+0.05,nodey(i),num2str(i))
    hold on
end

%flooding process starts %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[num,txt,raw]=xlsread('static faults');
[row col]=size(num);
blank_mat=[];
for i=1:row
    blank_mat(i,:)= zeros(1,col);
end
xlswrite('static faults',blank_mat,1,'A5')

x=1; %initialize the index of master node
for i=1:sn    
    for j=1:length(fni)
        if i~=fni(j)
            x=i; % master node index which is fault free
            break
        end
    end
    if x==i
        break
    end
end            

pause(0.5)
plot(nodex(x),nodey(x),'b*','LineWidth',5)
text(nodex(x)+0.05,nodey(x),'\leftarrow Master Node','FontSize',15,'FontWeight','bold')
pause(0.5)
for i=1:sn
    plot([nodex(x) nodex(i)],[nodey(x) nodey(i)])
end
pause(0.5)
for i=1:sn
    plot([nodex(x) nodex(i)],[nodey(x) nodey(i)],'w')
end
pause(0.5)
for i=1:sn
    plot([nodex(x) nodex(i)],[nodey(x) nodey(i)])
end
pause(0.5)
for i=1:sn
    plot([nodex(x) nodex(i)],[nodey(x) nodey(i)],'w')
end
for i=1:sn
    plot([nodex(x) nodex(i)],[nodey(x) nodey(i)])
end
pause(0.5)
for i=1:sn
    plot([nodex(x) nodex(i)],[nodey(x) nodey(i)],'w')
end

time=[];
for i=[1:(x-1) (x+1):sn]
    dist=sqrt((nodex(x)-nodex(i))^2+(nodey(x)-nodey(i))^2);
    time=[time; dist]; % calculating the distances of each node from master node
end

xlswrite('static faults',[1:(x-1) (x+1):sn]',1,'A5')
xlswrite('static faults',time,1,'B5')
xlswrite('static faults',time,1,'C5')

ind=1;
for i=[1:(x-1) (x+1):sn] %excluding the master node here
    for j=[fni(1:(l/2))] %these excludes the dynamic faults, they are not yet discovered. also excludes intermittent faults
        if i==j
            time(ind)=0;
            break
        end
    end
    
    for j=[fni((ceil(l/2)+1):ceil((3*l)/4))]
        if i==j
            a=time(ind);
            b=time(ind)+5; 
            X= a + (b-a).*rand(1,1);
            time(ind)=time(ind)+X;
            break
        end
    end    
    ind=ind+1;
end
xlswrite('static faults',time,1,'D5')
%flooding process ends %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

plot(pfx,pfy,'ro','LineWidth',3) %displaying the permanent faults
plot(tfx,tfy,'ko','LineWidth',3) %displaying the transient faults
plot(ifx,ify,'go','LineWidth',3) %displaying the intermittent faults
%plot(dfx,dfy,'mo','LineWidth',3) %displaying the dynamic faults
%legend('r* Permanent','k* Transient','g* Intermittent','m* Dynamic','Location','NorthEastOutside')

%line 98-102 for the erased nodes during flooding
for i=1:sn
    plot(nodex(i),nodey(i),'b*') % plotting all the mobiles
    text(nodex(i)+0.05,nodey(i),num2str(i))
    hold on
end

end

Code 4 – Function M File – check_nn2.m

function [coor2]=check_nn2(nn,fnodex,fnodey,len,nodex,nodey,coor1)

i=1;
while i>=1
    [r1 c1]=size(nn);
    if i>r1
        x=randi(4);
        switch x
            case 1
                [leftnodesx,leftnodesy]=nodes_left(coor1,nodex,nodey);
                searchx=leftnodesx;
                searchy=leftnodesy;
            case 2
                [upnodesx,upnodesy]=nodes_up(nodex,nodey,coor1);
                searchx=upnodesx;
                searchy=upnodesy;
            case 3
                [downnodesx,downnodesy]=nodes_down(nodex,nodey,coor1);
                searchx=downnodesx;
                searchy=downnodesy;
            case 4
                [rightnodesx,rightnodesy]=nodes_right(coor1,nodex,nodey);
                searchx=rightnodesx;
                searchy=rightnodesy;
            otherwise
                disp('wrong')
        end        
        [nn]=nearest_node(searchx,searchy,coor1);
        i=1;
    end 
% i=1;
% while i>=1    
    for j=1:length(fnodex)
        if nn(i,1)==fnodex(j) && nn(i,2)==fnodey(j)        
%             bad=[bad; fnodex(j) fnodey(j)];
%             total=[total; fnodex(j) fnodey(j)];
            i=i+1;
            coor2=[];
            break
        else
            coor2=[nn(i,1) nn(i,2)];
        end
    end
    
    if ~isempty(coor2)        
        break
    end
end

end

Code 5 – Function M File – nearest_node.m

%function [coor2_1,coor2_2,coor2_3,coor2_4,coor2_5]=nearest_node(nodesx,nodesy,coor1,savenodes)
function [nn]=nearest_node(nodesx,nodesy,coor1)
distance=[];
nn=[];
%[rs cs]=size(savenodes);
% for i=1:length(nodesx)
%     for j=1:rs
%         if nodesx(i)~=savenodes(j,1) && nodesy(i)~=savenodes(j,2)
%             remnodesx=[remnodesx nodesx(i)];
%             remnodesy=[remnodesy nodesy(i)];
%         end
%     end
% end

for i=1:length(nodesx)
    dist=sqrt( ((coor1(1)-nodesx(i))^2) + ((coor1(2)-nodesy(i))^2) );
    distance=[distance dist];
end

[b,ix]=sort(distance); 

for i=ix
    nn=[nn; nodesx(i) nodesy(i)];
end


% [r1 c1]=size(nn);
% [r2 c2]=size(used_nodes);
% for i=1:r1
%     for j=1:r2
%         if nn(i,1)==used_nodes(j,1) && nn(i,2)==used_nodes(j,2)
%             nn(i,:)=[];
%         end
%     end
% end

% if nargout==0
%     coor2_1=coor1;
%     coor2_2=coor1;
%     coor2_3=coor1;
%     coor2_4=coor1;
%     coor2_5=coor1;
% end

end

Code 6 – Function M File – blinking_line.m

function blinking_line(coor1,coor2)
%disp('BLINKING LINE')
for iiii=1:3   
        abc=plot([coor1(1) coor2(1)],[coor1(2) coor2(2)]);
        pause(0.3)
        delete(abc)
        pause(0.3)
        abc=plot([coor1(1) coor2(1)],[coor1(2) coor2(2)]);
        pause(0.3)
        delete(abc)
        pause(0.3)
%        abc=plot([coor1(1) coor2(1)],[coor1(2) coor2(2)]);
end
    
end

Code 7 – Function M File – bestmatch.m

function bestmatch(iii,coor1,coor2,fnodex,fnodey,l)
% coor1
% coor2
% pause
if iii>=1 && iii<=ceil(l/4)
    hold on
    blinking_line(coor1,coor2) %%%%%%%%%%% NOT WORKING %%%%%%%%%%%
    plot([coor1(1) fnodex(iii)],[coor1(2) fnodey(iii)],'r','LineWidth',2) %%%%%%%%%%% NOT WORKING %%%%%%%%%%%
    plot(fnodex(iii),fnodey(iii),'r*','LineWidth',2)
    text(fnodex(iii)+0.05,fnodey(iii),'\leftarrow Permanent Error')
elseif iii>=(ceil(l/2)+1) && iii<=ceil((3*l)/4)
    hold on
    blinking_line(coor1,coor2)  %%%%%%%%%%% NOT WORKING %%%%%%%%%%%
    plot([coor1(1) fnodex(iii)],[coor1(2) fnodey(iii)],'g','LineWidth',2) %%%%%%%%%%% NOT WORKING %%%%%%%%%%%
    plot(fnodex(iii),fnodey(iii),'g*','LineWidth',2)
    text(fnodex(iii)+0.05,fnodey(iii),'\leftarrow Intermittent Error')
elseif iii>=(ceil((3*l)/4)+1) && iii<=l
    hold on
    blinking_line(coor1,coor2)  %%%%%%%%%%% NOT WORKING %%%%%%%%%%%
    plot([coor1(1) fnodex(iii)],[coor1(2) fnodey(iii)],'m','LineWidth',2)  %%%%%%%%%%% NOT WORKING %%%%%%%%%%%
    plot(fnodex(iii),fnodey(iii),'m*','LineWidth',2)
    text(fnodex(iii)+0.05,fnodey(iii),'\leftarrow Dynamic Error')
end

end

Code 8 – Function M File – infotransfer1.m

function nn=infotransfer1(coor1,r_coor,nodex,nodey,total)

hori=coor1(1)-r_coor(1); 
vert=coor1(2)-r_coor(2); 

if abs(hori)>abs(vert)
    
    
elseif abs(hori)<abs(vert)
    
end

Code 9 – Function M File – nodes_down.m

function [downnodesx,downnodesy]=nodes_down(nodesx,nodesy,coor1,r_coor)

downnodesx=[];
downnodesy=[];
%downnodes_index=[];

for i=1:length(nodesx)
    if nodesy(i)<coor1(2) && nodesy(i)>=r_coor(2)
        downnodesx=[downnodesx nodesx(i)];            
        downnodesy=[downnodesy nodesy(i)];
        
%        downnodes_index=[downnodes_index i]; % index of nodex and nodey for upnodesx and upnodesy
    end
end



end

Code 10 – Function M File – nodes_left.m

function [leftnodesx,leftnodesy]=nodes_left(coor1,nodex,nodey,r_coor)

leftnodesx=[];
leftnodesy=[];
%leftnodes_index=[];

for i=1:length(nodex)
    if nodex(i)<coor1(1) && nodex(i)>=r_coor(1)
        leftnodesx=[leftnodesx nodex(i)];            
        leftnodesy=[leftnodesy nodey(i)];
        
 %       leftnodes_index=[leftnodes_index i]; % index of nodex and nodey for leftnodex and leftnodey
    end
end

end

Code 11 – Function M File – nodes_right.m

function [rightnodesx,rightnodesy]=nodes_right(coor1,nodex,nodey,r_coor)

rightnodesx=[];
rightnodesy=[];
%rightnodes_index=[];

for i=1:length(nodex)
    if nodex(i)>coor1(1) && nodex(i)<=r_coor(1)
        rightnodesx=[rightnodesx nodex(i)];            
        rightnodesy=[rightnodesy nodey(i)];
        
%        rightnodes_index=[rightnodes_index i]; % index of nodex and nodey for leftnodex and leftnodey
    end
end

end

Code 12 – Function M File – nodes_up.m

function [upnodesx,upnodesy]=nodes_up(nodesx,nodesy,coor1,r_coor)

upnodesx=[];
upnodesy=[];
%upnodes_index=[];

for i=1:length(nodesx)
    if nodesy(i)>coor1(2) && nodesy(i)<=r_coor(2)
        upnodesx=[upnodesx nodesx(i)];            
        upnodesy=[upnodesy nodesy(i)];
        
 %       upnodes_index=[upnodes_index i]; % index of nodex and nodey for upnodesx and upnodesy
    end
end

end

Code 13 – Function M File – getsensorinfo.m

function [sender,receiver,s_coor,r_coor,opt]=getsensorinfo(sn,fni,nodex,nodey)

opt=0;
sender=input('Enter the sender node ID: '); %sender node ID
while isempty(sender) || sender>sn  %getting a valid value
    sender=input('Enter the sender node ID: ');
end

for i=fni
    if sender==i;
%        error('The sender is a faulty node')                
        opt=1; %when sender is out bound
    end
end

receiver=input('Enter the receiver node ID: '); %reciever node ID
while isempty(receiver) || receiver>sn  %getting a valid value
    receiver=input('Enter the receiver node ID: ');
end

for i=fni
    if receiver==i;
        %error('The receiver is a faulty node')                
        opt=2; %when reciever is out bound
    end
end

s_coor=[nodex(sender) nodey(sender)]; %sender coordinates
r_coor=[nodex(receiver) nodey(receiver)]; %receiver coordinates

end

Code 14 – Function M File – infotransfer.m

function nn=infotransfer(coor1,r_coor,nodex,nodey,total)

hori=coor1(1)-r_coor(1); %horizontal distance between "coor1" and "r_coor"
vert=coor1(2)-r_coor(2); %vertical distance between "coor1" and "r_coor"
% searchnodesx1=[];
% searchnodesy1=[];
if abs(hori)>abs(vert) %if hosirzontal distance is greater then vertical distance
    % search horizontally 
    if coor1(1)>r_coor(1) % search in left direction    
        [leftnodesx,leftnodesy]=nodes_left(coor1,nodex,nodey,r_coor); %set of nearest nodes in left direction till "r_coor"       
        
%         for i=1:length(leftnodesx)
%             if r_coor(1)<leftnodesx(i)
%                 searchnodesx1=[searchnodesx1; leftnodesx(i)];
%                 searchnodesy1=[searchnodesy1; leftnodesy(i)];
%             end
%         end
                
        if coor1(2)<r_coor(2) %search in upwards direction
            [upnodesx,upnodesy]=nodes_up(leftnodesx,leftnodesy,coor1,r_coor);
            searchnodesx=upnodesx;
            searchnodesy=upnodesy;
        elseif coor1(2)>r_coor(2) %search in downwards direction
            [downnodesx,downnodesy]=nodes_down(leftnodesx,leftnodesy,coor1,r_coor);
            searchnodesx=downnodesx;
            searchnodesy=downnodesy;
        end                 
    elseif coor1(1)<r_coor(1) % search in right direction
        [rightnodesx,rightnodesy]=nodes_right(coor1,nodex,nodey,r_coor);
        
%         for i=1:length(rightnodesx)
%             if r_coor(1)>rightnodesx(i)
%                 searchnodesx1=[searchnodesx1; rightnodesx(i)];
%                 searchnodesy1=[searchnodesy1; rightnodesy(i)];
%             end
%         end
        
        if coor1(2)<r_coor(2) %search in upwards direction
            [upnodesx,upnodesy]=nodes_up(rightnodesx,rightnodesy,coor1,r_coor);
            searchnodesx=upnodesx;
            searchnodesy=upnodesy;
        elseif coor1(2)>r_coor(2) %search in downwards direction
            [downnodesx,downnodesy]=nodes_down(rightnodesx,rightnodesy,coor1,r_coor);
            searchnodesx=downnodesx;
            searchnodesy=downnodesy;
        end                    
    end    
elseif abs(hori)<abs(vert)
    % search vertically
    if coor1(2)>r_coor(2) % search in down direction
        [downnodesx,downnodesy]=nodes_down(nodex,nodey,coor1,r_coor);        
        
%         for i=1:length(downnodesy)
%            if r_coor(2)<downnodesy(i)
%                 searchnodesx1=[searchnodesx1; downnodesx(i)];
%                 searchnodesy1=[searchnodesy1; downnodesy(i)];
%             end
%         end
        
        if coor1(1)<r_coor(1) %search in right direction
            [rightnodesx,rightnodesy]=nodes_right(coor1,downnodesx,downnodesy,r_coor);            
            searchnodesx=rightnodesx;
            searchnodesy=rightnodesy;
        elseif coor1(1)>r_coor(1) %search in left direction
            [leftnodesx,leftnodesy]=nodes_left(coor1,downnodesx,downnodesy,r_coor);            
            searchnodesx=leftnodesx;
            searchnodesy=leftnodesy;
        end        
    elseif coor1(2)<r_coor(2) % search in up direction
        [upnodesx,upnodesy]=nodes_up(nodex,nodey,coor1,r_coor);        
        
%         for i=1:length(upnodesy)
%            if r_coor(2)>upnodesy(i)
%                 searchnodesx1=[searchnodesx1; upnodesx(i)];
%                 searchnodesy1=[searchnodesy1; upnodesy(i)];
%             end
%         end

        if coor1(1)<r_coor(1) %search in right direction
            [rightnodesx,rightnodesy]=nodes_right(coor1,upnodesx,upnodesy,r_coor);            
            searchnodesx=rightnodesx;
            searchnodesy=rightnodesy;
        elseif coor1(1)>r_coor(1) %search in left direction
            [leftnodesx,leftnodesy]=nodes_left(coor1,upnodesx,upnodesy,r_coor);            
            searchnodesx=leftnodesx;
            searchnodesy=leftnodesy;
        end        
    end    
end

[nn]=nearest_node(searchnodesx,searchnodesy,coor1); %set of nearest nodes from "coor1" in the direction of "r_coor"
%nn2=nn;
 nn2=[];
 %pause
if ~isempty(total) %loop to delete already occured nodes 
    [r1 c1]=size(nn);
    [r2 c2]=size(total);
    for i=1:r1
        for j=1:r2            
            if nn(i,1)==total(j,1) && nn(i,2)==total(j,2)
                nn2=[nn2 i];
%                 i
%                 disp('caught')
%                 nn2(i,:)
%                 nn2(i,:)=[]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            end
        end
    end    
end
nn(nn2,:)=[]; %deleting the rows from "nn" which have already occured

% [r c]=size(nn);
% for i=1:r
%     plot(nn(i,1),nn(i,2),'y*')
% end
% pause(1)
% for i=1:r
%     plot(nn(i,1),nn(i,2),'b*')
% end
    
%nn=nn2;
end

Code 15 – Function M File – placing_sensors.m

function [nodex,nodey,avg]=placing_sensors(sn)

low=0; %lower bound to both the axis
high=10; %upper bound to both the axis
 
nodex=[];
nodey=[];
for i=1:sn
    nodex=[nodex (low+(high-low)*rand)];  %x coordinates of all the points
    nodey=[nodey (low+(high-low)*rand)];  %y coordinates of all the points
end
 
for i=1:sn 
    plot(nodex(i),nodey(i),'b*') %ploting the x and y coordinates
    text(nodex(i)+0.05,nodey(i),num2str(i)) %giving all the nodes there respective numbers
    hold on
end

av=0;
ind=0;
for i=1:length(nodex)
    for j=1:length(nodex)
        dist=sqrt((nodex(i)-nodex(j))^2+(nodey(i)-nodey(j))^2);
        av=av+dist;
        ind=ind+1;
    end
end

avg=av/ind;
end

Code 16 – Function M File – witherror.m

%function [total,good,bad,diag]=witherror(s_coor,r_coor,nodex,nodey,fnodex,fnodey,l)
function [total]=witherror(s_coor,r_coor,nodex,nodey,fnodex,fnodey,l,avg,fni,sender,receiver)

coor1=s_coor; %initialising "coor1" with the value of "sender coordinate" i.e. "s_coor"
%blinking will always occur from "coor1" to "coor2"
total=[];
total=[total; coor1];
% good=[];
% bad=[];
% diag=[];
while coor1(1)~=r_coor(1) && coor1(2)~=r_coor(2)   % loop will run untill "coor1" is not equal to "receiver coordinates" i.e. "r_coor"
    nn=infotransfer(coor1,r_coor,nodex,nodey,total); %finding out the valid group of nodes to mark "coor2"
    %pause    
    [coor2,total,x]=check_nn(nn,fnodex,fnodey,l,nodex,nodey,coor1,total,r_coor); %finding suitable node "coor2" from "nn". also stores its coordinates
    if x==0 %the node is not diagnosable
        [coor2]=check_avg(coor2,coor1,avg,nodex,nodey,r_coor,fni,sender,receiver); 
    end    
    blinking_line(coor1,coor2)
    plot([coor1(1) coor2(1)],[coor1(2) coor2(2)],'k','LineWidth',2)
    if coor2(1)==r_coor(1) && coor2(2)==r_coor(2)
        total=[total; coor2];
%        good=[good; coor2];        
        break
    else
        coor1=coor2;                
        total=[total; coor2];
%        good=[good; coor1];
    end
end

end

Code 17 – Function M File – withouterror.m

function [total]=withouterror(s_coor,r_coor,nodex,nodey,fnodex,fnodey,l,avg,fni,sender,receiver)

coor1=s_coor;
total=[];
while coor1(1)~=r_coor(1) && coor1(2)~=r_coor(2)    
    nn=infotransfer(coor1,r_coor,nodex,nodey,total);
%    [coor2]=check_nn2(nn,fnodex,fnodey,l,nodex,nodey,coor1);
    coor2=[nn(1,1) nn(1,2)];
    [coor2]=check_avg2(coor2,coor1,avg,nodex,nodey,r_coor,fni,sender,receiver);
    blinking_line(coor1,coor2)
    plot([coor1(1) coor2(1)],[coor1(2) coor2(2)],'k','LineWidth',2)
    total=[total; coor1];    
    if coor2(1)==r_coor(1) && coor2(2)==r_coor(2)
        total=[total; r_coor];    
        break
    else
        coor1=coor2;                
    end
end

end

Code 18 – Function M File – check_nn.m

%function [coor2,bad,total,diag]=check_nn(nn,fnodex,fnodey,len,nodex,nodey,coor1,bad,total,r_coor,diag)
function [coor2,total,x]=check_nn(nn,fnodex,fnodey,len,nodex,nodey,coor1,total,r_coor,fni,avg,sender,receiver)
%[coor2]=check_avg2(coor2,coor1,avg,nodex,nodey,r_coor,fni,sender,receiver)
i=1;
x=0;
while i>=1
    [r1 c1]=size(nn);
    if i>r1 % loop will run when the given "nn" does not have any value. we have to find new set of "nn"
 %       disp('yes')
        [leftnodesx,leftnodesy]=nodes_left(coor1,nodex,nodey,r_coor); %nodes to the left of "coor1" till "r_coor"
        [upnodesx,upnodesy]=nodes_up(nodex,nodey,coor1,r_coor); %nodes to the up of "coor1" till "r_coor"
        [downnodesx,downnodesy]=nodes_down(nodex,nodey,coor1,r_coor); %nodes to the down of "coor1" till "r_coor"
        [rightnodesx,rightnodesy]=nodes_right(coor1,nodex,nodey,r_coor); %nodes to the right of "coor1" till "r_coor"
       
        [nn1]=nearest_node(upnodesx,upnodesy,coor1); %arranging the obtained sets in ascending order. it contains the nearest nodes 
        [nn2]=nearest_node(downnodesx,downnodesy,coor1);
        [nn3]=nearest_node(leftnodesx,leftnodesy,coor1);
        [nn4]=nearest_node(rightnodesx,rightnodesy,coor1);
        
        if ~isempty(nn1) %if "nn1" is not empty, it will find the nearest node 
            for ii=1:length(fnodex)
                if nn1(1,1)==fnodex(ii) && nn1(1,2)==fnodey(ii) %cheking if the nearest nodes in up direction is faulty
                    a=[];
                    break
                else
                    a=[nn1(1,1) nn1(1,2)]; %nearest nodes in up direction
                end
            end
        else % if "nn1" is empty
             a=[];
        end 
       
         if ~isempty(nn2)%if "nn2" is not empty, it will find the nearest node 
            for ii=1:length(fnodex)
                if nn2(1,1)==fnodex(ii) && nn2(1,2)==fnodey(ii) %cheking if the nearest nodes in down direction is faulty
                    b=[];
                    break
                else
                    b=[nn2(1,1) nn2(1,2)]; %nearest node in down direction
                end
            end
         else% if "nn2" is empty
             b=[];
         end
        
         if ~isempty(nn3)%if "nn3" is not empty, it will find the nearest node 
            for ii=1:length(fnodex)    
                if nn3(1,1)==fnodex(ii) && nn3(1,2)==fnodey(ii) %cheking if the nearest nodes in left direction is faulty
                    c=[];
                    break
                else
                    c=[nn3(1,1) nn3(1,2)]; %nearest node in left direction
                end
            end
         else% if "nn3" is empty
             c=[];
         end
        
         if ~isempty(nn4)%if "nn4" is not empty, it will find the nearest node 
            for ii=1:length(fnodex)    
                if nn4(1,1)==fnodex(ii) && nn4(1,2)==fnodey(ii) %cheking if the nearest nodes in right direction is faulty
                    d=[];
                    break
                else
                    d=[nn4(1,1) nn4(1,2)]; %nearest node in right direction
                end
            end
         else% if "nn4" is empty
             d=[];
         end
            
        if ~isempty(a)
            ad=sqrt((coor1(1)-a(1))^2+(coor1(2)-a(2))^2); %distance to the nearest up node
        else
            ad=50; %high value given so that it will not be chosen at the time of selection
        end
        
        if ~isempty(b)
            bd=sqrt((coor1(1)-b(1))^2+(coor1(2)-b(2))^2); %distance to the nearest down node
        else
            bd=50;%high value given so that it will not be chosen at the time of selection
        end
        
        if ~isempty(c)
            cd=sqrt((coor1(1)-c(1))^2+(coor1(2)-c(2))^2); %distance to the nearest left node
        else
            cd=50;%high value given so that it will not be chosen at the time of selection
        end
        
        if ~isempty(d)
            dd=sqrt((coor1(1)-d(1))^2+(coor1(2)-d(2))^2); %distance to the nearest right node
        else
            dd=50;%high value given so that it will not be chosen at the time of selection
        end
        
        mat=[ad bd cd dd];
        [mini,ind]=min(mat);  %finding the closest of all the 4 direction nodes
        switch ind
            case 1
                nn=nn1; %up is closest
            case 2
                nn=nn2; %down is closest
            case 3
                nn=nn3; %left is closest
            case 4
                nn=nn4; %right is closest
            otherwise
                disp('wrong')
        end
        
        i=1;
    end 
    
    for j=1:length(fnodex) %loop will rum for the number of faulty nodes times
        if nn(i,1)==fnodex(j) && nn(i,2)==fnodey(j) %checking the nearest node for faultyness                        
            coor_1=coor1;
            coor_2=[fnodex(j) fnodey(j)];
            %[coor2]=check_avg2(coor2,coor1,avg,nodex,nodey,r_coor,fni,sender,receiver);
            %pause
            blinking_line(coor_1,coor_2)  %this blinking is till the faulty node
%            disp('---------')            
            x=0;
            if j>=(ceil(len/4)+1) && j<=ceil(len/2)
                plot(fnodex(j),fnodey(j),'ko','LineWidth',2)
                text(fnodex(j)+0.05,fnodey(j),'\leftarrow Transient Error Diagnosed')
                coor2=[fnodex(j) fnodey(j)];
                %diag=[diag; coor2];
%                total=[total; coor2];
                x=1; %this means that the faulty node is diagnosable
                break
            else
                bestmatch(j,coor_1,coor_2,fnodex,fnodey,len) 
                %bad=[bad; fnodex(j) fnodey(j)]; %storing the coordinates
                total=[total; fnodex(j) fnodey(j)];
            end     
            
            if x==1 % if the node can be diagnosed, break. no need to search further
                break
            else % if the node cnt be diagnosed, mark it with its color
                i=i+1; % and move on to the next nearest node in "nn"
                coor2=[]; %no value of "coor2" obtained
                break
            end
        else
            coor2=nn(i,:); % "coor2" is the i^th nearest node from "nn" as it is not a faulty node as checked at line 113
        end
    end
    
    if ~isempty(coor2) %breaks the loop if we have a value of "coor2"
        break
    end
end

end

Code 19 – Function M File – check_avg.m

function [coor2]=check_avg(coor2,coor1,avg,nodex,nodey,r_coor,fni,sender,receiver)

dist=sqrt((coor1(1)-coor2(1))^2+(coor1(2)-coor2(2))^2);
range=ceil(avg/2);

if dist<range;
    coor2=coor2;
    
elseif dist>range;
    range_ind=[]; %nodes in the range of coor1
    for i=[1:sender-1  sender+1:length(nodex)]
        dist=sqrt((coor1(1)-nodex(i))^2+(coor1(2)-nodey(i))^2);
        if dist<=range
            range_ind=[range_ind i]; %finding all the nodes in the range of coor1
        end
    end    
    %range_ind
    
    for i=1:length(fni)
        x=find(range_ind==fni(i));
        range_ind(x)=[]; %deleting the faulty indexes
    end
    %range_ind
    %pause

    %the closest node to r_coor in the range of coor1 will connected
    distances=[];
    for i=range_ind
        dist=sqrt((r_coor(1)-nodex(i))^2+(r_coor(2)-nodey(i))^2);
        distances=[distances; i dist];
    end    
    x=find(distances(:,2)==min(distances(:,2)));
    coor2=[nodex(distances(x,1)) nodey(distances(x,1))];    
end    

Code 20 – Function M File – check_avg2.m

function [coor2]=check_avg2(coor2,coor1,avg,nodex,nodey,r_coor,fni,sender,receiver)

dist=sqrt((coor1(1)-coor2(1))^2+(coor1(2)-coor2(2))^2);
range=ceil(avg/2);

if dist<range;
    coor2=coor2;
    
elseif dist>range;
    range_ind=[]; %nodes in the range of coor1
    for i=[1:sender-1  sender+1:length(nodex)]
        dist=sqrt((coor1(1)-nodex(i))^2+(coor1(2)-nodey(i))^2);
        if dist<=range
            range_ind=[range_ind i]; %finding all the nodes in the range of coor1
        end
    end    
    %range_ind
    
    %the closest node to r_coor in the range of coor1 will connected
    distances=[];
    for i=range_ind
        dist=sqrt((r_coor(1)-nodex(i))^2+(r_coor(2)-nodey(i))^2);
        distances=[distances; i dist];
    end    
    x=find(distances(:,2)==min(distances(:,2)));
    coor2=[nodex(distances(x,1)) nodey(distances(x,1))];    
end    

 

Recent Posts

Tags

ad-hoc networks AODV boundary detection process classification clustering clustering algorithm Colour Information computer vision Decryption Encryption EZRP ICM (Iterated Conditional Modes) image denoising image enhancement IMAGE PROCESSING image segmentation Imaging and image processing MANET Markov Random Fields neutrosophic logic optical network proposed method PSNR QLab system region growing Robert’s operator Seed point selection segmentation semi-automatic algorithm Shadow Detection shadow removal wall motion wireless communication Wireless network wireless networks Wireless Sensor Network wireless sensor networks ZRP