Exemple #1
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 (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);
        }
Exemple #2
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 this.FindResponse(AVT_852_IDLE);

            if (m.Status == ResponseStatus.Success)
            {
                this.Logger.AddUserMessage("AVT device reset ok");
            }
            else
            {
                this.Logger.AddUserMessage("AVT device not found or failed reset");
                this.Logger.AddDebugMessage("Expected " + AvtDevice.AVT_852_IDLE.GetString());
                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.GetString());
                return(false);
            }

            await AVTSetup();

            return(true);
        }
Exemple #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.GetString());
                return(false);
            }

            await AVTSetup();

            return(true);
        }
Exemple #4
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);
                }
            }
        }
        /// <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);
        }