add openhack files

This commit is contained in:
Ryan Peters
2022-11-03 16:41:13 -04:00
commit b2c9f7e29f
920 changed files with 118861 additions and 0 deletions

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9A377DF7-3E28-4B4B-8BD2-61416F7AEA1F}</ProjectGuid>
<ProjectTypeGuids>{EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<RootNamespace>ObdLibAndroid</RootNamespace>
<AssemblyName>ObdLibAndroid</AssemblyName>
<TargetFrameworkVersion>v7.1</TargetFrameworkVersion>
<AndroidResgenFile>Resources\Resource.designer.cs</AndroidResgenFile>
<AndroidResgenClass>Resource</AndroidResgenClass>
<MonoAndroidResourcePrefix>Resources</MonoAndroidResourcePrefix>
<MonoAndroidAssetsPrefix>Assets</MonoAndroidAssetsPrefix>
<AndroidUseLatestPlatformSdk>true</AndroidUseLatestPlatformSdk>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<AndroidLinkMode>None</AndroidLinkMode>
<EmbedAssembliesIntoApk>
</EmbedAssembliesIntoApk>
<AndroidFastDeploymentType>
</AndroidFastDeploymentType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<AndroidUseSharedRuntime>false</AndroidUseSharedRuntime>
<EmbedAssembliesIntoApk>
</EmbedAssembliesIntoApk>
<AndroidFastDeploymentType>
</AndroidFastDeploymentType>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="Mono.Android" />
</ItemGroup>
<ItemGroup>
<Compile Include="Resources\Resource.designer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ObdWrapper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\AboutResources.txt" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ObdShare\ObdShare.csproj">
<Project>{7a88da9b-a374-4de2-b46e-ed2c45434508}</Project>
<Name>ObdShare</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project>

View File

@ -0,0 +1,293 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using Android.Bluetooth;
using Java.Util;
using System.IO;
using System.Threading.Tasks;
namespace ObdLibAndroid
{
public class ObdWrapper
{
const int Interval = 100;
const string DefValue = "-255";
private static readonly UUID SppUuid = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
private readonly Object _lock = new Object();
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
private bool connected = true;
private Dictionary<string, string> data;
private Dictionary<string, string> piDs;
private Stream reader;
private bool running = true;
private bool simulatormode;
private Stream writer;
public async Task<bool> Init(bool simulatormode = false)
{
running = true;
//initialize _data
data = new Dictionary<string, string> {{"vin", DefValue}};
//VIN
piDs = ObdShare.ObdUtil.GetPIDs();
foreach (var v in piDs.Values)
{
data.Add(v, DefValue);
}
this.simulatormode = simulatormode;
if (simulatormode)
{
return true;
}
bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
if (bluetoothAdapter == null)
{
System.Diagnostics.Debug.WriteLine("Bluetooth is not available");
return false;
}
try
{
var ba = bluetoothAdapter.BondedDevices;
foreach (var bd in ba)
{
if (bd.Name.ToLower().Contains("obd"))
bluetoothDevice = bd;
}
if (bluetoothDevice == null)
{
return false;
}
bluetoothSocket = bluetoothDevice.CreateRfcommSocketToServiceRecord(SppUuid);
await bluetoothSocket.ConnectAsync();
connected = true;
}
catch (Java.IO.IOException)
{
// Close the socket
try
{
connected = false;
bluetoothSocket.Close();
}
catch (Java.IO.IOException)
{
}
catch (Exception)
{
}
return false;
}
catch (Exception)
{
}
if (connected)
{
reader = bluetoothSocket.InputStream;
writer = bluetoothSocket.OutputStream;
string s;
s = await SendAndReceive("ATZ\r");
s = await SendAndReceive("ATE0\r");
s = await SendAndReceive("ATL1\r");
s = await SendAndReceive("ATSP00\r");
PollObd();
return true;
}
else
return false;
}
public Dictionary<string, string> Read()
{
var ret = new Dictionary<string, string>();
string s;
if (simulatormode)
{
s = "SIMULATORANDROID1";
ret.Add("vin", s);
foreach (var cmd in piDs.Keys)
{
var key = piDs[cmd];
s = ObdShare.ObdUtil.GetEmulatorValue(cmd);
ret.Add(key, s);
}
return ret;
}
if (!simulatormode && bluetoothSocket == null)
{
//if there is no connection
return null;
}
lock (_lock)
{
foreach (var key in data.Keys)
{
ret.Add(key, data[key]);
}
foreach (var v in piDs.Values)
{
data[v] = DefValue;
}
}
return ret;
}
private async void PollObd()
{
try
{
string s;
if (simulatormode)
s = "SIMULATOR12345678";
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 (reader != null)
{
reader.Close();
reader = null;
}
if (writer != null)
{
writer.Close();
writer = null;
}
if (bluetoothSocket != null)
{
bluetoothSocket.Close();
bluetoothSocket = null;
}
}
}
public async Task<string> GetVIN()
{
var result = await SendAndReceive("0902\r");
if (result.StartsWith("49"))
{
while (!result.Contains("49 02 05"))
{
string tmp = await ReadAsync();
result += tmp;
}
}
return ObdShare.ObdUtil.ParseVINMsg(result);
}
private async Task<string> SendAndReceive(string msg)
{
await WriteAsync(msg);
string s = await ReadAsync();
System.Diagnostics.Debug.WriteLine("Received: " + s);
s = s.Replace("SEARCHING...\r\n", "");
return s;
}
private async Task WriteAsync(string msg)
{
System.Diagnostics.Debug.WriteLine(msg);
byte[] buffer = GetBytes(msg);
await writer.WriteAsync(buffer, 0, buffer.Length);
}
private byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length*sizeof (char)];
Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
private async Task<string> ReadAsync()
{
string ret = await ReadAsyncRaw();
while (!ret.Trim().EndsWith(">"))
{
string tmp = await ReadAsyncRaw();
ret = ret + tmp;
}
return ret;
}
private async Task<string> ReadAsyncRaw()
{
byte[] buffer = new byte[1024];
var bytes = await reader.ReadAsync(buffer, 0, buffer.Length);
var s1 = new Java.Lang.String(buffer, 0, bytes);
var s = s1.ToString();
System.Diagnostics.Debug.WriteLine(s);
return s;
}
private async Task<string> RunCmd(string cmd)
{
var result = await SendAndReceive(cmd + "\r");
return ObdShare.ObdUtil.ParseObd01Msg(result);
}
public async Task Disconnect()
{
running = false;
if (reader != null)
{
reader.Close();
reader = null;
}
if (writer != null)
{
writer.Close();
writer = null;
}
if (bluetoothSocket != null)
{
try
{
bluetoothSocket.Close();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
bluetoothSocket = null;
}
}
}
}

View File

@ -0,0 +1,32 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System.Reflection;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("ObdLibAndroid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Microsoft")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: UsesPermission(Android.Manifest.Permission.Bluetooth)]
[assembly: UsesFeature("android.hardware.bluetooth", Required = false)]

View File

@ -0,0 +1,44 @@
Images, layout descriptions, binary blobs and string dictionaries can be included
in your application as resource files. Various Android APIs are designed to
operate on the resource IDs instead of dealing with images, strings or binary blobs
directly.
For example, a sample Android app that contains a user interface layout (main.axml),
an internationalization string table (strings.xml) and some icons (drawable-XXX/icon.png)
would keep its resources in the "Resources" directory of the application:
Resources/
drawable/
icon.png
layout/
main.axml
values/
strings.xml
In order to get the build system to recognize Android resources, set the build action to
"AndroidResource". The native Android APIs do not operate directly with filenames, but
instead operate on resource IDs. When you compile an Android application that uses resources,
the build system will package the resources for distribution and generate a class called "R"
(this is an Android convention) that contains the tokens for each one of the resources
included. For example, for the above Resources layout, this is what the R class would expose:
public class R {
public class drawable {
public const int icon = 0x123;
}
public class layout {
public const int main = 0x456;
}
public class strings {
public const int first_string = 0xabc;
public const int second_string = 0xbcd;
}
}
You would then use R.drawable.icon to reference the drawable/icon.png file, or R.layout.main
to reference the layout/main.axml file, or R.strings.first_string to reference the first
string in the dictionary file values/strings.xml.

View File

View File

@ -0,0 +1,178 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{812692D4-C638-4FD1-AEA7-407824B134A6}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ObdLibUWP</RootNamespace>
<AssemblyName>ObdLibUWP</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.10586.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<PlatformTarget>x86</PlatformTarget>
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<PlatformTarget>ARM</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<PlatformTarget>ARM</PlatformTarget>
<OutputPath>bin\ARM\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<PlatformTarget>x64</PlatformTarget>
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .Net Framework and Windows SDK are automatically included -->
<None Include="project.json" />
</ItemGroup>
<ItemGroup>
<Compile Include="ObdWrapper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\ObdLibUWP.rd.xml" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ObdShare\ObdShare.csproj">
<Project>{7a88da9b-a374-4de2-b46e-ed2c45434508}</Project>
<Name>ObdShare</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'XTC|AnyCPU'">
<OutputPath>bin\XTC\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoStdLib>true</NoStdLib>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'XTC|x86'">
<OutputPath>bin\x86\XTC\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'XTC|ARM'">
<OutputPath>bin\ARM\XTC\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'XTC|x64'">
<OutputPath>bin\x64\XTC\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,360 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace ObdLibUWP
{
public class ObdWrapper
{
const int Interval = 100;
const string DefValue = "-255";
private readonly Object _lock = new Object();
private bool connected = true;
private Dictionary<string, string> data;
private DataReader dataReaderObject;
private DataWriter dataWriterObject;
private Dictionary<string, string> piDs;
private bool running = true;
private RfcommDeviceService service;
private bool simulatormode;
private StreamSocket socket;
public async Task<bool> Init(bool simulatormode = false)
{
running = true;
//initialize _data
data = new Dictionary<string, string> {{"vin", DefValue}};
//VIN
piDs = ObdShare.ObdUtil.GetPIDs();
foreach (var v in piDs.Values)
{
data.Add(v, DefValue);
}
this.simulatormode = simulatormode;
if (simulatormode)
{
PollObd();
return true;
}
DeviceInformationCollection deviceInfoCollection =
await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
var numDevices = deviceInfoCollection.Count();
DeviceInformation device = null;
foreach (DeviceInformation info in deviceInfoCollection)
{
if (info.Name.ToLower().Contains("obd"))
{
device = info;
}
}
if (device == null)
return false;
try
{
service = await RfcommDeviceService.FromIdAsync(device.Id);
// Disposing the socket with close it and release all resources associated with the socket
socket?.Dispose();
socket = new StreamSocket();
try
{
// Note: If either parameter is null or empty, the call will throw an exception
await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);
connected = true;
}
catch (Exception ex)
{
connected = false;
System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message);
}
// If the connection was successful, the RemoteAddress field will be populated
if (connected)
{
string msg = String.Format("Connected to {0}!", socket.Information.RemoteAddress.DisplayName);
System.Diagnostics.Debug.WriteLine(msg);
dataWriterObject = new DataWriter(socket.OutputStream);
dataReaderObject = new DataReader(socket.InputStream);
//initialize the device
string s;
s = await SendAndReceive("ATZ\r");
s = await SendAndReceive("ATE0\r");
s = await SendAndReceive("ATL1\r");
s = await SendAndReceive("ATSP00\r");
PollObd();
return true;
}
else
return false;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message);
if (dataReaderObject != null)
{
dataReaderObject.Dispose();
dataReaderObject = null;
}
if (dataWriterObject != null)
{
dataWriterObject.Dispose();
dataWriterObject = null;
}
if (socket != null)
{
socket.Dispose();
socket = null;
}
return false;
}
}
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)
{
socket.Dispose();
socket = null;
}
}
}
private async Task<string> ReadAsync()
{
string ret = await ReadAsyncRaw();
while (!ret.Trim().EndsWith(">"))
{
string tmp = await ReadAsyncRaw();
ret = ret + tmp;
}
return ret;
}
public async Task<string> GetSpeed()
{
if (simulatormode)
{
var r = new Random();
return r.Next().ToString();
}
var result = await SendAndReceive("010D\r");
return ObdShare.ObdUtil.ParseObd01Msg(result);
}
public async Task<string> GetVIN()
{
var result = await SendAndReceive("0902\r");
if (result.StartsWith("49"))
{
while (!result.Contains("49 02 05"))
{
string tmp = await ReadAsync();
result += tmp;
}
}
return ObdShare.ObdUtil.ParseVINMsg(result);
}
public Dictionary<string, string> Read()
{
if (!simulatormode && socket == null)
{
//if there is no connection
return null;
}
var ret = new Dictionary<string, string>();
lock (_lock)
{
foreach (var key in data.Keys)
{
ret.Add(key, data[key]);
}
foreach (var v in piDs.Values)
{
data[v] = DefValue;
}
}
return ret;
}
private async Task<string> SendAndReceive(string msg)
{
await WriteAsync(msg);
string s = await ReadAsync();
System.Diagnostics.Debug.WriteLine("Received: " + s);
s = s.Replace("SEARCHING...\r\n", "");
return s;
}
private async void Send(string msg)
{
try
{
if (socket.OutputStream != null)
{
//Launch the WriteAsync task to perform the write
await WriteAsync(msg);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Send(): " + ex.Message);
}
finally
{
// Cleanup once complete
if (dataWriterObject != null)
{
dataWriterObject.DetachStream();
dataWriterObject = null;
}
}
}
private async Task WriteAsync(string msg)
{
Task<UInt32> storeAsyncTask;
if (msg.Length != 0)
{
// Load the text from the sendText input text box to the dataWriter object
dataWriterObject.WriteString(msg);
// Launch an async task to complete the write operation
storeAsyncTask = dataWriterObject.StoreAsync().AsTask();
UInt32 bytesWritten = await storeAsyncTask;
if (bytesWritten > 0)
{
string statusText = msg + ", ";
statusText += bytesWritten.ToString();
statusText += " bytes written successfully!";
System.Diagnostics.Debug.WriteLine(statusText);
}
}
}
private async Task<string> ReadAsyncRaw()
{
uint readBufferLength = 1024;
// Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
// Create a task object to wait for data on the serialPort.InputStream
var loadAsyncTask = dataReaderObject.LoadAsync(readBufferLength).AsTask();
// Launch the task and wait
UInt32 bytesRead = await loadAsyncTask;
if (bytesRead > 0)
{
try
{
string recvdtxt = dataReaderObject.ReadString(bytesRead);
System.Diagnostics.Debug.WriteLine(recvdtxt);
return recvdtxt;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("ReadAsync: " + ex.Message);
return "";
}
}
return "";
}
private async Task<string> RunCmd(string cmd)
{
var result = await SendAndReceive(cmd + "\r");
return ObdShare.ObdUtil.ParseObd01Msg(result);
}
public async Task Disconnect()
{
running = false;
if (dataReaderObject != null)
{
dataReaderObject.Dispose();
dataReaderObject = null;
}
if (dataWriterObject != null)
{
dataWriterObject.Dispose();
dataWriterObject = null;
}
if (socket != null)
{
try
{
await socket.CancelIOAsync();
socket.Dispose();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
socket = null;
}
}
}
}

View File

@ -0,0 +1,33 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ObdLibUWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ObdLibUWP")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains Runtime Directives, specifications about types your application accesses
through reflection and other dynamic code patterns. Runtime Directives are used to control the
.NET Native optimizer and ensure that it does not remove code accessed by your library. If your
library does not do any reflection, then you generally do not need to edit this file. However,
if your library reflects over types, especially types passed to it or derived from its types,
then you should write Runtime Directives.
The most common use of reflection in libraries is to discover information about types passed
to the library. Runtime Directives have three ways to express requirements on types passed to
your library.
1. Parameter, GenericParameter, TypeParameter, TypeEnumerableParameter
Use these directives to reflect over types passed as a parameter.
2. SubTypes
Use a SubTypes directive to reflect over types derived from another type.
3. AttributeImplies
Use an AttributeImplies directive to indicate that your library needs to reflect over
types or methods decorated with an attribute.
For more information on writing Runtime Directives for libraries, please visit
http://go.microsoft.com/fwlink/?LinkID=391919
-->
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Library Name="ObdLibUWP">
<!-- add directives for your library here -->
</Library>
</Directives>

View File

@ -0,0 +1,16 @@
{
"dependencies": {
"Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
},
"frameworks": {
"uap10.0": {}
},
"runtimes": {
"win10-arm": {},
"win10-arm-aot": {},
"win10-x86": {},
"win10-x86-aot": {},
"win10-x64": {},
"win10-x64-aot": {}
}
}

View File

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{8B136D60-8E68-4871-BF25-52E27C61E8E9}</ProjectGuid>
<ProjectTypeGuids>{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<RootNamespace>ObdLibiOS</RootNamespace>
<IPhoneResourcePrefix>Resources</IPhoneResourcePrefix>
<AssemblyName>ObdLibiOS</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'XTC|AnyCPU'">
<OutputPath>bin\XTC\</OutputPath>
<DefineConstants>__UNIFIED__;__MOBILE__;__IOS__;</DefineConstants>
<Optimize>true</Optimize>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="Xamarin.iOS" />
</ItemGroup>
<ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<ItemGroup>
<Compile Include="ObdWrapper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<ProjectReference Include="..\ObdShare\ObdShare.csproj">
<Project>{7a88da9b-a374-4de2-b46e-ed2c45434508}</Project>
<Name>ObdShare</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.CSharp.targets" />
</Project>

View File

@ -0,0 +1,293 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.IO;
using System.Net.NetworkInformation;
namespace ObdLibiOS
{
public class ObdWrapper
{
const uint BufSize = 1024;
const int Interval = 100;
const string DefValue = "-255";
private readonly Object _lock = new Object();
private bool connected = true;
private Dictionary<string, string> data;
private IPAddress ipAddress;
private IPEndPoint ipEndPoint;
private Dictionary<string, string> piDs;
private int port;
private bool running = true;
private bool simulatormode;
private Socket socket;
private Stream stream;
public async Task<bool> Init(bool simulatormode = false)
{
running = true;
//initialize _data
data = new Dictionary<string, string> {{"vin", DefValue}};
//VIN
piDs = ObdShare.ObdUtil.GetPIDs();
foreach (var v in piDs.Values)
{
data.Add(v, DefValue);
}
this.simulatormode = simulatormode;
if (simulatormode)
{
PollObd();
return true;
}
bool isObdReaderAvailable = false;
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211
|| netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
{
var ipaddr = addrInfo.Address;
if (ipaddr.ToString().StartsWith("192.168.0"))
{
isObdReaderAvailable = true;
break;
}
}
}
}
if (!isObdReaderAvailable)
{
socket = null;
running = false;
connected = false;
return false;
}
if (!ConnectSocket())
{
socket = null;
running = false;
connected = false;
return false;
}
if (connected)
{
//initialize the device
string s;
s = await SendAndReceive("ATZ\r");
s = await SendAndReceive("ATE0\r");
s = await SendAndReceive("ATL1\r");
s = await SendAndReceive("ATSP00\r");
PollObd();
return true;
}
else
return false;
}
public Dictionary<string, string> Read()
{
if (!simulatormode && socket == null)
{
//if there is no connection
return null;
}
var ret = new Dictionary<string, string>();
lock (_lock)
{
foreach (var key in data.Keys)
{
ret.Add(key, data[key]);
}
foreach (var v in piDs.Values)
{
data[v] = DefValue;
}
}
return ret;
}
private async void PollObd()
{
try
{
string s;
if (simulatormode)
s = "SIMULATORIPHONE12";
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 (stream != null)
{
stream.Close();
stream = null;
}
if (socket != null)
{
socket.Close();
socket = null;
}
}
}
private async Task<string> GetVIN()
{
var result = await SendAndReceive("0902\r");
if (result.StartsWith("49"))
{
while (!result.Contains("49 02 05"))
{
string tmp = await ReceiveAsync();
result += tmp;
}
}
return ObdShare.ObdUtil.ParseVINMsg(result);
}
private bool ConnectSocket()
{
//setup the connection via socket
ipAddress = IPAddress.Parse("192.168.0.10"); //hard coded in obdlink MX
port = 35000; //hard coded in obdlink MX
ipEndPoint = new IPEndPoint(ipAddress, port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect(ipEndPoint);
stream = new NetworkStream(socket);
connected = true;
}
catch (Exception)
{
connected = false;
return false;
}
return true;
}
private async Task<string> SendAndReceive(string msg)
{
try
{
await WriteAsync(msg);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
System.Threading.Thread.Sleep(100);
try
{
string s = await ReceiveAsync();
System.Diagnostics.Debug.WriteLine("Received: " + s);
s = s.Replace("SEARCHING...\r\n", "");
return s;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return "";
}
private async Task WriteAsync(string msg)
{
System.Diagnostics.Debug.WriteLine(msg);
byte[] buffer = Encoding.ASCII.GetBytes(msg);
await stream.WriteAsync(buffer, 0, buffer.Length);
stream.Flush();
}
private async Task<string> ReceiveAsync()
{
string ret = await ReceiveAsyncRaw();
while (!ret.Trim().EndsWith(">"))
{
string tmp = await ReceiveAsyncRaw();
ret = ret + tmp;
}
return ret;
}
private async Task<string> ReceiveAsyncRaw()
{
byte[] buffer = new byte[BufSize];
var bytes = await stream.ReadAsync(buffer, 0, buffer.Length);
var s = Encoding.ASCII.GetString(buffer, 0, bytes);
System.Diagnostics.Debug.WriteLine(s);
return s;
}
private async Task<string> RunCmd(string cmd)
{
var result = await SendAndReceive(cmd + "\r");
return ObdShare.ObdUtil.ParseObd01Msg(result);
}
public async Task Disconnect()
{
running = false;
if (stream != null)
{
stream.Dispose();
stream.Close();
stream = null;
}
if (socket != null)
{
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
socket.Close();
socket = null;
}
}
}
}

View File

@ -0,0 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ObdLibiOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ObdLibiOS")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8b136d60-8e68-4871-bf25-52e27c61e8e9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<MinimumVisualStudioVersion>10.0</MinimumVisualStudioVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{7A88DA9B-A374-4DE2-B46E-ED2C45434508}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ObdShare</RootNamespace>
<AssemblyName>ObdShare</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkProfile>Profile111</TargetFrameworkProfile>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'XTC|AnyCPU'">
<OutputPath>bin\XTC\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
</ItemGroup>
<ItemGroup>
<Compile Include="ObdUtil.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,269 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Globalization;
namespace ObdShare
{
public class ObdUtil
{
static string _outsideTemperature = "0";
static double _distancewithMl;
static int _runtime;
private static int ParseString(string str, int bytes)
{
return int.Parse(str.Substring(4, bytes * 2), NumberStyles.HexNumber);
}
public static string ParseObd01Msg(string input)
{
string str = input.Replace("\r", "").Replace("\n", "").Replace(" ", "").Replace(">", "").Trim();
if (!str.StartsWith("41") || str.Length < 6)
return "-255";
string pid = str.Substring(2, 2);
int result;
switch (pid)
{
case "04": //EngineLoad
return (ParseString(str, 1) * 100 / 255).ToString();
case "06": //ShortTermFuelBank1
return ((ParseString(str, 1) - 128) * 100 / 128).ToString();
case "07": //LongTermFuelBank1
return ((ParseString(str, 1) - 128) * 100 / 128).ToString();
case "0C": //RPM
result = (ParseString(str, 2) / 4);
if (result < 0 || result > 16383)
result = -255;
return result.ToString();
case "0D": //Speed
result = ParseString(str, 1);
if (result < 0 || result > 255)
result = -255;
return result.ToString();
case "0F": //InsideTemperature
return (ParseString(str, 1) - 40).ToString();
case "10": //MAF air flow rate
result = (ParseString(str, 2) / 100);
if (result < 0 || result > 655)
result = -255;
return result.ToString();
case "11": //Throttle position
return (ParseString(str, 1) * 100 / 255).ToString();
case "1F": //Runtime
return ParseString(str, 2).ToString();
case "21": //DistancewithML
return ParseString(str, 2).ToString();
case "2C": //Commanded EGR
return (ParseString(str, 1) * 100 / 255).ToString();
case "2D": //EGR Error
return ((ParseString(str, 1) - 128) * 100 / 128).ToString();
case "33": //BarometricPressure
return ParseString(str, 1).ToString();
case "45": //Relative throttle position
return (ParseString(str, 1) * 100 / 255).ToString();
case "46": //OutsideTemperature
return (ParseString(str, 1) - 40).ToString();
case "5E": //EngineFuelRate
result = (ParseString(str, 2) / 20);
if (result < 0 || result > 3212)
result = -255;
return result.ToString();
}
return "ERROR";
}
public static string ParseVINMsg(string result) //VIN
{
try
{
if (result.Contains("STOPPED"))
return result;
if (result.Contains("NO DATA") || result.Contains("ERROR"))
return result;
string temp = result.Replace("\r\n", "");
int index = temp.IndexOf("0: ");
if (index < 0)
return ParseLongVIN(result);
temp = temp.Substring(index);
temp = temp.Replace("0: ", "");
temp = temp.Replace("1: ", "");
temp = temp.Replace("2: ", "");
temp = temp.Trim();
if (temp.Length > 59)
temp = temp.Substring(0, 59);
var items = temp.Split(' ');
string ret = "";
foreach (var s in items)
{
ret += (char)int.Parse(s, NumberStyles.HexNumber);
}
if (ret.Length > 17)
ret = ret.Substring(ret.Length - 17);
//mask last 7 digits
ret = ret.Substring(0, 10);
ret += "0000000";
return ret;
}
catch (Exception exp)
{
return exp.Message;
}
}
public static string ParseLongVIN(string result) //VIN
{
if (result.Contains("STOPPED"))
return result;
if (result.Contains("NO DATA") || result.Contains("ERROR"))
return result;
var items = result.Replace("\r\n", "").Split(' ');
if (items.Length < 36)
return "ERROR";
if (items[0].Trim() != "49")
return "ERROR";
string ret = "";
int tint;
char tchar;
switch (items[1])
{
case "02": //VIN
tint = int.Parse(items[6], NumberStyles.HexNumber);
tchar = (char)tint;
ret += tchar.ToString();
for (int i = 10; i < 14; i++)
{
tint = int.Parse(items[i], NumberStyles.HexNumber);
tchar = (char)tint;
ret += tchar.ToString();
}
for (int i = 17; i < 21; i++)
{
tint = int.Parse(items[i], NumberStyles.HexNumber);
tchar = (char)tint;
ret += tchar.ToString();
}
for (int i = 24; i < 28; i++)
{
tint = int.Parse(items[i], NumberStyles.HexNumber);
tchar = (char)tint;
ret += tchar.ToString();
}
for (int i = 31; i < 35; i++)
{
tint = int.Parse(items[i], NumberStyles.HexNumber);
tchar = (char)tint;
ret += tchar.ToString();
}
//mask last 7 digits
ret = ret.Substring(0, 10);
ret += "0000000";
return ret;
}
return "ERROR";
}
public static Dictionary<string, string> GetPIDs()
{
//return PIDs we want to collect
//the structure is <cmd, key>
var ret = new Dictionary<string, string>
{
{"0110", "fr"},
{"0104", "el"},
{"0106", "stfb"},
{"0107", "ltfb"},
{"010C", "rpm"},
{"010D", "spd"},
{"0111", "tp"},
{"011F", "rt"},
{"0121", "dis"},
{"0145", "rtp"},
{"0146", "ot"},
{"015E", "efr"}
};
//EngineLoad
//ShortTermFuelBank1
//LongTermFuelBank1
//EngineRPM
//Speed
//MAFFlowRate
//ThrottlePosition
//Runtime
//DistancewithMIL
//RelativeThrottlePosition
//OutsideTemperature
//EngineFuelRate
return ret;
}
public static string GetEmulatorValue(string cmd)
{
var r = new Random();
switch (cmd)
{
case "0104":
return r.Next(0, 100).ToString();
case "0106":
return (r.Next(0, 200) - 100).ToString();
case "0107":
return (r.Next(0, 200) - 100).ToString();
case "010C":
return r.Next(0, 2500).ToString();
case "010D":
return r.Next(5, 70).ToString();
case "0110":
return r.Next(0, 50).ToString();
case "0111":
return r.Next(0, 100).ToString();
case "011F":
_runtime = _runtime + 2;
return _runtime.ToString();
case "0121":
_distancewithMl = _distancewithMl + 0.1;
return ((int)_distancewithMl).ToString();
case "0145":
return r.Next(0, 100).ToString();
case "0146":
return SimulateTemperatureValue(r);
case "015E":
return SimulateEngineFuelRateValue(r);
}
return "0";
}
static string SimulateTemperatureValue(Random r)
{
if (_outsideTemperature == "0")
{
_outsideTemperature = r.Next(0, 38).ToString();
}
else
{
var temperature = Double.Parse(_outsideTemperature);
// Returns variance value between .01 and .05
var variance = r.NextDouble() * (0.04) + .01;
var varyTemperatureDirection = r.Next(0, 2);
if (varyTemperatureDirection == 0)
temperature += variance;
else
temperature -= variance;
_outsideTemperature = temperature.ToString();
}
return _outsideTemperature;
}
static string SimulateEngineFuelRateValue(Random r)
{
var variance = r.NextDouble() * 6 + 8;
return variance.ToString();
}
}
}

View File

@ -0,0 +1,33 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System.Resources;
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ObdShare")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ObdShare")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]