Exemplo n.º 1
0
        public override async Task <bool> Initialize()
        {
            this.Logger.AddDebugMessage("Initializing " + this.ToString());


            SerialPortConfiguration configuration = new SerialPortConfiguration();

            configuration.BaudRate = 115200;
            configuration.Timeout  = 1000;
            await this.Port.OpenAsync(configuration);

            System.Threading.Thread.Sleep(100);

            ////Reset scantool - ensures starts at ELM protocol
            bool Status = await ResetDevice();

            if (Status == false)
            {
                this.Logger.AddUserMessage("Unable to reset DVI device.");
                return(false);
            }

            //Request Board information
            Response <string> BoardName = await GetBoardDetails();

            if (BoardName.Status != ResponseStatus.Success)
            {
                this.Logger.AddUserMessage("Unable to get DVI device details.");
                return(false);
            }

            //Set protocol to VPW mode
            Status = await SetProtocol(OBDProtocols.VPW);

            if (Status == false)
            {
                this.Logger.AddUserMessage("Unable to set DVI device protocol to VPW.");
                return(false);
            }

            Response <bool> SetupStatus = await DVISetup();

            if (SetupStatus.Status != ResponseStatus.Success)
            {
                this.Logger.AddUserMessage("DVI device initialization failed.");
                return(false);
            }

            this.Logger.AddUserMessage("Device Successfully Initialized and Ready");
            return(true);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Open the serial port.
        /// </summary>
        Task IPort.OpenAsync(PortConfiguration configuration)
        {
            // Clean up the existing SerialPort object, if we have one.
            if (this.port != null)
            {
                this.port.Dispose();
            }
            SerialPortConfiguration config = configuration as SerialPortConfiguration;

            this.port          = new SerialPort(this.name);
            this.port.BaudRate = config.BaudRate;
            this.port.DataBits = 8;
            this.port.Parity   = Parity.None;
            this.port.StopBits = StopBits.One;
            if (config.Timeout == 0)
            {
                config.Timeout = 1000;                      // default to 1 second but allow override.
            }
            this.port.ReadTimeout = config.Timeout;

            if (this.port.IsOpen == true)
            {
                this.port.Close();
            }

/*            if (config.DataReceived != null)
 *          {
 *              this.dataReceivedCallback = config.DataReceived;
 *              this.port.DataReceived += this.DataReceived;
 *          }
 */

            this.port.Open();

            // This line must come AFTER the call to port.Open().
            // Attempting to use the BaseStream member will throw an exception otherwise.
            //
            // However, even after setting the BaseStream.ReadTimout property, calls to
            // BaseStream.ReadAsync will hang indefinitely. It turns out that you have
            // to implement the timeout yourself if you use the async approach.
            this.port.BaseStream.ReadTimeout = this.port.ReadTimeout;

            return(Task.CompletedTask);
        }
Exemplo n.º 3
0
        public override async Task <bool> Initialize()
        {
            this.Logger.AddDebugMessage("Initializing " + this.ToString());

            Response <Message> m;

            SerialPortConfiguration configuration = new SerialPortConfiguration();

            configuration.BaudRate = 115200;
            await this.Port.OpenAsync(configuration);

            await this.Port.DiscardBuffers();

            this.Logger.AddDebugMessage("Sending 'reset' message.");
            await this.Port.Send(AvtDevice.AVT_RESET.GetBytes());

            m = await ReadAVTPacket();

            if (m.Status == ResponseStatus.Success)
            {
                switch (m.Value.GetBytes()[0])
                {
                case 0x27:
                    this.Logger.AddUserMessage("AVT 852 Reset OK");
                    break;

                case 0x12:
                    this.Logger.AddUserMessage("AVT 842 Reset OK");
                    break;

                default:
                    this.Logger.AddUserMessage("Unknown and unsupported AVT device detected. Please add support and submit a patch!");
                    return(false);
                }
            }
            else
            {
                this.Logger.AddUserMessage("AVT device not found or failed reset");
                return(false);
            }

            this.Logger.AddDebugMessage("Looking for Firmware message");
            m = await this.FindResponse(AVT_FIRMWARE);

            if (m.Status == ResponseStatus.Success)
            {
                byte firmware = m.Value.GetBytes()[1];
                int  major    = firmware >> 4;
                int  minor    = firmware & 0x0F;
                this.Logger.AddUserMessage("AVT Firmware " + major + "." + minor);
            }
            else
            {
                this.Logger.AddUserMessage("Firmware not found or failed reset");
                this.Logger.AddDebugMessage("Expected " + AVT_FIRMWARE.GetBytes());
                return(false);
            }

            await this.Port.Send(AvtDevice.AVT_ENTER_VPW_MODE.GetBytes());

            m = await FindResponse(AVT_VPW);

            if (m.Status == ResponseStatus.Success)
            {
                this.Logger.AddDebugMessage("Set VPW Mode");
            }
            else
            {
                this.Logger.AddUserMessage("Unable to set AVT device to VPW mode");
                this.Logger.AddDebugMessage("Expected " + AvtDevice.AVT_VPW.ToString());
                return(false);
            }

            await AVTSetup();

            return(true);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Configure the device for use - and also confirm that the device is what we think it is.
        /// </summary>
        public override async Task <bool> Initialize()
        {
            this.Logger.AddDebugMessage("Initializing " + this.ToString());

            // We're going to reset the interface device, which means that it's going
            // to forgot what header the app previously told it to use. That requires
            // the app to forget what header the interface was told to use - that will
            // cause the app to send another set-header command later on.
            this.currentHeader = "header not yet set";

            SerialPortConfiguration configuration = new SerialPortConfiguration();

            configuration.BaudRate = 115200;
            configuration.Timeout  = 1200;

            await this.Port.OpenAsync(configuration);

            await this.Port.DiscardBuffers();

            try
            {
                // Reset
                await this.SendRequest("");                                   // send a cr/lf to prevent the ATZ failing.

                this.Logger.AddDebugMessage(await this.SendRequest("AT Z"));  // reset
                this.Logger.AddDebugMessage(await this.SendRequest("AT E0")); // disable echo
                this.Logger.AddDebugMessage(await this.SendRequest("AT S0")); // no spaces on responses

                // Device Identification
                string elmID = await this.SendRequest("AT I");                // Identify (ELM)

                string stID = await this.SendRequest("ST I");                 // Identify (ScanTool.net)

                string apID = await this.SendRequest("AT #1");                // Identify (AllPro)

                if (elmID != "?")
                {
                    this.Logger.AddUserMessage("Elm ID: " + elmID);
                    if (elmID.Contains("ELM327 v1.5"))
                    {
                        // TODO: Add a URL to a web page with a list of supported devices.
                        // No such web page exists yet, but I'm sure we'll create one some day...
                        this.Logger.AddUserMessage("ERROR: This OBD2 interface is not supported.");
                        return(false);
                    }
                }

                if (stID != "?")
                {
                    this.Logger.AddUserMessage("ScanTool ID: " + stID);
                }

                if (apID != "?")
                {
                    this.Logger.AddUserMessage("All Pro ID: " + apID);
                    this.Logger.AddUserMessage("All Pro self test result: " + await this.SendRequest("AT #3"));  // self test
                    this.Logger.AddUserMessage("All Pro firmware: " + await this.SendRequest("AT @1"));          // firmware check

                    this.Supports4X     = true;
                    this.MaxSendSize    = 2048 + 12;
                    this.MaxReceiveSize = 2048 + 12;
                }

                string voltage = await this.SendRequest("AT RV");             // Get Voltage

                this.Logger.AddUserMessage("Voltage: " + voltage);

                if (!await this.SendAndVerify("AT AL", "OK") ||                                 // Allow Long packets
                    !await this.SendAndVerify("AT SP2", "OK") ||                                // Set Protocol 2 (VPW)
                    !await this.SendAndVerify("AT DP", "SAE J1850 VPW") ||                      // Get Protocol (Verify VPW)
                    !await this.SendAndVerify("AT AR", "OK") ||                                 // Turn Auto Receive on (default should be on anyway)
                    !await this.SendAndVerify("AT AT0", "OK") ||                                // Disable adaptive timeouts
                    !await this.SendAndVerify("AT SR " + DeviceId.Tool.ToString("X2"), "OK") || // Set receive filter to this tool ID
                    !await this.SendAndVerify("AT H1", "OK") ||                                 // Send headers
                    !await this.SendAndVerify("AT ST 20", "OK")                                 // Set timeout (will be adjusted later, too)
                    )
                {
                    return(false);
                }
            }
            catch (Exception exception)
            {
                this.Logger.AddDebugMessage("Unable to initalize " + this.ToString());
                this.Logger.AddDebugMessage(exception.ToString());
                return(false);
            }

            return(true);
        }
Exemplo n.º 5
0
        public override async Task <bool> Initialize()
        {
            this.Logger.AddDebugMessage("Initializing " + this.ToString());


            SerialPortConfiguration configuration = new SerialPortConfiguration();

            configuration.BaudRate = 500000;
            await this.Port.OpenAsync(configuration);

            System.Threading.Thread.Sleep(100);
            await this.Port.DiscardBuffers();

            ////Reset scantool first
            //this.Logger.AddDebugMessage("Sending 'reset' message.");
            //await this.Port.Send(DVIDevice.DVI_RESET.GetBytes());
            //Response<Message> m = await this.FindResponse(DVI_RESET_RESP);
            //this.Logger.AddUserMessage("DVI Reset OK");

            //
            //  System.Threading.Thread.Sleep(1000);

            //Request Board information
            await this.Port.Send(DviDevice.DVI_BOARD_NAME.GetBytes());

            Response <Message> m = await ReadDVIPacket();

            if (m.Status == ResponseStatus.Success)
            {
                byte[] Val  = m.Value.GetBytes();
                string name = System.Text.Encoding.ASCII.GetString(Val, 3, Val[1] - 1);
                this.Logger.AddUserMessage("Device Found: " + name);
            }
            else
            {
                this.Logger.AddUserMessage("DVI device not found or failed response");
                return(false);
            }

            await this.Port.DiscardBuffers();

            //Set protocol to VPW mode
            await this.Port.Send(DviDevice.DVI_ENTER_VPW_MODE.GetBytes());

            m = await FindResponse(DVI_VPW_RESP);

            if (m.Status == ResponseStatus.Success)
            {
                this.Logger.AddDebugMessage("Set VPW Mode");
            }
            else
            {
                this.Logger.AddUserMessage("Unable to set DVI device to VPW mode");
                this.Logger.AddDebugMessage("Expected " + DviDevice.DVI_VPW_RESP.ToString());
                return(false);
            }

            await DVISetup();

            return(true);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Use the related classes to discover which type of device is currently connected.
        /// </summary>
        public override async Task <bool> Initialize()
        {
            try
            {
                this.Logger.AddDebugMessage("ElmDevice initialization starting.");

                SerialPortConfiguration configuration = new SerialPortConfiguration();
                configuration.BaudRate = 115200;
                configuration.Timeout  = 1200;

                await this.Port.OpenAsync(configuration);

                await this.Port.DiscardBuffers();

                if (!await this.SharedInitialization())
                {
                    return(false);
                }

                AllProDeviceImplementation allProDevice = new AllProDeviceImplementation(
                    this.Enqueue,
                    () => this.ReceivedMessageCount,
                    this.Port,
                    this.Logger);
                if (await allProDevice.Initialize())
                {
                    this.implementation = allProDevice;
                }
                else
                {
                    ScanToolDeviceImplementation scanToolDevice = new ScanToolDeviceImplementation(
                        this.Enqueue,
                        () => this.ReceivedMessageCount,
                        this.Port,
                        this.Logger);

                    if (await scanToolDevice.Initialize())
                    {
                        this.implementation = scanToolDevice;
                    }
                }

                // These are shared by all ELM-based devices.
                if (!await this.implementation.SendAndVerify("AT AL", "OK") ||                                 // Allow Long packets
                    !await this.implementation.SendAndVerify("AT SP2", "OK") ||                                // Set Protocol 2 (VPW)
                    !await this.implementation.SendAndVerify("AT DP", "SAE J1850 VPW") ||                      // Get Protocol (Verify VPW)
                    !await this.implementation.SendAndVerify("AT AR", "OK") ||                                 // Turn Auto Receive on (default should be on anyway)
                    !await this.implementation.SendAndVerify("AT AT0", "OK") ||                                // Disable adaptive timeouts
                    !await this.implementation.SendAndVerify("AT SR " + DeviceId.Tool.ToString("X2"), "OK") || // Set receive filter to this tool ID
                    !await this.implementation.SendAndVerify("AT H1", "OK") ||                                 // Send headers
                    !await this.implementation.SendAndVerify("AT ST 20", "OK")                                 // Set timeout (will be adjusted later, too)
                    )
                {
                    return(false);
                }

                this.MaxSendSize    = this.implementation.MaxSendSize;
                this.MaxReceiveSize = this.implementation.MaxReceiveSize;
                this.Supports4X     = this.implementation.Supports4X;
            }
            catch (Exception exception)
            {
                this.Logger.AddDebugMessage("Unable to initalize " + this.ToString());
                this.Logger.AddDebugMessage(exception.ToString());
                return(false);
            }

            return(true);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Run the HTTP server. Just handle requests as they come in.
        /// </summary>
        public async void Run(object unused)
        {
            // This loop restarts the server if it crashes.
            while (true)
            {
                try
                {
                    this.listener = new HttpListener();
                    this.listener.Prefixes.Add("http://*:11411/pcm/");
                    this.listener.Start();

                    SerialPortConfiguration configuration = new SerialPortConfiguration();
                    configuration.BaudRate = 115200;
                    await this.port.OpenAsync(configuration);

                    // This loop handles incoming connections.
                    while (true)
                    {
                        var context = await this.listener.GetContextAsync();

                        context.Response.ContentType = "text/plain";

                        try
                        {
                            string path = context.Request.Url.AbsolutePath;

                            if (path == "/pcm/send")
                            {
                                await this.Send(context);
                            }
                            else if (path == "/pcm/receive")
                            {
                                await this.Receive(context);
                            }
                            else
                            {
                                var writer = new StreamWriter(context.Response.OutputStream);
                                await writer.WriteLineAsync("Unsupported URL path");

                                context.Response.StatusCode = 404;
                            }
                        }
                        catch (TimeoutException)
                        {
                            context.Response.StatusCode = 504;
                        }
                        catch (Exception exception)
                        {
                            this.logger.AddUserMessage("HTTP 500 " + exception.ToString());

                            var writer = new StreamWriter(context.Response.OutputStream);
                            context.Response.StatusCode = 500;
                            await writer.WriteLineAsync(exception.ToString());

                            await writer.FlushAsync();
                        }

                        context.Response.Close();
                    }
                }
                catch (Exception exception)
                {
                    this.logger.AddUserMessage("The web server crashed. Will restart in 5 seconds.");
                    this.logger.AddUserMessage(exception.ToString());

                    if (this.listener != null)
                    {
                        this.listener.Close();
                        this.listener = null;
                    }

                    if (this.port != null)
                    {
                        this.port.Dispose();
                        this.port = null;
                    }

                    await Task.Delay(5000);
                }
            }
        }