private async void PollObd() { try { string s; if (simulatormode) { s = "SIMULATORWINPHONE"; } else { s = await GetVIN(); } lock (_lock) { data["vin"] = s; } while (true) { foreach (var cmd in piDs.Keys) { var key = piDs[cmd]; if (simulatormode) { s = ObdShare.ObdUtil.GetEmulatorValue(cmd); } else { s = await RunCmd(cmd); } if (s != "ERROR") { lock (_lock) { data[key] = s; } } if (!running) { return; } } await Task.Delay(Interval); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); running = false; if (dataReaderObject != null) { dataReaderObject.Dispose(); dataReaderObject = null; } if (dataWriterObject != null) { dataWriterObject.Dispose(); dataWriterObject = null; } if (socket != null) { await socket.CancelIOAsync(); socket.Dispose(); socket = null; } } }
private async void ProcessRequestAsync(StreamSocket socket) { // very rudimentary web server request processing try { // grab the request StringBuilder request = new StringBuilder(); byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; using (IInputStream input = socket.InputStream) { while (dataRead == BufferSize) { await Task.Delay(50); // allow time for the data to arrive esp on wifi var result = await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, (int)result.Length)); dataRead = result.Length; } } // build some handy wrapper objects for request and response var req = new Request(request.ToString()); var res = new Response(socket); if (req.Method == null) { Debug.WriteLine("Cannot retrieve HTTP method"); return; } // go through the defined routes to handle the request // TODO: implement route matching based on string patterns var path = req.Path; bool handled = false; switch (req.Method) { case "GET": foreach (var t in getRoutes) { if (t.Item1 == path) { await t.Item2(req, res); handled = true; break; } } if (!handled) { foreach (var t in getStaticRoutes) { if (path.StartsWith(t.Item1)) { await t.Item2(req, res); handled = true; break; } } } if (!handled) { // REVIEW: is 404 the right status code to return? await res.SendStatusAsync(404); } break; case "POST": foreach (var t in postRoutes) { if (t.Item1 == path) { await t.Item2(req, res); handled = true; break; } } if (!handled) { // REVIEW: is 404 the right status code to return? await res.SendStatusAsync(404); } break; default: Debug.WriteLine("HTTP method not supported: " + req.Method); break; } } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { await socket.CancelIOAsync(); socket.Dispose(); } }