Cannot initialize the Relay Object

I have a little project that I am working on using the Maple Web Server. I followed the instructions for controlling a servo through the web server and it works great. Next I tried to add a relay switch and now it just hangs during initialization of the relay. Here is the code I have to initialize the relay in the MeadowApp.cs class:

RelayController.Relay.Initialize(Device, Device.Pins.D02);

Here is the RelayController class:

using Meadow.Devices;
using Meadow.Foundation.Relays;
using Meadow.Hardware;

namespace ConnectedServo.Meadow
{
    public class RelayController
    {
        Relay relay;

        protected bool initialized = false;
        public static RelayController Relay { get; private set; }

        private RelayController() { }

        static RelayController()
        {
            
        }

        public void Initialize(IMeadowDevice device, IPin PwmPin)
        {
            if (initialized)
            {
                return;
            }
            relay = new Relay(device.CreateDigitalOutputPort(PwmPin));
            relay.IsOn = true;
            relay.IsOn = false;
            initialized = true;
        }

        public void OpenRelay()
        {
            relay.IsOn = true;
        }

        public void CloseRelay()
        {
            relay.IsOn = false;
        }
    }
}

It just hangs in a loop on the relay=new Relay(device.CreateDigitalOutputPort(PwmPin)); line. It will execute the line then jump to the top of the loop. Any help is appreciated.

John

We just released RC-1, can you try with the new build, please? Wilderness Labs Developer Portal

I just did the update, but now the WifiAdapter.Connect is gone. I looked through the docs for the new method of connecting to WIFI and I can’t find it. How do you initialize the WIFI under the new Update?

Okay I got this fixed. But trying to debug I get this pop up

image

I have updated the code to the new version. Here is my updated MeadowApp.cs file:

 public class MeadowApp : App<F7FeatherV1>
    {
        MapleServer mapleServer;
        

        public MeadowApp()
        {
            Initialize().Wait();

            mapleServer.Start();
            
        }
        public override Task Run()
        {
            mapleServer.Start();
            return base.Run();
           
        }
        public override  Task Initialize()
        {
            var onboardLed = new RgbPwmLed(device: Device,
                redPwmPin: Device.Pins.OnboardLedRed,
                greenPwmPin: Device.Pins.OnboardLedGreen,
                bluePwmPin: Device.Pins.OnboardLedBlue);
            onboardLed.SetColor(Color.Red);

            ServoController.Current.Initialize(Device, Device.Pins.D10);

            RelayController.Relay.Initialize(Device, Device.Pins.D02);

            onboardLed.SetColor(Color.Blue);
            var result = SetupWiFi();
            if(result.Result == true)
            {
                onboardLed.SetColor(Color.Green);
            }
            else
            {
                onboardLed.SetColor(Color.Red);
            }

            return base.Initialize();

            
        }

        private async Task<bool> SetupWiFi()
        {
            var wifi = Device.NetworkAdapters.Primary<IWiFiNetworkAdapter>();
           
            wifi.NetworkConnected += WiFiAdapter_NetworkConnected;

            ScanForAccessPoints(wifi);

            Console.WriteLine($"Connecting to WiFi Network {Secrets.WIFI_NAME}");

            var connectionResult = await wifi.Connect(Secrets.WIFI_NAME, Secrets.WIFI_PASSWORD, TimeSpan.FromSeconds(45));
            if (connectionResult.ConnectionStatus != ConnectionStatus.Success)
            {
                
                Console.WriteLine($"Cannot connect to network: {connectionResult.ConnectionStatus}");
                return false;
            }
            else
            {
               
                mapleServer = new MapleServer(wifi.IpAddress, 5417, true);
                DisplayNetworkInformation();
                return true;
            }
        }

        private void DisplayNetworkInformation()
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            if (adapters.Length == 0)
            {
                Console.WriteLine("No adapters available.");
            }
            foreach (NetworkInterface adapter in adapters)
            {
                IPInterfaceProperties properties = adapter.GetIPProperties();
                Console.WriteLine();
                Console.WriteLine(adapter.Description);
                Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length, '='));
                Console.WriteLine($"  Adapter name: {adapter.Name}");
                Console.WriteLine($"  Interface type .......................... : {adapter.NetworkInterfaceType}");
                Console.WriteLine($"  Physical Address ........................ : {adapter.GetPhysicalAddress().ToString()}");
                Console.WriteLine($"  Operational status ...................... : {adapter.OperationalStatus}");
                string versions = String.Empty;
                if (adapter.Supports(NetworkInterfaceComponent.IPv4))
                {
                    versions = "IPv4";
                }
                if (adapter.Supports(NetworkInterfaceComponent.IPv6))
                {
                    if (versions.Length > 0)
                    {
                        versions += " ";
                    }
                    versions += "IPv6";
                }
                Console.WriteLine($"  IP version .............................. : {versions}");
                if (adapter.Supports(NetworkInterfaceComponent.IPv4))
                {
                    IPv4InterfaceProperties ipv4 = properties.GetIPv4Properties();
                    Console.WriteLine("  MTU ..................................... : {0}", ipv4.Mtu);
                }
                if ((adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) || (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet))
                {
                    foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            Console.WriteLine($"  IP address .............................. : {ip.Address.ToString()}");
                            Console.WriteLine($"  Subnet mask ............................. : {ip.IPv4Mask.ToString()}");
                        }
                    }
                }
            }
        }

        private async Task ScanForAccessPoints(IWiFiNetworkAdapter wifi)
        {
            Console.WriteLine("Getting list of access points.");
            var networks = await wifi.Scan(TimeSpan.FromSeconds(60));

            if (networks.Count > 0)
            {
                Console.WriteLine("|-------------------------------------------------------------|---------|");
                Console.WriteLine("|         Network Name             | RSSI |       BSSID       | Channel |");
                Console.WriteLine("|-------------------------------------------------------------|---------|");

                foreach (WifiNetwork accessPoint in networks)
                {
                    Console.WriteLine($"| {accessPoint.Ssid,-32} | {accessPoint.SignalDbStrength,4} | {accessPoint.Bssid,17} |   {accessPoint.ChannelCenterFrequency,3}   |");
                }
            }
            else
            {
                Console.WriteLine($"No access points detected.");
            }
        }

        private void WiFiAdapter_NetworkConnected(object sender, EventArgs args)
        {
            Console.WriteLine("Connection request Complete...");
            
        }
    }

I get this error while running it:

Launching application…

[10/27/2022 3:30:26 PM] Meadow StdOut: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.NullReferenceException: Object reference not set to an instance of an object.
at MapleWithServoAndRelay.MeadowApp.Initialize () [0x00083] in <1133e8c17183465087ee745f33520b6e>:0
at MapleWithServoAndRelay.MeadowApp…ctor () [0x00008] in <1133e8c17183465087ee745f33[10/27/2022 3:30:26 PM] Meadow StdOut: 20b6e>:0
at (wrapper managed-to-native) System.Reflection.RuntimeConstructorInfo.InternalInvoke(System.Reflection.RuntimeConstructorInfo,object,object[],System.Exception&)
at System.Reflection.RuntimeConstructorInfo.InternalInvoke (System.Object obj, System.Object[] parameters, System.Boolean wrapExceptions) [0x00005] in <77563d7372d948198f425b41a9b84c90>:0
— End of inn[10/27/2022 3:30:26 PM] Meadow StdOut: r exception stack trace —
at System.Reflection.RuntimeConstructorInfo.InternalInvoke (System.Object obj, System.Object[] parameters, System.Boolean wrapExceptions) [0x0001a] in <77563d7372d948198f425b41a9b84c90>:0
at System.RuntimeType.CreateInstanceMono (System.Boolean nonPublic, System.Boolean wrapExceptions) [0x00095] in <77563d7372d948198f425b41a9b84c90>:0
at System.[10/27/2022 3:30:26 PM] Meadow StdOut: untimeType.CreateInstanceSlow (System.Boolean publicOnly, System.Boolean wrapExceptions, System.Boolean skipCheckThis, System.Boolean fillCache) [0x00009] in <77563d7372d948198f425b41a9b84c90>:0
at System.RuntimeType.CreateInstanceDefaultCtor (System.Boolean publicOnly, System.Boolean skipCheckThis, System.Boolean fillCache, System.Boolean wrapExceptions, System.Threading.Stack[10/27/2022 3:30:26 PM] Meadow StdOut: rawlMark& stackMark) [0x00027] in <77563d7372d948198f425b41a9b84c90>:0
at System.Activator.CreateInstance (System.Type type, System.Boolean nonPublic, System.Boolean wrapExceptions) [0x00020] in <77563d7372d948198f425b41a9b84c90>:0
at System.Activator.CreateInstance (System.Type type, System.Boolean nonPublic) [0x00000] in <77563d7372d948198f425b41a9b84c90>:0
at Meadow.Me[10/27/2022 3:30:26 PM] Meadow StdOut: dowOS.Initialize () [0x000e8] in :0
[10/27/2022 3:30:26 PM] Meadow StdOut: ERROR: Device Initialization Failure
[10/27/2022 3:30:26 PM] Meadow StdOut: INFORMATION: CRASH: Meadow will restart in 5 seconds.

It looks like it can’t initialize the relay. Here is the relay class:

 public class RelayController
    {
        Relay relay;
        protected bool initialized = false;
        public static RelayController Relay { get; private set; }

        
        public void Initialize(IMeadowDevice device, IPin pin)
        {
            if (initialized){
                return;
            };
            relay = new Relay(device.CreateDigitalOutputPort(pin));
            relay.IsOn = true;
            relay.IsOn = false;
            initialized = true;
        }
        public void OpenRelay()
        {
            relay.IsOn = true;
        }
        public void CloseRelay()
        {
            relay.IsOn = false;
        }
    }

Any help would be much appreciated.