Ejemplo n.º 1
0
        private void btnStartUpdate_Click(object sender, RoutedEventArgs e)
        {
            if (!StartUpdate)
            {
                if (!startDebug)
                {
                    MessageBox.Show(this, "请先启动远程诊断服务!", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Stop);
                    return;
                }
                if (string.IsNullOrWhiteSpace(this.txtUpdateFilePath.Text) ||
                    this.txtUpdateFilePath.Text.Trim() == "点击右侧浏览按钮选择文件")
                {
                    MessageBox.Show(this, "还没有选择升级固件!", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                if (string.IsNullOrWhiteSpace(this.txtUpdatePort.Text))
                {
                    MessageBox.Show(this, "还没有输入更新服务器端口号!", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                else
                {
                    if (Regex.IsMatch(this.txtUpdatePort.Text.Trim(), @"^\d+$")) //确认是数字
                    {
                        bool suc = ushort.TryParse(this.txtUpdatePort.Text.Trim(), out updatePort1);
                        if (!suc)
                        {
                            MessageBox.Show(this, "输入的更新服务器端口号范围不正确!", "温馨提示", MessageBoxButton.OK,
                                            MessageBoxImage.Information);
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "输入的更新服务器端口号不正确!", "温馨提示", MessageBoxButton.OK,
                                        MessageBoxImage.Information);
                        this.txtUpdatePort.Text = "4518";
                        return;
                    }
                }

                if (string.IsNullOrEmpty(updateVer))
                {
                    MessageBox.Show(this, "更新版本号解析错误!请检查升级文件!", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Stop);
                    return;
                }

                try
                {
                    strUpdatefmt  = "$UPDUPD,U@d8k%4#jD,"; //头
                    strUpdatefmt += "{0},0,";              //版本号

                    FileInfo   fileInfo = new FileInfo(filePath);
                    FileStream fs       = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                    long       fileSize = fs.Length;
                    fs.Position = 0;
                    fileStream  = new byte[fileSize];
                    fs.Read(fileStream, 0, fileStream.Length);
                    fs.Close();
                    strUpdatefmt += fileSize + ",";                                          //升级文件大小
                    strUpdatefmt += fileInfo.LastWriteTime.ToString("HH:mm:ss MM-dd-yyyy,"); //文件修改时间

                    UInt32 Crc32       = 0;
                    int    readBufSize = 512;
                    int    position    = 0;
                    do
                    {
                        int readCount = (int)fileSize - position;
                        readCount = readCount > readBufSize ? readBufSize : readCount;
                        byte[] fileBuf = fileStream.Where((b, index) => index >= position && index < (position + readCount))
                                         .ToArray();
                        Crc32     = CRC.crc_32_calc(fileBuf, (UInt16)(readCount * 8), Crc32);
                        position += readCount;
                    } while (position < fileSize);
                    strUpdatefmt += Crc32.ToString("X") + ",1,"; //CRC校验
                    strUpdatefmt += serverIP + ":" + updatePort; //ip和端口
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "升级文件打开错误,请检查升级文件!\r\n错误信息:" + ex.Message, "启动失败", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                }

                if (string.IsNullOrWhiteSpace(strUpdatefmt))
                {
                    MessageBox.Show(this, "获取\"更新SMS串\"出错,请检查升级文件是否正确!", "温馨提示", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return;
                }

                this.txtSMS.Text = strUpdate();
                btnEnterMac_Click(null, null);


                if (updateServer_2G == null)
                {
                    updateServer_2G      = new UpdateServer_2G();
                    updateServer_2G.main = this;
                }
                updateServer_2G.Start(new Action(() =>
                {
                    this.btnStartUpdate.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        this.StartUpdate                       = true;
                        this.btnStartUpdate.Content            = "停止服务\n(已启动)";
                        this.MenuItemStartUpdate.IsEnabled     = this.MenuItemStopUpdate.IsEnabled =
                            this.MenuItemForceUpdate.IsEnabled = this.MenuItemPauseUpdate.IsEnabled = true;
                        this.btnSelectUpdateCarFile.IsEnabled  = this.btnSelectUpdateFile.IsEnabled = false;
                    }));
                })); //启动更新服务器
            }
            else
            {
                if (updateServer_2G.Stop())
                {
                    this.StartUpdate                       = false;
                    this.btnStartUpdate.Content            = "启动升级";
                    this.MenuItemStartUpdate.IsEnabled     = this.MenuItemStopUpdate.IsEnabled =
                        this.MenuItemForceUpdate.IsEnabled = this.MenuItemPauseUpdate.IsEnabled = false;
                    this.btnSelectUpdateCarFile.IsEnabled  = this.btnSelectUpdateFile.IsEnabled = true;
                }
            }
        }
Ejemplo n.º 2
0
        private void run()
        {
            try
            {
                byte[] buf = new byte[_recBufferSize];
                while (true)
                {
                    int count = client.Receive(buf);
                    if (count == 0) //远程主机关闭了连接
                    {
                        client.Close();
                        OnClientClosed("下载断开");
                        return;
                    }
                    else
                    {
                        string str = Encoding.ASCII.GetString(buf, 0, count);

                        if (str.StartsWith("$UPD"))   //确认是升级串
                        {
                            str = str.Split('\0')[0]; //去除重复数据
                            string[] array = str.Split('*');
                            if (array.Length > 1)     //正确串
                            {
                                string upStr  = array[0];
                                string sumStr = array[1];
                                string csstr  = Common.GetCheckSumString(upStr);
                                if (csstr == sumStr)            //检验和正确
                                {
                                    upStr = upStr.Remove(0, 4); //移除前缀
                                    if (upStr.StartsWith("DLREQ"))
                                    {
                                        var tmpArray = upStr.Split(',');
                                        if (tmpArray.Length == 6)
                                        {
                                            if (tmpArray[1] == "U@d8k%4#jD" && Common.IsNumricForNum(tmpArray[2]) && Common.IsNumricForNum(tmpArray[3]) && Common.IsNumricForNum(tmpArray[4]))
                                            {
                                                mac = tmpArray[5];
                                                if (_server_2G.listClient.Any(x => x.mac == mac && x != this))
                                                {   //存在相同的连接
                                                    UpdateClient_2G sameClient = _server_2G.listClient.First(x => x.mac == mac && x != this);
                                                    try
                                                    {
                                                        if (sameClient.thread != null)
                                                        {
                                                            sameClient.thread.Abort();
                                                        }
                                                    }
                                                    catch { }
                                                    sameClient.OnClientClosed(null);
                                                }

                                                if (updateInfo == null || !updateInfo.AutoUpdate || !updateInfo.needUpdate)
                                                {
                                                    client.Close();
                                                    OnClientClosed(null);
                                                    return;
                                                }

                                                int upVer = Convert.ToInt32(tmpArray[2]);
                                                if (main.upVer == upVer || main.upVer + 1 == upVer) //升级版本一致
                                                {
                                                    int offset = Convert.ToInt32(tmpArray[3]);
                                                    int size   = ConfigHelper.GetConfigInt("UpPkgSize", -1);
                                                    if (size == -1)
                                                    {
                                                        size = Convert.ToInt32(tmpArray[4]);
                                                    }
                                                    if (size <= 0)
                                                    {
                                                        size = 480;
                                                    }

                                                    int readLen = main.fileStream.Length - offset;
                                                    if (readLen > size)
                                                    {
                                                        readLen = size;
                                                    }
                                                    double rspOffset     = offset + readLen;
                                                    byte[] readFileBytes =
                                                        main.fileStream
                                                        .Where((b, index) => index >= offset && index < rspOffset)
                                                        .ToArray();
                                                    int    rspSize  = readLen + 80;
                                                    byte[] rspBytes = new byte[rspSize];
                                                    uint   crc      = CRC.crc_32_calc(readFileBytes, (UInt16)(readLen * 8),
                                                                                      0);
                                                    string header      = $"$UPDDLACK,{upVer},{offset},{readLen},";
                                                    byte[] headerBytes = Encoding.ASCII.GetBytes(header);
                                                    int    nlen        = headerBytes.Length;
                                                    Array.Copy(headerBytes, rspBytes, nlen);
                                                    Array.Copy(readFileBytes, 0, rspBytes, nlen, readLen);
                                                    nlen += readLen;
                                                    string crcStr   = crc.ToString("X8") + "\n";
                                                    byte[] crcBytes = Encoding.ASCII.GetBytes(crcStr);
                                                    Array.Copy(crcBytes, 0, rspBytes, nlen, crcBytes.Length);
                                                    nlen += crcBytes.Length;
                                                    byte   cs       = Common.CheckSumBytes(rspBytes, nlen);
                                                    string cumStr   = "*" + (((uint)cs) & 0xFF).ToString("X2");
                                                    byte[] cumBytes = Encoding.ASCII.GetBytes(cumStr);
                                                    Array.Copy(cumBytes, 0, rspBytes, nlen, cumBytes.Length);
                                                    nlen += cumBytes.Length;

                                                    //未启动升级 或者 无需升级 或者 暂停升级 跳过升级
                                                    if (updateInfo.PauseUpdate)
                                                    {
                                                        pauseBytes = rspBytes.Take(nlen).ToArray();
                                                        continue;
                                                    }
                                                    pauseBytes = null;

                                                    client.Send(rspBytes, nlen, SocketFlags.None);

                                                    if (main.ProgressMode == "P")
                                                    {
                                                        updateInfo.sended = string.Format("{1} ({0:P2})",
                                                                                          rspOffset / main.fileStream.Length,
                                                                                          main.fileStream.Length - rspOffset);
                                                    }
                                                    else if (main.ProgressMode == "T")
                                                    {
                                                        updateInfo.sended = (main.fileStream.Length - rspOffset).ToString();
                                                    }

                                                    if (rspOffset >= main.fileStream.Length)
                                                    {
                                                        updateInfo.DevStatus = DevStatus.DownloadRomSuccess;
                                                    }

                                                    updateInfo.lastUpdSendTime = DateTime.Now;
                                                }
                                                else
                                                {
                                                    updateInfo.sended    = "版本不一致";
                                                    updateInfo.DevStatus = DevStatus.DownloadRomError;
                                                }
                                            }
                                        }
                                    }
                                    else if (upStr.StartsWith("REG"))
                                    {
                                    }
                                    else if (upStr.StartsWith("UPDACK"))
                                    {
                                        var tmpArray = upStr.Split(',');
                                        if (tmpArray.Length == 3)
                                        {
                                            mac = tmpArray[1];
                                        }

                                        if (updateInfo != null)
                                        {
                                            if (pauseBytes == null)
                                            {
                                                updateInfo.sended = "升级启动...";
                                            }
                                            else
                                            {
                                                client.Send(pauseBytes, SocketFlags.None);
                                            }
                                            updateInfo.lastUpdSendTime = DateTime.Now;
                                        }
                                    }
                                    else
                                    {
                                    }
                                }
                            }
                        }
                        else
                        {
                            client.Send(buf);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is SocketException)
                {
                    OnClientClosed("下载断开");
                }
                else
                {
                    if (!(ex is ThreadAbortException))
                    {
                        LogHelper.WriteError(ex, "UpdateClient_2G");
                    }
                }
                try
                {
                    client?.Close();
                }
                catch
                {
                }
                //MessageBox.Show(ex.Message);
            }
        }