peony3000

Gadgeteer_Weather_Crier_05

Feb 21st, 2013
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 33.07 KB | None | 0 0
  1. // load the main libraries
  2. using System;
  3. using System.Collections;
  4. using System.Threading;
  5. using Microsoft.SPOT;
  6.  
  7. // used for the display screen
  8. //using Microsoft.SPOT.Presentation;
  9. //using Microsoft.SPOT.Presentation.Controls;
  10. //using Microsoft.SPOT.Presentation.Media;
  11. //using Microsoft.SPOT.Touch;
  12.  
  13. // used for the wifi networking
  14. using Microsoft.SPOT.Net;
  15. using Microsoft.SPOT.Hardware;
  16. using System.Net;
  17. using System.Net.Sockets;
  18.  
  19. // used to access and read the http xml file
  20. using System.Xml;
  21. using System.IO;
  22.  
  23. // used to enable the gadgeteer hardware
  24. //using GHI.Premium.USBHost;
  25. using GHI.Premium.Net;
  26. using Gadgeteer.Networking;
  27. using GT = Gadgeteer;
  28. using GTM = Gadgeteer.Modules;
  29. using Gadgeteer.Modules.Seeed;
  30. using Gadgeteer.Modules.GHIElectronics;
  31. using Gadgeteer.Modules.Music_Driver;
  32.  
  33.  
  34. namespace Gadgeteer_Weather_Crier_05
  35. {
  36.  
  37.     public partial class Program
  38.     {
  39.         // global variables
  40.         GT.StorageDevice usbStorage;
  41.  
  42.         // are we using the old weather or shall we get the latest?
  43.         bool oldWeather = false;
  44.  
  45.         // are we using the RISD network or are we at home?
  46.         bool risdNet = true;
  47.  
  48.         // usb drive
  49.         String root;
  50.  
  51.         // music file handling
  52.         FileStream stream;
  53.         String[] musicFiles = new String[6];
  54.         //ArrayList musicFiles = new ArrayList();
  55.         int currentFile = 0;
  56.  
  57.         // log file
  58.         //StreamWriter usbLogFile;
  59.         String logFilename = "system\\queryLog.txt";
  60.         String audioLogFilename = "system\\audioLog.txt";
  61.         //String preferencesFileName = "system\\preferences.txt";
  62.         //String errorFilename = "system\\error.txt";
  63.  
  64.         // query start and close times
  65.         int startTime = 8;
  66.         int closeTime = 20;
  67.         float maxWeatherReports = 6;
  68.  
  69.         // time object to control blink
  70.         TimeSpan blinkTime = new TimeSpan(0,0,1);
  71.            
  72.         // networking socket for weird time protocol
  73.         Socket socket;
  74.  
  75.         // create a time based event robot to trigger something
  76.         GT.Timer timer = new GT.Timer(5000, GT.Timer.BehaviorType.RunOnce);
  77.  
  78.         // This method is run when the mainboard is powered up or reset.  
  79.         void ProgramStarted()
  80.         {
  81.  
  82.             Debug.Print("Initializing Accelerometer Events");
  83.             // set the calibration point (the device shouldn't be moving!)
  84.             accelerometer.Calibrate();
  85.             //accelerometer threshold bump method
  86.             accelerometer.ThresholdExceeded += new Accelerometer.ThresholdExceededEventHandler(accelerometer_ThresholdExceeded);
  87.             accelerometer.MeasurementRange = GTM.Seeed.Accelerometer.Range.TwoG;
  88.            
  89.             Debug.Print("Initializing Music Player Events");
  90.             // music finished listening robot (who is a bit deaf!!)
  91.             music.MusicFinished += new Music.MusicFinishedPlayingEventHandler(music_musicFinished);
  92.             music.SetVolume(255);
  93.             // mark the musicFiles as empty
  94.             musicFiles[0] = "empty";
  95.  
  96.             // timer event handler
  97.             Debug.Print("Initializing Timer Event");
  98.             timer.Tick += new GT.Timer.TickEventHandler(timer_Tick);
  99.            
  100.             // switch the green blue leds
  101.             multicolorLed.GreenBlueSwapped = true;
  102.  
  103.             Debug.Print("Initializing USB Drive Events");
  104.             usbHost.USBDriveConnected += new UsbHost.USBDriveConnectedEventHandler(usbHost_USBDriveConnected);
  105.             usbHost.USBDriveDisconnected += new UsbHost.USBDriveDisconnectedEventHandler(usbHost_USBDriveDisconnected);
  106.             Debug.Print("Checking for USB Drive Connected Event....");
  107.  
  108.             Debug.Print("Turning on LED");
  109.             // turn LED to red flashing
  110.             multicolorLed.BlinkRepeatedly(GT.Color.Red, blinkTime, GT.Color.Black, blinkTime);
  111.  
  112.             Debug.Print("Program Started");
  113.  
  114.         }
  115.  
  116.         void accelerometer_ThresholdExceeded(Accelerometer sender)
  117.         {
  118.             Debug.Print("Bump detected!");
  119.  
  120.             // turn LED to blue
  121.             multicolorLed.TurnBlue();
  122.  
  123.             // reset the audio queue
  124.             currentFile = 0;
  125.  
  126.             // read the last query time and date from the log so we can make sure that we aren't exceeding our 6 per day query allowance
  127.  
  128.             // a string for the next allowed query
  129.             String logReadFileString = readDataFile(logFilename);
  130.  
  131.             Debug.Print("Today is : " + DateTime.Now.ToString("yyMMdd"));
  132.             Debug.Print("Reading the log file.... The next query is allowed at " + logReadFileString.Substring(logReadFileString.IndexOf(":") + 1, 2) + " hours");
  133.             Debug.Print("The logged date is " + int.Parse(logReadFileString.Substring(0, 6)));
  134.  
  135.             if (int.Parse(DateTime.Now.ToString("HH")) > startTime
  136.             && closeTime > int.Parse(DateTime.Now.ToString("HH"))
  137.             )
  138.             {
  139.                 Debug.Print("In the active time period!");
  140.                 Debug.Print("Working out what to do....");
  141.  
  142.                 // if current date is more than the log date then get new report
  143.                 if ((int.Parse(DateTime.Now.ToString("yyMMdd")) > int.Parse(logReadFileString.Substring(0, 6))))
  144.                 {
  145.                     Debug.Print("New day! Getting a new weather report");
  146.                     // get the new weather report
  147.                     getXmlFromWeb();
  148.                     // get the time
  149.                     //NTPTime("time.windows.com", (-(60 * 5)));
  150.  
  151.  
  152.                 }
  153.                 // else if current date is equal to the log date
  154.                 // and the current time is more than or equal to the log time
  155.                 else if (int.Parse(DateTime.Now.ToString("HH")) >= int.Parse(logReadFileString.Substring(logReadFileString.IndexOf(":") + 1, 2))
  156.                 && (int.Parse(DateTime.Now.ToString("yyMMdd")) >= int.Parse(logReadFileString.Substring(0, 6)))
  157.                 )
  158.                 {
  159.                     // get a new weather report
  160.                     Debug.Print("Getting a new weather report");
  161.                     // get the new weather report
  162.                     getXmlFromWeb();
  163.  
  164.                 }
  165.                 // else use existing weather report
  166.                 else
  167.                 {
  168.                     Debug.Print("Going to use an existing report");
  169.  
  170.                     // if the empty marker has been overwritten
  171.                     if (musicFiles[0] != "empty")
  172.                     {
  173.                         Debug.Print("Not enough time has yet passed. Using the existing weather report.");
  174.                         // play the old weather report that already is in the memory
  175.                         playTrack();
  176.                     }
  177.                     else
  178.                     {
  179.                         Debug.Print("No musicFiles!! We must have just been turned on and off or crashed");
  180.                         // get the log entry
  181.                         // an array for the music files
  182.                         String[] audioLog = readDataFile(audioLogFilename).Split('\r');
  183.                         // what about '\n'?
  184.  
  185.                         Debug.Print("audioLog.Length " + audioLog.Length);
  186.                         Debug.Print("audioLog[0] " + audioLog[0]);
  187.                         Debug.Print("audioLog[1] " + audioLog[1]);
  188.                         Debug.Print("audioLog[2] " + audioLog[2]);
  189.                         Debug.Print("audioLog[3] " + audioLog[3]);
  190.                         Debug.Print("audioLog[4] " + audioLog[4]);
  191.                         Debug.Print("audioLog[5] " + audioLog[5]);
  192.                         musicFiles[0] = audioLog[0].Trim();
  193.                         musicFiles[1] = audioLog[1].Trim();
  194.                         musicFiles[2] = audioLog[2].Trim();
  195.                         musicFiles[3] = audioLog[3].Trim();
  196.                         musicFiles[4] = audioLog[4].Trim();
  197.                         musicFiles[5] = audioLog[5].Trim();
  198.  
  199.                         // reset greeting
  200.                         if (DateTime.Now.ToString("tt") == "AM")
  201.                         {
  202.                             Debug.Print("Adding: audio\\Good Morning");
  203.                             musicFiles[0] = ("audio" + Path.DirectorySeparatorChar + "goodmorning.mp3");
  204.                         }
  205.                         else if (DateTime.Now.ToString("tt") == "PM")
  206.                         {
  207.                             Debug.Print(DateTime.Now.Hour.ToString());
  208.                             if (DateTime.Now.Hour > 17)
  209.                             {
  210.                                 Debug.Print("Adding: audio\\Good Evening");
  211.                                 musicFiles[0] = ("audio" + Path.DirectorySeparatorChar + "goodevening.mp3");
  212.                             }
  213.                             else
  214.                             {
  215.                                 Debug.Print("Adding: audio\\Good Afternoon");
  216.                                 musicFiles[0] = ("audio" + Path.DirectorySeparatorChar + "goodafternoon.mp3");
  217.  
  218.                             }
  219.                         }
  220.  
  221.                         // play logged tracks from last query
  222.                         playTrack();
  223.  
  224.                     }
  225.                 }
  226.             }
  227.             else
  228.             {
  229.                 Debug.Print("Outside of the allowed time period");
  230.                 Debug.Print("You'll have to wait.....");
  231.                 Debug.Print("Resetting bump detection");
  232.                 // reset bump detection
  233.                 accelerometer.ResetThresholdDetection();
  234.  
  235.                 // turn LED to blue
  236.                 multicolorLed.TurnBlue();
  237.             }
  238.         }
  239.  
  240.         void getXmlFromWeb()
  241.         {
  242.             if (oldWeather)
  243.             {
  244.                 WebClient.GetFromWeb("http://inbetwixt.com/weather/weather.xml").ResponseReceived += new HttpRequest.ResponseHandler(Program_ResponseReceived);
  245.             }
  246.             else
  247.             {
  248.                 WebClient.GetFromWeb("http://api.wunderground.com/api/yournumber/forecast/q/yourzip.xml").ResponseReceived += new HttpRequest.ResponseHandler(Program_ResponseReceived);
  249.             }
  250.             Debug.Print("***Waiting for response...");
  251.  
  252.         }
  253.  
  254.         void writeLogFile()
  255.         {
  256.             Debug.Print("Writing Log Query File");
  257.             // create a file input writing stream
  258.             // root comes from the usb connected method
  259.             FileStream createdFile = File.Open(usbStorage.RootDirectory + Path.DirectorySeparatorChar + logFilename, FileMode.Create);
  260.             StreamWriter usbLogFile = new StreamWriter(createdFile);
  261.  
  262.             String logWriteFileString = (DateTime.Now.ToString("yyMMdd") + ":" + ((int.Parse(DateTime.Now.ToString("HH")) + (int)(closeTime - startTime) / maxWeatherReports)));
  263.  
  264.             Debug.Print("Start time: " + startTime);
  265.             for (int increment = 1; increment <= maxWeatherReports; increment++)
  266.             {
  267.                 Debug.Print("Slot " + increment + " ends: " + (int)(startTime + ((closeTime - startTime) / maxWeatherReports) * increment));
  268.             }
  269.             Debug.Print("Closing time: " + closeTime);
  270.  
  271.             try
  272.             {
  273.                 // write the line
  274.                 usbLogFile.Write(logWriteFileString);
  275.             }
  276.             catch (IOException e)
  277.             {
  278.                 Debug.Print("IOException " + e);
  279.             }
  280.             catch (Exception e)
  281.             {
  282.                 Debug.Print("Exception " + e);
  283.             }
  284.             finally
  285.             {
  286.                 if (usbLogFile != null)
  287.                     usbLogFile.Close();
  288.             }
  289.  
  290.         }
  291.         void writeAudioLogFile()
  292.         {
  293.             Debug.Print("Writing Audio Log Query File");
  294.             // create a file input writing stream
  295.             // root comes from the usb connected method
  296.             FileStream createdFile = File.Open(usbStorage.RootDirectory + Path.DirectorySeparatorChar + audioLogFilename, FileMode.Create);
  297.             StreamWriter usbLogFile = new StreamWriter(createdFile);
  298.  
  299.             String[] logWriteFileString = new String[6];
  300.             // first line is
  301.             logWriteFileString[0] = musicFiles[0];
  302.             Debug.Print(logWriteFileString[0]);
  303.             // second line is
  304.             logWriteFileString[1] = musicFiles[1];
  305.             Debug.Print(logWriteFileString[1]);
  306.             // third line is
  307.             logWriteFileString[2] = musicFiles[2];
  308.             Debug.Print(logWriteFileString[2]);
  309.             // fourth line is
  310.             logWriteFileString[3] = musicFiles[3];
  311.             Debug.Print(logWriteFileString[3]);
  312.             // fifth line is
  313.             logWriteFileString[4] = musicFiles[4];
  314.             Debug.Print(logWriteFileString[4]);
  315.             // sixth line is
  316.             logWriteFileString[5] = musicFiles[5];
  317.             Debug.Print(logWriteFileString[5]);
  318.  
  319.             try
  320.             {
  321.                 // how do you write an array in one line?
  322.                 usbLogFile.WriteLine(logWriteFileString[0]);
  323.                 usbLogFile.WriteLine(logWriteFileString[1]);
  324.                 usbLogFile.WriteLine(logWriteFileString[2]);
  325.                 usbLogFile.WriteLine(logWriteFileString[3]);
  326.                 usbLogFile.WriteLine(logWriteFileString[4]);
  327.                 usbLogFile.WriteLine(logWriteFileString[5]);
  328.                 usbLogFile.Close();
  329.             }
  330.             catch (IOException e)
  331.             {
  332.                 Debug.Print("IOException " + e);
  333.             }
  334.             catch (Exception e)
  335.             {
  336.                 Debug.Print("Exception " + e);
  337.             }
  338.             //finally
  339.             //{
  340.             //    if (usbLogFile != null)
  341.             //        usbLogFile.Close();
  342.             //}
  343.  
  344.         }
  345.  
  346.         String readDataFile(String dataFileName)
  347.         {
  348.             Debug.Print("Reading Data File " + dataFileName);
  349.             String fileContent = "";
  350.  
  351.             if (File.Exists(usbStorage.RootDirectory + Path.DirectorySeparatorChar + logFilename))
  352.             {
  353.                 StreamReader usbReadFile = new StreamReader(new FileStream(usbStorage.RootDirectory + Path.DirectorySeparatorChar + dataFileName, FileMode.Open, FileAccess.Read));
  354.                 fileContent = usbReadFile.ReadToEnd();
  355.                 usbReadFile.Close();
  356.             }
  357.             Debug.Print("Reading in: " + fileContent);
  358.             return fileContent;
  359.         }
  360.  
  361.         void playTrack()
  362.         {
  363.  
  364.             // turn LED to green flashing
  365.             multicolorLed.BlinkRepeatedly(GT.Color.Green, blinkTime, GT.Color.Black, blinkTime);
  366.  
  367.            
  368.             Debug.Print("currentFile " + currentFile);
  369.             Debug.Print("Opening track: " + (String)musicFiles[currentFile]);
  370.             stream = usbStorage.Open((String)musicFiles[currentFile], FileMode.Open, FileAccess.Read);
  371.             music.SetVolume(255);
  372.             Debug.Print("Starting to play: " + (String)musicFiles[currentFile]);
  373.             music.Play(stream);
  374.             while (music.IsBusy)
  375.             {
  376.                 // You can't call music.StopPlaying or set volume with this loop running.    
  377.                 Thread.Sleep(10);
  378.             }
  379.  
  380.         }
  381.  
  382.  
  383.         void music_musicFinished(Music sender)
  384.         {
  385.             Debug.Print("Music Finished");
  386.             // close the usb stream
  387.             stream.Close();
  388.  
  389.             if (currentFile < musicFiles.Length - 1)
  390.             {
  391.                 // next track
  392.                 currentFile++;
  393.                 Debug.Print("Moving to next audio track: currentFile = " + currentFile);
  394.  
  395.                 playTrack();
  396.             }
  397.             else
  398.             {
  399.                 // reset
  400.                 Debug.Print("Resetting bump and audio");
  401.                 accelerometer.ResetThresholdDetection();
  402.  
  403.                 // turn LED to green steady (not flashing)
  404.                 multicolorLed.TurnGreen();
  405.             }
  406.         }
  407.  
  408.         void usbHost_USBDriveDisconnected(UsbHost sender)
  409.         {
  410.             Debug.Print("USB Storage Disconnected");
  411.             //musicFiles.Clear();
  412.             usbStorage = null;
  413.         }
  414.  
  415.         void usbHost_USBDriveConnected(UsbHost sender, GT.StorageDevice storageDevice)
  416.         {
  417.             Debug.Print("USB Storage connected");
  418.  
  419.             usbStorage = storageDevice;
  420.             root = usbStorage.RootDirectory;
  421.  
  422.             // on the usb drive there should be:
  423.             // an 'audio' folder with all the files listed at the bottom of this page
  424.             // and a 'system' folder with:
  425.             // a file called preferences.txt
  426.             // a file called queryLog.txt
  427.             // a file called audioLog.txt
  428.             // a file called error.txt
  429.  
  430.             // read the settings file to get:
  431.             // audio folder name
  432.             // system folder name
  433.             // wifi network name and password
  434.             // world clock location
  435.             // timezone or gmt offset for your location
  436.  
  437.             // pointless
  438.             //string[] rootAudioFolder = usbStorage.ListFiles("audio");
  439.             //foreach (string fileName in rootAudioFolder)
  440.             //{
  441.             //    Debug.Print(fileName);
  442.  
  443.             //}
  444.  
  445.             // now we have the settings
  446.             // start the Wifi
  447.             startWifi();
  448.  
  449.         }
  450.  
  451.         void startWifi()
  452.         {
  453.  
  454.             // turn LED to red flashing
  455.             multicolorLed.BlinkRepeatedly(GT.Color.Red, blinkTime, GT.Color.Black, blinkTime);
  456.  
  457.             if (!wifi_RS21.Interface.IsOpen)
  458.             {
  459.                 wifi_RS21.Interface.Open();
  460.             }
  461.  
  462.             if (!wifi_RS21.Interface.NetworkInterface.IsDhcpEnabled)
  463.             {
  464.                 wifi_RS21.Interface.NetworkInterface.EnableDhcp();
  465.             }
  466.  
  467.             GHI.Premium.Net.NetworkInterfaceExtension.AssignNetworkingStackTo(wifi_RS21.Interface);
  468.  
  469.             wifi_RS21.Interface.WirelessConnectivityChanged += new GHI.Premium.Net.WiFiRS9110.WirelessConnectivityChangedEventHandler(Interface_WirelessConnectivityChanged);
  470.             wifi_RS21.Interface.NetworkAddressChanged += new GHI.Premium.Net.NetworkInterfaceExtension.NetworkAddressChangedEventHandler(Interface_NetworkAddressChanged);
  471.  
  472.             String networkName;
  473.             String networkPassword;
  474.  
  475.             try
  476.             {
  477.                 // Your router SSID needed here
  478.                 if (risdNet)
  479.                 {
  480.                     //GHI.Premium.Net.WiFiNetworkInfo[] ScanResp = wifi_RS21.Interface.Scan("RISD-MiscDevices"); //< Needs to be changed to SSID you are looking for
  481.                     networkName = "RISD-MiscDevices";
  482.                     Debug.Print("Trying RISD network");
  483.                 }
  484.                 else
  485.                 {
  486.                     // home network
  487.                     networkName = "Network Name";
  488.                     Debug.Print("Trying home network");
  489.            
  490.                 }
  491.  
  492.                 // wifi needs your SSID network name
  493.                 GHI.Premium.Net.WiFiNetworkInfo[] ScanResp = wifi_RS21.Interface.Scan(networkName);
  494.  
  495.                 if (ScanResp != null && ScanResp.Length > 0)
  496.                 {
  497.  
  498.                     // passkey needed here
  499.                     if (risdNet)
  500.                     {
  501.                         networkPassword = "RISD Password";
  502.                     }
  503.                     else
  504.                     {
  505.                         networkPassword = "Home Password";
  506.                     }
  507.  
  508.                     // wifi needs the password key
  509.                     wifi_RS21.Interface.Join(ScanResp[0], networkPassword);
  510.                     Debug.Print("***Connected to network...");
  511.  
  512.                 }
  513.                 else
  514.                 {
  515.                     Debug.Print("***Wireless network was not found");
  516.                     Debug.Print("Switching networks");
  517.                     // flip the network switch?
  518.                     risdNet = !risdNet;
  519.                     startWifi();
  520.                    
  521.  
  522.                 }
  523.             }
  524.             catch (Exception e)
  525.             {
  526.                 Debug.Print("!!! Exception : " + e.Message);
  527.             }
  528.  
  529.         }
  530.  
  531.         void timer_Tick(GT.Timer timer)
  532.         {
  533.             //Debug.Print("Restarting Wifi");
  534.             //startWifi();
  535.             timer.Stop();
  536.  
  537.             Debug.Print("Retrying Time");
  538.             if (NTPTime("time.windows.com", (-(60 * 5))))
  539.             {
  540.  
  541.                 Debug.Print("The time has been set correctly");
  542.                 // turn LED to green steady
  543.                 multicolorLed.TurnGreen();
  544.  
  545.                 // reset
  546.                 Debug.Print("Starting bump detection");
  547.                 // turn on the bump detection
  548.                 accelerometer.EnableThresholdDetection(-3.0, false, false, true, true, false, false);
  549.             }
  550.             else
  551.             {
  552.                 Debug.Print("The time wasn't set!");
  553.                 // no where to go from here!!
  554.  
  555.                 // turn LED to red steady
  556.                 multicolorLed.TurnRed();
  557.  
  558.                 // try to restart wifi
  559.                 timer.Start();
  560.             }
  561.  
  562.  
  563.            
  564.         }
  565.  
  566.         void Interface_WirelessConnectivityChanged(object sender, GHI.Premium.Net.WiFiRS9110.WirelessConnectivityEventArgs e)
  567.         {
  568.  
  569.             if (e.IsConnected)
  570.             {
  571.  
  572.                 // Add the time zone offset to the retrieved UTC Time
  573.                 // (in this example, it assumes that the time zone is GMT-6).
  574.                 // You will need to adjust TimeService.SetTimeZoneOffset value for your time zone
  575.  
  576.                 //UTC -6 hours for Central Standard Time. Use -(60 * 5) for Daylight savings time.
  577.                 //You will need to change NTPTime to your Time Zone
  578.  
  579.                 Debug.Print("***WirelessConnectivityChanged event!");
  580.                 Debug.Print("***Wifi Connected!");
  581.                 Debug.Print("***RSSI : " + e.NetworkInformation.RSSI.ToString());
  582.                 Debug.Print("***IP Address : " + wifi_RS21.Interface.NetworkInterface.IPAddress);
  583.  
  584.                 // now we are connected
  585.                 // get the time
  586.                 // set the offset from GMT
  587.                 if (NTPTime("time.windows.com", (-(60 * 5))))
  588.                 {
  589.  
  590.                     Debug.Print("The time has been set correctly");
  591.                     // turn LED to green steady
  592.                     multicolorLed.TurnGreen();
  593.  
  594.                     // reset
  595.                     Debug.Print("Starting bump detection");
  596.                     // turn on the bump detection
  597.                     accelerometer.EnableThresholdDetection(-3.0, false, false, true, true, false, false);
  598.                 }
  599.                 else
  600.                 {
  601.                     Debug.Print("The time wasn't set!");
  602.                     // no where to go from here!!
  603.                    
  604.                     // turn LED to red steady
  605.                     multicolorLed.TurnRed();
  606.  
  607.                     // try to restart wifi
  608.                     timer.Start();
  609.                 }
  610.  
  611.             }
  612.             else
  613.             {
  614.                 Debug.Print("***WirelessConnectivityChanged event!");
  615.                 Debug.Print("***Wifi Not Connected!");
  616.                 Debug.Print("***RSSI : " + e.NetworkInformation.RSSI.ToString());
  617.                 Debug.Print("***IP Address : " + wifi_RS21.Interface.NetworkInterface.IPAddress);
  618.  
  619.             }
  620.         }
  621.  
  622.         bool NTPTime(string TimeServer, int GmtOffset = 0)
  623.         {
  624.             // check the time
  625.  
  626.             socket = null;
  627.             try
  628.             {
  629.  
  630.                 EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
  631.                 socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  632.                 byte[] ntpData = new byte[48];
  633.                 Array.Clear(ntpData, 0, 48);
  634.                 // Set protocol version
  635.                 ntpData[0] = 0x1B;
  636.                 // Send Request  
  637.                 socket.SendTo(ntpData, rep);
  638.                 if (socket.Poll(60 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 60s, if nothing: timeout
  639.                 {
  640.  
  641.                     socket.ReceiveFrom(ntpData, ref rep); // Receive Time
  642.                     byte offsetTransmitTime = 40;
  643.                     ulong intpart = 0;
  644.                     ulong fractpart = 0;
  645.                     for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
  646.                     for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
  647.                     ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
  648.                     socket.Close();
  649.                     DateTime dateTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
  650.  
  651.                     Utility.SetLocalTime(dateTime.AddMinutes(GmtOffset));
  652.                     Debug.Print("### Time Server : " + DateTime.Now.ToString("hh tt"));  // should be something like 09 AM
  653.                     //("yyyy-MM-dd hh:mm:ss tt")
  654.                     // turn LED to green flashing
  655.                     //multicolorLed.BlinkRepeatedly(GT.Color.Green, blinkTime, GT.Color.Black, blinkTime);
  656.  
  657.                     return true;
  658.                 }
  659.                 else
  660.                 {
  661.                      Debug.Print("Failed to get the time");
  662.                    
  663.                 }
  664.                 socket.Close();
  665.             }
  666.             catch (Exception e)
  667.             {
  668.  
  669.                 Debug.Print("Exception " + e);
  670.  
  671.                 try
  672.                 {
  673.                     socket.Close();
  674.                 }
  675.                 catch
  676.                 {
  677.                     Debug.Print("Failed to close the socket");
  678.                  
  679.                 }
  680.                 // turn LED to red
  681.                 multicolorLed.TurnRed();
  682.            
  683.                 return false;
  684.             }
  685.                    
  686.             return false;
  687.         }
  688.  
  689.  
  690.  
  691.         void Program_ResponseReceived(HttpRequest sender, HttpResponse response)
  692.         {
  693.  
  694.             // the general format is:
  695.             // musicFiles[0] = greeting
  696.             // audio\Good Morning.mp3
  697.             // musicFiles[1] = today
  698.             // audio\Today.mp3
  699.             // musicFiles[2] = today's forecast
  700.             // audio\Partly Cloudy.mp3
  701.             // musicFiles[3] = tomorrow
  702.             // audio\Tomorrow.mp3
  703.             // musicFiles[4] = tomorrow's forecast
  704.             // audio\Sunny.mp3
  705.             // musicFiles[5] = goodbye
  706.  
  707.  
  708.             // check the new correct time
  709.             // using a bizzare am pm method!!??
  710.             if (DateTime.Now.ToString("tt") == "AM")
  711.             {
  712.                 Debug.Print("Adding: audio\\Good Morning");
  713.                 musicFiles[0] = ("audio" + Path.DirectorySeparatorChar + "goodmorning.mp3");
  714.             }
  715.             else if (DateTime.Now.ToString("tt") == "PM")
  716.             {
  717.                 Debug.Print(DateTime.Now.Hour.ToString());
  718.                 if (DateTime.Now.Hour > 17)
  719.                 {
  720.                     Debug.Print("Adding: audio\\Good Evening");
  721.                     musicFiles[0] = ("audio" + Path.DirectorySeparatorChar + "goodevening.mp3");
  722.                 }
  723.                 else
  724.                 {
  725.                     Debug.Print("Adding: audio\\Good Afternoon");
  726.                     musicFiles[0] = ("audio" + Path.DirectorySeparatorChar + "goodafternoon.mp3");
  727.  
  728.                 }
  729.             }
  730.  
  731.             XmlReader reader = XmlReader.Create(response.Stream);
  732.  
  733.             // use the simpleforecast
  734.             // extract the conditions
  735.             // change this to read the <icon> as there are less options and they are all known
  736.  
  737.             while (reader.Read())
  738.             {
  739.                 switch (reader.NodeType)
  740.                 {
  741.                     case XmlNodeType.Element:
  742.                         //Debug.Print("Element: " + reader.Name);
  743.  
  744.                         if (reader.Name.Equals("simpleforecast"))
  745.                         {
  746.                             reader.ReadToFollowing("forecastday");
  747.                             reader.ReadToFollowing("period");
  748.                             if (reader.ReadElementString().Equals("1"))
  749.                             {
  750.                                 //reader.ReadToFollowing("conditions");
  751.                                 reader.ReadToFollowing("icon");
  752.                                 string todaysCondition = reader.ReadElementString();
  753.                                 Debug.Print("Today's forecast is: " + todaysCondition);
  754.                                 musicFiles[1] = ("audio" + Path.DirectorySeparatorChar + "today.mp3");
  755.                                 musicFiles[2] = ("audio" + Path.DirectorySeparatorChar + todaysCondition + ".mp3");
  756.  
  757.                             }
  758.  
  759.                             reader.ReadToFollowing("forecastday");
  760.                             reader.ReadToFollowing("period");
  761.                             if (reader.ReadElementString().Equals("2"))
  762.                             {
  763.                                 //reader.ReadToFollowing("conditions");
  764.                                 reader.ReadToFollowing("icon");
  765.                                 string tomorrowsCondition = reader.ReadElementString();
  766.                                 Debug.Print("Tomorrow's forecast is: " + tomorrowsCondition);
  767.                                 musicFiles[3] = ("audio" + Path.DirectorySeparatorChar + "tomorrow.mp3");
  768.                                 musicFiles[4] = ("audio" + Path.DirectorySeparatorChar + tomorrowsCondition + ".mp3");
  769.  
  770.                             }
  771.  
  772.                             Debug.Print("Goodbye");
  773.                             musicFiles[5] = ("audio" + Path.DirectorySeparatorChar + "goodbye.mp3");
  774.  
  775.                             Debug.Print("End of message construction");
  776.  
  777.                             // write the time and date of the next query to the log
  778.                             // so we can check later
  779.                             // making sure we aren't exceeding our 6 per day query allowance
  780.                             writeLogFile();
  781.                             // write the current forecast in case we loose power
  782.                             // write audio files log
  783.                             writeAudioLogFile();
  784.  
  785.                         }
  786.  
  787.                         break;
  788.  
  789.                     case XmlNodeType.EndElement:
  790.                         //Debug.Print("End of Element");
  791.                         break;
  792.  
  793.                     case XmlNodeType.Attribute:
  794.                         //Debug.Print("Attribute");
  795.                         break;
  796.  
  797.                     case XmlNodeType.Text:
  798.                         //Debug.Print("Text");
  799.                         break;
  800.  
  801.                 }
  802.  
  803.             }
  804.  
  805.  
  806.             if (music.IsBusy)
  807.             {
  808.                 // do nothing?
  809.                 // this shouldn't ever happen
  810.             }
  811.             else
  812.             {
  813.  
  814.                 playTrack();
  815.  
  816.             }
  817.         }
  818.  
  819.         void Interface_NetworkAddressChanged(object sender, EventArgs e)
  820.         {
  821.             Debug.Print("***NetworkDown event! (maybe?)");
  822.  
  823.             // don't we have to do something?
  824.             // it stalls here if the network goes off
  825.  
  826.            
  827.             // turn LED to red flashing
  828.             //multicolorLed.BlinkRepeatedly(GT.Color.Red, blinkTime, GT.Color.Black, blinkTime);
  829.  
  830.        
  831.         }
  832.     }
  833. }
  834.  
  835. /*
  836.  * icon-set
  837.  * http://www.wunderground.com/weather/api/d/docs?d=resources/icon-sets
  838.  *
  839.     chanceflurries - chanceflurries.gif"
  840.     chancerain - chancerain.gif"
  841.     chancesleet - chancesleet.gif"
  842.     chancesleet - chancesleet.gif"
  843.     chancesnow - chancesnow.gif"
  844.     chancetstorms - chancetstorms.gif"
  845.     chancetstorms - chancetstorms.gif"
  846.     clear - clear.gif"
  847.     cloudy - clear.gif"
  848.     flurries - flurries.gif"
  849.     fog - fog.gif"
  850.     hazy - hazy.gif"
  851.     mostlycloudy - mostlycloudy.gif"
  852.     mostlysunny - mostlysunny.gif"
  853.     partlycloudy - partlycloudy.gif"
  854.     partlysunny - partlysunny.gif"
  855.     sleet - sleet.gif"
  856.     rain - rain.gif"
  857.     sleet - sleet.gif"
  858.     snow - snow.gif"
  859.     sunny - sunny.gif"
  860.     tstorms - tstorms.gif"
  861.     tstorms - tstorms.gif"
  862.     tstorms - tstorms.gif"
  863.     cloudy - cloudy.gif"
  864.     partlycloudy - partlycloudy.gif"
  865.  
  866.     nt_chanceflurries - chanceflurries.gif"
  867.     nt_chancerain - chancerain.gif"
  868.     nt_chancesleet - chancesleet.gif"
  869.     nt_chancesleet - chancesleet.gif"
  870.     nt_chancesnow - chancesnow.gif"
  871.     nt_chancetstorms - chancetstorms.gif"
  872.     nt_chancetstorms - chancetstorms.gif"
  873.     nt_clear - clear.gif"
  874.     nt_cloudy - clear.gif"
  875.     nt_flurries - flurries.gif"
  876.     nt_fog - fog.gif"
  877.     nt_hazy - hazy.gif"
  878.     nt_mostlycloudy - mostlycloudy.gif"
  879.     nt_mostlysunny - mostlysunny.gif"
  880.     nt_partlycloudy - partlycloudy.gif"
  881.     nt_partlysunny - partlysunny.gif"
  882.     nt_sleet - sleet.gif"
  883.     nt_rain - rain.gif"
  884.     nt_sleet - sleet.gif"
  885.     nt_snow - snow.gif"
  886.     nt_sunny - sunny.gif"
  887.     nt_tstorms - tstorms.gif"
  888.     nt_tstorms - tstorms.gif"
  889.     nt_tstorms - tstorms.gif"
  890.     nt_cloudy - cloudy.gif"
  891.     nt_partlycloudy - partlycloudy.gif
  892. */
Advertisement
Add Comment
Please, Sign In to add comment