Example #1
0
        public HttpResponse Send(HttpRequest req)
        {
            if (_activeRequest != null)
                throw new InvalidOperationException("A request is already outstanding");

            _activeRequest = req;
            _requestCompletedEvent.Reset();

            using (var socket = GetSocket(req.Uri.Host, req.Uri.Port))
            {
                try
                {
                    StringBuilder buffer = new StringBuilder();

                    req.AppendMethod(buffer);
                    req.AppendHeaders(buffer);

                    socket.Send(buffer.ToString());
                    if (req.Body != null && req.Body.Length > 0)
                        socket.Send(req.Body);

                    _requestCompletedEvent.WaitOne();
                }
                finally
                {
                    socket.SocketClosed -= SocketOnSocketClosed;
                    socket.DataReceived -= SocketOnDataReceived;
                }
            }
            return _lastResponse;
        }
Example #2
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);
            }
        }
Example #3
0
        public void SendAsync(HttpRequest req)
        {
            if (_activeRequest != null)
                throw new InvalidOperationException("A request is already outstanding");

            _activeRequest = req;

            _socket = GetSocket(req.Uri.Host, req.Uri.Port);

            StringBuilder buffer = new StringBuilder();

            req.AppendMethod(buffer);
            req.AppendHeaders(buffer);

            _socket.Send(buffer.ToString());
            if (req.Body != null && req.Body.Length > 0)
                _socket.Send(req.Body);
        }
        /// <summary>
        /// Prepares a HttpWebRequest with required headers of x-ms-date, x-ms-version and Authorization
        /// </summary>
        /// <param name="url"></param>
        /// <param name="authHeader"></param>
        /// <param name="dateHeader"></param>
        /// <param name="versionHeader"></param>
        /// <param name="fileBytes"></param>
        /// <param name="contentLength"></param>
        /// <param name="httpVerb"></param>
        /// <returns></returns>
        private static HttpRequest PrepareRequest(string url, string authHeader, string dateHeader, string versionHeader, byte[] fileBytes , int contentLength, string httpVerb, bool expect100Continue = false, Hashtable additionalHeaders = null)
        {
            var uri = new Uri(url);
            var request = new HttpRequest();
            request.Uri = new Uri(url);
            request.Method = httpVerb;
            request.ContentLength = contentLength;
            request.Headers.Add("x-ms-date", dateHeader);
            request.Headers.Add("x-ms-version", versionHeader);
            request.Headers.Add("Authorization", authHeader);

            if (expect100Continue)
            {
                request.Expect = "100-continue";
            }

            if (additionalHeaders != null)
            {
                foreach (var additionalHeader in additionalHeaders.Keys)
                {
                    request.Headers.Add(additionalHeader.ToString(), additionalHeaders[additionalHeader].ToString());
                }
            }

            //if (AttachFiddler)
            //{
            //    request.Proxy = new WebProxy("127.0.0.1", 8888);
            //}

            if (contentLength != 0)
            {
                request.Body = fileBytes;
            }
            return request;
        }
Example #5
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);
            }
        }
        private void SendBacklog()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            bool fFirst = true;
            foreach (var item in _backlog)
            {
                if (!fFirst)
                    sb.Append(",");
                fFirst = false;
                sb.Append(item);
            }
            sb.Append("]");

            //TODO: With large backlogs and large property sets, this will exceed the ESP8266 buffer. To fix that, send each backlog item separately

            // Send the data
            var adapter = (INetworkAdapter)DiContainer.Instance.Resolve(typeof(INetworkAdapter));
            var httpClient = new HttpClient(adapter);
            var request = new HttpRequest(HttpMethod.Post, new Uri("http://192.168.1.236/"));
            request.Body = Encoding.UTF8.GetBytes(sb.ToString());
            //request.ResponseReceived += HttpResponseReceived;
            httpClient.SendAsync(request);

            //TODO: We're always assuming the tranmission worked, and it doesn't. We're not building up the backlog of failed transmissions
            _backlog.Clear();
        }
Example #7
0
        private void SocketOnDataReceived(object sender, SocketReceivedDataEventArgs args)
        {
            if (_activeRequest == null)
                return;

            ISocket socket = (ISocket)sender;

            if (_activeRequest.OnResponseReceived(args))
            {
                _lastResponse = _activeRequest.Response;
                _activeRequest = null;
                // If this was an async send, we saved a ref to the socket.  Clean that up now.
                if (_socket!=null && _socket == socket)
                {
                    _socket.SocketClosed -= SocketOnSocketClosed;
                    _socket.DataReceived -= SocketOnDataReceived;
                    _socket.Dispose();
                    _socket = null;
                }
                _requestCompletedEvent.Set();
            }
        }