Main Site Documentation

Timer, Azure and Potential Blocking


#1

Hello, I have a short program that is connecting to my wifi; then starting a timer which has a counter which then triggers a write Azure using the UCloudy Library.

I have been getting some random freezing of the board … sometimes in a few minutes, some times in hours …

I have a board running in my office with poor internet … at home I have a fast connection and have a second board running … it appears to be more reliable at home? Perhaps a clue!

Board is Cobra II with Wift running 4.3.6 with VS 2013.

My timer fires every 2 seconds and I flash the on board LED … there are times when the LED stops and does not restart … so showing the board has crashed … this is confirmed directly by looking at the data on Azure … At present the write to Azure is every 20 seconds, not for any particular reason … but I would like it to be quicker?

So there are times when the flashing is not consistent … so it will stop for a period and then flash rapidly … I assume this is showing that something is blocking? Azure or the net connection?

Would this be expected, do I need to put the Azure call in a thread? if so I have attempted this and have not been able to build, can anyone give me some clues on how to drop the azure call into a thread?

Or any other ideas to resolve this?

Many thanks
Robert


#2

@ Robert24 - it would be useful, if you could post some code.


#3

@ Robert24 - Given our recent email exchanges you might want to check this out from @ andre.m. Looks like it might help with knowing if you’re online or not. The exchange could run using WebRequest and WebResponse.

https://www.ghielectronics.com/community/forum/topic?id=17670&page=1#msg175731


#4

@ AWSOMEDEVSIGNER



using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Net.NetworkInformation;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using GHI.Networking;
using GHI.Pins;
using uPLibrary.Cloud.WindowsAzure.MobileService;

namespace Cobra436
{
    public partial class Program
    {
        // =============================================================================
        // Modify these lines to use your application key and Azure URL (Remember to 
        // change from https to http
        private const string APPLICATIONKEY = "";
        private readonly Uri _appUri = new Uri("");
        // =============================================================================
        
        GT.Timer t;
        GT.Timer networkReconnect;

        bool ledStatus = false;
        int counter = 0;

        Boolean azureWriteLock = false;

        long networkAvailableCount = 0;
        long networkUnavailableCount = 0;
        long networkChangedCount = 0;
        long networkReconnectCount = 0;
        long networkReconnectFailCount = 0;
        long azureExceptionCount = 0;
        long azureWriteCount = 0;
        long azureTimeout = 0;
        long loggerCount = 0;
        long loggerExceptionCount = 0;

        
        private static WiFiRS9110 netif;
        // This method is run when the mainboard is powered up or reset.   
        
        

        void ProgramStarted()
        {
            Thread azureThread = new Thread(azureThreadWriteData);

            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
            Debug.Print("Program Started");

            NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
            NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;

            netif = new WiFiRS9110(SPI.SPI_module.SPI2, G120.P1_10, G120.P2_11, G120.P1_9);
            netif.Open();
            netif.EnableDhcp();
            // Used to test DHCP and Staic IP
            //netif.EnableStaticIP("192.168.43.227", "255.255.255.0", "192.168.43.254");
            netif.EnableDynamicDns();
// =============================================================================
            // Update this line to use your Wifi Credentials
            netif.Join("","");
           // =============================================================================

            t = new GT.Timer(2000);
            t.Tick += t_Tick;
            t.Start();

            networkReconnect = new GT.Timer(60000);
            networkReconnect.Tick += networkReconnect_Tick;

            
        }
        
        void azureThreadWriteData()
        {
            WriteToAzure();
        }

        private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            Debug.Print("Network address changed - " + netif.IPAddress);

            // Wait a bit
            Thread.Sleep(2000);

            if (netif.IPAddress != "0.0.0.0")
            {
                //The network is now ready to use.
                Debug.Print("IP Address: " + netif.IPAddress);
                Debug.Print("Link Connected : " + netif.LinkConnected.ToString());
            }

            networkChangedCount++;
        }

        private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            Debug.Print("Network availability: " + e.IsAvailable.ToString());

            if (e.IsAvailable)
            {
                networkAvailableCount++;

                networkReconnect.Stop();
            }
            else
            {
                networkUnavailableCount++;

                networkReconnect.Start();
            }
        }

        void networkReconnect_Tick(GT.Timer timer)
        {
            
            Debug.Print("Network Reconnect");

            networkReconnect.Stop();

            networkReconnectCount++;

            try
            {
                netif.Close();
                netif.Dispose();
                netif = null;

                netif = new WiFiRS9110(SPI.SPI_module.SPI2, G120.P1_10, G120.P2_11, G120.P1_9);
                netif.Open();
                netif.EnableDhcp();
                netif.EnableDynamicDns();
                netif.Join("TRYW02", "TRYW022012");
            }
            catch (Exception ex)
            {

                networkReconnectFailCount++;

                Debug.Print("Network Reconnect Exception: " + ex.ToString());
                networkReconnect.Start();
            }
        }

        void t_Tick(GT.Timer timer)
        {
            // Flash the LED
            Mainboard.SetDebugLED(!ledStatus);
            ledStatus = !ledStatus;

            Debug.Print("IP Addr in main: " + netif.IPAddress + " - Link: " + netif.LinkConnected.ToString());

            counter++;

            // =============================================================================
            // This only gets called every 150 x 2 seconds or 5 minutes to reduce the amount
            // of data sent to Azure. I would reduce it from 150 to 1 or 2 for debugging
            // =============================================================================
            if (counter == 10) // Reduce this to increase the number of calls to Azure
            {
                counter = 0;
                // Only write if the DHCP has assigned an address
                if (netif.IPAddress != "0.0.0.0" && !azureWriteLock)
                {

                    azureWriteLock = true;

                    WriteToAzure();
                    WriteToLog();

                    azureWriteLock = false;

                    //aureThread.Start(); 
                }
                else
                {
                    azureTimeout++;
                }

                Debug.Print("networkAvailableCount=" + networkAvailableCount.ToString());
                Debug.Print("networkUnavailableCount=" + networkUnavailableCount.ToString());
                Debug.Print("networkChangedCount=" + networkChangedCount.ToString());
                Debug.Print("networkReconnectCount=" + networkReconnectCount.ToString());
                Debug.Print("networkReconnectFailCount=" + networkReconnectFailCount.ToString());
                Debug.Print("azureWriteCount=" + azureWriteCount.ToString());
                Debug.Print("azureExceptionCount=" + azureExceptionCount.ToString());
                Debug.Print("azureTimeout=" + azureTimeout.ToString());
                Debug.Print("logCount=" + loggerCount.ToString());
                Debug.Print("logExceptionCount=" + loggerExceptionCount.ToString());
            }
        }

        #region Mobile Services

        

        private void WriteToAzure()
        {
         

            try
            {
                Debug.Print("Writing to Azure");
                // Create the mobile services client using the url and key from manage.windowsazure.com
                var mobileServiceClient = new MobileServiceClient(_appUri, null, APPLICATIONKEY);
                // Retrieve the table, using the table name from Azure
                IMobileServiceTable myTable = mobileServiceClient.GetTable("CobraTable");

                // =============================================================================
                // A table called CobraTable must exist in your Azure Service before executing 
                // these lines otherwise you will recevie an error
                // Otherwise rename the class to something you like and make sure tha cable in
                //Azure is called the same. You don't need to add the fields, this will be
                // done automatically when the first record is written
                CobraTable t = new CobraTable() { Name = "Robert", RandomNumber = System.Math.PI };
                // Insert the new record
                string result = myTable.Insert(t);
                // =============================================================================

                azureWriteCount++;

                Debug.Print("writeData: " + t.ToJson());
                Debug.Print("Result: " + result);
            }
            catch (Exception ex)
            {
                Debug.Print("Azure Error: " + ex.Message);

                azureExceptionCount++;
            }
        }

        private void WriteToLog()
        {


            try
            {
                Debug.Print("Writing to Azure Log");
                // Create the mobile services client using the url and key from manage.windowsazure.com
                var mobileServiceClient = new MobileServiceClient(_appUri, null, APPLICATIONKEY);
                // Retrieve the table, using the table name from Azure
                IMobileServiceTable myTable = mobileServiceClient.GetTable("Log");

                // =============================================================================
                // A table called CobraTable must exist in your Azure Service before executing 
                // these lines otherwise you will recevie an error
                // Otherwise rename the class to something you like and make sure tha cable in
                //Azure is called the same. You don't need to add the fields, this will be
                // done automatically when the first record is written
                LogTable t = new LogTable() { lognetworkAvailableCount = networkAvailableCount, lognetworkUnAvailableCount = networkUnavailableCount,
                lognetworkChangedCount = networkChangedCount, lognetworkReconnectCount = networkReconnectCount, lognetworkReconnectFailCount = networkReconnectFailCount,
                logazureWriteCount = azureWriteCount, logazureExceptionCount = azureExceptionCount, logazureTimeoutCount = azureTimeout, logCount = loggerCount, logExceptionCount = loggerExceptionCount };
                // Insert the new record
                string result = myTable.Insert(t);
                // =============================================================================

                loggerCount++;

                Debug.Print("writeData: " + t.ToJson());
                Debug.Print("Result: " + result);
                Debug.Print("WriteCount=" + azureWriteCount.ToString());
            }
            catch (Exception ex)
            {
                Debug.Print("Azure Log Error: " + ex.Message);

                loggerExceptionCount++;
            }
        }

        #endregion


    }
}


#5

edit your post and fix up the code tags !


#6

@ Robert24 - I am not sure if the amount of debug-messages you are printing leads to the problems. Could you try to comment out all of your log messages and try to run your app again?


#7

@ AWSOMEDEVSIGNER

interesting thought; I have done this and have 2 devices running… I will give an update when they stop or after 24 hours if they are still running!

Thx


#8

@ AWSOMEDEVSIGNER

I am afraid both boards locked over night … however, when considering issues like the Debug.Print … I also have them powered via USB through my monitors.

So I have connected to mains supply today to see if that makes any difference! Why would it? We will find out!

The code is shown in this thread, can anyone else see why this would lock the boards?


#9

@ Robert24 - Hi Robert, I am not sure about the whole issue. Curious to see if it makes any difference. And I will try some experiments on my own with the Azure library you have used.


#10

@ AWSOMEDEVSIGNER

it has run for 24 hours so far … so if it is still running tomorrow … then it points to the USB power supply … I will let you know!


#11

Robert, my Cobra has been running since about 3pm on Friday from a mains powered PSU running the Azure Mobile Services code based on @ ppatierno source. I’ll keep you posted.


#12

Xmas party last night; great a hang over today … but good news … both Cobra boards are still blinking … I have not checked Azure as yet, but I assume the data is being sent!

I will try a test by connecting one back to my USB hub … and one to an alternative USB connection …

To try and understand if this is problem with the Cobra or supply from my USB source!