Пример #1
0
        public static void Main()
        {
            // For neon
            var wifi = new Esp8266WifiDevice(new SerialPort("COM2", 115200, Parity.None, 8, StopBits.One), new OutputPort((Cpu.Pin) 19, false), null);

            wifi.Connect("Xxxxx", "Xxxxx");

            var sntp = new SntpClient(wifi, "time1.google.com");

            sntp.SetTime();

            // You have to change this - the storage account does not exist and the key is not valid
            var account = new CloudStorageAccount("pdazurestoragedemo", "PblOktyRKcKQy+5qMe3doPcxzcUqKU38ZBTGCOs8g+10CamdApbJd1FDw2WTsZ8/k+LoUvCQsc4NPBZ0jY/9DA==");
            var blob    = new BlobClient(wifi, account);

            var containerName = "cont3";

            // if needed...
            //blob.CreateContainer(containerName);

            var someBytes = new byte[256];

            for (int i = 0; i < someBytes.Length; ++i)
            {
                someBytes[i] = (byte)i;
            }
            blob.PutBlockBlob(containerName, "mybytes", someBytes);
        }
Пример #2
0
        public static void Main()
        {
            var wifi = new NeonWifiDevice();

            wifi.Connect(SSID, PASSWD);

            var sntp = new SntpClient(wifi, "time1.google.com");

            sntp.SetTime();

            MobileServiceClient msc = new MobileServiceClient(wifi, azureMobileAppUri, null, AzureAppKey);
            IMobileServiceTable tab = msc.GetTable("environment_measures");

            // Test a dummy insert for now
            MeasurementRow row    = new MeasurementRow();
            string         result = tab.Insert(row);

            Debug.Print(DateTime.Now.ToString("T") + " " + result);

            bool state    = true;
            int  iCounter = 0;

            while (true)
            {
                Hardware.UserLed.Write(state);
                state = !state;
                if (++iCounter == 10)
                {
                    Debug.Print("Current UTC time : " + DateTime.UtcNow);
                    iCounter = 0;
                }
                Thread.Sleep(500);
            }
        }
Пример #3
0
        // The disk file service allows you to serve and browse files from flash/disk storage
        public static void Main()
        {
            // Initialize logging
            Logger.Initialize(new DebugLogger(), LoggerLevel.Debug);

            // Create Http server pipeline
            ModuleManager ModuleManager = new ModuleManager();

            // Create file/disk service for storage
            DiskFileService fileService = new DiskFileService(@"/", @"\WINFS\WebSite");

            // Add the file module to pipeline and enable the file listing feature
            ModuleManager.Add(new FileModule(fileService) { AllowListing = true });

            // Add the error module as the last module to pipeline
            ModuleManager.Add(new ErrorModule());

            //  Create the http server
            HttpService HttpServer = new HttpService(ModuleManager);

            // Sets interface ip address
            HttpServer.InterfaceAddress = IPAddress.GetDefaultLocalAddress();

            // Starts Http service
            HttpServer.Start();

            // Set local time
            SntpClient TimeService = new SntpClient();
            TimeService.Synchronize();
        }
Пример #4
0
        // The disk file service allows you to serve and browse files from flash/disk storage
        public static void Main()
        {
            // Initialize logging
            Logger.Initialize(new DebugLogger(), LoggerLevel.Debug);

            // Create Http server pipeline
            ModuleManager ModuleManager = new ModuleManager();

            // Create file/disk service for storage
            DiskFileService fileService = new DiskFileService(@"/", @"\WINFS\WebSite");

            // Add the file module to pipeline and enable the file listing feature
            ModuleManager.Add(new FileModule(fileService)
            {
                AllowListing = true
            });

            // Add the error module as the last module to pipeline
            ModuleManager.Add(new ErrorModule());

            //  Create the http server
            HttpService HttpServer = new HttpService(ModuleManager);

            // Sets interface ip address
            HttpServer.InterfaceAddress = IPAddress.GetDefaultLocalAddress();

            // Starts Http service
            HttpServer.Start();

            // Set local time
            SntpClient TimeService = new SntpClient();

            TimeService.Synchronize();
        }
Пример #5
0
        public void IntegrationTest()
        {
            // Arrange

            // Act
            var currentUtcTime      = SntpClient.GetTime("time.windows.com");
            var currentTimeZoneTime = TimeZoneInfo.ConvertTime(currentUtcTime, TimeZoneInfo.Local);

            // Assert
            Assert.IsNotNull(currentUtcTime);
            Assert.IsNotNull(currentTimeZoneTime);
        }
Пример #6
0
        public static void Main()
        {
            var wifi = new NeonWifiDevice();

            //wifi.EnableDebugOutput = true;
            //wifi.EnableVerboseOutput = true;

            wifi.Booted += WifiOnBooted;  // or you can wait on the wifi.IsInitializedEvent
            //wifi.Error += WifiOnError;
            //wifi.ConnectionStateChanged += WifiOnConnectionStateChanged;

            //var apList = wifi.GetAccessPoints();
            //Debug.Print("Access points:");
            //foreach (var ap in apList)
            //{
            //    Debug.Print("ECN : " + ap.Ecn);
            //    Debug.Print("SSID : " + ap.Ssid);
            //    Debug.Print("RSSI : " + ap.Rssi);
            //    Debug.Print("MAC addr : " + ap.MacAddress);
            //    Debug.Print("Connection is : " + (ap.AutomaticConnectionMode ? "Automatic" : "Manual"));
            //}

            wifi.Connect("XXX", "XXX");

            var sntp = new SntpClient(wifi, "time1.google.com");

            sntp.SetTime();

            var uri        = new Uri("http://www.example.com");
            var httpClient = new HttpClient(wifi);
            var request    = new HttpRequest(uri);

            request.Uri = uri;
            request.Headers.Add("Connection", "Keep-Alive");
            request.ResponseReceived += HttpResponseReceived;
            httpClient.SendAsync(request);

            bool state    = true;
            int  iCounter = 0;

            while (true)
            {
                Hardware.UserLed.Write(state);
                state = !state;
                if (++iCounter == 10)
                {
                    Debug.Print("Current UTC time : " + DateTime.UtcNow);
                    iCounter = 0;
                }
                Thread.Sleep(500);
            }
        }
Пример #7
0
        public static void Main()
        {
            var wifi = new NeonWifiDevice();

            //wifi.EnableDebugOutput = true;
            //wifi.EnableVerboseOutput = true;

            wifi.Booted += WifiOnBooted;  // or you can wait on the wifi.IsInitializedEvent

            wifi.Connect(SSID, PASSWD);

            var sntp = new SntpClient(wifi, "time1.google.com");

            sntp.SetTime();

            MobileServiceClient msc = new MobileServiceClient(wifi, ak16Uri, null, AzureAppKey);
            IMobileServiceTable tab = msc.GetTable("environment_measures");

            //try
            //{
            // Test a dummy insert for now
            MeasurementRow row = new MeasurementRow();

            row.DateTimeStamp = DateTime.Now;
            row.where         = "here"; //Resources.GetString(Resources.StringResources.VanWie);
            row.what          = "nothing";
            row.value         = -1f;
            row.uom           = " ";
            string surprise = tab.Insert(row); // Failing on this line

            Debug.Print(DateTime.Now.ToString("T") + " " + surprise);

            bool state    = true;
            int  iCounter = 0;

            while (true)
            {
                Hardware.UserLed.Write(state);
                state = !state;
                if (++iCounter == 10)
                {
                    Debug.Print("Current UTC time : " + DateTime.UtcNow);
                    iCounter = 0;
                }
                Thread.Sleep(500);
            }
        }
Пример #8
0
        public async Task CanConnectToAtLeastTwoNtpServers()
        {
            var standardTimerServer = AbstractLicenseValidator.StandardTimeServer;
            int failingHosts        = 0;

            foreach (var host in standardTimerServer)
            {
                var hostTiming = Stopwatch.StartNew();
                var addresses  = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);

                var endPoint = new IPEndPoint(addresses[0], 123);

                using (var udpClient = new UdpClient())
                {
                    udpClient.Connect(endPoint);
                    var sntpData = new byte[SntpClient.SntpDataLength];
                    sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)

                    var sendTask = udpClient.SendAsync(sntpData, sntpData.Length);
                    if (await Task.WhenAny(sendTask, Task.Delay(TimeSpan.FromMilliseconds(500))).ConfigureAwait(false) != sendTask)
                    {
                        failingHosts++;
                        continue;
                    }


                    var receiveTask = udpClient.ReceiveAsync();
                    if (await Task.WhenAny(receiveTask, Task.Delay(TimeSpan.FromMilliseconds(500))).ConfigureAwait(false) != receiveTask)
                    {
                        failingHosts++;
                        continue;
                    }
                    var result = receiveTask.Result;
                    hostTiming.Stop();
                    if (SntpClient.IsResponseValid(result.Buffer) == false)
                    {
                        failingHosts++;
                        continue;
                    }
                    var transmitTimestamp = SntpClient.GetTransmitTimestamp(result.Buffer);
                    //The idea is not to validate our own clock but to make sure we didn't get garbage.
                    Assert.True((DateTime.UtcNow - transmitTimestamp).Duration() < TimeSpan.FromHours(1));
                }
            }
            Assert.True(standardTimerServer.Length - failingHosts > 2, $"Connection failed in {failingHosts} or more hosts");
        }
Пример #9
0
        public static void Main()
        {
            Server = new ServiceManager(LogType.Output, LogLevel.Info, @"\winfs");

            //INITIALIZING : Server Services
            Server.InterfaceAddress = System.Net.IPAddress.GetDefaultLocalAddress().ToString();
            Server.ServerName       = "example";
            Server.DnsSuffix        = "iot.local";

            // SERVICES:  disable services
            Server.HttpEnabled = false;

            // SERVICES INIT: quickly enable/disable services
            //HttpInit();
            //DhcpInit();
            //DnsInit();
            //SntpInit();

            // SERVICES: Start all services
            //Server.StartAll();

            // Test Harness: Set local time
            SntpClient TimeService = new SntpClient();

            TimeService.Synchronize();

            // enables basic authentication on server using AccountService class for user name and password
            //Server.HttpService.Add(new AuthenticationModule(new BasicAuthentication(new AccountService(), Server.ServerName)));

            //Type[] myTypes = new Type[2](typeof(TestMe), typeof(TestMe2));

            //Type[] myTypes = new Type[2];
            //myTypes[0] = typeof(TestMe);
            //myTypes[1] = typeof(TestMe2);

            foreach (DictionaryEntry properties in TypeUtility.GetProperties(typeof(TestMe2)))
            {
                string propName = (string)properties.Key;
                Type   propType = (Type)properties.Value;

                Debug.Print("name: " + propName + " type: " + propType.ToString());
            }
            ;
        }
Пример #10
0
        public async Task CanConnectToAllNtpServers()
        {
            foreach (var host in AbstractLicenseValidator.StandardTimeServer)
            {
                var hostTiming = Stopwatch.StartNew();

                var exceptionWasThrown = false;

                var addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);

                var endPoint = new IPEndPoint(addresses[0], 123);

                using (var udpClient = new UdpClient())
                {
                    udpClient.Connect(endPoint);
                    var sntpData = new byte[SntpClient.SntpDataLength];
                    sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)

                    var sendTask = udpClient.SendAsync(sntpData, sntpData.Length);
                    if (await Task.WhenAny(sendTask, Task.Delay(TimeSpan.FromMilliseconds(500))).ConfigureAwait(false) != sendTask)
                    {
                        throw new TimeoutException("Failed to send data to " + host + "within 500ms");
                    }



                    var receiveTask = udpClient.ReceiveAsync();
                    if (await Task.WhenAny(receiveTask, Task.Delay(TimeSpan.FromMilliseconds(500))).ConfigureAwait(false) != receiveTask)
                    {
                        throw new TimeoutException("Failed to receive data to " + host + " within 500ms");
                    }
                    var result = receiveTask.Result;
                    hostTiming.Stop();
                    if (SntpClient.IsResponseValid(result.Buffer) == false)
                    {
                        throw new BadRequestException("Did not get valid time information from " + host + " took " + hostTiming.Elapsed);
                    }
                    var transmitTimestamp = SntpClient.GetTransmitTimestamp(result.Buffer);
                    //The idea is not to validate our own clock but to make sure we didn't get garbage.
                    Assert.True((DateTime.UtcNow - transmitTimestamp).Duration() < TimeSpan.FromHours(1));
                }
            }
        }
Пример #11
0
        // In order to create a truly robust long-running solution, you must combine the code below
        //   with proper use of a Watchdog Timer and exception handling on the wifi calls.
        // Hardware note: It has been our experience that to work at 115200 with the ESP8266 and NETMF, you need a 1024 byte serial buffer.
        //   Smaller serial buffers may result in portions of incoming TCP traffic being dropped, which can also break the protocol processing
        //   and result in hangs.

        public static void Main()
        {
            var port = new SerialPort("COM2", 115200, Parity.None, 8, StopBits.One);
            var wifi = new Esp8266WifiDevice(port, _rfPower, null);

            // On Oxygen+Neon, you can use use new NeonWifiDevice() without providing a port or power pin definition

            // Enable echoing of commands
            wifi.EnableDebugOutput = true;
            // Enable dump of every byte sent or received (may introduce performance delays and can cause buffer overflow
            //   at low baud rates or with small serial buffers.
            //wifi.EnableVerboseOutput = true;

            Debug.Print("Access points:");
            var apList = wifi.GetAccessPoints();

            foreach (var ap in apList)
            {
                Debug.Print("ssid:" + ap.Ssid + "  ecn:" + ap.Ecn);
            }
            Debug.Print("-- end of list -------------");

#if CREATE_ACCESS_POINT
            wifi.Mode = OperatingMode.Both;
            wifi.ConfigureAccessPoint("serwifitest", "24681234", 5, Ecn.WPA2_PSK);
            wifi.EnableDhcp(OperatingMode.AccessPoint, true);
#else
            wifi.Mode = OperatingMode.Station;
#endif
            wifi.Connect("XXX", "XXX");

            Debug.Print("Station IP address : " + wifi.StationIPAddress.ToString());
            Debug.Print("Station MAC address : " + wifi.StationMacAddress);
            Debug.Print("Station Gateway address : " + wifi.StationGateway.ToString());
            Debug.Print("Station netmask : " + wifi.StationNetmask.ToString());

            Debug.Print("AP SSID : " + wifi.AccessPointSsid);
            Debug.Print("AP Password : "******"AP Channel : " + wifi.AccessPointChannel);
            Debug.Print("AP ECN : " + wifi.AccessPointEcn);

            Debug.Print("AP IP address : " + wifi.AccessPointIPAddress.ToString());
            Debug.Print("AP MAC address : " + wifi.AccessPointMacAddress);
            Debug.Print("AP Gateway address : " + wifi.AccessPointGateway.ToString());
            Debug.Print("AP netmask : " + wifi.AccessPointNetmask.ToString());

            var sntp = new SntpClient(wifi, "time1.google.com");
            // You should repeat this every day or so, to counter clock drift, or use .Start()
            // to update the clock against and SNTP server automatically in the background.
            sntp.SetTime();

            wifi.CreateServer(80, OnServerConnectionOpened);

            var httpClient = new HttpClient(wifi);
            var request    = new HttpRequest(new Uri("http://www.example.com/"));
            request.ResponseReceived += HttpResponseReceived;
            httpClient.SendAsync(request);

            int  iCounter = 0;
            bool state    = true;
            while (true)
            {
                _userLed.Write(state);
                state = !state;
                ++iCounter;
                if (iCounter % 10 == 0)
                {
                    Debug.Print("Current UTC time : " + DateTime.UtcNow);
                }
                // Every 15 seconds
                if (iCounter % 30 == 0)
                {
#if CREATE_ACCESS_POINT
                    Debug.Print("Clients connected to this AP");
                    var clientList = wifi.GetConnectedClients();
                    foreach (var client in clientList)
                    {
                        Debug.Print("IP:" + client.IpAddress.ToString() + "  MAC:" + client.MacAddress);
                    }
                    Debug.Print("-- end of list -------------");
#endif
                    iCounter = 0;
                }
                Thread.Sleep(500);
            }
        }
Пример #12
0
        static void Main(string[] args)
        {
            string serverAddress   = "ntp2d.mcc.ac.uk";
            bool   addressExplicit = false;
            bool   setSystemTime   = false;
            bool   help            = false;
            int    count           = 3;
            bool   verbose         = false;
            int?   port            = null;

            var p = new OptionSet()
            {
                { "s=|server=", "Server to request time from", v => { serverAddress = v; addressExplicit = true; } },
                { "c=|count=", "Number of requests to make", (int v) => count = v },
                { "p=|port=", "The port to contact the server on", (int v) => port = v },
                { "u|update", "Update the system clock with the received time", v => setSystemTime = v != null },
                { "v|verbose", "Print verbose information", v => verbose = v != null },
                { "h|?|help", "Print command line help", v => help = v != null }
            };

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("SntpUpdate: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `SntpUpdate --help' for more information.");
                return;
            }

            if (!addressExplicit && extra.Count > 0)
            {
                serverAddress = extra[0];
            }

            if (help)
            {
                p.WriteOptionDescriptions(Console.Out);
            }
            else
            {
                SntpClient client = new SntpClient(serverAddress);
                if (port != null)
                {
                    client.Port = (int)port;
                }
                List <NtpData> data = client.GetTime(count, setSystemTime);
                if (verbose)
                {
                    foreach (var d in data)
                    {
                        Console.WriteLine(d.ToString());
                    }
                }

                TimeSpan median = data[data.Count / 2].LocalClockOffset;
                Console.WriteLine("\r\nMedian Offset: " + median.TotalMilliseconds.ToString() + " ms");

                if (setSystemTime)
                {
                    Console.WriteLine("\r\nSystem Clock Updated to: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff"));
                }
            }
        }
Пример #13
0
        public static void Main()
        {
            using (ServiceManager Server = new ServiceManager(LogType.Output, LogLevel.Info, @"\winfs"))
            {
                Server.LogInfo("MicroServer.Emulator", "Starting service manager main code");

                ConfigManager.Load(Server.StorageRoot + @"\settings.xml");

                // general interface information settings
                //Server.InterfaceAddress = ConfigManager.GetSetting("ipAddress", System.Net.IPAddress.GetDefaultLocalAddress().ToString());
                Server.InterfaceAddress = "192.168.10.8";
                Server.DnsSuffix = ConfigManager.GetSetting("dnsSuffix","iot.local");
                Server.ServerName = ConfigManager.GetSetting("serverName", "mfhost");

                // enable the services you would like to start
                Server.HttpEnabled = true;

                // dhcp server settings
                bool dhcpEnabled;
                if (ParseUtility.TryParseBool(ConfigManager.GetSetting("dhcpEnabled", "false"), out dhcpEnabled))
                {
                    Server.DhcpEnabled = dhcpEnabled;
                    Server.DhcpService.PoolRange(
                        ConfigManager.GetSetting("startAddress", "192.168.50.100"),
                        ConfigManager.GetSetting("endAddress", "192.168.50.254")
                        );
                    //Server.DhcpService.PoolReservation("192.168.10.99", "000C291DBB7D");
                    Server.DhcpService.GatewayAddress = Server.InterfaceAddress;
                    Server.DhcpService.SubnetMask = ConfigManager.GetSetting("subnetMask", "255.255.255.0");
                    Server.DhcpService.NameServers = new NameServerCollection(Server.InterfaceAddress);
                }

                // dns server settings
                bool dnsEnabled;
                if (ParseUtility.TryParseBool(ConfigManager.GetSetting("dnsEnabled", "false"), out dnsEnabled))
                    Server.DnsEnabled = dnsEnabled;

                // sntp server settings
                bool sntpEnabled;
                if (ParseUtility.TryParseBool(ConfigManager.GetSetting("sntpEnabled", "false"), out sntpEnabled))
                    Server.SntpEnabled = sntpEnabled;

                // event handlers for dhcp service
                Server.DhcpService.OnDhcpMessageReceived += DhcpService_OnDhcpMessageReceived;
                Server.DhcpService.OnDhcpMessageSent += DhcpService_OnDhcpMessageSent;
                Server.DhcpService.OnLeaseAcknowledged += DhcpService_OnLeaseAcknowledged;
                Server.DhcpService.OnLeaseDeclined += DhcpService_OnLeaseDeclined;
                Server.DhcpService.OnLeaseReleased += DhcpService_OnLeaseReleased;

                // event handlers for dns service
                Server.DnsService.OnDnsMessageReceived += DnsService_OnDnsMessageReceived;
                Server.DnsService.OnDnsMessageSent += DnsService_OnDnsMessageSent;

                // event handlers for sntp service
                Server.SntpService.OnSntpMessageReceived += SntpService_OnSntpMessageReceived;
                Server.SntpService.OnSntpMessageSent += SntpService_OnSntpMessageSent;

                // start all enabled services
                Server.StartAll();

                Server.LogInfo("MicroServer.Emulator", "Ending service manager main code");
            }

            if (SystemInfo.IsEmulator)
            {
                SntpClient TimeService = new SntpClient();
                TimeService.Synchronize();
            }
        }
Пример #14
0
        // In order to create a truly robust long-running solution, you must combine the code below
        //   with proper use of a Watchdog Timer and exception handling on the wifi calls.
        //
        // Hardware note: It has been our experience that to work at 115200 with the ESP8266 and NETMF, you need a 1024 byte serial buffer.
        //   Smaller serial buffers may result in portions of incoming TCP traffic being dropped, which can also break the protocol processing
        //   and result in hangs.

        static void Main()
        {
            _rfPower = GpioController.GetDefault().OpenPin(5);
            _rfPower.SetDriveMode(GpioPinDriveMode.Output);
            _rfPower.Write(GpioPinValue.High);

            _userLed = GpioController.GetDefault().OpenPin(45);
            _userLed.SetDriveMode(GpioPinDriveMode.Output);

            var port = UartController.FromName(SC20100.UartPort.Uart8);

            port.SetActiveSettings(115200, 8, UartParity.None, UartStopBitCount.One, UartHandshake.None);

            var wifi = new Esp8266WifiDevice(port, _rfPower, null);

            // Enable echoing of commands
            wifi.EnableDebugOutput = false;


            Debug.WriteLine("--------------------------------");
            Debug.WriteLine("----Esp 8266 Wifi TinyClr 2 ----");
            Debug.WriteLine("--------------------------------");
            wifi.Connect("valoninet", "valoni1234567");


            Debug.WriteLine("Station IP address : " + wifi.StationIPAddress.ToString());
            Debug.WriteLine("Station MAC address : " + wifi.StationMacAddress);
            Debug.WriteLine("Station Gateway address : " + wifi.StationGateway.ToString());
            Debug.WriteLine("Station netmask : " + wifi.StationNetmask.ToString());
            Debug.WriteLine("------------------------");

            Thread.Sleep(1000);

            var sntp = new SntpClient(wifi, "time1.google.com");

            sntp.SetTime();

            int iCounter = 0;

            bool state = true;

            while (true)
            {
                state = !state;

                if (state)
                {
                    _userLed.Write(GpioPinValue.High);
                }
                else
                {
                    _userLed.Write(GpioPinValue.Low);
                }

                ++iCounter;
                if (iCounter % 10 == 0)
                {
                    Debug.WriteLine("Current UTC time : " + DateTime.UtcNow);
                    Debug.WriteLine("------------------------");
                }
                // Every 15 seconds

                Thread.Sleep(500);
            }
        }
Пример #15
0
        public static void Main()
        {
            using (ServiceManager Server = new ServiceManager(LogType.Output, LogLevel.Info, @"\winfs"))
            {
                Server.LogInfo("MicroServer.Emulator", "Starting service manager main code");

                ConfigManager.Load(Server.StorageRoot + @"\settings.xml");

                // general interface information settings
                //Server.InterfaceAddress = ConfigManager.GetSetting("ipAddress", System.Net.IPAddress.GetDefaultLocalAddress().ToString());
                Server.InterfaceAddress = "192.168.10.8";
                Server.DnsSuffix        = ConfigManager.GetSetting("dnsSuffix", "iot.local");
                Server.ServerName       = ConfigManager.GetSetting("serverName", "mfhost");

                // enable the services you would like to start
                Server.HttpEnabled = true;

                // dhcp server settings
                bool dhcpEnabled;
                if (ParseUtility.TryParseBool(ConfigManager.GetSetting("dhcpEnabled", "false"), out dhcpEnabled))
                {
                    Server.DhcpEnabled = dhcpEnabled;
                    Server.DhcpService.PoolRange(
                        ConfigManager.GetSetting("startAddress", "192.168.50.100"),
                        ConfigManager.GetSetting("endAddress", "192.168.50.254")
                        );
                    //Server.DhcpService.PoolReservation("192.168.10.99", "000C291DBB7D");
                    Server.DhcpService.GatewayAddress = Server.InterfaceAddress;
                    Server.DhcpService.SubnetMask     = ConfigManager.GetSetting("subnetMask", "255.255.255.0");
                    Server.DhcpService.NameServers    = new NameServerCollection(Server.InterfaceAddress);
                }

                // dns server settings
                bool dnsEnabled;
                if (ParseUtility.TryParseBool(ConfigManager.GetSetting("dnsEnabled", "false"), out dnsEnabled))
                {
                    Server.DnsEnabled = dnsEnabled;
                }

                // sntp server settings
                bool sntpEnabled;
                if (ParseUtility.TryParseBool(ConfigManager.GetSetting("sntpEnabled", "false"), out sntpEnabled))
                {
                    Server.SntpEnabled = sntpEnabled;
                }

                // event handlers for dhcp service
                Server.DhcpService.OnDhcpMessageReceived += DhcpService_OnDhcpMessageReceived;
                Server.DhcpService.OnDhcpMessageSent     += DhcpService_OnDhcpMessageSent;
                Server.DhcpService.OnLeaseAcknowledged   += DhcpService_OnLeaseAcknowledged;
                Server.DhcpService.OnLeaseDeclined       += DhcpService_OnLeaseDeclined;
                Server.DhcpService.OnLeaseReleased       += DhcpService_OnLeaseReleased;

                // event handlers for dns service
                Server.DnsService.OnDnsMessageReceived += DnsService_OnDnsMessageReceived;
                Server.DnsService.OnDnsMessageSent     += DnsService_OnDnsMessageSent;

                // event handlers for sntp service
                Server.SntpService.OnSntpMessageReceived += SntpService_OnSntpMessageReceived;
                Server.SntpService.OnSntpMessageSent     += SntpService_OnSntpMessageSent;

                // start all enabled services
                Server.StartAll();

                Server.LogInfo("MicroServer.Emulator", "Ending service manager main code");
            }

            if (SystemInfo.IsEmulator)
            {
                SntpClient TimeService = new SntpClient();
                TimeService.Synchronize();
            }
        }
Пример #16
0
        public static void Main()
        {
            var port = new SerialPort(GHI.Pins.FEZCobraII.Socket5.SerialPortName, 115200, Parity.None, 8, StopBits.One);
            var wifi = new Esp8266WifiDevice(port, null, null);

            wifi.EnableDebugOutput   = false;
            wifi.EnableVerboseOutput = false;

            Debug.Print("Access points:");
            var apList = wifi.GetAccessPoints();

            foreach (var ap in apList)
            {
                Debug.Print("ssid:" + ap.Ssid + "  ecn:" + ap.Ecn);
            }
            Debug.Print("-- end of list -------------");

            wifi.Connect("XXX", "XXX");

            Debug.Print("Station IP address : " + wifi.StationIPAddress.ToString());
            Debug.Print("Station MAC address : " + wifi.StationMacAddress);
            Debug.Print("Station Gateway address : " + wifi.StationGateway.ToString());
            Debug.Print("Station netmask : " + wifi.StationNetmask.ToString());

            var sntp = new SntpClient(wifi, "time1.google.com");

            sntp.SetTime();

            wifi.CreateServer(80, OnServerConnectionOpened);

            var httpClient = new HttpClient(wifi);
            //var request = new HttpRequest(new Uri("http://www.example.com/"));
            var request =
                new HttpRequest(new Uri("http://www.webservicex.net/uszip.asmx/GetInfoByAreaCode?USAreaCode=919"));

            request.ResponseReceived += HttpResponseReceived;
            httpClient.SendAsync(request);

            int  iCounter = 0;
            bool state    = true;

            while (true)
            {
                _userLed.Write(state);
                state = !state;
                ++iCounter;
                if (iCounter % 10 == 0)
                {
                    Debug.Print("Current UTC time : " + DateTime.UtcNow);
                }
                // Every 15 seconds
                if (iCounter % 30 == 0)
                {
#if CREATE_ACCESS_POINT
                    Debug.Print("Clients connected to this AP");
                    var clientList = wifi.GetConnectedClients();
                    foreach (var client in clientList)
                    {
                        Debug.Print("IP:" + client.IpAddress.ToString() + "  MAC:" + client.MacAddress);
                    }
                    Debug.Print("-- end of list -------------");
#endif
                    iCounter = 0;
                }
                Thread.Sleep(500);
            }
        }