I have a G120 based control system that uses internet. It use DHCP and works generally fine.
I have delivered a system to an installation in Ireland. They have problems to get internet access. Either they do not get an ip-address or NetworkAvailabilityChanged is false. They tried to use another port in the switch and that worked for a short time, but after a restart they had same problem. Their router says, that it has given an ip-addres to the G120 controller. I had not been able to debug the system and I have never had the same problem in my own office.
My code looks like this, the available memeber is used to detect if network is ok and that member is false in the faulty installation.
The init function was quite simple at first, just following the suggestion from GHI, but I added some extra enable / disable in case of fault. I do not know how the best way is to handle the situation with ip_address == “0.0.0.0”.
static void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
Debug.Print("Network available: " + e.IsAvailable.ToString());
available = e.IsAvailable;
}
static public void Init()
{
int cnt = 0;
Byte[] ma = EepromCtrl.GetMacAddressByteArray();
enc.PhysicalAddress = ma;
enc.Open();
enc.EnableDhcp();
//enc.NetworkInterface.EnableDhcp();
enc.EnableDynamicDns();
Thread.Sleep(2000);
if (enc.IPAddress == "0.0.0.0")
{
cnt = 0;
while (enc.IPAddress == "0.0.0.0" && cnt < 20)
{
Debug.Print("Awaiting IP Address, step 1");
Thread.Sleep(1000);
if (enc.IsDhcpEnabled)
enc.EnableDhcp();
else
enc.RenewDhcpLease();
cnt++;
}
WatchDogCtrl.Kick(0);
if (enc.IPAddress == "0.0.0.0")
{
enc.RenewDhcpLease();
cnt = 0;
while (enc.IPAddress == "0.0.0.0" && cnt < 20)
{
Debug.Print("Awaiting IP Address, step 2");
Thread.Sleep(1000);
cnt++;
}
WatchDogCtrl.Kick(0);
if (enc.IPAddress == "0.0.0.0")
{
try
{
enc.Close();
Thread.Sleep(1000);
enc.Dispose();
enc = null;
GC.WaitForPendingFinalizers();
Thread.Sleep(5000);
}
catch (Exception ex)
{
Debug.Print("Exception: " + ex.ToString());
}
enc = new GHI.Networking.EthernetENC28J60(SPI.SPI_module.SPI2, G120.P1_17, G120.P0_5, G120.P1_14); //change to target
enc.Open();
enc.EnableDynamicDns();
enc.EnableDhcp();
Thread.Sleep(2000);
cnt = 0;
while (enc.IPAddress == "0.0.0.0" && cnt < 20)
{
Debug.Print("Awaiting IP Address, step 3");
Thread.Sleep(1000);
cnt++;
}
if (enc.IPAddress == "0.0.0.0")
{
available = false;
Debug.Print("No IP Address Granted: " + enc.NetworkInterface.IPAddress);
}
else
{
available = true;
Debug.Print("IP Address Granted: " + enc.NetworkInterface.IPAddress);
}
}
else
{
available = true;
Debug.Print("IP Address Granted: " + enc.NetworkInterface.IPAddress);
}
}
else
{
available = true;
Debug.Print("IP Address Granted: " + enc.NetworkInterface.IPAddress);
}
}
else
{
available = true;
Debug.Print("IP Address already assigned: " + enc.NetworkInterface.IPAddress);
}
}