public static bool Connect()
        {
            messageHandler = new MessageHandler();

            //create channel
            //InstanceContext represents the running instance of the service.
            //OperationContext is the instance of the client accessing the service.
            InstanceContext instanceContext = new InstanceContext(messageHandler);

            _factory = new DuplexChannelFactory <IChannel>(instanceContext, "GridEndpoint");
            channel  = _factory.CreateChannel();


            try
            {
                ((ICommunicationObject)channel).Open();
            }
            catch (CommunicationException e) {
                ((ICommunicationObject)channel).Abort();
                _factory.Abort();

                XMLLogger.WriteErrorMessage("Connector", "Could not find resolver.  If you are using a custom resolver, please ensure that the service is running.");
                XMLLogger.WriteErrorMessage("Connector", "System Error: " + e.ToString());

                return(false);
            }

            return(true);
        }
        private void CreateProposal(StatusNotifyMessage message)
        {
            if (message.status == PeerStatus.Consumer)
            {
                if (_peerStatus == PeerStatus.Producer)
                {
                    XMLLogger.WriteLocalActivity(message.energyReq + "kW Energy Request Received from: " + message.header.Sender);

                    float enAvailable = getEnergyLevel() - (_enPeak + _enSold);

                    if (enAvailable > 0)
                    {
                        float enSold = enAvailable >= message.energyReq ? message.energyReq : enAvailable;

                        EnergyProposalMessage respMessage = MessageFactory.createEnergyProposalMessage(
                            message.header.MessageID,
                            message.header.Sender,
                            _name,
                            enSold,
                            _price
                            );

                        Connector.channel.energyProposal(respMessage);

                        XMLLogger.WriteLocalActivity(enSold + "kW Energy Proposal Sent to: " + message.header.Sender);
                    }
                }
            }
        }
        private void _mainTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //Check the energy level
            if ((getEnergyLevel() + _enBought) < _enPeak)
            {
                if (messageSent == false)
                {
                    float enReq = _enPeak - (getEnergyLevel() + _enBought);
                    Connector.channel.statusAdv(MessageFactory.createEnergyRequestMessage("@All", _name, _peerStatus, enReq));

                    messageSent = true;
                    XMLLogger.WriteLocalActivity(enReq + "kW Energy Request Sent to Local Network...");

                    //start the timer to waiting for proposals
                    if (_proposalCountdown.Enabled == false)
                    {
                        _proposalCountdown.Enabled = true;
                    }
                }
            }
            else
            {
                messageSent = false;
                _proposalCountdown.Enabled = false;
            }
        }
Example #4
0
        private bool StartLocalResolver()
        {
            bool bRet = false;

            _customResolver = new ServiceHost(_crs);

            XMLLogger.WriteLocalActivity("Starting Custom Local Peer Resolver Service...");

            try
            {
                _crs.Open();
                _customResolver.Open();
                bRet = true;
                XMLLogger.WriteLocalActivity("Custom Local Peer Resolver Service is started");
            }
            catch (Exception e)
            {
                XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), "Error in starting Custom Local Peer Resolver Service");
                XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), e.ToString());
                _crs.Close();
                _customResolver.Abort();
                bRet = false;
            }

            return(bRet);
        }
Example #5
0
        private bool StartRemoteService()
        {
            bool bRet = false;

            _remoteMessageHandler = new PeerServices();

            _remoteHost = new ServiceHost(_remoteMessageHandler);

            //To handle the remote traffic
            _remoteMessageHandler.OnRemoteEnergyRequest += new manageEnergyRequest(ManageRemoteEnergyRequest);
            _remoteMessageHandler.OnRemoteEnergyReply   += new replyEnergyRequest(ManageRemoteEnergyReply);
            _remoteMessageHandler.OnRemotePeerIsDown    += new remotePeerIsDown(RemotePeerIsDown);

            try
            {
                _remoteHost.Open();
                bRet = true;
                XMLLogger.WriteRemoteActivity("Remote service started.");
            }
            catch (Exception e)
            {
                XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), "Unable to start Remote Service.");
                //XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), e.ToString()); //For debug purpose
                _remoteHost.Abort();
            }

            return(bRet);
        }
Example #6
0
        private void HelloResponse(HelloMessage message)
        {
            //Elaborates the Hello Message
            TempBuilding b = new TempBuilding();

            #region setting fields
            b.Address    = message.Address;
            b.Admin      = message.Admin;
            b.EnBought   = 0;
            b.EnSold     = 0;
            b.EnPeak     = message.EnPeak;
            b.EnPrice    = message.EnPrice;
            b.EnProduced = message.EnProduced;
            b.EnType     = message.EnType;
            b.Name       = message.header.Sender;
            b.status     = message.Status;
            b.iconPath   = b.status == PeerStatus.Producer ? @"/WPF_Resolver;component/img/producer.png" : @"/WPF_Resolver;component/img/consumer.png";
            #endregion

            lock (_lLock)
                _buildings.Add(b);

            XMLLogger.WriteLocalActivity("New Peer: " + b.Name + " is up!");

            //Be polite! Send an HelloResponse
            Connector.channel.HelloResponse(MessageFactory.createHelloResponseMessage("@All", Tools.getResolverName(), Tools.getResolverName()));
        }
Example #7
0
        public void CloseService()
        {
            XMLLogger.WriteLocalActivity("Closing Application...");

            _GarbageCollectorTimer.Enabled = false;

            try
            {
                if (this.isRemoteServiceStarted == true)
                {
                    _remoteHost.Close();
                }

                if (this.isRemoteConnected == true)
                {
                    _remoteChannel.Close();
                }

                if (this.isLocalConnected == true)
                {
                    _crs.Close();
                    _customResolver.Close();
                }

                StopService(); //Calls the base.StopService method
            }
            catch (Exception e)
            {
                XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), "App Fault on Exit");
            }
        }
 private void ReceiveProposal(EnergyProposalMessage message)
 {
     if (message.header.Receiver == _name)
     {
         XMLLogger.WriteLocalActivity("Received Proposal for " + message.energyAvailable + "kW; price " + message.price + " From " + message.header.Sender);
         _proposalList.Add(message);
     }
 }
 public void StopService()
 {
     if (this.isConnected == true)
     {
         Connector.Disconnect();
         XMLLogger.WriteLocalActivity("OffLine.");
     }
 }
Example #10
0
        private void ForwardEnergyRequest(StatusNotifyMessage message)
        {
            XMLLogger.WriteRemoteActivity("Forwarding " + message.energyReq + "kW Energy Request from: " + message.header.Sender);
            XMLLogger.WriteRemoteActivity("MessageID: " + message.header.MessageID);

            _requestThread = new Thread(new ParameterizedThreadStart(ConnectToRemoteHost));
            _requestThread.Start(message);
        }
        public void StopEnergyProduction()
        {
            _pwManager.ShutDown();
            Connector.channel.sayGoodBye(MessageFactory.createGoodByeMessage("@All", _name, _name));

            base.StopService();

            XMLLogger.WriteLocalActivity("Leaving the Mesh...");
        }
 ILogger ILoggerProvider.CreateLogger(string categoryName)
 {
     // Only 1 instance of logger per logger provider.
     if (Logger == null)
     {
         Logger = new XMLLogger(LogLevel, categoryName, OutputPath, DefaultMaxRows);
     }
     return(Logger);
 }
        public void Start()
        {
            _pwManager.Start();

            XMLLogger.WriteLocalActivity("Power Manager Started. Sending Hello Message.");

            //send hello message
            Connector.channel.sayHello(MessageFactory.CreateHelloMessage("@All", _name, _status, _enType, _enProduced,
                                                                         _enPeak, _price, _address, _adminName));

            XMLLogger.WriteLocalActivity("Hello Message Sent.");
        }
 public void StartService()
 {
     if (Connector.Connect())
     {
         this.isConnected = true;
         XMLLogger.WriteLocalActivity("OnLine.");
     }
     else
     {
         this.isConnected = false;
         XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), "Connection Error");
     }
 }
Example #15
0
        private void ManageRemoteEnergyRequest(RemoteEnergyRequest message)
        {
            RemoteConnection remConn;

            Guid   MessageID  = message.enReqMessage.header.MessageID;
            string remotePeer = message.enReqMessage.header.Sender;

            XMLLogger.WriteRemoteActivity("Received Remote Energy Request from: " + message.enReqMessage.header.Sender + " by Remote Resolver: " + message.header.Sender);
            XMLLogger.WriteRemoteActivity("Message ID: " + message.enReqMessage.header.MessageID);

            remConn = GetConnection(message.IP, message.port, ConnectionType.Incoming);

            if (remConn == null)//If entry doesn't exist
            {
                remConn = new RemoteConnection()
                {
                    type = ConnectionType.Incoming,

                    remoteResolver = new RemoteHost()
                    {
                        name       = message.header.Sender,
                        IP         = message.IP,
                        port       = message.port,
                        netAddress = @"net.tcp://" + message.IP + ":" + message.port + @"/Remote"
                    }
                };

                remConn.requests.Add(MessageID, new RemoteRequest()
                {
                    localePeerName = "",
                    remotePeerName = remotePeer,
                    energy         = 0
                });

                _remoteConnections.Add(remConn);
            }
            else
            {
                remConn.requests.Add(MessageID, new RemoteRequest()
                {
                    localePeerName = "",
                    remotePeerName = remotePeer,
                    energy         = 0
                });
            }


            _broker.EnergyLookUp(message.enReqMessage);
        }
        private void ProposalAccepted(EnergyAcceptMessage message)
        {
            if (message.header.Receiver == _name)
            {
                Boolean status        = false;
                float   energyCanSell = 0;

                float enAvailable = getEnergyLevel() - (_enPeak + _enSold);

                if (enAvailable > 0)
                {
                    energyCanSell = enAvailable >= message.energy ? message.energy : enAvailable;

                    status   = true;
                    _enSold += energyCanSell;

                    XMLLogger.WriteLocalActivity("Ok, " + energyCanSell + " KW/h sold to " + message.header.Sender);

                    EnergyLink link = new EnergyLink(message.peerName, energyCanSell, _price);
                    consumers.Add(link);

                    //Advise the Local Resolver About the energy status change.
                    Connector.channel.updateEnergyStatus(MessageFactory.createUpdateStatusMessage(_resolverName, _name, _enSold, _enBought));

                    XMLLogger.WriteLocalActivity("Updating Stutus");
                    XMLLogger.WriteLocalActivity("Peer " + message.header.Sender + " - Energy Sold: " + _enSold);
                    XMLLogger.WriteLocalActivity("Peer " + message.header.Sender + " - Energy Bought: " + _enBought);
                }

                EndProposalMessage respMessage = MessageFactory.createEndProposalMessage(
                    message.header.MessageID,
                    message.header.Sender,
                    _name,
                    status,
                    energyCanSell,
                    _price
                    );

                if (message.header.Sender == _resolverName)
                {
                    Connector.channel.forwardEnergyReply(respMessage);
                }
                else
                {
                    Connector.channel.endProposal(respMessage);
                }
            }
        }
        private void EndProposal(EndProposalMessage message)
        {
            if (message.header.Receiver == _name)
            {
                if (message.endStatus == true)
                {
                    _enBought += message.energy;

                    XMLLogger.WriteLocalActivity("Energy received from " + message.header.Sender);

                    EnergyLink link = new EnergyLink(message.header.Sender, message.energy, message.price);
                    producers.Add(link);

                    //Advise the Local Resolver About the energy status change.
                    Connector.channel.updateEnergyStatus(MessageFactory.createUpdateStatusMessage(_resolverName, _name, _enSold, _enBought));

                    _proposalList.Clear();

                    if ((getEnergyLevel() + _enBought) < _enPeak)
                    {
                        messageSent = false;
                    }
                }
                else
                {
                    //Nothing to do..Delete this Producer and go on with the next.
                    for (int i = 0; i < _proposalList.Count; i++)
                    {
                        if (_proposalList[i].header.Sender == message.header.Sender)
                        {
                            _proposalList.RemoveAt(i);
                            break;
                        }
                    }

                    //More Proposal? Evaluate it or Start again
                    if (_proposalList.Count > 0)
                    {
                        EvaluateProposal();
                    }
                    else
                    {
                        messageSent = false;
                    }
                }
            }
        }
Example #18
0
        private void removeBuildingByName(string name)
        {
            string leavingPeer = name;

            XMLLogger.WriteLocalActivity("Peer: " + leavingPeer + " is down!");

            //Remove the deadly peer but first alert the folks.
            Connector.channel.peerDown(MessageFactory.createPeerIsDownMessage("@All", this.name, leavingPeer));

            lock (_connectionLock)
            {
                //Alert Remote Resolvers
                foreach (var remConn in _remoteConnections)
                {
                    NetTcpBinding   tcpBinding     = new NetTcpBinding();
                    EndpointAddress remoteEndpoint = new EndpointAddress(remConn.remoteResolver.netAddress);
                    tcpBinding.Security.Mode = SecurityMode.None;

                    ChannelFactory <IRemote> cf = new ChannelFactory <IRemote>(tcpBinding, remoteEndpoint);
                    IRemote tChannel            = cf.CreateChannel();

                    try
                    {
                        tChannel.PeerDownAlert(MessageFactory.createPeerIsDownMessage("@All", this.name, leavingPeer));
                    }
                    catch (Exception ex)
                    {
                        XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), "Error in sending Remote Peer Alert Message" + ex.ToString());
                    }
                }
            }

            updateLocalConnectionsList(leavingPeer);

            var itemToRemove = from b in _buildings
                               where b.Name == leavingPeer
                               select b;

            lock (_lLock)
            {
                if (itemToRemove.Count() > 0)
                {
                    _buildings.Remove(itemToRemove.First());
                }
            }
        }
        private void EvaluateProposal()
        {
            var m = (from element in _proposalList
                     orderby element.price ascending
                     select element).First();

            XMLLogger.WriteLocalActivity("The lowest price is " + m.price + " provided by " + m.header.Sender);

            EnergyAcceptMessage respMessage = MessageFactory.createEnergyAcceptMessage(
                m.header.MessageID,
                m.header.Sender,
                _name,
                this._name,
                _enPeak - (getEnergyLevel() + _enBought));

            Connector.channel.acceptProposal(respMessage);
        }
        //public void EnergyLookUp(object m)
        public void EnergyLookUp(StatusNotifyMessage message)
        {
            //StatusNotifyMessage message = (StatusNotifyMessage)m;

            _sem.Wait();

            _originPeerName = message.header.Sender;
            _enLookUp       = message.energyReq;
            _originGuid     = message.header.MessageID;

            message.header.Sender = this._name;

            XMLLogger.WriteRemoteActivity("Broker is serving: " + message.header.MessageID + " session.");

            Connector.channel.statusAdv(message);

            _proposalCountdown.Enabled = true;
        }
Example #21
0
        void ForwardEnergyReply(EndProposalMessage message)
        {
            RemoteConnection conn = GetConnectionByMessageID(message.header.MessageID, ConnectionType.Incoming);

            XMLLogger.WriteRemoteActivity("Forwarding Remote Response about message: " + message.header.MessageID + " Status = " + message.endStatus);
            XMLLogger.WriteRemoteActivity("Message ID: " + message.header.MessageID);

            if (conn != null)
            {
                //Header re-handling
                conn.requests[message.header.MessageID].localePeerName = message.header.Sender;
                conn.requests[message.header.MessageID].energy         = message.energy;
                message.header.Receiver = conn.requests[message.header.MessageID].remotePeerName;

                #region Creating Channel
                NetTcpBinding   tcpBinding     = new NetTcpBinding();
                EndpointAddress remoteEndpoint = new EndpointAddress(conn.remoteResolver.netAddress);
                tcpBinding.Security.Mode = SecurityMode.None;

                ChannelFactory <IRemote> cf = new ChannelFactory <IRemote>(tcpBinding, remoteEndpoint);
                IRemote tChannel            = cf.CreateChannel();
                #endregion

                RemoteEndProposalMessage remoteEndMessage = (MessageFactory.createRemoteEndProposalMessage(message, conn.remoteResolver.name, this.name, Tools.getLocalIP(), Tools.getResolverServicePort()));

                try
                {
                    tChannel.ReplyEnergyRequest(remoteEndMessage);
                }
                catch (Exception e)
                {
                    XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), "Error in Forwarding Energy Reply Message: " + e.ToString());
                }
            }
            else
            {
                XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), "Could not find the following message: " + message.header.MessageID);
            }
        }
        private void _proposalCountdown_Elapsed(object sender, ElapsedEventArgs e)
        {
            _proposalCountdown.Enabled = false; //Stop the timer

            if (_proposalList.Count > 0)
            {
                _proposalTimeout = 0;
                EvaluateProposal();
            }
            else
            {
                _proposalTimeout++;

                if (_proposalTimeout > 2)  //Go Outbound
                {
                    float enReq = _enPeak - (getEnergyLevel() + _enBought);

                    XMLLogger.WriteRemoteActivity("Going Outside to find " + enReq + " KW/h");

                    Connector.channel.forwardEnergyRequest(MessageFactory.createEnergyRequestMessage(_resolverName, _name, _peerStatus, enReq));
                    messageSent = true;

                    _proposalTimeout = 0;

                    //start the timer to waiting for proposals
                    if (_proposalCountdown.Enabled == false)
                    {
                        _proposalCountdown.Enabled = true;
                    }
                }
                else
                {
                    XMLLogger.WriteLocalActivity("No Energy proposal receveid");
                    messageSent = false; //send the request message again
                }
            }
        }
Example #23
0
 public virtual void peerDown(PeerIsDownMessage message)
 {
     XMLLogger.WriteRemoteActivity("Peer " + message.peerName + " is down");
 }
Example #24
0
        private void ConnectToRemoteHost(object m)
        {
            bool connected = false;
            StatusNotifyMessage message = (StatusNotifyMessage)m;

            _remoteResolvers = Tools.getRemoteHosts();

            while (connected == false && _nHostIndex < _remoteResolvers.Count)
            {
                lock (_counterLock)
                {
                    //localhost connections filter
                    if (_remoteResolvers[_nHostIndex].IP == "127.0.0.1" || _remoteResolvers[_nHostIndex].IP.ToLower() == "localhost")
                    {
                        if (_nHostIndex < (_remoteResolvers.Count - 1))
                        {
                            _nHostIndex++;
                        }
                        else
                        {
                            _nHostIndex = 0;
                        }

                        continue;
                    }

                    XMLLogger.WriteRemoteActivity("Connecting to " + _remoteResolvers[_nHostIndex].IP);

                    NetTcpBinding   tcpBinding     = new NetTcpBinding();
                    EndpointAddress remoteEndpoint = new EndpointAddress(_remoteResolvers[_nHostIndex].netAddress);
                    tcpBinding.Security.Mode = SecurityMode.None;

                    ChannelFactory <IRemote> cf = new ChannelFactory <IRemote>(tcpBinding, remoteEndpoint);
                    _remoteChannel = cf.CreateChannel();

                    try
                    {
                        _remoteChannel.Open();

                        //Retrieve Remote IP Addresses
                        foreach (var newRemote in _remoteChannel.RetrieveContactList())
                        {
                            if (!_remoteResolvers.Exists(delegate(RemoteHost x) { return(x.netAddress == newRemote.netAddress); }))
                            {
                                _remoteResolvers.Add(newRemote);
                                Tools.updateRemoteHosts(newRemote);
                            }
                        }

                        XMLLogger.WriteRemoteActivity("Connected to: " + _remoteResolvers[_nHostIndex].IP);

                        XMLLogger.WriteRemoteActivity("Forwarding Energy Request from: " + message.header.Sender + "To: " + _remoteResolvers[_nHostIndex]);
                        XMLLogger.WriteRemoteActivity("Message ID: " + message.header.MessageID);

                        _remoteChannel.ManageRemoteEnergyRequest(MessageFactory.createRemoteEnergyRequestMessage(message,
                                                                                                                 _remoteResolvers[_nHostIndex].name,
                                                                                                                 this.name,
                                                                                                                 Tools.getLocalIP(),
                                                                                                                 Tools.getResolverServicePort()
                                                                                                                 ));

                        this.isRemoteConnected = true;
                        connected = true;
                    }

                    catch (Exception e)
                    {
                        XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), "Unable to connect to remote host.");
                        //XMLLogger.WriteErrorMessage(this.GetType().FullName.ToString(), e.ToString()); //For debug purpose
                        _nHostIndex++;
                        if (_nHostIndex >= _remoteResolvers.Count)
                        {
                            _nHostIndex = 0;
                            _remoteChannel.Abort();
                        }

                        connected = false;
                    }
                }
            }


            if (_nHostIndex >= _remoteResolvers.Count)
            {
                lock (_counterLock)
                {
                    _nHostIndex = 0;
                }
            }
        }
Example #25
0
        void ManageRemoteEnergyReply(RemoteEndProposalMessage message)
        {
            string localBuilding  = message.endProposalMessage.header.Receiver;
            string remoteBuilding = message.endProposalMessage.header.Sender;
            float  energyBought   = message.endProposalMessage.energy;

            if (message.endProposalMessage.endStatus == true)
            {
                RemoteConnection oC;

                oC = GetConnection(message.IP, message.port, ConnectionType.Outgoing);

                if (oC == null)
                {
                    oC = new RemoteConnection()
                    {
                        type = ConnectionType.Outgoing,

                        remoteResolver = new RemoteHost()
                        {
                            name       = message.header.Sender,
                            IP         = message.IP,
                            port       = message.port,
                            netAddress = @"net.tcp://" + message.IP + ":" + message.port + @"/Remote"
                        }
                    };

                    oC.requests.Add(message.endProposalMessage.header.MessageID, new RemoteRequest()
                    {
                        localePeerName = localBuilding,
                        remotePeerName = remoteBuilding,
                        energy         = energyBought
                    });

                    _remoteConnections.Add(oC);
                }
                else
                {
                    oC.requests.Add(message.endProposalMessage.header.MessageID, new RemoteRequest()
                    {
                        localePeerName = localBuilding,
                        remotePeerName = remoteBuilding,
                        energy         = energyBought
                    });
                }

                XMLLogger.WriteRemoteActivity("Received Remote Energy Reply from: " + remoteBuilding + "@" + message.header.Sender);
                XMLLogger.WriteRemoteActivity("Message ID: " + message.endProposalMessage.header.MessageID);

                Connector.channel.endProposal(message.endProposalMessage);
            }
            else //No Energy From this remote resolver..Go with the next
            {
                Connector.channel.endProposal(message.endProposalMessage);

                lock (_counterLock)
                {
                    _nHostIndex++;
                }
            }
        }