示例#1
0
 //Have the camera flash for a specified time
 public void MakeCameraFlash()
 {
     //check how long the flash has lasted
     if (secondsPast <= flashExposureTime)
     {
         if (!playedFlash)
         {
             playedFlash = true;
             audioSource.PlayOneShot(flash, 1.5f);
         }
         //set intensity of light to the specified one
         if (flashObject.intensity != flashIntensity)
         {
             flashObject.intensity = flashIntensity;
         }
         //increase the time passed
         secondsPast += Time.deltaTime;
     }
     else
     {
         //set to next state and reset the time passed
         currentFlashState = FlashState.Fading;
         playedFlash       = false;
         secondsPast       = 0;
     }
 }
示例#2
0
        private void SetFlashState(FlashState state)
        {
            try
            {
                _device.SetProperty(KnownCameraPhotoProperties.FlashMode, state);

                _flashState = state;

                if (_flashState == FlashState.Auto)
                {
                    _flashButton.IconUri = new Uri("/Assets/Icons/flash_auto.png", UriKind.Relative);
                }
                else if (_flashState == FlashState.On)
                {
                    _flashButton.IconUri = new Uri("/Assets/Icons/flash_on.png", UriKind.Relative);
                }
                else // FlashState.Off
                {
                    _flashButton.IconUri = new Uri("/Assets/Icons/flash_off.png", UriKind.Relative);
                }
            }
            catch (Exception)
            {
            }
        }
        private void FixedUpdate()
        {
            float smoothAmount = Time.fixedDeltaTime * this.emissionSmoothSpeed;

            switch (this.currentState)
            {
            case FlashState.None:
                this.currentEmission = 0f;
                break;

            case FlashState.Down:
                this.currentEmission -= smoothAmount;
                if (this.currentEmission <= 0f)
                {
                    this.currentEmission = 0f;
                    this.currentState    = FlashState.None;
                }
                break;

            case FlashState.Up:
                this.currentEmission += smoothAmount;
                if (this.currentEmission >= this.maxEmission)
                {
                    this.currentEmission = this.maxEmission;
                    this.currentState    = FlashState.Down;
                }
                break;
            }

            if (this.bodyMat)
            {
                this.bodyMat.SetFloat("_EmPower", this.currentEmission);
            }
        }
示例#4
0
 /// <summary>
 /// 设置闪烁状态
 /// </summary>
 /// <param name="flashState">不变,正常闪烁,快速闪烁</param>
 /// <param name="flashModel">CONFIRM熄灭返回按键,当递减到“00000”按CONFIRM熄灭,按CONFIRM灯闪烁5次后熄灭返回当前数值</param>
 /// <param name="flashSwitchBit"></param>
 public void SetFlashState(FlashState flashState, FlashModel flashModel, int flashSwitchBit)
 {
     byte[] switchBit = BitConverter.GetBytes(flashSwitchBit);
     ((Protocal)this.Com.Encoder).BtFlashState[0] = switchBit[0];
     ((Protocal)this.Com.Encoder).BtFlashState[1] = (byte)((switchBit[1] & 0X3FFF) ^ (byte)((byte)flashState << 6));
     ((Protocal)this.Com.Encoder).BtFlashState[2] = (byte)flashModel;
 }
示例#5
0
    //decrease the intensity of the light all the way to zero
    private void MakeFlashDisipate()
    {
        if (secondsPast < flashExposureTime)
        {
            // Reduce light intensity based on time that has passed.
            flashObject.intensity = Mathf.Lerp(flashIntensity, 0, secondsPast / flashExposureTime);
        }
        else
        {
            flashObject.intensity = 0;
        }

        // Use the hiddenObjectFadeDelay to give our hidden objects a bit of extra visible time
        // after the light goes out.
        if (secondsPast > flashExposureTime + hiddenObjectFadeDelay)
        {
            //reset everything
            //make the foot steps disappear
            Camera.main.cullingMask &= ~(1 << LayerMask.NameToLayer("FootSteps"));
            secondsPast              = 0;
            showFootSteps            = false;
            //set the next state
            currentFlashState = FlashState.Winding;
        }
        else
        {
            secondsPast += Time.deltaTime;
        }
    }
        private void Awake()
        {
            this.body         = this.GetComponent <CharacterBody>();
            this.model        = this.GetComponentInChildren <CharacterModel>();// baseRendererInfos[0].defaultMaterial;
            this.currentState = FlashState.None;

            Invoke("GetMaterial", 0.2f);
        }
 private void FlashAutoButton_Click(object sender, RoutedEventArgs e)
 {
     _flashState = FlashState.Auto;
     ModeAuto();
     if (FlashStateChanged != null)
     {
         FlashStateChanged(_flashState);
     }
 }
示例#8
0
    void FlashProcesss()
    {
        if (m_player.size <= m_pinchStartSize && m_player.size > 0)
        {
            m_flashTime -= Time.deltaTime;
            switch (m_flashState)
            {
            case FlashState.ON:
                if (m_flashTime <= 0)
                {
                    m_flashState = FlashState.OFF;
                    //	 m_frame.enabled = false;
                    m_flashTime     = Mathf.Lerp(m_flashingMinTime, m_flashingMaxTime, m_player.size / m_pinchStartSize);
                    m_alphaVariable = 1.0f / m_flashTime;
                    m_frame.color   = new Color(m_frame.color.r, m_frame.color.g, m_frame.color.b, 0);
                }
                else
                {
                    m_frame.color -= new Color(0, 0, 0, m_alphaVariable * Time.deltaTime);
                }
                break;

            case FlashState.OFF:
                if (m_flashTime <= 0)
                {
                    m_flashState    = FlashState.ON;
                    m_flashTime     = Mathf.Lerp(m_flashingMinTime, m_flashingMaxTime, m_player.size / m_pinchStartSize);
                    m_alphaVariable = 1.0f / m_flashTime;

                    m_frame.color = new Color(m_frame.color.r, m_frame.color.g, m_frame.color.b, 1);
                }
                else
                {
                    m_frame.color += new Color(0, 0, 0, m_alphaVariable * Time.deltaTime);
                }

                break;

            default:
                break;
            }
        }
        else if (m_player.size <= 0)
        {
            m_frame.color = new Color(m_frame.color.r, m_frame.color.g, m_frame.color.b, 1);
        }
        else if (m_player.size > m_pinchStartSize)
        {
            m_frame.color   = new Color(m_frame.color.r, m_frame.color.g, m_frame.color.b, 0);
            m_flashTime     = 0;
            m_alphaVariable = 1.0f / m_flashTime;

            FlashState m_flashState = FlashState.OFF;
        }
    }
示例#9
0
        private void Update()
        {
            TimeInState += Time.deltaTime;

            switch (State)
            {
            case FlashState.FadeIn:
            {
                float ratio = TimeInState / FadeInTime;

                Light.intensity = Mathf.Lerp(MinIntensity, MaxIntensity, ratio);

                if (TimeInState >= FadeInTime)
                {
                    State       = FlashState.Hold;
                    TimeInState = 0;
                }
            }
            break;

            case FlashState.Hold:
            {
                if (TimeInState >= HoldTime)
                {
                    State       = FlashState.FadeOut;
                    TimeInState = 0;
                }
            }
            break;

            case FlashState.FadeOut:
            {
                float ratio = TimeInState / FadeOutTime;

                Light.intensity = Mathf.Lerp(MinIntensity, MaxIntensity, 1f - ratio);

                if (TimeInState >= FadeOutTime)
                {
                    if (Repeat)
                    {
                        State = FlashState.FadeIn;
                    }
                    else
                    {
                        Light.intensity = 0;
                        //Light.enabled = false;
                        enabled = false;
                    }
                }
            }
            break;
            }
        }
示例#10
0
        // Gets the configuration of the specified camera
        private async Task <CameraConfig> GetCameraConfiguration(
            CameraType cameraType, CameraSensorLocation sensorLocation)
        {
            CameraConfig            cameraConfig       = null;
            PhotoCaptureDevice      photoCaptureDevice = null;
            FlashState              flash       = FlashState.Off;
            List <CameraResolution> resolutions = new List <CameraResolution>();

            try
            {
                // Read supported resolutions
                System.Collections.Generic.IReadOnlyList <Windows.Foundation.Size> SupportedResolutions =
                    PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation);
                resolutions = (from resolution in SupportedResolutions
                               select new CameraResolution
                {
                    Width = resolution.Width,
                    Height = resolution.Height
                }).ToList();

                // Read flash support.
                // Opening camera is required to read flash, request to open with min resolution
                var minResolution = SupportedResolutions.OrderBy(size => size.Width).First();
                photoCaptureDevice = await PhotoCaptureDevice.OpenAsync(sensorLocation, minResolution);

                Enum.TryParse <FlashState>(
                    photoCaptureDevice.GetProperty(KnownCameraPhotoProperties.FlashMode).ToString(),
                    true,
                    out flash);

                // Create the camera config
                cameraConfig = new CameraConfig
                {
                    Type  = (int)cameraType,
                    Sizes = resolutions,
                    Flash = flash != FlashState.Off ? true : false
                };
            }
            catch (Exception e)
            {
                Logger.Error("Error in Camera get configuration. Reason - " + e.Message);
            }
            finally
            {
                if (photoCaptureDevice != null)
                {
                    try { photoCaptureDevice.Dispose(); }
                    catch { }
                }
            }
            return(cameraConfig);
        }
示例#11
0
 public static void MakeFlash()
 {
     if (m_State == FlashState.INACTIVE || m_State == FlashState.FADE_OUT)
     {
         m_StartMilliseconds = MyMinerGame.TotalGamePlayTimeInMilliseconds;
         m_State             = FlashState.FADE_IN;
     }
     else
     if (m_State == FlashState.FLASH)
     {
         m_StartMilliseconds = MyMinerGame.TotalGamePlayTimeInMilliseconds;
     }
 }
示例#12
0
 public static void MakeFlash()
 {
     if (m_State == FlashState.INACTIVE || m_State == FlashState.FADE_OUT)
     {
         m_StartMilliseconds = MyMinerGame.TotalGamePlayTimeInMilliseconds;
         m_State = FlashState.FADE_IN;
     }
     else
     if (m_State == FlashState.FLASH)
     {
         m_StartMilliseconds = MyMinerGame.TotalGamePlayTimeInMilliseconds;
     }
 }
示例#13
0
 /// <summary>
 /// COMPORTNUMBER e.g. "COM1" 
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="comportnumber"></param>
 public override void FlashFile(string filename, string comportnumber)
 {
     _filename = filename;
     _logfileName = Path.Combine(Path.GetDirectoryName(_filename), "commlog.txt");
     FileInfo fi = new FileInfo(_filename);
     _length2Send = (int)fi.Length;
     Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
     if (InitializeFlasher(comportnumber))
     {
         CastInfoEvent("Preparing to erase flash", 0);
         Thread.Sleep(2000);
         _state = FlashState.StartErase;
     }
 }
示例#14
0
 // Start is called before the first frame update
 void Start()
 {
     //set intial intensity
     flashIntensity        = flashObject.intensity;
     flashObject.intensity = 0;
     //if object is not set, then find it
     if (flashObject == null)
     {
         flashObject = GameObject.FindGameObjectWithTag("CameraFlash").GetComponent <Light>();
     }
     //set intial flash state
     currentFlashState         = FlashState.Ready;
     audioSource               = GetComponent <AudioSource>();
     playerCameraImage.enabled = false;
 }
示例#15
0
        /// <summary>
        /// COMPORTNUMBER e.g. "COM1"
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="comportnumber"></param>
        public override void FlashFile(string filename, string comportnumber)
        {
            _filename    = filename;
            _logfileName = Path.Combine(Path.GetDirectoryName(_filename), "commlog.txt");
            FileInfo fi = new FileInfo(_filename);

            _length2Send = (int)fi.Length;
            Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
            if (InitializeFlasher(comportnumber))
            {
                CastInfoEvent("Preparing to erase flash", 0);
                Thread.Sleep(2000);
                _state = FlashState.StartErase;
            }
        }
        private void ToggleFlashState(object sender, EventArgs e)
        {
            FlashState currentFlashState         = this.viewModel.FlashState;
            int        currentIndexInOrderedList = this.desiredFlashStateOrder.IndexOf(currentFlashState);
            int        newIndex = (currentIndexInOrderedList + 1) % this.desiredFlashStateOrder.Count;

            while (this.viewModel.AvailableFlashStates.Contains <FlashState>(this.desiredFlashStateOrder[newIndex]) == false)
            {
                newIndex = (newIndex + 1) % this.desiredFlashStateOrder.Count;
            }

            this.viewModel.FlashState = this.desiredFlashStateOrder[newIndex];

            DisplayNewFlashStateText();
        }
示例#17
0
        /// <summary>
        /// Reads supported flash mode values from Parameter.Device and populates
        /// ArrayParameter.Options accordingly. Sets the SelectedOption as well.
        /// </summary>
        protected override void PopulateOptions()
        {
            IReadOnlyList <object> supportedValues = PhotoCaptureDevice.GetSupportedPropertyValues(Device.SensorLocation, PropertyId);
            object value = Device.GetProperty(PropertyId);

            foreach (dynamic i in supportedValues)
            {
                FlashState fm = (FlashState)i;

                ArrayParameterOption option = new ArrayParameterOption(fm, fm.EnumerationToParameterName <FlashState>(), "Assets/Icons/overlay.flashmode." + fm.ToString().ToLower() + ".png");

                Options.Add(option);

                if (i.Equals(value))
                {
                    SelectedOption = option;
                }
            }
        }
示例#18
0
    private void WindCameraUp()
    {
        playerCameraImage.enabled = true;
        //get the scroll wheel delta value
        float scrollWheel = Input.GetAxis("Mouse ScrollWheel");

        //if scrolling up increase the amount of clicks
        if (scrollWheel > 0)
        {
            //if not clicked and less than set amount
            if (!clicked && clicks < cameraWindClicks)
            {
                //set clicked
                clicked = true;
                //increase click amount
                clicks += 1;
                audioSource.PlayOneShot(wind);
                print(clicks);
            }
        }
        //if no longer scrolling up, reset the values
        else if (scrollWheel <= 0)
        {
            if (clicked)
            {
                clicked = false;
            }
        }
        //if wound up then reset
        if (clicks >= cameraWindClicks)
        {
            audioSource.Stop();
            //set the next state
            currentFlashState = FlashState.Ready;
            //reset the values
            playerCameraImage.enabled = false;
            audioSource.PlayOneShot(finishWind);
            clicks  = 0;
            clicked = false;
        }
    }
 public void SetCurrentFlashMode(FlashState mode)
 {
     _flashState = mode;
     switch (mode)
     {
         case FlashState.Auto:
             {
                 ModeAuto();
                 break;
             }
         case FlashState.On:
             {
                 ModeOn();
                 break;
             }
         case FlashState.Off:
             {
                 ModeOff();
                 break;
             }
     }
 }
        private void SetFlashState(FlashState state)
        {
            try
            {
                _device.SetProperty(KnownCameraPhotoProperties.FlashMode, state);

                _flashState = state;

                if (_flashState == FlashState.Auto)
                {
                    _flashButton.IconUri = new Uri("/Assets/Icons/flash_auto.png", UriKind.Relative);
                }
                else if (_flashState == FlashState.On)
                {
                    _flashButton.IconUri = new Uri("/Assets/Icons/flash_on.png", UriKind.Relative);
                }
                else // FlashState.Off
                {
                    _flashButton.IconUri = new Uri("/Assets/Icons/flash_off.png", UriKind.Relative);
                }
            }
            catch (Exception ex)
            {
            }
        }
 private void FlashOnButton_Click(object sender, RoutedEventArgs e)
 {
     _flashState = FlashState.On;
     ModeOn();
     if (FlashStateChanged != null)
     {
         FlashStateChanged(_flashState);
     }
 }
示例#22
0
 public override void VerifyChecksum(string filename, string comportnumber)
 {
     _filename = filename;
     _logfileName = Path.Combine(Path.GetDirectoryName(_filename), "commlog.txt");
     AddToLogfile("VerifyChecksum started");
     FileInfo fi = new FileInfo(_filename);
     _length2Send = (int)fi.Length;
     Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
     if (InitializeFlasher(comportnumber))
     {
         CastInfoEvent("Preparing to checksum verification", 0);
         Thread.Sleep(500);
         _state = FlashState.VerifyChecksum;
     }
 }
示例#23
0
        public static void SwitchFlashMode(Camera camera, ref FlashState _flashState)
        {
            Camera.Parameters _params = camera.GetParameters();

            IList <string> flashModes = _params.SupportedFlashModes;

            if (flashModes == null || flashModes.Count == 0)
            {
                _flashState = FlashState.NotAvailable;
                return;
            }

            switch (_flashState)
            {
            case FlashState.Auto:
                if (flashModes.Contains(Camera.Parameters.FlashModeOn))
                {
                    _params.FlashMode = Camera.Parameters.FlashModeOn;
                    _flashState       = FlashState.On;
                }
                else if (flashModes.Contains(Camera.Parameters.FlashModeOff))
                {
                    _params.FlashMode = Camera.Parameters.FlashModeOff;
                    _flashState       = FlashState.Off;
                }
                else
                {
                    _flashState = FlashState.NotAvailable;
                    return;
                }
                break;

            case FlashState.On:
                if (flashModes.Contains(Camera.Parameters.FlashModeOff))
                {
                    _params.FlashMode = Camera.Parameters.FlashModeOff;
                    _flashState       = FlashState.Off;
                }
                else if (flashModes.Contains(Camera.Parameters.FlashModeAuto))
                {
                    _params.FlashMode = Camera.Parameters.FlashModeAuto;
                    _flashState       = FlashState.Auto;
                }
                else
                {
                    _flashState = FlashState.NotAvailable;
                    return;
                }
                break;

            case FlashState.Off:
                if (flashModes.Contains(Camera.Parameters.FlashModeAuto))
                {
                    _params.FlashMode = Camera.Parameters.FlashModeAuto;
                    _flashState       = FlashState.Auto;
                }
                else if (flashModes.Contains(Camera.Parameters.FlashModeOn))
                {
                    _params.FlashMode = Camera.Parameters.FlashModeOn;
                    _flashState       = FlashState.On;
                }
                else
                {
                    _flashState = FlashState.NotAvailable;
                    return;
                }
                break;

            case FlashState.NotAvailable:
                if (flashModes.Contains(Camera.Parameters.FlashModeAuto))
                {
                    _params.FlashMode = Camera.Parameters.FlashModeAuto;
                    _flashState       = FlashState.Auto;
                }
                else if (flashModes.Contains(Camera.Parameters.FlashModeOn))
                {
                    _params.FlashMode = Camera.Parameters.FlashModeOn;
                    _flashState       = FlashState.On;
                }
                else
                {
                    _flashState = FlashState.NotAvailable;
                    return;
                }
                break;

            default:
                return;
            }

            camera.SetParameters(_params);
        }
示例#24
0
        void _timer_ElapsedOLD(object sender, ElapsedEventArgs e)
        {
            _timer.Enabled = false;
            try
            {
                switch (_state)
                {
                    case FlashState.Idle:   // waiting for a signal to start the flash sequence
                        _communicationTimeout = 0;
                        break;
                        //TODO: This should be started later when flashing is done! <GS-18042011>
                    case FlashState.VerifyChecksum:
                        CastInfoEvent("Starting checksum verification:" + _checksumType.ToString(), 0);
                        _communicationTimeout = 0;
                        allBytes = File.ReadAllBytes(_filename);
                        fileChecksum = 0;

                        switch (_checksumType)
                        {
                            case 0: // normal calculation
                                for (int ci = 0; ci < 0x1FF00; ci++)
                                {
                                    fileChecksum += allBytes[ci];
                                }
                                fileChecksum &= 0xFFFF;

                                strChecksumToSend = "3AFE55443322110000000000000300000000" + fileChecksum.ToString("X4") + "0000000000000000000000000000000000";
                                break;
                            case 1: // assume first bank programmed, and second bank empty (FFs)
                                for (int ci = 0; ci < 0x10000; ci++)
                                {
                                    fileChecksum += allBytes[ci];
                                }
                                for (int ci = 0; ci < 0xFF00; ci++)
                                {
                                    fileChecksum += 0xFF;
                                }
                                fileChecksum &= 0xFFFF;
                                strChecksumToSend = "3AFE55443322110000000000000300000000" + fileChecksum.ToString("X4") + "0000000000000000000000000000000000";
                                break;
                            case 2: // assume entire flash chip empty (FFs)
                                for (int ci = 0; ci < 0x1FF00; ci++)
                                {
                                    fileChecksum += 0xFF;
                                }
                                fileChecksum &= 0xFFFF;
                                strChecksumToSend = "3AFE55443322110000000000000300000000" + fileChecksum.ToString("X4") + "0000000000000000000000000000000000";
                                break;
                            case 3: // assume entire flash chip 00s
                                fileChecksum &= 0xFFFF;
                                strChecksumToSend = "3AFE55443322110000000000000300000000" + fileChecksum.ToString("X4") + "0000000000000000000000000000000000";
                                break;
                            /*case 4: // assume first bank overwritten with second bank (possible?)
                                for (int ci = 0; ci < 0x1FF00; ci++)
                                {
                                    fileChecksum += 0xFF;
                                }
                                fileChecksum &= 0xFFFF;
                                strChecksumToSend = "3AFE55443322110000000000000300000000" + fileChecksum.ToString("X4") + "0000000000000000000000000000000000";
                                break;*/
                        }
                        chksum = calculateChecksumForString(strChecksumToSend);
                        strChecksumToSend += chksum.ToString("X2");
                        CastInfoEvent(strChecksumToSend, 0);
                        WriteBinaryData(strChecksumToSend);
                        _switchBankDone = 0;

                        _state = FlashState.WaitChecksumResults;
                        break;
                    case FlashState.WaitChecksumResults:
                        if (rxmsgtype == RxMsgType.StartChecksumVerification)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Verifying checksum", 0);
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.FinishChecksumVerificationOK)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Verified checksum OK", 0);
                            _communicationTimeout = 0;
                            _state = FlashState.Idle;
                        }
                        else if (rxmsgtype == RxMsgType.FinishChecksumVerificationFailed)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Verified checksum failed", 0);
                            _communicationTimeout = 0;
                            _switchBankDone++;
                            if (_switchBankDone == 3)
                            {
                                _checksumType++;
                                if (_checksumType == 4) _state = FlashState.Idle;
                                else _state = FlashState.VerifyChecksum; // next try
                                Thread.Sleep(2500); // give it a rest
                            }
                        }
                        break;
                    case FlashState.StartErase:
                        if (_port.IsOpen)
                        {
                            allBytes = File.ReadAllBytes(_filename);
                            int tx_buf_pnt = 0;
                            int _partBufferLength = _length2Send / 2;
                            _fileOffset = 0;
                            // build the complete transmit buffer for lower flash bank
                            while (_fileOffset < _partBufferLength)
                            {
                                uint checksum = 0;
                                completeflashbuffer_lower[tx_buf_pnt ++] = 0x3A;
                                completeflashbuffer_lower[tx_buf_pnt++] = 0x20; // 32 bytes
                                checksum += completeflashbuffer_lower[tx_buf_pnt - 1];
                                byte addresshigh = Convert.ToByte(_fileOffset / 256);
                                byte addresslow = Convert.ToByte((_fileOffset - (256 * addresshigh)));
                                completeflashbuffer_lower[tx_buf_pnt++] = addresshigh;
                                checksum += completeflashbuffer_lower[tx_buf_pnt - 1];
                                completeflashbuffer_lower[tx_buf_pnt++] = addresslow;
                                checksum += completeflashbuffer_lower[tx_buf_pnt - 1];
                                completeflashbuffer_lower[tx_buf_pnt++] = 0x00; // indicate lower bank
                                checksum += completeflashbuffer_lower[tx_buf_pnt - 1];
                                for (int j = 0; j < 32; j++)
                                {
                                    completeflashbuffer_lower[tx_buf_pnt++] = allBytes[_fileOffset + j];
                                    checksum += completeflashbuffer_lower[tx_buf_pnt - 1];
                                }
                                checksum = 0x100 - checksum;
                                completeflashbuffer_lower[tx_buf_pnt++] = Convert.ToByte(checksum & 0x000000FF);
                                _fileOffset += 32;
                            }
                            tx_buf_pnt = 0;
                            // build the complete transmit buffer for upper flash bank
                            while (_fileOffset < _length2Send - 0x100)
                            {
                                uint checksum = 0;
                                completeflashbuffer_upper[tx_buf_pnt++] = 0x3A;
                                completeflashbuffer_upper[tx_buf_pnt++] = 0x20; // 32 bytes
                                checksum += completeflashbuffer_upper[tx_buf_pnt - 1];
                                byte addresshigh = Convert.ToByte((_fileOffset - 0x10000) / 256);
                                byte addresslow = Convert.ToByte(((_fileOffset - 0x10000) - (256 * addresshigh)));
                                completeflashbuffer_upper[tx_buf_pnt++] = addresshigh;
                                checksum += completeflashbuffer_upper[tx_buf_pnt - 1];
                                completeflashbuffer_upper[tx_buf_pnt++] = addresslow;
                                checksum += completeflashbuffer_upper[tx_buf_pnt - 1];
                                completeflashbuffer_upper[tx_buf_pnt++] = 0x00; // indicate upper bank <GS-19042011> was 0x02!
                                checksum += completeflashbuffer_upper[tx_buf_pnt - 1];
                                for (int j = 0; j < 32; j++)
                                {
                                    completeflashbuffer_upper[tx_buf_pnt++] = allBytes[_fileOffset + j];
                                    checksum += completeflashbuffer_upper[tx_buf_pnt - 1];
                                }
                                checksum = 0x100 - checksum;
                                completeflashbuffer_upper[tx_buf_pnt++] = Convert.ToByte(checksum & 0x000000FF);
                                _fileOffset += 32;
                            }
                            DumpTransmitBuffer();
                            _fileOffset = 0;
                            _communicationTimeout = 0;
                            CastInfoEvent("Starting erase", 0);
                            // send the erase command to the ECU
                            //WriteBinaryData("3A30303030303030314646");
                            //Thread.Sleep(2000);
                            WriteBinaryData("3AFF554433221100000000000002000000000000000000000000000000000000000000000000"); // checksum is also 00
                            _state = FlashState.WaitEraseComplete;
                        }
                        break;
                    case FlashState.WaitEraseComplete:
                        // waiting for reception of
                        // 02 30 59 30 35 03 6F
                        // 02 31 59 30 35 03 6E
                        // 02 31 59 30 35 03 6E
                        if (rxmsgtype == RxMsgType.StartErasingFlash)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Erasing flash", 0);
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.FinishedErasingFlash)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Finished erasing flash", 0);
                            _eraseFlashDone++;
                            if (_eraseFlashDone == 3)
                            {
                                _state = FlashState.StartFlashing;
                                _communicationTimeout = 0;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Failed to erase flash", 0);
                            _state = FlashState.EraseError;
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.ProgrammingVoltageOutOfRange)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Failed to erase flash, voltage out of range", 0);
                            AddToLogfile("Failed to erase flash, voltage out of range");

                            _state = FlashState.EraseError;
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.Unknown)
                        {
                            _communicationTimeout++;
                            if (_communicationTimeout > 1500)
                            {
                                rxmsgtype = RxMsgType.Unknown;
                                CastInfoEvent("Timeout erasing flash", 0);
                                _state = FlashState.EraseError;
                            }
                        }
                        break;
                    case FlashState.StartFlashing:
                        _retries = 0;
                        Thread.Sleep(2500);
                        CastInfoEvent("Start sending flash data", 0);
                        _fileOffset = 0;
                        _state = FlashState.SendFlashData;
                        break;
                    case FlashState.SendFlashData:

                        // send a portion of the flash data from _fileOffset, 32 bytes
                        for (int t = 0; t < completeflashbuffer_lower.Length; t++)
                        {
                            _port.Write(completeflashbuffer_lower, t, 1);
                            if (t % 1024 == 0) CastInfoEvent("Flashing...", ((t * 100) / (completeflashbuffer_lower.Length * 2)));
                        }
                        _state = FlashState.WaitForFinishFirstBank;
                        break;
                    case FlashState.WaitForFinishFirstBank:
                        //TODO: <GS-18042011> Now we first have to wait for 3x MessageRxMsgType.FinishedFlashing - 0x34
                        if (rxmsgtype == RxMsgType.FinishedFlashing)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            _communicationTimeout = 0;
                            _waitFirstBankFlashed++;
                            if (_waitFirstBankFlashed == 3)
                            {
                                for (int i = 0; i < 250; i++)
                                {
                                    CastInfoEvent("Waiting...", 50);
                                    Thread.Sleep(1);
                                }
                                while (_port.BytesToWrite > 0) CastInfoEvent("Flashing...", 50); // wait it out.. maybe we should wait

                                _state = FlashState.SwitchBank;
                                CastInfoEvent("First bank programmed", 50);
                                AddToLogfile("First bank programmed");
                            }
                        }
                        else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Flashing bank 0 failed", 0);
                            _communicationTimeout = 0;
                            _state = FlashState.FlashingError;
                        }
                        break;
                    case FlashState.SwitchBank:
                        // now switch to upper bank
                                         //8788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F
                                         //ACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBE

                        // UPTO 0x01FF00
                        WriteBinaryData("3AFF554433221100000000000001FF0001010000000000000000000000000000000000000000"); // checksum is 00 again!
                        // UPTO 0x020000
                        //WriteBinaryData("3AFF5544332211000000000000020000010100000000000000000000000000000000000000FE"); // checksum is 00 again!

                    //WriteBinaryData("3AFF554433221100000000000000000001010000000000000000000000000000000000000000"); // checksum is 00 again!
                        // update state to waiting for bankswitch
                        _communicationTimeout = 0;
                        CastInfoEvent("Switching bank", 50);
                        _state = FlashState.WaitBankSwitch;
                        break;
                    case FlashState.WaitBankSwitch:
                        if (rxmsgtype == RxMsgType.StartSwitchingBank)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.FinishedSwitchingBank)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Bank switched", 50);
                            AddToLogfile("Bank switched");
                            _switchBankDone++;
                            if (_switchBankDone == 3)
                            {
                                _state = FlashState.SendFlashDataUpper; // <GS-19042011> nothing more to do, the extra acks where ghosts
                                echoCount = 0; // force buffer to be empty!
                                _switchBankDone = 0;
                                _communicationTimeout = 0;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Failed to switch bank", 0);
                            _state = FlashState.FlashingError;
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.Unknown)
                        {
                            _communicationTimeout++;
                            if (_communicationTimeout > 1500)
                            {
                                rxmsgtype = RxMsgType.Unknown;
                                CastInfoEvent("Timeout switching bank", 0);
                                _state = FlashState.FlashingError;
                            }
                        }
                        break;
                    case FlashState.WaitAckForNextBank:
                        //CastInfoEvent("Waiting for ack for next bank", 0);
                        AddToLogfile("State = FlashState.WaitAckForNextBank");
                        if (rxmsgtype == RxMsgType.FinishedFlashing)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Ack for next bank", 50);
                            _switchBankDone++;
                            if (_switchBankDone == 3)
                            {
                                _state = FlashState.SendFlashDataUpper;
                                _communicationTimeout = 0;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.Unknown)
                        {
                            _communicationTimeout++;
                            if (_communicationTimeout > 1000) // 10 seconds for testing
                            {
                                rxmsgtype = RxMsgType.Unknown;
                                CastInfoEvent("Timeout waiting for ack for next bank", 0);
                                _state = FlashState.SendFlashDataUpper; // proceed with next bank anyway
                            }
                        }
                        break;
                    case FlashState.SendFlashDataUpper:
                        // TODO: Do we have to wait here again, just like the first bank?
                        Thread.Sleep(2500); // <GS-20042011> testing
                        CastInfoEvent("Start sending upper bank flash data", 50);
                        for (int t = 0; t < completeflashbuffer_upper.Length; t++)
                        {
                            _port.Write(completeflashbuffer_upper, t, 1);
                            if (t % 1024 == 0) CastInfoEvent("Flashing...", 50 + ((t * 100) / (completeflashbuffer_upper.Length * 2)));
                        }
                        CastInfoEvent("Waiting...", 100);
                        for (int i = 0; i < 250; i++)
                        {
                            Thread.Sleep(1);
                        }
                        while (_port.BytesToWrite > 0) CastInfoEvent("Flashing...", 100); // wait it out.. maybe we should wait
                        _switchBankDone = 0;
                        _communicationTimeout = 0;
                        _state = FlashState.WaitEndFlashUpperBank;
                        break;
                    case FlashState.WaitFlashData:
                        if (_fileOffset >= _length2Send)
                        {
                            _state = FlashState.SendEndFlash;
                            //Thread.Sleep(100);
                        }
                        else _state = FlashState.SendFlashData;
                        break;
                    case FlashState.WaitEndFlashUpperBank:
                        //TODO: <GS-19042011> we receive three Acks here ... wait for that first!
                        if (rxmsgtype == RxMsgType.OutOfRangeError)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Out of range for bank 1", 100);
                            _switchBankDone++;
                            if (_switchBankDone == 3)
                            {
                                _state = FlashState.FlashingError;
                                _communicationTimeout = 0;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Failed to flash bank 1", 100);
                            _switchBankDone++;
                            if (_switchBankDone == 3)
                            {
                                _state = FlashState.FlashingError;
                                _communicationTimeout = 0;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.FinishedFlashing)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Finished flashing bank 1", 100);
                            _switchBankDone++;
                            if (_switchBankDone == 3)
                            {
                                _state = FlashState.SendEndFlash;
                                _communicationTimeout = 0;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.Unknown)
                        {
                            _communicationTimeout++;
                            if (_communicationTimeout > 1000) // 10 seconds for testing
                            {
                                rxmsgtype = RxMsgType.Unknown;
                                CastInfoEvent("Timeout waiting for ack for bank 1", 0);
                                _state = FlashState.SendEndFlash; // done?
                            }
                        }
                        break;
                    case FlashState.SendEndFlash:
                        /*Thread.Sleep(2000);
                        CastInfoEvent("Sending flash end sequence...", 100);
                        rxmsgtype = RxMsgType.Unknown;
                        WriteBinaryData("3A0000000000"); // null command
                        Thread.Sleep(500);
                        WriteBinaryData("3A30303030303030314646");
                        _communicationTimeout = 0;
                        _state = FlashState.WaitEndFlash;*/

                        Thread.Sleep(2000);
                        _communicationTimeout = 0;
                        CastInfoEvent("Starting checksum verification", 100);
                        // file checksum (0-0x20000) should be in location
                                                    //8788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F
                        fileChecksum = 0;
                        for (int ci = 0; ci < 0x1FF00; ci++)
                        {
                            fileChecksum += allBytes[ci];
                        }
                        fileChecksum &= 0xFFFF;
                                             //8788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F
                        strChecksumToSend = "3AFE55443322110000000000000300000000" + fileChecksum.ToString("X4") + "0000000000000000000000000000000000";
                        chksum = calculateChecksumForString(strChecksumToSend);
                        strChecksumToSend += chksum.ToString("X2");
                        WriteBinaryData(strChecksumToSend);

                                           //8788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F
                        //WriteBinaryData("3AFE554433221100000000000003000000000000000000000000000000000000000000000000"); // checksum is also 00
                        _state = FlashState.WaitChecksumResultsAfterFlashing;
                        break;
                    case FlashState.WaitChecksumResultsAfterFlashing:
                        if (rxmsgtype == RxMsgType.StartChecksumVerification)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Verifying checksum", 100);
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.FinishChecksumVerificationOK)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Verified checksum OK", 100);
                            _communicationTimeout = 0;
                            _state = FlashState.FlashingDone;
                        }
                        else if (rxmsgtype == RxMsgType.FinishChecksumVerificationFailed)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Verified checksum failed", 0);
                            _communicationTimeout = 0;
                            _state = FlashState.FlashingError;
                        }
                        break;
                    case FlashState.WaitEndFlash:
                        if (rxmsgtype == RxMsgType.FinishedFlashing)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Finished writing flash", 100);
                            _state = FlashState.FlashingDone;
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            _communicationTimeout = 0;
                            _retries++;
                            if (_retries < 3)
                            {
                                CastInfoEvent("Retry end flash sequence: " + _retries.ToString(), 0);
                                _state = FlashState.SendEndFlash;
                            }
                            else
                            {
                                //CastInfoEvent("Flashing failed", 0);
                                _state = FlashState.FlashingError;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.Unknown)
                        {
                            //TODO: Implement timeout here
                            _communicationTimeout++;
                            if (_communicationTimeout > 500)
                            {
                                rxmsgtype = RxMsgType.Unknown;
                                CastInfoEvent("Timeout writing flash", 0);
                                _state = FlashState.FlashingError;
                            }
                        }
                        else
                        {
                            AddToLogfile("Ignoring message: " + rxmsgtype.ToString());
                            rxmsgtype = RxMsgType.Unknown;
                        }
                        break;
                    case FlashState.FlashingDone:
                        CastInfoEvent("Flashing completed", 100);
                        CleanupFlasher();
                        _state = FlashState.Idle;
                        break;
                    case FlashState.EraseError:
                        CastInfoEvent("Erase failed", 0);
                        CleanupFlasher();
                        _state = FlashState.Idle;
                        break;
                    case FlashState.FlashingError:
                        CastInfoEvent("Flashing failed", 0);
                        CleanupFlasher();
                        _state = FlashState.Idle;
                        break;
                }
            }
            catch (Exception E)
            {
                CastInfoEvent("Internal error: " + E.Message, 0);
            }
            _timer.Enabled = true;
        }
 public void Flash()
 {
     Util.PlaySound("RegigigasFlash", this.gameObject);
     this.currentState = FlashState.Up;
 }
示例#26
0
        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Enabled = false;
            try
            {
                switch (_state)
                {
                case FlashState.Idle:       // waiting for a signal to start the flash sequence
                    _communicationTimeout = 0;
                    break;

                case FlashState.StartErase:
                    if (_port.IsOpen)
                    {
                        byte[] allBytes   = File.ReadAllBytes(_filename);
                        int    tx_buf_pnt = 0;
                        _fileOffset = 0;
                        // build the complete transmit buffer

                        while (_fileOffset < _length2Send)
                        {
                            uint checksum = 0;
                            completeflashbuffer[tx_buf_pnt++] = 0x3A;
                            completeflashbuffer[tx_buf_pnt++] = 0x20;     // 32 bytes
                            checksum += completeflashbuffer[tx_buf_pnt - 1];
                            byte addresshigh = Convert.ToByte(_fileOffset / 256);
                            byte addresslow  = Convert.ToByte((_fileOffset - (256 * addresshigh)));
                            completeflashbuffer[tx_buf_pnt++] = addresshigh;
                            checksum += completeflashbuffer[tx_buf_pnt - 1];
                            completeflashbuffer[tx_buf_pnt++] = addresslow;
                            checksum += completeflashbuffer[tx_buf_pnt - 1];
                            completeflashbuffer[tx_buf_pnt++] = 0x00;
                            checksum += completeflashbuffer[tx_buf_pnt - 1];
                            for (int j = 0; j < 32; j++)
                            {
                                completeflashbuffer[tx_buf_pnt++] = allBytes[_fileOffset + j];
                                checksum += completeflashbuffer[tx_buf_pnt - 1];
                            }
                            checksum = 0x100 - checksum;
                            completeflashbuffer[tx_buf_pnt++] = Convert.ToByte(checksum & 0x000000FF);
                            _fileOffset += 32;
                        }
                        DumpTransmitBuffer();
                        _fileOffset           = 0;
                        _communicationTimeout = 0;
                        CastInfoEvent("Starting erase", 0);
                        // send the erase command to the ECU
                        WriteBinaryData("3A30303030303030314646");
                        Thread.Sleep(2000);
                        WriteBinaryData("3A011122334455");
                        _state = FlashState.WaitEraseComplete;
                    }
                    break;

                case FlashState.WaitEraseComplete:
                    // waiting for reception of
                    // 02 30 59 30 35 03 6F
                    // 02 31 59 30 35 03 6E
                    // 02 31 59 30 35 03 6E
                    if (rxmsgtype == RxMsgType.StartErasingFlash)
                    {
                        rxmsgtype = RxMsgType.Unknown;
                        CastInfoEvent("Erasing flash", 0);
                        _communicationTimeout = 0;
                    }
                    else if (rxmsgtype == RxMsgType.FinishedErasingFlash)
                    {
                        rxmsgtype = RxMsgType.Unknown;
                        CastInfoEvent("Finished erasing flash", 0);
                        _eraseFlashDone++;
                        if (_eraseFlashDone == 3)
                        {
                            _state = FlashState.StartFlashing;
                            _communicationTimeout = 0;
                        }
                    }
                    else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                    {
                        rxmsgtype = RxMsgType.Unknown;
                        CastInfoEvent("Failed to erase flash", 0);
                        _state = FlashState.EraseError;
                        _communicationTimeout = 0;
                    }
                    else if (rxmsgtype == RxMsgType.Unknown)
                    {
                        //TODO: Implement timeout here
                        _communicationTimeout++;
                        if (_communicationTimeout > 1500)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Timeout erasing flash", 0);
                            _state = FlashState.EraseError;
                        }
                    }
                    break;

                case FlashState.StartFlashing:
                    _retries = 0;
                    Thread.Sleep(2500);
                    CastInfoEvent("Start sending flash data", 0);
                    _fileOffset = 0;
                    _state      = FlashState.SendFlashData;
                    break;

                case FlashState.SendFlashData:

                    // the flasher takes about 155 seconds to complete the flash sending
                    // this means 0x10000 bytes in 155 seconds = 423 bytes per second
                    // since we transmit 32 bytes at a time that means we have 423/32 packets to
                    // send per second which comes down to ~13 packets per second
                    // every packet consists of 38 bytes of data (32 flash bytes) which means
                    // ~ 500 bytes per second transfer. Bitrate = 9k6 which translates roughly to
                    // 1000 bytes per second, so there should be NO delay between the packets if
                    // we count the echo string into the transmission speed

                    // send a portion of the flash data from _fileOffset, 32 bytes
//                        _read_data = false;
                    for (int t = 0; t < completeflashbuffer.Length; t++)
                    {
                        _port.Write(completeflashbuffer, t, 1);
                        //_echo = true;
                        //Thread.Sleep(1);
                        if (t % 1024 == 0)
                        {
                            CastInfoEvent("Flashing...", ((t * 100) / completeflashbuffer.Length));
                        }
                        // wait it out here?
                    }
                    for (int i = 0; i < 250; i++)
                    {
                        CastInfoEvent("Waiting...", 100);
                        Thread.Sleep(1);
                    }

//                        _read_data = true;

                    /*while (_fileOffset < _length2Send)
                     * {
                     *  byte[] data2send = readdatafromfile(_filename, _fileOffset, 32);
                     *  byte[] command2send = new byte[38];
                     *  command2send[0] = 0x3A;
                     *  command2send[1] = 0x20;
                     *  byte addresshigh = Convert.ToByte(_fileOffset / 256);
                     *  byte addresslow = Convert.ToByte((_fileOffset - (256 * addresshigh)));
                     *  //AddToLog("Address: " + curaddress.ToString("X4") + " hi: " + addresshigh.ToString("X2") + " lo: " + addresslow.ToString("X2"));
                     *  command2send[2] = addresshigh;
                     *  command2send[3] = addresslow;
                     *  command2send[4] = 0x00;
                     *  for (int j = 0; j < 32; j++)
                     *  {
                     *      command2send[5 + j] = data2send[j];
                     *  }
                     *  command2send[37] = CalcChecksum(command2send);
                     *  _fileOffset += 32;
                     *  _port.Write(command2send, 0, command2send.Length);
                     *  //Thread.Sleep( command2send.Length);
                     *  while (_port.BytesToWrite > 0) Thread.Sleep(0);
                     *  Thread.Sleep(75); // sleep 75 ms to get to ~13 packets per second
                     *  CastInfoEvent("Flashing...", ((_fileOffset * 100) / _length2Send));
                     * }*/
                    //_state = FlashState.WaitFlashData;

                    // todo: use a stopwatch to hold on for a few moments ?
                    while (_port.BytesToWrite > 0)
                    {
                        CastInfoEvent("Flashing...", 100);                                // wait it out.. maybe we should wait
                    }
                    // until no more characters are received from the port?
                    _state = FlashState.SendEndFlash;

                    //_port.Write(txString);
                    // wait until buffer = empty?

                    break;

                case FlashState.WaitFlashData:
                    if (_fileOffset >= _length2Send)
                    {
                        _state = FlashState.SendEndFlash;
                        //Thread.Sleep(100);
                    }
                    else
                    {
                        _state = FlashState.SendFlashData;
                    }
                    break;

                case FlashState.SendEndFlash:
                    Thread.Sleep(2000);
                    CastInfoEvent("Sending flash end sequence...", 100);
//                        _logAllData = true;
                    rxmsgtype = RxMsgType.Unknown;
                    WriteBinaryData("3A0000000000");
                    Thread.Sleep(500);
                    WriteBinaryData("3A30303030303030314646");
                    //WriteBinaryData("3A00000000003A30303030303030314646");
                    _communicationTimeout = 0;
                    _state = FlashState.WaitEndFlash;
                    break;

                case FlashState.WaitEndFlash:
                    if (rxmsgtype == RxMsgType.FinishedFlashing)
                    {
                        rxmsgtype = RxMsgType.Unknown;
                        CastInfoEvent("Finished writing flash", 0);
                        _state = FlashState.FlashingDone;
                        _communicationTimeout = 0;
                    }
                    else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                    {
                        rxmsgtype             = RxMsgType.Unknown;
                        _communicationTimeout = 0;
                        _retries++;
                        if (_retries < 3)
                        {
                            CastInfoEvent("Retry end flash sequence: " + _retries.ToString(), 0);
                            _state = FlashState.SendEndFlash;
                        }
                        else
                        {
                            CastInfoEvent("Flashing failed", 0);
                            _state = FlashState.FlashingError;
                        }
                    }
                    else if (rxmsgtype == RxMsgType.Unknown)
                    {
                        //TODO: Implement timeout here
                        _communicationTimeout++;
                        if (_communicationTimeout > 500)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Timeout writing flash", 0);
                            _state = FlashState.FlashingError;
                        }
                    }
                    else
                    {
                        AddToLogfile("Ignoring message: " + rxmsgtype.ToString());
                        rxmsgtype = RxMsgType.Unknown;
                    }
                    break;

                case FlashState.FlashingDone:
                    CastInfoEvent("Flashing completed", 100);
                    CleanupFlasher();
                    _state = FlashState.Idle;
                    break;

                case FlashState.EraseError:
                    CastInfoEvent("Erase failed", 0);
                    CleanupFlasher();
                    _state = FlashState.Idle;
                    break;

                case FlashState.FlashingError:
                    CastInfoEvent("Flashing failed", 0);
                    CleanupFlasher();
                    _state = FlashState.Idle;
                    break;
                }
            }
            catch (Exception E)
            {
                CastInfoEvent("Internal error: " + E.Message, 0);
            }
            _timer.Enabled = true;
        }
示例#27
0
 /// <summary>
 /// ������˸״̬
 /// </summary>
 /// <param name="flashState">����,������˸,������˸</param>
 /// <param name="flashModel">CONFIRMϨ�𷵻ذ���,���ݼ�����00000����CONFIRMϨ��,��CONFIRM����˸5�κ�Ϩ�𷵻ص�ǰ��ֵ</param>
 /// <param name="flashSwitchBit"></param>
 public void SetFlashState(FlashState flashState, FlashModel flashModel, int flashSwitchBit)
 {
     byte[] switchBit = BitConverter.GetBytes(flashSwitchBit);
     ((Protocal)this.Com.Encoder).BtFlashState[0] = switchBit[0];
     ((Protocal)this.Com.Encoder).BtFlashState[1] = (byte)((switchBit[1] & 0X3FFF) ^ (byte)((byte)flashState << 6));
     ((Protocal)this.Com.Encoder).BtFlashState[2] = (byte)flashModel;
 }
示例#28
0
        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Enabled = false;
            try
            {
                switch (_state)
                {
                    case FlashState.Idle:   // waiting for a signal to start the flash sequence
                        _communicationTimeout = 0;
                        break;
                    case FlashState.StartErase:
                        if (_port.IsOpen)
                        {
                            byte[] allBytes = File.ReadAllBytes(_filename);
                            int tx_buf_pnt = 0;
                            _fileOffset = 0;
                            // build the complete transmit buffer

                            while (_fileOffset < _length2Send)
                            {
                                uint checksum = 0;
                                completeflashbuffer[tx_buf_pnt ++] = 0x3A;
                                completeflashbuffer[tx_buf_pnt++] = 0x20; // 32 bytes
                                checksum += completeflashbuffer[tx_buf_pnt-1];
                                byte addresshigh = Convert.ToByte(_fileOffset / 256);
                                byte addresslow = Convert.ToByte((_fileOffset - (256 * addresshigh)));
                                completeflashbuffer[tx_buf_pnt++] = addresshigh;
                                checksum += completeflashbuffer[tx_buf_pnt - 1];
                                completeflashbuffer[tx_buf_pnt++] = addresslow;
                                checksum += completeflashbuffer[tx_buf_pnt - 1];
                                completeflashbuffer[tx_buf_pnt++] = 0x00;
                                checksum += completeflashbuffer[tx_buf_pnt - 1];
                                for (int j = 0; j < 32; j++)
                                {
                                    completeflashbuffer[tx_buf_pnt++] = allBytes[_fileOffset + j];
                                    checksum += completeflashbuffer[tx_buf_pnt - 1];
                                }
                                checksum = 0x100 - checksum;
                                completeflashbuffer[tx_buf_pnt++] = Convert.ToByte(checksum & 0x000000FF);
                                _fileOffset += 32;
                            }
                            DumpTransmitBuffer();
                            _fileOffset = 0;
                            _communicationTimeout = 0;
                            CastInfoEvent("Starting erase", 0);
                            // send the erase command to the ECU
                            WriteBinaryData("3A30303030303030314646");
                            Thread.Sleep(2000);
                            WriteBinaryData("3A011122334455");
                            _state = FlashState.WaitEraseComplete;
                        }
                        break;
                    case FlashState.WaitEraseComplete:
                        // waiting for reception of
                        // 02 30 59 30 35 03 6F
                        // 02 31 59 30 35 03 6E
                        // 02 31 59 30 35 03 6E
                        if (rxmsgtype == RxMsgType.StartErasingFlash)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Erasing flash", 0);
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.FinishedErasingFlash)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Finished erasing flash", 0);
                            _eraseFlashDone++;
                            if (_eraseFlashDone == 3)
                            {
                                _state = FlashState.StartFlashing;
                                _communicationTimeout = 0;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Failed to erase flash", 0);
                            _state = FlashState.EraseError;
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.Unknown)
                        {
                            //TODO: Implement timeout here
                            _communicationTimeout++;
                            if (_communicationTimeout > 1500)
                            {
                                rxmsgtype = RxMsgType.Unknown;
                                CastInfoEvent("Timeout erasing flash", 0);
                                _state = FlashState.EraseError;
                            }
                        }
                        break;
                    case FlashState.StartFlashing:
                        _retries = 0;
                        Thread.Sleep(2500);
                        CastInfoEvent("Start sending flash data", 0);
                        _fileOffset = 0;
                        _state = FlashState.SendFlashData;
                        break;
                    case FlashState.SendFlashData:

                        // the flasher takes about 155 seconds to complete the flash sending
                        // this means 0x10000 bytes in 155 seconds = 423 bytes per second
                        // since we transmit 32 bytes at a time that means we have 423/32 packets to
                        // send per second which comes down to ~13 packets per second
                        // every packet consists of 38 bytes of data (32 flash bytes) which means
                        // ~ 500 bytes per second transfer. Bitrate = 9k6 which translates roughly to
                        // 1000 bytes per second, so there should be NO delay between the packets if
                        // we count the echo string into the transmission speed

                        // send a portion of the flash data from _fileOffset, 32 bytes
            //                        _read_data = false;
                        for (int t = 0; t < completeflashbuffer.Length; t++)
                        {
                            _port.Write(completeflashbuffer, t, 1);
                            //_echo = true;
                            //Thread.Sleep(1);
                            if( t % 1024 == 0) CastInfoEvent("Flashing...", ((t * 100) / completeflashbuffer.Length));
                            // wait it out here?
                        }
                        for (int i = 0; i < 250; i++)
                        {
                            CastInfoEvent("Waiting...", 100);
                            Thread.Sleep(1);
                        }

            //                        _read_data = true;

                        /*while (_fileOffset < _length2Send)
                        {
                            byte[] data2send = readdatafromfile(_filename, _fileOffset, 32);
                            byte[] command2send = new byte[38];
                            command2send[0] = 0x3A;
                            command2send[1] = 0x20;
                            byte addresshigh = Convert.ToByte(_fileOffset / 256);
                            byte addresslow = Convert.ToByte((_fileOffset - (256 * addresshigh)));
                            //AddToLog("Address: " + curaddress.ToString("X4") + " hi: " + addresshigh.ToString("X2") + " lo: " + addresslow.ToString("X2"));
                            command2send[2] = addresshigh;
                            command2send[3] = addresslow;
                            command2send[4] = 0x00;
                            for (int j = 0; j < 32; j++)
                            {
                                command2send[5 + j] = data2send[j];
                            }
                            command2send[37] = CalcChecksum(command2send);
                            _fileOffset += 32;
                            _port.Write(command2send, 0, command2send.Length);
                            //Thread.Sleep( command2send.Length);
                            while (_port.BytesToWrite > 0) Thread.Sleep(0);
                            Thread.Sleep(75); // sleep 75 ms to get to ~13 packets per second
                            CastInfoEvent("Flashing...", ((_fileOffset * 100) / _length2Send));
                        }*/
                        //_state = FlashState.WaitFlashData;

                        // todo: use a stopwatch to hold on for a few moments ?
                        while (_port.BytesToWrite > 0) CastInfoEvent("Flashing...", 100); // wait it out.. maybe we should wait
                        // until no more characters are received from the port?
                        _state = FlashState.SendEndFlash;

                        //_port.Write(txString);
                        // wait until buffer = empty?

                        break;
                    case FlashState.WaitFlashData:
                        if (_fileOffset >= _length2Send)
                        {
                            _state = FlashState.SendEndFlash;
                            //Thread.Sleep(100);
                        }
                        else _state = FlashState.SendFlashData;
                        break;
                    case FlashState.SendEndFlash:
                        Thread.Sleep(2000);
                        CastInfoEvent("Sending flash end sequence...", 100);
            //                        _logAllData = true;
                        rxmsgtype = RxMsgType.Unknown;
                        WriteBinaryData("3A0000000000");
                        Thread.Sleep(500);
                        WriteBinaryData("3A30303030303030314646");
                        //WriteBinaryData("3A00000000003A30303030303030314646");
                        _communicationTimeout = 0;
                        _state = FlashState.WaitEndFlash;
                        break;
                    case FlashState.WaitEndFlash:
                        if (rxmsgtype == RxMsgType.FinishedFlashing)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            CastInfoEvent("Finished writing flash", 0);
                            _state = FlashState.FlashingDone;
                            _communicationTimeout = 0;
                        }
                        else if (rxmsgtype == RxMsgType.NegativeAcknowledge)
                        {
                            rxmsgtype = RxMsgType.Unknown;
                            _communicationTimeout = 0;
                            _retries++;
                            if (_retries < 3)
                            {
                                CastInfoEvent("Retry end flash sequence: " + _retries.ToString(), 0);
                                _state = FlashState.SendEndFlash;
                            }
                            else
                            {
                                CastInfoEvent("Flashing failed", 0);
                                _state = FlashState.FlashingError;
                            }
                        }
                        else if (rxmsgtype == RxMsgType.Unknown)
                        {
                            //TODO: Implement timeout here
                            _communicationTimeout++;
                            if (_communicationTimeout > 500)
                            {
                                rxmsgtype = RxMsgType.Unknown;
                                CastInfoEvent("Timeout writing flash", 0);
                                _state = FlashState.FlashingError;
                            }
                        }
                        else
                        {
                            AddToLogfile("Ignoring message: " + rxmsgtype.ToString());
                            rxmsgtype = RxMsgType.Unknown;
                        }
                        break;
                    case FlashState.FlashingDone:
                        CastInfoEvent("Flashing completed", 100);
                        CleanupFlasher();
                        _state = FlashState.Idle;
                        break;
                    case FlashState.EraseError:
                        CastInfoEvent("Erase failed", 0);
                        CleanupFlasher();
                        _state = FlashState.Idle;
                        break;
                    case FlashState.FlashingError:
                        CastInfoEvent("Flashing failed", 0);
                        CleanupFlasher();
                        _state = FlashState.Idle;
                        break;
                }
            }
            catch (Exception E)
            {
                CastInfoEvent("Internal error: " + E.Message, 0);
            }
            _timer.Enabled = true;
        }