unit FbusMain;

interface
 uses SysUtils,ComPort,Windows,UnitMisc,HexUtils,FBoots,Classes,Messages, Variants, StdCtrls, forms, D2XXUnit ;

var
  FbusBl   : byte = 1 ;
  FbusFr   : byte = $41 ;
  FLcon : boolean = true;
  FbusTx : array [0..$FF] of byte;
  FbusAnsB : array [0..256] of byte ;
  FbusAckB  : array [0..9] of byte ;
  FbusBlA : byte =1;
  FbusStr: string = '';

function FbusReadPhMode():string;
function FbusExecModeCommand(Command:pointer;Len:integer):string;
function FbusExecCommand (Command: pointer;Len:integer):boolean;
function FbusGetChk (Buf:pointer;Len:integer):word;
function FbusSendCommand (Buf:pointer;Len:integer):boolean;
function FbusChkMode():integer;
function FbusSendSynk : boolean ;
function FbusAck ():boolean;
function FbusAns ():boolean;
function FbusSendAsk ():boolean;
function FbusRunCommand (Command: pointer;Len:integer):boolean;
function FbusSetPhoneMode (mode:integer):string ;
function FbusPmGetRecCou(Field:word):integer;
function FbusPmGetRecLen(Field:word;Rec:word):dword;
function FbusPmReadRecord(Field:word;Rec:word;Len:dword):string;
function FbusReadPPItem(Item:byte):string;
function FbusReadAPECoreSW():string;
function FbusReadPhName():string;
function FbusReadMcuSw():string;
procedure FbusReadPhInfo ();
procedure FbusReadPhInfoAll ();
function FbusReadApeVarVer():string;
function FbusReadIMEIPl():string;
function FbusReadAPEAdsp():string;
function FbusReadDSP():string;
function FbusReadApetest():string;
function FbusReadPPMversioninfo():string;
function FbusReadCNTInfo():string;
function FbusReadPSN():string;
function FbusReadProductCode():string;
function FbusReadBasicProductionCode():string;
function FbusReadMcode():string;
function FbusReadLSN():string;
function FbusReadHWID():string;
function FbusReadRetu():string;
function FbusReadTahvo():string;
function FbusReadBatvalue():string;
function FbusReadBTver():string;
function FbusReadAPEBT():string;
function FbusReadAPEHW():string;
function FbusReadLCD():string;
function FbusReadRFic():string;
function FbusReadAsk():string;
function FbusWritePPItem(Item:byte;Data:byte):string;
function FbusPmWriteRecord(Field:word;Rec:word;s:string):string;
function FbusPmWriteRecordBuf(Field:word;Rec:word;Buf:Pointer;Len:word):string;
function FbusFullFactorySet():boolean;
function FbusSWupgrDef():boolean;
function FbusServiceCentreDef():boolean;
function FbusPrdTuneSet():boolean;
function FbusUserDefSet():boolean;
function FbusLeaveFactSet():boolean;
function FbusSetPat(pat:word):string;
function fbusaperun():string; // APE sybsystem check
function ResetLifeTimerFbus():string;
function WriteLTFbus():string;
function fbuswriteprdcode(prdstring:string):string;
function FbusGetS40PhbCou():integer;
function FbusGetS40PhbRecord(RecNum:word):string;
function FbusS40PhbRecWr(Buf:pointer;Len:word):string;
function getlockdata():string;
function FbusGetfileSize(filewithpath:string):integer;
function FbusGetfiles60n(F:TMemoryStream;filewithpath:string;len:integer;info:integer):boolean;
function fbuststarttest():string;
function FSelftestitem(testid:string):string;
function fbusgettemp():integer;
function fbusgetbbat():integer;
function fbusgetintsize():integer;
function restrtphone(mode:integer):string;   // рестар/смена режима
function restrtphone2():string;   // безглючный пост-рестарт
function FbusGetS40FSize(fullpath:string):integer;
function fbusgetfileS40(F:TMemorystream;fullpath:string;len:Integer;info:Integer):Boolean;
function fbusscandrives():string;  //скан дисков
function s60f1st(drive:Byte):string;  // первый стэп форматирования с60
function fbs60cyclef (drive:Byte):string;  //цикл форматирования для серии 60
function fbusgetdrives40():string; //берет диски с с40
function fbusgetdrives60():string;  // берет диски с с60
function s40frmtdrv(drv:string):string;  // формат с40
function fncksend(code:string;level:Integer):string;  // посыл нцк
function FbusS40ContList(path:string):string;
function FbusS40ListFile(path:string):string;
function FbusRunLongCommand (Command: pointer;Len:integer):boolean;
function FbusS60ListFile(path:string):string;
function FbusS60ContList(path:string):string;
function fpreformats40():string;
function WD2listdir(path:string):integer;
function fbusgetfileWd2nd(F:TMemoryStream;fullpath:string;len:Integer):boolean;
function FbusWriteFileS60(InFile:TMemoryStream;filewithpath:string;info:integer):boolean;
function fbusdeletefiles60(filewithpath:string):Boolean;
function fbuschngrigths40(level:word;filepath:string):Boolean;
function FbusWriteFileS40(InFile:TMemoryStream;filewithpath:string;info:integer):boolean;
function FbusDelFileS40(filepath:string):Boolean;
function FKBstest():Boolean;   //S40 KeybTest  start
function FKBtestEnd():Boolean;    //S40 KeybTest  end
function s40getKbstatus():Boolean;  //S40 KeybTest check
function FBfinkeybtests60 () : Boolean;  //S60 KeybTest  end
function FBcheckkeys60 () : Boolean;    //S60 KeybTest check
function F60startkeybtest () : Boolean;  //S60 KeybTest  start
function FbusDelPhoneBookwd2():Boolean;
function fbuswritefilewd2(InFile:TMemoryStream;filewithpath:string):Boolean;
function FbusExLongCommand (Command: pointer;Len:integer):boolean;
function csbyte (b:Byte):Byte;
function UFSRead(Buf:Pointer;Len:integer):boolean;
function FbusS40CreateDir(fullpath:string):byte;
function FbusreadPBcount():DWORD;
function WriteSLkeySL2(Dkey:string):Boolean;
function WriteSLDataSL2(key:string):Boolean;
function FWriteSDkeySLx(Dkey:string):Boolean;
function stopfbusop():Boolean;
function FbusSx4chst():string;
function FbusSx4st3(s:string):string;
function FbusSx4st2(s:string):string;
function FbusSx4st1():string;
function FbusGetSlStat():string;
function FbusGetSlInfo():string;
function GetInfoDct4():Boolean;

implementation
uses Unit1, UnitAndrey;

function FbusGetSlStat():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FGetSlStat, Length(FGetSlStat)) then
          Result:=BufToHexStr(@FbusStr[7],(Length(FBusStr)-6));
end;

function FbusGetSlInfo():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FGetSlInfo, Length(FGetSlInfo)) then
          Result:=BufToHexStr(@FbusStr[5],(Length(FBusStr)-4));
end;

function FbusSx4chst():string;
var
  buf:string;
begin
          buf:='Error';
          if FbusRunCommand(@FSx4chst, Length(FSx4chst)) then
          if FbusAnsB[11] = 0 then buf:='Ok';
  Result:=buf;
end;

function FbusSx4st3(s:string):string;
var
  buf,kom:string;
begin
   buf:='Error';
   kom:='';
   SetLength(kom,Length(FSx43st));
   BufCopy(@FSx43st,@kom[1],Length(FSx43st));
   kom:=kom+s+Chr(1)+Chr(0);
   if FbusRunCommand(@kom[1], Length(kom)) then
         if FbusAnsB[11]=0 then buf:='Ok';
  Result:=buf;
end;

function FbusSx4st2(s:string):string;
var
  buf,kom:string;
begin
   buf:='Error';
   kom:='';
   SetLength(kom,Length(FSx42st));
   BufCopy(@FSx42st,@kom[1],Length(FSx42st));
   kom:=kom+s+Chr(1)+Chr(0);
   if FbusRunCommand(@kom[1], Length(kom)) then
         if FbusAnsB[11]=0 then buf:=BufToHexStr(@FbusAnsB[12],24);
  Result:=buf;
end;

function FbusSx4st1():string;
var
  buf:string;
begin
          FbusSendSynk;
   buf:='Error';
          if FbusRunCommand(@FSx41st, Length(FSx41st)) then
          if FbusAnsB[11] = 0 then buf:=BufToHexStr(@FbusAnsB[12],16);
  Result:=buf;
end;

function fbuswritefilewd2(InFile:TMemoryStream;filewithpath:string):Boolean;
var
  hider,s:string;
  p:dword;
  l,k:word;
begin
 Result:=false;
 form1.pb1.maxvalue:=InFile.Size;
 if InFile.Size>$3cc then begin
 hider:=chr($1E)+chr($00)+chr($10)+chr($58)+chr($00)+chr($7A)+chr($00)+chr($11)+chr($11)+chr($0F)+chr($30)+chr($02)+chr($07)+chr($20)+chr($0E)+chr($0C)+filewithpath+chr($00)+chr($00)+chr($04)+chr($03)+chr($D8)+chr($8E)+chr($10)+chr($00)+chr($03)+chr($CC)+chr($00)+chr($00)+chr($00)+chr($00);
 s:=hider;
 SetLength(s,(Length(s)+$3cc));
 InFile.Read(s[(Length(hider)+1)],$3cc);
 s:=s+chr($00)+chr($41);
 FbusRunLongCommand(@s[1],Length(s));
 while (InFile.Size-InFile.Position)>$3ec do begin
 hider:=chr($1E)+chr($00)+chr($10)+chr($58)+chr($00)+chr($7A)+chr($00)+chr($11)+chr($11)+chr($0F)+chr($50)+chr($01)+chr($04)+chr($03)+chr($F8)+chr($4E)+chr($10)+chr($00)+chr($03)+chr($EC)+chr($00)+chr($00)+chr($00)+chr($00);
 p:=InFile.Position;
 dword((@hider[21])^):=p;
 form1.pb1.progress:=p;
 DwordSwap(@hider[21]);
 s:=hider;
 SetLength(s,(Length(s)+$3ec));
 InFile.Read(s[(Length(hider)+1)],$3ec);
 s:=s+chr($00)+chr($41);
 if not FbusExLongCommand(@s[1],Length(s)) then exit; // form1._msg('Packet CS #3');
 Application.ProcessMessages;
 sleep(100);
 Application.ProcessMessages;
 end;
 hider:=chr($1E)+chr($00)+chr($10)+chr($58)+chr($00)+chr($7A)+chr($00)+chr($11)+chr($11)+chr($0F)+chr($30)+chr($01)+chr($04)+chr($00)+chr($E0)+chr($8F)+chr($10)+chr($00)+chr($00)+chr($00)+chr($00)+chr($00)+chr($00)+chr($00);
 p:=InFile.Position;
 dword((@hider[21])^):=p;
 form1.pb1.progress:=p;
 DwordSwap(@hider[21]);
 l:=InFile.Size-InFile.Position;
 word((@hider[19])^):=l;
 WordSwap(@hider[19]);
 k:=l;
 if (l and 3)<>0 then begin
 k:=l and $FFFC;
 k:=k+4;
 end;
 word((@hider[5])^):=k+20;
 WordSwap(@hider[5]);
 word((@hider[14])^):=k+12;
 WordSwap(@hider[14]);
 s:='';
 SetLength(s,k);
 InFile.Read(s[1],l);
 s:=hider+s+chr($01)+chr($40);
 FbusRunLongCommand(@s[1],Length(s));
 Result:=true;
 end;

end;

function csbyte (b:Byte):Byte;
begin
  b:=b+1;
  if b=$48 then result:=$40 else result:=b;
end;

function FbusDelPhoneBookwd2():Boolean;
var
  s:string;
  framelen:word;
begin
 s:=chr($1E)+chr($00)+chr($10)+chr($58)+chr($00)+chr($28)+chr($00)+chr($11)+chr($08)+chr($15)+chr($01)+chr($01)+chr($07)+chr($20)+chr($0E)+chr($0C)+chr($43)+chr($3A)+chr($5C)+chr($53)+chr($79)+chr($73)+chr($74)+chr($65)+chr($6D)+chr($5C)+chr($44)+chr($61)+chr($74)+chr($61)+chr($43)+chr($6F)+chr($6E)+chr($74)+chr($61)+chr($63)+chr($74)+chr($73)+chr($2E)+chr($63)+chr($64)+chr($62)+chr($00)+chr($00)+chr($01)+chr($00);
 framelen:=Length(s)-6;
 word((@s[5])^):=framelen;
 WordSwap(@s[5]);
 FbusRunlongCommand(@s[1], Length(s));
 //form1._msg(buftohexstr(@Fbusstr[1], Length(fbusstr)));
 //form1._msg(Byte2Str(fbusansb[9])+Byte2Str(fbusansb[10])+Byte2Str(fbusansb[11]));
 case FbusAnsB[10] of
 $0: begin
    result:=True;
    Form1._msg('Clear : Cl_Ok');
    end;
 $40:
    begin
    result:=false;
    Form1._msg('Clear : Cl_Er');
    end;
 $05:
    begin
    result:=True;
    Form1._msg('Clear : Cl_skip');
    end;
  else result:=False;
 end;
end;


function fpreformats40():string;
begin
          Fbussendsynk;
          Result:='Error';
          if FbusRunCommand(@fs40preformat, Length(fs40preformat))then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusS60ContList(path:string):string;
label long;
var
i,Len:integer;
s:string;
begin
     FBusStr:='';
     Result:='';
     if not FLcon then begin FLcon:=true; exit; end;
long:
     if not FbusAns then exit;
     if not FbusSendAsk then exit;
     if FbusBlA <> 1 then goto long;
          if FbusStr[5]=Chr($0F) then begin FLcon:=false; exit; end;
          Result:='Ok';
end;

function FbusS60ListFile(path:string):string;
Label cont;
var
i:integer;
s,kom:string;
sw:WideString;
Len:word;
begin
          FbusSendSynk;
          Result:='';
          kom:='';
          FLcon:=true;
          for i:=0 to Length(FGet60ListGal) do kom:=kom+Chr(FGet60ListGal[i]);
          sw:=UTF8Decode(path);
          Len:=Length(sw);
          byte ((@kom[18])^):=Len;
          Len:=Len shl 1;
          SetLength(kom,Length(kom)+Len-1);
          BufCopySwapWord(@sw[1],@kom[19],Len);
          kom:=kom+chr(0)+chr(0)+Chr(1)+Chr($41); ///  -> ну собственно два байта добавляем
          word ((@kom[5])^):=Len+16;   //в конце необходимо добавлять 2 байта 0 прибавляем их к длинне
          WordSwap(@kom[5]);
          word ((@kom[15])^):=length(kom)-14; // хидер-длина универсальный тип - подходит ко всем генерациям ( в каждой версии длина разная ) - я использовал общее среднее-  работает
          WordSwap(@kom[15]);
          if FbusRunLongCommand(@kom[1],Length(kom)) then begin;
          if FbusStr[5]=Chr($0F) then begin FLcon:=false; Result:=''; exit; end;
          Result:='Ok';
          end;
end;

function FbusS40ContList(path:string):string;
label long;
var
i,Len:integer;
s:string;
begin
     FBusStr:='';
     Result:='';
     if not FLcon then begin FLcon:=true; exit; end;
long:
     if not FbusAns then exit;
     if not FbusSendAsk then exit;
     if FbusBlA <> 1 then goto long;
          if FbusStr[5]=Chr(0) then FLcon:=false;
          if FbusStr[10]=Chr(0) then begin FLcon:=false; exit; end;
          Len:=byte((@FbusStr[32])^);
          i:=33;
          while word((@FbusStr[i])^)<>0 do begin
          WordSwap(@FbusStr[i]);
          i:=i+2;
          end;
          SetLength(s,255);
          i:=UnicodeToUtf8(@s[1],255,@FbusStr[33],Len);
          SetLength(s,i-2);
          if s='' then exit;
          DwordSwap(@FbusStr[11]);
          Len:=dword((@FbusStr[11])^);
          if Len=0 then s:=s+Chr($5C);
          Result:=path+s;
end;

function FbusS40ListFile(path:string):string;
Label cont;
var
i:integer;
s,kom:string;
sw:WideString;
Len:word;
begin
          FbusSendSynk;
          Result:='';
          kom:='';
          FLcon:=true;
          for i:=0 to Length(FGet40ListGal) do kom:=kom+Chr(FGet40ListGal[i]);
          sw:=UTF8Decode(path+'*');
          Len:=(Length(sw) shl 1)+2;
          word ((@kom[11])^):=Len;
          WordSwap(@kom[11]);
          SetLength(kom,Length(kom)+Len-1);
          BufCopySwapWord(@sw[1],@kom[13],Len);;
          kom:=kom+Chr(1);
          kom:=kom+Chr($41);
          word ((@kom[5])^):=Len+8;
          WordSwap(@kom[5]);
          if FbusRunLongCommand(@kom[1],Length(kom)) then begin;
          if FbusStr[5]=Chr(0) then FLcon:=false;
          if FbusStr[10]=Chr(0) then begin FLcon:=false; exit; end;
          Len:=byte((@FbusStr[32])^);
          i:=33;
          while word((@FbusStr[i])^)<>0 do begin
          WordSwap(@FbusStr[i]);
          i:=i+2;
          end;
          SetLength(s,255);
          i:=UnicodeToUtf8(@s[1],255,@FbusStr[33],Len);
          SetLength(s,i-2);
          if s='' then exit;
          DwordSwap(@FbusStr[11]);
          Len:=dword((@FbusStr[11])^);
          if Len=0 then s:=s+Chr($5C);
          Result:=path+s;
          end;
end;

function FbusS40PhbRecWr(Buf:pointer;Len:word):string;
var
TLen,ELen:word;
Co:byte;
TPoz:Pointer;
begin
     Result:='Error';
     BufCopy (@FS40PhbRecWr,@FbusTx,Length(FS40PhbRecWr));
//     Len:=StrToBufHex(s,@FbusTx[20]);
     if Len <=100 then begin
      BufCopy (Buf,@FbusTx[26],Len);
      word((@FbusTx[4])^):=Len+$16;
      WordSwap(@FbusTx[4]);
      word((@FbusTx[Len+$1A])^):=$4101;
       if FbusRunCommand(@FbusTx[0], Len+28)then
       if FbusAnsB[10]<> 0 then exit;
            if FbusRunCommand(@FS40PhbRecWrEnd,Length(FS40PhbRecWrEnd))then
           if FbusAnsB[10]<>0 then exit;
            WordSwap(@FbusAnsB[26]);
            Result:=IntToStr(word((@FbusAnsB[26])^));
       exit;
     end;
     TLen:=Len-100;
     Co:=1+(TLen Div 120);
     ELen:=TLen Mod 120;
     if ELen<>0 then Co:=Co+1 else ELen:=120;
     Buf:=BufCopy (Buf,@FbusTx[26],100);
      word((@FbusTx[4])^):=$7A00;
      FbusTx[126]:=Co;
//      FbusTx[127]:=$41;
      if not FbusExecCommand(@FbusTx[0],128) then exit;
      Co:=Co-1;
        FbusFr:=FbusFr and 7;
       while Co<>1 do begin
        Buf:=BufCopy (Buf,@FbusTx[6],120);
        FbusTx[126]:=Co;
        if not FbusExecCommand(@FbusTx[0],128) then exit;
        Co:=Co-1;
       end;
      Buf:=BufCopy (Buf,@FbusTx[6],ELen);
      word((@FbusTx[4])^):=ELen+$2;
      WordSwap(@FbusTx[4]);
      word((@FbusTx[ELen+6])^):=$101;
       if FbusRunCommand(@FbusTx[0], ELen+8)then begin
       FbusFr:=FbusFr or $40;
       if FbusAnsB[10]<> 0 then exit;
            if FbusRunCommand(@FS40PhbRecWrEnd,Length(FS40PhbRecWrEnd))then
           if FbusAnsB[10]<>0 then exit;
            WordSwap(@FbusAnsB[26]);
            Result:=IntToStr(word((@FbusAnsB[26])^));
       end;
end;

function FbusGetS40PhbRecord(RecNum:word):string;
var
Len:integer;
begin
          Result:='';
          word((@FGetS40PhbRecC[20])^):=RecNum;
          WordSwap(@FGetS40PhbRecC[20]);
          if FbusRunCommand(@FGetS40PhbRecC, Length(FGetS40PhbRecC)) then
          if word((@FbusAnsB[18])^)= 0 then exit;
          Result:=BufToHexStr(@FbusStr[21],Length(FbusStr)-20);
end;

function FbusGetS40PhbCou():integer;
begin
          FbusSendSynk;
          Result:=0;
          if FbusRunCommand(@FGetS40PhbCouC, Length(FGetS40PhbCouC)) then
          if FbusAnsB[10]<> 0 then exit;
          WordSwap(@FbusAnsB[26]);
          Result:=word((@FbusAnsB[26])^);
end;

function FbusSetPat(pat:word):string;
begin
          FbusSendSynk;
     Result:='Error';
          word((@FbusLCDpat[14])^):=pat;
          if FbusRunCommand(@FbusLCDpat, Length(FbusLCDpat)) then
          if FbusAnsB[10]<> 0 then exit;
          Result:='Ok';
end;

function FbusLeaveFactSet():boolean;
begin
          FbusSendSynk;
          Result:=false;
          if FbusRunCommand(@FbusLeavefactoryset, Length(FbusLeavefactoryset)) then
          if FbusAnsB[9]<>2 then exit;
          Result:=true;
end;

function FbusUserDefSet():boolean;
begin
          FbusSendSynk;
          Result:=false;
          if FbusRunCommand(@FbusUserDataRes, Length(FbusUserDataRes)) then
          if FbusAnsB[9]<>2 then exit;
          Result:=true;
end;

function FbusPrdTuneSet():boolean;
begin
          FbusSendSynk;
          Result:=false;
          if FbusRunCommand(@FbusProductTune, Length(FbusProductTune)) then
          if FbusAnsB[9]<>2 then exit;
          Result:=true;
end;

function FbusServiceCentreDef():boolean;
begin
          FbusSendSynk;
          Result:=false;
          if FbusRunCommand(@FbusServiceCentre, Length(FbusServiceCentre)) then
          if FbusAnsB[9]<>2 then exit;
          Result:=true;
end;

function FbusSWupgrDef():boolean;
begin
          FbusSendSynk;
          Result:=false;
          if FbusRunCommand(@FbusSoftupgr, Length(FbusSoftupgr)) then
          if FbusAnsB[9]<>2 then exit;
          Result:=true;
end;

function FbusFullFactorySet():boolean;
begin
          FbusSendSynk;
          Result:=false;
          if FbusRunCommand(@FbusFullFactory, Length(FbusFullFactory)) then
          if FbusAnsB[9]<>2 then exit;
          Result:=true;
end;

function FbusPmWriteRecord(Field:word;Rec:word;s:string):string;
var
Len:word;
st:string;
begin
     st:='';
     SetLength(st,(Length(s)shr 1)+1);
     Len:=StrToBufHex(s,@st[1]);
     Result:= FbusPmWriteRecordBuf(Field,Rec,@st[1],Len);
end;

function FbusRunLongCommand (Command: pointer;Len:integer):boolean;
label long;
var
TLen,ELen:word;
i:integer;
Co:byte;
Chk:word;
begin
     if Len<=128 then begin Result:=FbusRunCommand(Command,Len); exit; end;
     Result:=false;
     FbusStr:='';
     Len:=Len-2;
     Command:=BufCopy(Command,@FbusTx[0],126);
     TLen:=Len-126;
     Co:=1+(TLen Div 120);
     ELen:=TLen Mod 120;
     if ELen<>0 then Co:=Co+1 else ELen:=120;
      word((@FbusTx[4])^):=$7A00;
      FbusTx[126]:=Co;
//      FbusTx[127]:=$41;
      if not FbusExecCommand(@FbusTx[0],128) then exit;
      Co:=Co-1;
        FbusFr:=FbusFr and 7;
       while Co<>1 do begin
        Command:=BufCopy (Command,@FbusTx[6],120);
        FbusTx[126]:=Co;
        if not FbusExecCommand(@FbusTx[0],128) then exit;
        Co:=Co-1;
       end;
      Command:=BufCopy (Command,@FbusTx[6],ELen);
      word((@FbusTx[4])^):=ELen+$2;
      WordSwap(@FbusTx[4]);
      word((@FbusTx[ELen+6])^):=$101;
       if not FbusRunCommand(@FbusTx[0], ELen+8)then exit;
       FbusFr:=FbusFr or $40;
long:
     if not FbusAns then exit;
     if not FbusSendAsk then exit;
      //Sleep(50);
     if FbusBlA <> 1 then goto long;
     Result:=true;
end;

function FbusExLongCommand (Command: pointer;Len:integer):boolean;
label long;
var
TLen,ELen:word;
i:integer;
Co:byte;
Chk:word;
begin
     if Len<=128 then begin Result:=FbusExecCommand(Command,Len); exit; end;
     Result:=false;
     FbusStr:='';
     Len:=Len-2;
     Command:=BufCopy(Command,@FbusTx[0],126);
     TLen:=Len-126;
     Co:=1+(TLen Div 120);
     ELen:=TLen Mod 120;
     if ELen<>0 then Co:=Co+1 else ELen:=120;
      word((@FbusTx[4])^):=$7A00;
      FbusTx[126]:=Co;
//      FbusTx[127]:=$41;
      if not FbusExecCommand(@FbusTx[0],128) then exit;
      Co:=Co-1;
        FbusFr:=FbusFr and 7;
       while Co<>1 do begin
        Command:=BufCopy (Command,@FbusTx[6],120);
        FbusTx[126]:=Co;
        if not FbusExecCommand(@FbusTx[0],128) then exit;
        Co:=Co-1;
       end;
      Command:=BufCopy (Command,@FbusTx[6],ELen);
      word((@FbusTx[4])^):=ELen+$2;
      WordSwap(@FbusTx[4]);
      word((@FbusTx[ELen+6])^):=$101;
       if not FbusExecCommand(@FbusTx[0], ELen+8)then exit;
       FbusFr:=FbusFr or $40;
     Result:=true;
end;

function FbusPmWriteRecordBuf(Field:word;Rec:word;Buf:Pointer;Len:word):string;
var
TLen,ELen:word;
Co:byte;
TPoz:Pointer;
begin
     Result:='Error';
     BufCopy (@FWritePmFieldRec,@FbusTx,Length(FWritePmFieldRec));
//     Len:=StrToBufHex(s,@FbusTx[20]);
     word((@FbusTx[10])^):=Field;
     word((@FbusTx[12])^):=Rec;
     WordSwap(@FbusTx[10]);
     WordSwap(@FbusTx[12]);
      word((@FbusTx[18])^):=Len;
      WordSwap(@FbusTx[18]);
     if Len <=106 then begin
      BufCopy (Buf,@FbusTx[20],Len);
      word((@FbusTx[4])^):=Len+$10;
      WordSwap(@FbusTx[4]);
      word((@FbusTx[Len+$14])^):=$4101;
       if FbusRunCommand(@FbusTx[0], Len+22)then
       if FbusAnsB[10]= $13 then exit;
       Result:='Ok';
       exit;
     end;
     TLen:=Len-106;
     Co:=1+(TLen Div 120);
     ELen:=TLen Mod 120;
     if ELen<>0 then Co:=Co+1 else ELen:=120;
     Buf:=BufCopy (Buf,@FbusTx[20],106);
      word((@FbusTx[4])^):=$7A00;
      FbusTx[126]:=Co;
//      FbusTx[127]:=$41;
      if not FbusExecCommand(@FbusTx[0],128) then exit;
      Co:=Co-1;
        FbusFr:=FbusFr and 7;
       while Co<>1 do begin
        Buf:=BufCopy (Buf,@FbusTx[6],120);
        FbusTx[126]:=Co;
        if not FbusExecCommand(@FbusTx[0],128) then exit;
        Co:=Co-1;
       end;
      Buf:=BufCopy (Buf,@FbusTx[6],ELen);
      word((@FbusTx[4])^):=ELen+$2;
      WordSwap(@FbusTx[4]);
      word((@FbusTx[ELen+6])^):=$101;
       if FbusRunCommand(@FbusTx[0], ELen+8)then begin
       FbusFr:=FbusFr or $40;
       if FbusAnsB[10]= $13 then exit;
       Result:='Ok';
       end;
end;

function FbusWritePPItem(Item:byte;Data:byte):string;
begin
     Result:='Error';
          FWrPPItem[16]:=Item;
          FWrPPItem[17]:=Data;
          if FbusRunCommand(@FWrPPItem, Length(FWrPPItem)) then
          if FbusAnsB[10]<> 0 then exit;
          Result:='Ok';
end;

function FbusReadAsk():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FGetASK, Length(FGetASK))then
          Result:=BufToHexStr(@FbusStr[23], 20);
end;


function FbusReadAPEAdsp():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FAPEAdsp, Length(FAPEAdsp)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadIMEIPl():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FIMEIplain, Length(FIMEIplain)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadMcuSw():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FSowtwareInfo, Length(FSowtwareInfo))then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadPhName():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FPhoneName, Length(FPhoneName)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadAPECoreSW():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FApeVer, Length(FApeVer)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadApeVarVer():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FApeVarVer, Length(FApeVarVer)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadDSP():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FDSPinf, Length(FDSPinf)) then
          Result:=Copy (FbusStr,13,Ord(FbusStr[12])-1);
end;

function FbusReadApetest():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FApetest, Length(FApetest)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadPPMversioninfo():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FPPMversioninfo, Length(FPPMversioninfo)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadCNTInfo():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FCNTinfo, Length(FCNTinfo)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadPSN():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FProductionSerialnumber, Length(FProductionSerialnumber)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadProductCode():string;
begin
          try
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FProductCode, Length(FProductCode)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
          except
          result:='';
          end;
end;

function FbusReadBasicProductionCode():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FBasicProductionCode, Length(FBasicProductionCode)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadMcode():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FMcode, Length(FMcode)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadLSN():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FLSN, Length(FLSN)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadHWID():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FHWversion, Length(FHWVersion)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadRetu():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FRetuVersion, Length(FRetuVersion)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadTahvo():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FTahvoVersion, Length(FTahvoVersion)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadBatvalue():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FBatvalue, Length(FBatvalue)) then
          WordSwap(@FbusAnsB[14]);
          Result:=IntToStr(word((@FbusAnsB[14])^));
end;

function FbusReadBTver():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FBtversion, Length(FBtversion)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadAPEBT():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FApebt, Length(FApebt)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadAPEHW():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FApehw, Length(FApehw)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadLCD():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FLCDver, Length(FLCDver)) then
          Result:=Copy (FbusStr,11,Ord(FbusStr[10])-1);
end;

function FbusReadRFic():string;
begin
          FbusSendSynk;
          Result:='Error';
          if FbusRunCommand(@FRFic, Length(FRFic)) then
          Result:=Copy (FbusStr,13,Ord(FbusStr[12])-1);
end;

procedure FbusReadPhInfo ();
begin
    PhInfoRecord.APECoreSW:= FbusReadAPECoreSW;
    PhInfoRecord.Name:= FbusReadPhName;
    PhInfoRecord.MCUSW:=FbusReadMcuSw;
    PhInfoRecord.IMEIPlain:=FbusReadIMEIPl;
    PhInfoRecord.ProductCode:= FbusReadProductCode;

//    ReadIMEI2net;
//    ReadIMEISV2net;
end;

procedure FbusReadPhInfoAll ();
begin
    PhInfoRecord.APECoreSW:= FbusReadAPECoreSW;
    if PhInfoRecord.APECoreSW='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.APECoreSW:= FbusReadAPECoreSW;
    end;
    PhInfoRecord.Name:= FbusReadPhName;
    if PhInfoRecord.Name='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.Name:= FbusReadPhName;
    end;
    PhInfoRecord.MCUSW:=FbusReadMcuSw;
    if PhInfoRecord.MCUSW='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.MCUSW:=FbusReadMcuSw;
    end;
    PhInfoRecord.IMEIPlain:=FbusReadIMEIPl;
    if PhInfoRecord.IMEIPlain='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.IMEIPlain:=FbusReadIMEIPl;
    end;
    PhInfoRecord.ProductCode:= FbusReadProductCode;
    if  PhInfoRecord.ProductCode='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.ProductCode:= FbusReadProductCode;
    end;
    PhInfoRecord.APEVariant:= FbusReadApeVarVer;
    if PhInfoRecord.APEVariant='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.APEVariant:= FbusReadApeVarVer;
    end;
    PhInfoRecord.APEADSPSW:= FbusReadAPEAdsp;
    if PhInfoRecord.APEADSPSW='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.APEADSPSW:= FbusReadAPEAdsp;
    end;
    PhInfoRecord.DSP:= FbusReadDSP;
    if PhInfoRecord.DSP='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.DSP:= FbusReadDSP;
    end;
    PhInfoRecord.APETest:= FbusReadApetest;
    if PhInfoRecord.APETest='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.APETest:= FbusReadApetest;
    end;
    PhInfoRecord.PPMInfo:= FbusReadPPMversioninfo;
    if PhInfoRecord.PPMInfo='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.PPMInfo:= FbusReadPPMversioninfo;
    end;
    PhInfoRecord.CNT:= FbusReadCNTInfo;
    if PhInfoRecord.CNT='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.CNT:= FbusReadCNTInfo;
    end;
    PhInfoRecord.PrdSerial:= FbusReadPSN;
    if PhInfoRecord.PrdSerial='Error' then
    begin
    Sleep(100);
    Application.ProcessMessages;
    PhInfoRecord.PrdSerial:= FbusReadPSN;
    end;
    //PhInfoRecord.ProductCode:= FbusReadProductCode;
    PhInfoRecord.BisicPrdCode:= FbusReadBasicProductionCode;
    PhInfoRecord.ModuleCode:= FbusReadMcode;
    PhInfoRecord.LSN:= FbusReadLSN;
    PhInfoRecord.HWID:= FbusReadHWID;
    PhInfoRecord.Retu:= FbusReadRetu;
    PhInfoRecord.Tahvo:= FbusReadTahvo;
    PhInfoRecord.Bat:= FbusReadBatvalue;
    PhInfoRecord.CMTBtver:= FbusReadBTver;
    PhInfoRecord.APEBT:= FbusReadAPEBT;
    PhInfoRecord.APEHW:= FbusReadAPEHW;
    PhInfoRecord.LCD:= FbusReadLCD;
    PhInfoRecord.RFIC:= FbusReadRFic;
//    ReadIMEI2net;
//    ReadIMEISV2net;
end;

function FbusReadPPItem(Item:byte):string;
begin
     Result:='Error';
          FRdPPItem[16]:=Item;
          if FbusRunCommand(@FRdPPItem, Length(FRdPPItem))then
          if FbusAnsB[10]= $2 then exit;
          Result:=IntToStr(FbusAnsB[17]);
end;

function FbusPmReadRecord(Field:word;Rec:word;Len:dword):string;
var
Tlen:dword;
i:integer;
begin
          Result:='';
          i:=0;
          dword((@FGetBlRecData[16])^):=0;
          word((@FGetBlRecData[10])^):=Field;
          word((@FGetBlRecData[12])^):=Rec;
          WordSwap(@FGetBlRecData[10]);
          WordSwap(@FGetBlRecData[12]);
          if len=0 then exit;
          if Len>$400 then
          begin
          i:=Len div $400;
          Len:=Len mod $400;
          Tlen:=0;
          word((@FGetBlRecLongData[10])^):=Field;
          word((@FGetBlRecLongData[12])^):=Rec;
          WordSwap(@FGetBlRecLongData[10]);
          WordSwap(@FGetBlRecLongData[12]);
            while i<>0 do begin
            dword((@FGetBlRecLongData[16])^):=Tlen;
            DWordSwap(@FGetBlRecLongData[16]);
            if FbusRunCommand(@FGetBlRecLongData, Length(FGetBlRecLongData)) then
             Result:=Result+BufToHexStr(@FbusStr[19],$400);
             i:=i-1;
             Tlen:=Tlen+$400;
             byte((@FGetBlRecLongData[8])^):=byte((@FGetBlRecLongData[8])^)+1;
            end;
            byte((@FGetBlRecData[8])^):=byte((@FGetBlRecLongData[8])^)+1;
            dword((@FGetBlRecData[16])^):=Tlen;
            DWordSwap(@FGetBlRecData[16]);
          end;
          dword((@FGetBlRecData[20])^):=Len;
          DWordSwap(@FGetBlRecData[20]);
          if FbusRunCommand(@FGetBlRecData, Length(FGetBlRecData)) then
          Result:=Result+BufToHexStr(@FbusStr[19],Len);
end;

function FbusPmGetRecLen(Field:word;Rec:word):dword;
begin
          Result:=$F0000000;
          word((@FGetBlockXXXFieldXXX[10])^):=Field;
          word((@FGetBlockXXXFieldXXX[12])^):=Rec;
          WordSwap(@FGetBlockXXXFieldXXX[10]);
          WordSwap(@FGetBlockXXXFieldXXX[12]);
          if FbusRunCommand(@FGetBlockXXXFieldXXX, Length(FGetBlockXXXFieldXXX)) then
          if FbusAnsB[10]<>0 then exit;
          DWordSwap(@FbusAnsB[16]);
          Result:=dword((@FbusAnsB[16])^);
end;

function FbusPmGetRecCou(Field:word):integer;
begin
    FBusSendSynk;
          Result:=0;
          word((@FGetBlock[10])^):=Field ;
          WordSwap(@FGetBlock[10]);
          if FbusRunCommand(@FGetBlock, Length(FGetBlock)) then
          if FbusAnsB[10]= $4 then exit;
          WordSwap(@FbusAnsB[14]);
          Result:=word((@FbusAnsB[14])^);
end;

function  FbusSetPhoneMode (mode:integer):string ;
var
i:integer;
begin
          FbusSendSynk;
     Result:='Error';
          byte((@FSetMode[10])^):=mode;
          FbusRunCommand(@rst1, Length(rst1));
     if not FbusExecCommand(@FSetMode,Length(FSetMode)) then exit;
     Result:='Ok';
end;

function FbusRunCommand (Command: pointer;Len:integer):boolean;
label long;
var
i:integer;
Chk:word;
begin
     Result:=false;
     FbusStr:='';
     BufCopy(Command,@FbusTx[0],Len);
//     FbusTx[Len-2]:=FbusBl;
     FbusTx[Len-1]:=FbusFr;
     FbusFr:=(FbusFr+1) and $47;
     if (FbusTx[5] and 1)<>0 then begin FbusTx[Len]:=0; Len:=Len+1; end;
     Chk:=FbusGetChk(@FbusTx[0],Len);
     word((@FbusTx[Len])^):=Chk;
     Len:=Len+2;
     if not FbusSendCommand(@FbusTx[0],Len) then exit;
     if not FbusAck then exit;
long:
     if not FbusAns then exit;
     if not FbusSendAsk then exit;
      //Sleep(50);
     if FbusBlA <> 1 then goto long;
     Result:=true;
end;

function FbusSendAsk ():boolean;
var
Ln:integer;
Chk:word;
begin
     Result:=false;
     BufCopy(@Ask,@FbusTx[0],8);
     FbusTx[6]:=byte((@FbusAnsB[3])^);
     ln:=byte((@FbusAnsB[5])^);
//     if (ln and 1) <> 0 then ln := ln+1 ;
     FbusTx[7]:=byte((@FbusAnsB[ln+5])^) and $0F;
     Chk:=FbusGetChk(@FbusTx[0],8);
     word((@FbusTx[8])^):=Chk;
     Result:=FbusSendCommand(@FbusTx[0],10) ;
end;

function FbusExecCommand (Command: pointer;Len:integer):boolean;
var
i:integer;
Chk:word;
begin
     Result:=false;
     BufCopy(Command,@FbusTx[0],Len);
//     FbusTx[Len-2]:=FbusBl;
     FbusTx[Len-1]:=FbusFr;
     FbusFr:=(FbusFr+1) and $47;
     if (FbusTx[5] and 1)<>0 then begin FbusTx[Len]:=0; Len:=Len+1; end;
     Chk:=FbusGetChk(@FbusTx[0],Len);
     word((@FbusTx[Len])^):=Chk;
     Len:=Len+2;
     if not FbusSendCommand(@FbusTx[0],Len) then exit;
     Result:= FbusAck ;
end;

function  FbusAns ():boolean;
label sink,fsynk;
var
ln,i,j:integer;
begin
        Result:= false;
        if fbdev=0 then begin
        if not FlgOvrlp then goto sink;
        if not GetComStat then exit;
        i:=100;
        while ((i<>0) and (COMst.cbInQue<5))  do begin sleep (zad); i:=i-1; GetComStat; end;
sink:   if not ReadCom (@FbusAnsB[0],1) then exit ;
        if byte (FbusAnsB[0]) = $55 then goto sink ;
        if not ReadCom (@FbusAnsB[1],5) then exit ;
        ln:= byte((@FbusAnsB[5])^);
        j:=0;
        if (ln and 1) <> 0 then j:=1;
        if not ReadCom (@FbusAnsB[6],ln+j) then exit ;
        for i:=0 to ln-3+j do FbusStr:=FbusStr+Chr(FbusAnsB[6+i]);
        FbusBlA:= byte((@FbusAnsB[6+ln-2])^);
        Result:=ReadCom (@FbusAnsB[6+ln+j],2);
        end else begin
fsynk:   if not UFSRead (@FbusAnsB[0],1) then exit ;
        if byte (FbusAnsB[0]) = $55 then goto fsynk ;
        if not UFSRead (@FbusAnsB[1],5) then exit ;
        ln:= byte((@FbusAnsB[5])^);
        j:=0;
        if (ln and 1) <> 0 then j:=1;
        if not UFSRead (@FbusAnsB[6],ln+j) then exit ;
        for i:=0 to ln-3+j do FbusStr:=FbusStr+Chr(FbusAnsB[6+i]);
        FbusBlA:= byte((@FbusAnsB[6+ln-2])^);
        Result:=UFSRead (@FbusAnsB[6+ln+j],2);
        end;
end;

function UFSRead(Buf:Pointer;Len:integer):boolean;
var
i,j,cnt:integer;
begin
//   if Len=1 then j:=1;
   Result:=false;
Cnt:=GetTickCount+300;
Get_USB_Device_Queuestatus;
while (FT_Q_Bytes<Len) do
  begin
    Application.ProcessMessages;
    // check if Time not exceeded.
    if (Cnt-GetTickCount)<=0 then break;
    Get_USB_Device_Queuestatus;
  end;
if (Cnt-GetTickCount)<=0 then exit;
   j:=Read_USB_Device_Buffer(Len);
   if j<>Len then exit;
   BufCopy(@FT_In_Buffer,Buf,Len);
   Result:=true;
end;

function  FbusAck ():boolean;
label sink,fsink;
var
i:integer;
begin
        Result:= false;
        if fbdev=0 then begin
        if not FlgOvrlp then goto sink;
        if not GetComStat then exit;
        i:=100;
        while ((i<>0) and (COMst.cbInQue<5))  do begin sleep (20); i:=i-1; GetComStat; end;
sink:   if not ReadCom (@FbusAckB[0],1) then exit ;
        if byte (FbusAckB[0]) = $55 then goto sink ;
        if not ReadCom (@FbusAckB[1],5) then exit ;
        if not ReadCom (@FbusAckB[6],byte((@FbusAckB[5])^)) then exit ;
        Result:=ReadCom (@FbusAckB[6+byte((@FbusAckB[5])^)],2);
        end else begin
fsink:   if not UFSRead (@FbusAckB[0],1) then exit ;
        if byte (FbusAckB[0]) = $55 then goto fsink ;
        if not UFSRead (@FbusAckB[1],5) then exit ;
        if not UFSRead (@FbusAckB[6],byte((@FbusAckB[5])^)) then exit ;
        Result:=UFSRead (@FbusAckB[6+byte((@FbusAckB[5])^)],2);
        end;
end;

function  FbusSendSynk : boolean ;
begin
  case fbdev of
  1: begin
       Purge_USB_device_Out;
       Purge_USB_Device_In;
	 end;
  0:PurgeCom(PURGE_TXCLEAR or PURGE_RXCLEAR);
  end;
  Application.ProcessMessages;
  Result:= FbusSendCommand(@Synk[0],8) ;
  Sleep(100);
  Application.ProcessMessages;
end;

function FbusSendCommand (Buf:pointer;Len:integer):boolean;
var
i,Write_Result:integer;
begin
      if fbdev =0 then Result:= WriteCom (Buf,Len) else begin
       BufCopy(Buf,@FT_OUT_Buffer,Len);
         i:=Write_USB_Device_Buffer(Len);
         if i<>Len then Result:=false else Result:=true;
      end;
end;

function FbusGetChk (Buf:pointer;Len:integer):word;
var
i:integer;
begin
         Result:=0 ;
          for i:=(Len div 2) downto 1 do begin
           Result:=Result xor word (Buf^);
           inc (integer (Buf));
           inc (integer (Buf));
          end;
end;

function FbusReadPhMode():string;
begin
          FbusSendSynk;
          Result:=FbusExecModeCommand(@FChkPhMode,Length(FChkPhMode));
end;

function FbusChkMode():integer;
begin
          FbusSendSynk;
          Result:=$FF;
          if not FbusRunCommand(@FChkPhMode,Length(FChkPhMode)) then exit;
          Result:=byte((@FbusAnsB[11])^);
end;

function FbusExecModeCommand(Command:pointer;Len:integer):string;
begin
          Result:='Error';
          if FbusRunCommand (Command,Len) then
          Result:=PhModeToStr(byte((@FbusAnsB[11])^));
end;

function  fbusaperun():string;
var
  a:string;
begin
 FbusSendSynk;
 result:='';
 FbusRunCommand(@FbusArun, Length(FbusArun));
  try
  a:=Copy (FbusStr,13,29);
  except
  a:='';
  end;
  if a<>'' then result:='Running : '+a else result:='APE Server Run fail! FS breaked... :(';

end;


function ResetLifeTimerFbus():string;
begin
FbusSendSynk;
Result:=FbusPmWriteRecord(88,0,'000000000000000000000000000000000000000000000000000000000000000000000000');
  end;

function WriteLTFbus():string;
begin
          FbusSendSynk;
  FbusRunCommand(@fbusreslt, Length(fbusreslt));
  //form1._msg(Byte2Str(fbusAnsB[13]));
  if fbusAnsB[13]=$04 then result:='Ok' else result:='Error';
end;

function fbuswriteprdcode(prdstring:string):string;
var
  i,s:integer;
  a:string;
begin
          FbusSendSynk;
  s:=1;
  a:='';
  i:=0;
 for i:=1 to length(prdstring) do
  begin
    a:=a+IntToHex(Ord(prdstring[s]),2); //
    Inc(s);
  END;
 a:=a+'00';
Result:=FbusPmWriteRecord(4,4,a);
end;

function getlockdata():string;
var
  hider,s1,s2,s:string;
  bx:byte;
  i:integer;
begin
          FbusSendSynk;
  s:='';
  bx:=$40;
 hider:=chr($1E)+chr(0)+chr($10)+chr($53)+chr(0)+chr($07)+chr(0)+chr($12)+chr(0)+chr($12)+chr($0D)+chr($01)+chr(bx);
 FbusRunCommand(@hider[1], Length(hider));
 s:=BufToHexStr(@FbusStr[25], Length(FbusStr)-24);
 bx:=bx+$01;
 hider:=chr($1E)+chr(0)+chr($10)+chr($53)+chr(0)+chr($07)+chr(0)+chr($12)+chr($01)+chr($12)+chr($0E)+chr($01)+chr(bx);
 FbusRunCommand(@hider[1], Length(hider));
 s:=s+Buftohexstr(@FbusStr[25],length(fbusstr)-24);
 // form1._msg(s);
 bx:=bx+$01;
 if length(s)<500 then begin
  for i:=1 to 12 do
    begin
    hider:=chr($1E)+chr(0)+chr($10)+chr($53)+chr(0)+chr($07)+chr(0)+chr($12)+chr($01)+chr($12)+chr($0E)+chr($01)+chr(bx);
    FbusRunCommand(@hider[1], Length(hider));
    s1:=Buftohexstr(@FbusStr[25],length(fbusstr)-24);
    //form1._msg(s1);
    s:=s+s1;
    bx:=bx+$01;
    if bx=$48 then bx:=$40;
    end;
 result:=s;
 end
 else result:=s;

 end;

function FbusGetfileSize(filewithpath:string):integer;
var
  hider,s,s2:string;
  i:integer;
  framelen:word;
  stringdata:string;
  pathlen:word;
  d:integer;
begin
  FbusSendSynk;
 s:=''; s2:=''; hider:='';
for i:=1 to Length(filewithpath) do s2:=s2+Chr(0)+filewithpath[i];
hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($11)+chr(0)+chr($19)+chr(0)+chr($01)+chr($F5)+chr(0)+chr(0)+chr(0)+chr($80)+chr(Length(filewithpath));
s:=hider+s2+chr($01)+chr($40);
framelen:=Length(s)-6;
word((@s[5])^):=framelen;
WordSwap(@s[5]);
pathlen:=length(s2)+6;
word((@s[15])^):=pathlen;
WordSwap(@s[15]);
 FbusRunCommand(@s[1], Length(s));
  stringdata:=copy(buftohexstr(@FbusStr[1],Length(FbusStr)),53,8);
 d:=hextoint(stringdata);
 {DWordSwap(@d);
 Result:=DWord((@d)^); }
 Result:=d;
 if d>0 then
 begin
 Application.ProcessMessages;
 end
 else begin
  form1._msg('Not found :( ');
  d:=0;
 end;

 end;

function FbusGetfiles60n(F:TMemoryStream;filewithpath:string;len:integer;info:integer):boolean;
label errcor;
var
  hider,s,s2,a,s3,scheck,a4:string;
  i,i2,icheck:integer;
  framelen:word;
  stringdata:string;
  pathlen:word;
  d:Int64;
  ostlen,ist:integer;
  readedlen:DWORD;
  bx:Byte;
begin
icheck:=0;
errcor:
  bx:=$40;
 s:=''; s2:=''; hider:='';
for i2:=1 to Length(filewithpath) do s2:=s2+Chr(0)+filewithpath[i2];
 if len>$400 then begin
 i:=Len div $400;
     case info of
	 1: begin
	    Form1.pb1.MaxValue:=i+1;
        form1._msg('Will read '+inttostr(i+1)+' blocks...');
        end;
	 2: Form1.pbsm1.MaxValue:=i+1;
	 3: Application.ProcessMessages;
	 end;
 ostlen:=len mod $400;
 //form1._msg('Left data: '+inttostr(ostlen));
 hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($11)+chr(0)+chr($0D)+chr(0)+chr($02)+chr($F5)+chr(0)+chr(0)+chr(0)+chr($80)+chr(Length(filewithpath));
 s:=hider+s2+chr($F8)+chr($08)+chr(0)+chr(0)+chr($04)+chr(0)+chr(0)+chr($01)+chr($01)+chr(bx);
 framelen:=Length(s)-6;
 word((@s[5])^):=framelen;
 WordSwap(@s[5]);
 pathlen:=length(s2)+6;
 word((@s[15])^):=pathlen;
 WordSwap(@s[15]);
 FbusRunCommand(@s[1], Length(s));
 a4:=buftohexstr(@FbusStr[19],Length(FbusStr)-18);
 F.Write(FbusStr[19], $400);
 readedlen:=$400;
 bx:=$41;
     case info of
	 1: Form1.pb1.progress:=1;
	 2: Form1.pbsm1.progress:=1;
	 3: Application.ProcessMessages;
	 end;
 Application.ProcessMessages;
 for ist:=1 to i-1 do
   begin
     hider:='';
     hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($12)+chr($05)+chr($0D)+chr(0)+chr($01)+chr($F0)+chr($0C)+chr($20)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr(bx);
     framelen:=Length(hider)-6;
     word((@hider[5])^):=framelen;
     WordSwap(@hider[5]);
     DWord((@hider[21])^):=readedlen;
     DWordSwap(@hider[21]);
      FbusRunCommand(@hider[1], Length(hider));
      a4:=buftohexstr(@FbusStr[19],length(FbusStr)-18);
      //form1._msg(a4);
        if Length(a4)<>$800 then
	    begin
          case info of
	        1: begin
	        form1._msg('Wrong packet chk at : '+inttostr(readedlen));
          Application.ProcessMessages;
          sleep(5000);
          icheck:=icheck+1;
            if icheck<>3 then begin
            form1._msg('Packet bricked, minor error...');
            form1._msg('Restarting Read Procedure....');
            f.Seek(0, soFromBeginning);
   Form1.pbsm1.Progress:=0;
            goto errcor;
            end
            else
            begin
            form1._msg('Packet bricked, major error...');
            form1._msg('Restart phone and try again...');
   Form1.pbsm1.Progress:=0;
            result:=false;
            exit;
            end;
          end;
		   2: begin
   Form1.pbsm1.Progress:=0;
		      result:=false;
          exit;
		      end;
		   3: begin
   Form1.pbsm1.Progress:=0;
		      result:=false;
          exit;
			    end;
		   end;
        end;
      F.Write(FbusStr[19], $400);
      readedlen:=readedlen+$400;
     // form1._msg('read next block at : '+inttostr(readedlen));
      bx:=bx+$01;
      if bx=$48 then begin
        bx:=$40;
      end;
      i:=i-1;
      Application.ProcessMessages;
	   case info of
      1: Form1.pb1.Progress:=Form1.pb1.Progress+1;
      2: Form1.pbsm1.Progress:=Form1.pbsm1.Progress+1;
	    3: Application.ProcessMessages;
	   end;
	  Application.ProcessMessages;
	end;

   if ostlen>0 then begin
    // form1._msg('Reading last block at : '+inttostr(readedlen));
     Application.ProcessMessages;
      hider:='';
     hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($12)+chr($05)+chr($0D)+chr(0)+chr($01)+chr($F0)+chr($0C)+chr($20)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr($41);
     framelen:=Length(hider)-6;
     word((@hider[5])^):=framelen;
     WordSwap(@hider[5]);
     DWord((@hider[21])^):=readedlen;
     DWordSwap(@hider[21]);
      FbusRunCommand(@hider[1], Length(hider));
      a4:=buftohexstr(@FbusStr[19],Length(FbusStr)-18);
     F.Write(FbusStr[19], ostlen);
     //form1._msg(BufToHexStr(@FbusStr[19], Length(FbusStr)));
      Application.ProcessMessages;
	  case info of
      1: Form1.pb1.Progress:=Form1.pb1.Progress+1;
      2: Form1.pbsm1.Progress:=Form1.pbsm1.Progress+1;
	    3: Application.ProcessMessages;
	  end;
	  Application.ProcessMessages;
   end;
   //finalaze frame
   hider:='';
    hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($12)+chr($05)+chr($0D)+chr(0)+chr($01)+chr($F0)+chr($0C)+chr($20)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr($41);
     framelen:=Length(hider)-6;
     word((@hider[5])^):=framelen;
     WordSwap(@hider[5]);
     DWord((@hider[21])^):=readedlen;
     DWordSwap(@hider[21]);
      FbusRunCommand(@hider[1], Length(hider));
      scheck:=buftohexstr(@Fbusstr[1],Length(FbusStr));
   // form1._msg('Last blk data : '+scheck);
    if scheck<>'' then result:=False else result:=True;
   Form1.pbsm1.Progress:=0;
 end
 else begin
  ostlen:=len mod $400;
  if info=1 then form1._msg('Will read 1 block...');
  hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($11)+chr(0)+chr($0D)+chr(0)+chr($02)+chr($F5)+chr(0)+chr(0)+chr(0)+chr($80)+chr(Length(filewithpath));
 s:=hider+s2;
 s3:=chr($F8)+chr($08)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr($01)+chr(bx);
 word((@s3[5])^):=ostlen;
 wordswap(@s[5]);
 s:=s+s3;
 framelen:=Length(s)-6;
 word((@s[5])^):=framelen;
 WordSwap(@s[5]);
 pathlen:=length(s2)+6;
 word((@s[15])^):=pathlen;
 WordSwap(@s[15]);
 FbusRunCommand(@s[1], Length(s));
 a4:=buftohexstr(@FbusStr[1],Length(FbusStr));
 F.Write(FbusStr[19], ostlen);
     //finalize frame
     hider:='';
     hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($12)+chr($05)+chr($0D)+chr(0)+chr($01)+chr($F0)+chr($0C)+chr($20)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr($41);
     framelen:=Length(hider)-6;
     word((@hider[5])^):=framelen;
     WordSwap(@hider[5]);
     DWord((@hider[21])^):=readedlen;
     DWordSwap(@hider[21]);
      FbusRunCommand(@hider[1], Length(hider));
      a4:=buftohexstr(@FbusStr[1],Length(FbusStr));
    scheck:=buftohexstr(@Fbusstr[1],Length(FbusStr));
   // form1._msg('Last blk data : '+scheck);
    if scheck<>'' then result:=False else result:=True;
   Form1.pbsm1.Progress:=0;
 end;
end;

function fbuststarttest():string;
var
  a,s,s1,s2,s3,s4:string;
  i:integer;
begin
  s2:='';
fbussendsynk;
Sleep(50);
{FbusRunCommand(@Ftest1st, length(Ftest1st));
Application.ProcessMessages;
//fbussendsynk;
FbusRunCommand(@Ftestst2, length(Ftestst2));
Application.ProcessMessages;
//fbussendsynk;
FbusRunCommand(@Ftestst3, length(Ftestst3));
Application.ProcessMessages;
fbussendsynk;
FbusRunCommand(@Ftestcol, length(Ftestcol));
s:=buftohexstr(@Fbusstr[1], length(FbusStr)-2);
s2:=Hex2Chr(s);
Application.ProcessMessages;
//fbussendsynk;
FbusRunCommand(@Faftertest, length(Faftertest));
}

Purge_USB_Device_In;
FbusRunCommand(@newFtest1, length(newFtest1));
s2:=buftohexstr(@Fbusstr[1], length(FbusStr)-2);
Application.ProcessMessages;

Purge_USB_Device_In;
FbusRunCommand(@newFtestcol, length(newFtestcol));
s:=buftohexstr(@Fbusstr[1], length(FbusStr)-2);
s2:=Hex2Chr(s);

result:=s2;
end;

function FSelftestitem(testid:string):string;
var
  res:string;
  testres:DWORD;
begin
 Ftesting[16]:=Str2Byte(testid);
 Application.ProcessMessages;
 fbusstr:='';
 fbussendsynk;
 fBusRunCommand(@Ftesting, Length(Ftesting));
 try
 DWordSwap(@FbusAnsb[8]);
 testres:=dword((@FbusAnsb[8])^);
 except
 testres:=$00000100;
 end;
 try
 case testres of
 $00010000:res:='PASSED';
 $00010A01:res:='->ERROR';
 $00000100:res:='MINOR';
 $00010001: begin
            case fbusansb[15] of
            $03:res:='NOT EXECUTED';
            $04:res:='NOT RUN';
            $01:res:='->ERROR';
            $0D:res:='MINOR';
            else res:='UNKNOW';
            end;
            end;
  else res:='MINOR';
  end;
  except
    res:='MINOR';
  end;
  if res='MINOR' then
  begin
   Ftesting[16]:=Str2Byte(testid);
   fbussendsynk;
   stopfbusop;
   Sleep(150);
   Application.ProcessMessages;
   fbusstr:='';
   fbussendsynk;
   Sleep(50);
   Application.ProcessMessages;
   fBusRunCommand(@Ftesting, Length(Ftesting));
   try
   DWordSwap(@FbusAnsb[8]);
   testres:=dword((@FbusAnsb[8])^);
   except
   testres:=$00000100;
   end;
   try
   case testres of
   $00010000:res:='PASSED';
   $00010A01:res:='->ERROR';
   $00000100:res:='MINOR';
   $00010001: begin
            case fbusansb[15] of
            $03:res:='NOT EXECUTED';
            $04:res:='NOT RUN';
            $01:res:='->ERROR';
            $0D:res:='MINOR';
            else res:='UNKNOW';
            end;
            end;
   else res:='MINOR';
   end;
   except
     res:='MINOR';
   end;

  end;
    result:=res;
 end;


function fbusgettemp():integer;
begin
  try
 FbusSendSynk;
 FbusRunCommand(@Getbtemp,Length(Getbtemp));
 result:=hextoint(buftohexstr(@fbusstr[9], 2));
 except
 result:=0;
 end;
end;

function fbusgetintsize():integer;
begin
 try
 FbusRunCommand(@intsizeind,Length(intsizeind));
 result:=hextoint(buftohexstr(@fbusstr[9], 2));
 except
 result:=0;
 end;
end;

function fbusgetbbat():integer;
begin
FbusSendSynk;
 FbusRunCommand(@getbbat,Length(getbbat));
 result:=hextoint(buftohexstr(@fbusstr[9], 2));
end;

function restrtphone(mode:integer):string;
var
  b:Byte;
begin
  FbusSendSynk;
  case mode of
  1:b:=$01;
  2:b:=$04;
  3:b:=$05;
  END;
  rst2[10]:=b;
  FbusRunCommand(@rst1, Length(rst1));
  sleep(100);
  FbusSendSynk;
  FbusRunCommand(@rst2, Length(rst2));
  sleep(100);
  FbusRunCommand(@rst3, Length(rst3));
  end;

function restrtphone2():string;
begin
  FbusSendSynk;
  FbusRunCommand(@rst31, Length(rst31));
  FbusRunCommand(@rst33, Length(rst33));
  FbusRunCommand(@rst34, Length(rst34));
  FbusRunCommand(@rst35, Length(rst35));
  FbusRunCommand(@rst36, Length(rst36));
  FbusRunCommand(@rst37, Length(rst37));
  FbusRunCommand(@rst38, Length(rst38));
  FbusRunCommand(@rst32, Length(rst32));
  Sleep(200);
  FbusRunCommand(@rst4, Length(rst4));
end;

function FbusGetS40FSize(fullpath:string):integer;
var
  hider,s,s2:string;
  framelen:Word;
  i:integer;
  res:string;
begin
          FbusSendSynk;
 s:='';  hider:='';
hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr($01)+chr($6C);
hider:=hider+PathConv(fullpath)+chr(0)+chr(0)+chr($01)+chr(0);
framelen:=Length(hider)-6;
 word((@hider[5])^):=framelen;
 WordSwap(@hider[5]);
//Form1._msg(BufToHexStr(@hider[1],Length(hider)));
FbusRunLongCommand(@hider[1],Length(hider));
res:=BufToHexStr(@fbusstr[1], Length(fbusstr));
//form1._msg(res);
//form1._msg(copy(res,21,8));
result:=hextoint(copy(res,21,8));
end;

function fbusgetfileS40(F:TMemorystream;fullpath:string;len:Integer;info:Integer):Boolean;
var
  hider,s,s2:string;
  framelen:Word;
  i,i1,ilen,ostlen:integer;
  res:string;
  controlpacket,readedlen:DWORD;
  packet,curread:Word;
begin
  FbusSendSynk;
 s:=''; hider:='';
hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr($02)+chr($72)+chr(0)+chr($01);
hider:=hider+PathConv(fullpath)+chr($01)+chr(0);
framelen:=Length(hider)-6;
 word((@hider[5])^):=framelen;
 WordSwap(@hider[5]);
FbusRunLongCommand(@hider[1],Length(hider));
//form1._msg(Byte2Str(fbusansB[12])+Byte2Str(fbusansB[13])+Byte2Str(fbusansB[14])+Byte2Str(fbusansB[15]));
Dwordswap(@fbusAnsB[12]);
controlpacket:=Dword((@FbusAnsB[12])^);

if controlpacket<>$FFFFFFFF then begin
//form1._msg(IntToStr(controlpacket));
//form1._msg('CSkey recived Ok!');
hider:='';
curread:=0;
readedlen:=0;
res:='';
case info of
1: Form1.pb1.Progress:=0;
2: form1.pbsm1.progress:=0;
3: Application.ProcessMessages;
end;
ostlen:=len mod $4000;
  if Len>$4000 then begin
  ilen:=Len div $4000;
  case info of
  1: Form1.pb1.MaxValue:=ilen;
  2: Form1.pbsm1.MaxValue:=ilen;
  3: Application.ProcessMessages;
  end;
  curread:=$4000;
  Application.ProcessMessages;
  if info=1 then form1._msg('Will read '+inttostr(ilen)+' blocks...');
   for i1:=1 to ilen do
   begin
   hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($5E)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr($47);
   framelen:=Length(hider)-6;
   word((@hider[5])^):=framelen;
   WordSwap(@hider[5]);
   Dword((@hider[13])^):=controlpacket;
   DWordSwap(@hider[13]);
   dword((@hider[17])^):=readedlen;
   DWordSwap(@hider[17]);
   Word((@hider[23])^):=curread;
   WordSwap(@hider[23]);
   Word((@hider[27])^):=curread;
  WordSwap(@hider[27]);
   fbusruncommand(@hider[1],Length(hider));
   try
   res:=BufToHexStr(@Fbusstr[11],$4000);
   F.Write(FbusStr[11], $4000);
   readedlen:=readedlen+$4000;
   Application.ProcessMessages;
   case info of
   1: Form1.pb1.Progress:=Form1.pb1.Progress+1;
   2: form1.pbsm1.progress:=Form1.pbsm1.Progress+1;
   3: Application.ProcessMessages;
   end;
   except
   form1._msg('Error while reading... ');
   result:=false;
   case info of
   1: Form1.pb1.Progress:=0;
   2: form1.pbsm1.progress:=0;
   3: Application.ProcessMessages;
   end;
   exit;
   end;
   end ;
     if ostlen>0 then begin
    curread:=ostlen;
    hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($5E)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr($47);
    framelen:=Length(hider)-6;
    word((@hider[5])^):=framelen;
    WordSwap(@hider[5]);
    Dword((@hider[13])^):=controlpacket;
    DWordSwap(@hider[13]);
    dword((@hider[17])^):=readedlen;
    DWordSwap(@hider[17]);
    Word((@hider[23])^):=curread;
    WordSwap(@hider[23]);
    Word((@hider[27])^):=curread;
    WordSwap(@hider[27]);
    fbusruncommand(@hider[1],Length(hider));
    try
      res:=BufToHexStr(@Fbusstr[11],ostlen);
    F.Write(FbusStr[11], ostlen);
    readedlen:=readedlen+ostlen;
    except
    form1._msg('Error while reading...');
    result:=false;
     case info of
     1: Form1.pb1.Progress:=0;
     2: form1.pbsm1.progress:=0;
     3: Application.ProcessMessages;
     end;
	exit;
    end;
    end;
  end else begin
    curread:=len;
    hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($5E)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr($47);
    framelen:=Length(hider)-6;
    word((@hider[5])^):=framelen;
    WordSwap(@hider[5]);
    Dword((@hider[13])^):=controlpacket;
    DWordSwap(@hider[13]);
    dword((@hider[17])^):=readedlen;
    DWordSwap(@hider[17]);
    Word((@hider[23])^):=curread;
    WordSwap(@hider[23]);
    Word((@hider[27])^):=curread;
    WordSwap(@hider[27]);
    fbusruncommand(@hider[1],Length(hider));
    try
      res:=BufToHexStr(@Fbusstr[11],ostlen);
    F.Write(FbusStr[11], ostlen);
    readedlen:=readedlen+ostlen;
    except
    form1._msg('Error while reading...');
    result:=false;
     case info of
     1: Form1.pb1.Progress:=0;
     2: form1.pbsm1.progress:=0;
     3: Application.ProcessMessages;
     end;
	exit;
    end;
    end;
   Application.ProcessMessages;
   //form1._msg('Finalising read...');
   readfinalizeS40[9]:=$66;
   DWord((@readfinalizeS40[12])^):=controlpacket;
   DWordSwap(@readfinalizeS40[12]);
   FbusRunCommand(@readfinalizeS40,Length(readfinalizeS40));
   //form1._msg(BufToHexStr(@fbusstr[1],Length(FbusStr)));
   DWord((@readfinalizeS40[12])^):=controlpacket;
   DWordSwap(@readfinalizeS40[12]);
   readfinalizeS40[9]:=$74;
   FbusRunCommand(@readfinalizeS40,Length(readfinalizeS40));
   //form1._msg(BufToHexStr(@fbusstr[1],Length(FbusStr)));
   Form1.pbsm1.Progress:=0;

result:=True;
end
else begin
if info=1 then form1._msg('Error on CSkey...');
result:=false;
end;
end;

function PathConv(path:string):string;
var
Len:integer;
s:string;
sw:WideString;
begin
          sw:=UTF8Decode(path);
          Len:=(Length(sw) shl 1)+2;
          Result:='';
          s:='';
          SetLength(s,2);
          word ((@s[1])^):=Len;
          WordSwap(@s[1]);
          SetLength(Result,Len+2);
          BufCopySwapWord(@sw[1],@Result[1],Len);
          Result:=s+Result;
end;

function fbusscandrives():string;
begin
          FbusSendSynk;
  result:='';
  fbusruncommand(@fpref,Length(fpref));
  fbusruncommand(@fbuss60getdrv, Length(fbuss60getdrv));
  result:=buftohexstr(@fbusstr[1], Length(FbusStr));
  end;

function s60f1st(drive:Byte):string;
var
  a,s:string;
begin
  FbusSendSynk;;
  fbs60format1st[11]:=drive;
  fbusruncommand(@fbs60format1st,Length(fbs60format1st));
  result:=BufToHexStr(@fbusstr[1],Length(FbusStr));
end;

function fbs60cyclef (drive:Byte):string;
var
  b,bn,bfr:Byte;
begin
  bn:=$02;
  bfr:=$42;
  fbs60formatcycle[11]:=drive;
  repeat
    begin
  fbusruncommand(@fbs60formatcycle,Length(fbs60formatcycle));
  fbs60formatcycle[8]:=bn;
  bn:=bn+$01;
  if bn=$FF then bn:=$01;
  fbs60formatcycle[17]:=bfr;
  bfr:=bfr+$01;
  if bfr=$48 then bfr:=$40;
  b:=fbusansB[11];
  end;
  until b<>$4C;
  if b=$4B then result:='Ok' else result:='Error!';
end;

function fbusgetdrives40():string;
var
  s,s1:string;
begin
  FbusSendSynk;
  s1:='';s:='';
FbusRunCommand(@Flistdrv1, length(flistdrv1));
FbusRunCommand(@Flistdrv2, length(flistdrv2));
  FbusSendSynk;
FbusRunCommand(@Flistdrv, length(flistdrv));
s:=BufToHexStr(@Fbusstr[6],Length(FbusStr)-4);
if Pos('43',s)>0 then s1:=s1+'C';
if Pos('53',s)>0 then s1:=s1+'S';
result:=s1;
end;

function s40frmtdrv(drv:string):string;
var
  s:string;
begin
  if drv='C' then
  Fs40FormatDrv[11]:=$43;
  if drv='S' then
  Fs40FormatDrv[11]:=$53;
  FbusSendSynk;
FbusRunCommand(@Fs40FormatDrv,Length(Fs40FormatDrv));
s:=BufToHexStr(@Fbusstr[1],Length(FbusStr));
if Pos('79',s)>0 then result:='Ok' else result:='Error';
end;

function fbusgetdrives60():string;
var
  s,s1:string;
begin
  //FbusSendSynk;
  s:='';s1:='';
FbusRunCommand(@Flistdrv60, length(Flistdrv60));
  //FbusSendSynk;
FbusRunCommand(@FgetS60drv, length(FgetS60drv));
try
s:=BufToHexStr(@Fbusstr[1],Length(FbusStr));
except
s:='';
end;
if Pos('43FF',s)>0 then s1:=s1+'C';
if Pos('44FF',s)>0 then s1:=s1+'D';
if Pos('53FF',s)>0 then s1:=s1+'S';
if Pos('59FF',s)>0 then s1:=s1+'Y';
result:=s1;
end;

function fncksend(code:string;level:Integer):string;
var
  schk:string;
  i:Integer;
  sw:WideString;
begin
          FbusSendSynk;
          Result:='Error';
          sw:=UTF8Decode(code);
          i:=(Length(sw) shl 1)+2;
          BufCopySwapWord(@sw[1],@FNCKput[20],i);
          FNCKput[10]:=level;
  FbusRuncommand(@FNCKput, Length(FNCKput));
  try
  i:=Ord(FbusStr[5]);
  except
  i:=8;
  end;
  case i of
 0: result:='Unlock code Accepted! :)';
 8: result:='Bad Code... :(';
 $0C: result:='Retries blocked! Counter full! :(';
 9: result:='Phone already unlocked! :)';
 end;
end;

function WD2listdir(path:string):integer;
var
  s,s2,hider:string;
  framelen,pathlen:Word;
  datalen:DWORD;
  i:Integer;
  data,data2:string;
begin
  FbusSendSynk;
  result:=0;
  Form1.pbsm1.MaxValue:=47;
  Form1.pbsm1.progress:=0;
s:='';hider:='';s2:=''; data2:='';
hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($11)+chr($06)+chr($0B)+chr(0)+chr($01)+chr($07)+chr($14)+chr(Length(path))+chr($00);
s:=hider+path+chr(0)+chr(0)+chr($01)+Chr($40);
framelen:=Length(s)-6;
word((@s[5])^):=framelen;
WordSwap(@s[5]);
i:=1;
 FbusRunCommand(@s[1], Length(s));
 data:=BufToHexStr(@fbusstr[1],Length(FbusStr));
 if Length(data)<10 then begin
   result:=0;
   Exit;
   end;
 repeat
   begin
   fbusstr:='';
    if not FbusSendAsk then begin
     if data2<>'' then begin
     result:=hextoint(Copy(data2,21,8));
      end
     else result:=0;
     Form1.pbsm1.progress:=0;
     exit;
    end;
    if not FbusAck then begin
     if data2<>'' then begin
     result:=hextoint(Copy(data2,21,8));
      end
     else result:=0;
     Form1.pbsm1.progress:=0;
     exit;
    end;
    if not FbusAns then begin
     if data2<>'' then begin
     result:=hextoint(Copy(data2,21,8));
      end
     else result:=0;
     Form1.pbsm1.progress:=0;
     exit;

    end;
   data:=BufToHexStr(@fbusstr[1],Length(FbusStr));
  Application.ProcessMessages;
  Form1.pbsm1.progress:=Form1.pbsm1.progress+1;
  ///form1.lst1.items.add(data);
  i:=i+1;
  if Pos('436F6E74616374732E636462',data)>0 then data2:=data;
   end;
    //Form1._msg(Byte2Str(FbusAnsB[10]));
 until FbusAnsB[10]=$0F ;
 Form1._msg('Scan done, processing data...');
 if data2<>'' then begin
   Form1._msg('Some data found, wait, checking...');
   Form1.pbsm1.progress:=0;
   Form1.pbsm1.MaxValue:=100;
   result:=hextoint(Copy(data2,21,8));
   end
   else result:=0;
    Form1.pbsm1.progress:=0;
 end;


function fbusgetfileWd2nd(F:TMemoryStream;fullpath:string;len:Integer):boolean;
var
  s,s2,hider:string;
  framelen,pathlen:Word;
  datalen:DWORD;
  curlen:word;
  z:Byte;
  i:integer;
begin
z:=$40;
Form1.pb1.progress:=0;
Form1.pb1.maxvalue:=100;
i:=0;
s:='';hider:='';s2:='';
hider:=chr($1E)+chr($00)+chr($10)+chr($58)+chr($00)+chr($00)+chr($00)+chr($11)+chr($0E)+chr($0D)+chr($10)+chr($01)+chr($07)+chr($20)+chr($0E)+chr($0C);
//hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($10)+chr($0C)+chr($0B)+chr(0)+chr($01)+chr($07)+chr($14)+chr($0E)+chr($0C);
s:=hider+fullpath+chr(0)+chr(0)+chr($01)+Chr($40);
framelen:=Length(s)-6;
word((@s[5])^):=framelen;
WordSwap(@s[5]);
     FbusSendSynk;
     try
      curlen:=0;
      datalen:=0;
      FbusRunCommand(@s[1], Length(s));
      curlen:=hextoint(BufToHexStr(@FbusStr[13],2));
      //form1._msg(inttostr(curlen));
      F.Write(FbusStr[19],curlen);
      Application.ProcessMessages;
      form1._msg('1st blk OK....');
      datalen:=datalen+curlen;
      DWord((@WD2readcycle[16])^):=0;
      DWordSwap(@WD2readcycle[16]);
      z:=csbyte(z);
      WD2readcycle[21]:=z;
      Form1.pb1.progress:=1;
      i:=1;
      repeat
      begin
        if (FbusAnsB[5]=$2F) and (FbusAnsB[15]=$8F) then Form1._msg('-> Packet CS #1');
        if curlen<>$3D4 then begin Form1._msg('-> Packet CS #2'); break; end;
        //form1._msg(buftohexstr(@WD2readcycle, Length(WD2readcycle)));
        FbusRunCommand(@WD2readcycle, Length(WD2readcycle));
        curlen:=hextoint(BufToHexStr(@FbusStr[13],2));
        //form1._msg(inttostr(curlen));
       F.Write(FbusStr[19],curlen);
       DWord((@WD2readcycle[16])^):=datalen;
       DWordSwap(@WD2readcycle[16]);
       z:=csbyte(z);
       WD2readcycle[21]:=z;
       Application.ProcessMessages;
       Form1.pb1.progress:=Form1.pb1.progress+1;
       datalen:=datalen+curlen;
       i:=i+1;
       end;
      until  FbusAnsB[5]=$44 ;
     Form1.pb1.progress:=100;
       if i=1 then begin
       form1._msg('-> Major read error [damaged data], nothing to save') ;
        Form1.pb1.MaxValue:=100;
        Form1.pb1.progress:=0;
        Result:=false;
        exit;
       end;
     if FbusAnsB[5]=$44 then form1._msg('-> Reading done! :)') else form1._msg('-> Minor [maybe data Ok], save collected data') ;
     form1._msg('Readed : '+inttostr(i)+' block(s)');
     Form1.pb1.MaxValue:=100;
     Form1.pb1.progress:=0;
     Result:=True;
     except
      begin
       if i>2 then form1._msg('-> Major read error [unexcepted data], try to save '+inttostr(i)+' block(s)') else form1._msg('-> Major read error [unexcepted data], nothing to save') ;
      Form1.pb1.MaxValue:=100;
      Form1.pb1.progress:=0;
      result:=false;
      end;
     end;
end;

function FbusWriteFileS60(InFile:TMemoryStream;filewithpath:string;info:integer):boolean;
var
  Ms:TmemoryStream;
  framelen,pathlen,bufsent,len,ost:word;
  Sentlen,filelen,ostflen:Dword;
  intlen,i,i2,ilen:integer;
  hider,s,s1,s2,s3,posthider:string;
begin
   FbusSendSynk;
s:=''; s2:=''; s3:=''; hider:='';
sentlen:=0;
  //создаем поток
Ms:=TmemoryStream.Create;
Ms.LoadfromStream(inFile);
 //получаем размер файла
 filelen:=ms.size;
 intlen:=ms.size;
 // выводим для информации
 if info=1 then form1._msg('File size is : '+inttostr(intlen)+' bytes');
 //считаем блоки и остаток
 ilen:=filelen div $400;
 ost:=filelen mod $400;
 case info of
 1: begin
    Form1.pb1.Maxvalue:=filelen div $400;
    if ost>0 then Form1.pb1.Maxvalue:=Form1.pb1.Maxvalue+1;
    end;
 2: begin
    Form1.pbsm1.Maxvalue:=filelen div $400;
    if ost>0 then Form1.pbsm1.Maxvalue:=Form1.pbsm1.Maxvalue+1;
    end;
 3: Begin
    Application.ProcessMessages;
    end;
 end;
 //создаем заголовок
  hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($12)+chr($05)+chr($0F)+chr(0)+chr($04)+chr($F5)+chr(0)+chr(0)+chr(0)+chr($80)+chr(Length(filewithpath));
  s2:=Copy(PathConv(filewithpath),3,Length(PathConv(filewithpath))-4);
  case info of
  1: begin
    form1._msg('Will write '+inttostr(ilen+1)+' blocks...');
    form1._msg('Patch header... Writing data...');
    end;
  2: Application.ProcessMessages;
  3: Application.ProcessMessages;
  end;
  if ilen>0 then begin   // Пишем блоки и все, что больше 1024 байт
     s:=hider+s2+chr($04)+chr($04)+chr($0C)+chr($0E)+chr(0)+chr(0)+chr($04)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0);
     SetLength(s,Length(s)+1024);  //сдвигаем длину строки
     Ms.read(s[Length(hider+s2)+13],$400); // читаем с потока в строку
     ////F8 08 00 00 04 00 00 01 F1 04 01 00 01 04  - добавляем постхидер
     s3:=chr($F8)+chr($08)+chr(0)+chr(0)+chr($04)+chr(0)+chr(0)+chr($01)+chr($F1)+chr($04)+chr($01)+chr($00)+chr(01)+chr($04);
     s:=s+s3;
     // строка создана
     framelen:=Length(s)-6;
     word((@s[5])^):=framelen;
     WordSwap(@s[5]);
     pathlen:=length(s2)+6;
     word((@s[15])^):=pathlen;
     WordSwap(@s[15]);
     FbusRunlongCommand(@s[1], Length(s));
     //form1._msg(buftohexstr(@Fbusstr[1], Length(fbusstr)));
     dwordswap(@fbusansb[20]);
     sentlen:=dword((@fbusansb[20])^);
     Application.ProcessMessages;
     if sentlen=$400 then // Если отправка удалась - то должно быть 1024 байта
                          // Заголовок записан - теперь понеслась! ^^
                           begin
                           Application.ProcessMessages;
                             case info of
                             1: Form1.pb1.Progress:=1;
                             2: Form1.pbsm1.Progress:=1;
                             3: Application.ProcessMessages;
                             end;
                           Application.ProcessMessages;
                           if info=1 then form1._msg('HDR:[Ok]');
                           while ilen<>1 do
                                 begin
                                  Application.ProcessMessages;
                                  s:=''; hider:='';
                                  SetLength(s,24);
                                  hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr($7A)+chr(0)+chr($12)+chr($05)+chr($0F)+chr(0)+chr($01)+chr($04)+chr($04)+chr($0C)+chr($0E)+chr(0)+chr(0)+chr($04)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0);
                                  SetLength(s,1048);
                                  s:=hider+s;
                                  Ms.read(s[Length(hider)+1],$400);
                                  Dword((@s[21])^):=sentlen;
                                  DWordSwap(@s[21]);
                                  FbusRunLongCommand(@s[1],Length(s));
                                //  form1._msg(BufToHexStr(@fbusstr[1], Length(Fbusstr)));  // для визуальной проверки целостности
                                  DWordSwap(@Fbusansb[20]);
                                  Sentlen:=dword((@Fbusansb[20])^);
                                  ilen:=ilen-1;
                                  Application.ProcessMessages;
                                   case info of
                                   1: Form1.pb1.Progress:=Form1.pb1.Progress+1;
                                   2: Form1.pbsm1.Progress:=Form1.pbsm1.Progress+1;
                                   3: Application.ProcessMessages;
                                   end;
                                  Application.ProcessMessages;
                                 end;
                           end
     else
     begin
     result:=False;
     Ms.Free;
       case info of
       1: Form1.pb1.Progress:=0;
       2: Form1.pbsm1.Progress:=0;
       3: Application.ProcessMessages;
       end;
     Form1._msg('Error while writing : CRC not match, try restart phone');
     Exit;
     end;
   if ost>0 then begin   // Если остаток больше нуля - то рисуем последний блок
     //Form1._msg('Exist last blk)');
     s:=''; hider:='';
     SetLength(s,24);
     hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($12)+chr($05)+chr($0F)+chr(0)+chr($01)+chr($04)+chr(0)+chr(0)+chr($0F)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0);
     SetLength(s,ost);
     s:=hider+s;
     Ms.read(s[Length(hider)+1],ost);
     s:=s+chr(0)+chr($01)+chr(0);
     word((@s[5])^):=length(s)-6;
     wordswap(@s[5]);
     word((@s[14])^):=ost+$C;  // Считаем т.н. CRC последнего блока - взял общее между всеми вариантами (B,C,D,F)
     Wordswap(@s[14]);
     word((@s[19])^):=ost;  // размер последнего кусочка
     WordSwap(@s[19]);
     Dword((@s[21])^):=sentlen;  // с какой позиции читаем
     DWordSwap(@s[21]);
     fbusrunlongCommand(@s[1],length(s));
     //form1._msg(buftohexstr(@Fbusstr[1],length(fbusstr)));
     DWordSwap(@FbusansB[20]);
     sentlen:=dword((@FbusAnsb[20])^);
     Application.ProcessMessages;
        case info of
        1: Form1.pb1.Progress:=Form1.pb1.Progress+1;
        2: Form1.pbsm1.Progress:=Form1.pbsm1.Progress+1;
        3: Application.ProcessMessages;
        end;
     Application.ProcessMessages;
   end;
  end
  else begin     // Пишем все, что меньше 1024 байт
     posthider:=''; hider:=''; pathlen:=0; s2:='';
   for i:=1 to Length(filewithpath) do s2:=s2+Chr(0)+filewithpath[i];
   pathlen:=Length(s2)+6;
   hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($12)+chr($05)+chr($0F)+chr(0)+chr($04)+chr($F5)+chr(0)+chr(0)+chr(0)+chr($80)+chr(Length(filewithpath));
  // form1._msg('Will write 1 block...');
   Application.ProcessMessages;
   posthider:=chr($04)+chr(0)+chr(0)+chr($0F)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0);
   word((@posthider[2])^):=ost+$D;
   wordswap(@posthider[2]);
   Dword((@posthider[5])^):=ost;
   DWordSwap(@posthider[5]);
   s2:=s2+posthider;
   s:=hider+s2;
   SetLength(s,Length(s)+ost);
   Ms.read(s[Length(hider+s2)+1],ost);
   s3:=chr(0)+chr($F8)+chr($08)+chr(0)+chr(0)+chr($04)+chr(0)+chr(0)+chr($01)+chr($F1)+chr($04)+chr($01)+chr($00)+chr(01)+chr($04);
   s:=s+s3;
   //заголовок создан
   framelen:=Length(s)-6;
     word((@s[5])^):=framelen;
     WordSwap(@s[5]);
     word((@s[15])^):=pathlen;
     WordSwap(@s[15]);
     FbusRunlongCommand(@s[1], Length(s));
     //form1._msg(buftohexstr(@Fbusstr[1], Length(fbusstr)));
     dwordswap(@fbusansb[20]);
     sentlen:=dword((@fbusansb[20])^);
   Application.ProcessMessages;
  end;
 if Sentlen=filelen then result:=True // Если размер отпрпавленных данных равен размеру данных - то все Ок, иначе - ошибка где-то.
 else result:=False;
  case info of
  1: Form1.pb1.Progress:=0;
  2: Form1.pbsm1.Progress:=0;
  3: Application.ProcessMessages;
  end;
 Ms.free;
 end;


function fbusdeletefiles60(filewithpath:string):Boolean;
var
  s,hider,s2:string;
  i2:integer;
  pathlen,framelen:Word;
begin
  FbusSendSynk;
  hider:=''; s:=''; s2:='';
  hider:=chr($1E)+chr(0)+chr($10)+chr($58)+chr(0)+chr(0)+chr(0)+chr($12)+chr($05)+chr($15)+chr($01)+chr($01)+chr($F5)+chr(0)+chr(0)+chr(0)+chr($80)+chr(Length(filewithpath));
  s2:=Copy(PathConv(filewithpath),3,Length(PathConv(filewithpath))-4);
  s:=hider+s2+chr(0)+chr(0)+chr($01)+chr(0);
  pathlen:=Length(s2)+8;
  framelen:=Length(s)-6;
     word((@s[5])^):=framelen;
     WordSwap(@s[5]);
     word((@s[15])^):=pathlen;
     WordSwap(@s[15]);
     FbusRunlongCommand(@s[1], Length(s));
  //form1._msg(buftohexstr(@Fbusstr[1], Length(fbusstr)));
  case fbusansb[10] of
  $00: begin
       //form1._msg('Delete Ok!');
       result:=true;
       end;
  $46: begin
       form1._msg('No data, delete skipped');
       result:=true;
       end;
  $40: begin
       Form1._msg('Acces denined! Restart phone and try again!');
       result:=false;
       end
   else result:=false;
  end;
  end;

function FbusDelFileS40(filepath:string):Boolean;
var
 s,hider,s2:string;
  i2:integer;
  pathlen,framelen:Word;
begin
  FbusSendSynk;
  hider:=''; s:=''; s2:=''; result:=false;
  // hider 1E 00 10 6D 00 60 00 12 0B 62 00 2B
  s2:=Copy(PathConv(filepath),3,Length(PathConv(filepath))-4);
  hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($62)+chr(0)+chr(Length(filepath)+1);
  hider:=hider+s2+chr(0)+chr(0)+chr($01)+chr($00);
  framelen:=Length(hider)-6;
  word((@hider[5])^):=framelen;
  WordSwap(@hider[5]);
   FbusRunlongCommand(@hider[1], Length(hider));
  // Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
  // Form1._msg(Byte2Str(fbusansb[9])+Byte2Str(fbusansb[10]));
  case fbusansb[10] of
  $00: begin
       //form1._msg('Delete Ok!');
       result:=true;
       end;
  $06: begin
       form1._msg('No data, delete skipped');
       result:=true;
       end;
  $03: begin
       Form1._msg('Acces denined! Restart phone and try again!');
       result:=false;
       end
   else result:=false;
  end;
end;

function FbusWriteFileS40(InFile:TMemoryStream;filewithpath:string;info:integer):boolean;
var
  Ms:TmemoryStream;
  framelen,pathlen,bufsent,len,ost:word;
  Sentlen,filelen,ostflen,sessionkey:Dword;
  intlen,i,i2,ilen:integer;
  hider,s,s1,s2,s3,posthider:string;
  b:byte;
begin
FbusSendSynk;
s:=''; s2:=''; s3:=''; hider:='';
sentlen:=0;
  //создаем поток
Ms:=TmemoryStream.Create;
Ms.LoadfromStream(inFile);
 //получаем размер файла
 filelen:=ms.size;
 intlen:=ms.size;
 // выводим для информации
 form1.pbsm1.Progress:=0;
 Application.ProcessMessages;
if info=1 then form1._msg('File size is : '+inttostr(intlen)+' bytes');
 //считаем блоки и остаток
 ilen:=filelen div $2000;
 ost:=filelen mod $2000;
   case info of
   1: begin
      Form1.pb1.Maxvalue:=filelen div $2000;
      if ost>0 then Form1.pb1.Maxvalue:=Form1.pb1.Maxvalue+1;
      end;
   2: begin
      Form1.pbsm1.Maxvalue:=filelen div $2000;
      if ost>0 then Form1.pbsm1.Maxvalue:=Form1.pbsm1.Maxvalue+1;
      end;
   3: Begin
      Application.ProcessMessages;
      end;
   end;
 Application.ProcessMessages;
 //создаем заголовок
 //1E 00 10 6D 00 7A 00 12 23 72 31 01 00 3F +s2+ 00 00 01 00
  s2:=Copy(PathConv(filewithpath),3,Length(PathConv(filewithpath))-4);
  hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($72)+chr($31)+chr($01)+chr(0)+chr(0);
  s:=hider+s2+chr(0)+chr(0)+chr($01)+chr(0);
  framelen:=Length(s)-6;
  word((@s[5])^):=framelen;
  WordSwap(@s[5]);
  pathlen:=Length(filewithpath)+1;
  wordswap(@s[13]);
  word((@s[13])^):=pathlen;
  FbusRunlongCommand(@s[1], Length(s));
  //Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
  //Form1._msg(Byte2Str(fbusansb[11])+Byte2Str(fbusansb[12])+Byte2Str(fbusansb[13])+Byte2Str(fbusansb[14]));
  Application.ProcessMessages;
   try
     DwordSwap(@fbusansb[12]);
   sessionkey:=Dword((@fbusansb[12])^);
   except
   sessionkey:=$FFFFFFFF;
  end;
       if sessionkey=$FFFFFFFF then begin
       // form1._msg('Invalid CSkey! Can'+#39+'t write file!');
       result:=false;
        form1.pbsm1.Progress:=0;
       ms.free;
       exit;
       end;
  Application.ProcessMessages;
  try
    if ilen>0 then begin
    case info of
    1: form1._msg('Will write '+inttostr(ilen+1)+' blocks...');
    2: Application.ProcessMessages;
    3: Application.ProcessMessages;
    end;
     Application.ProcessMessages;
     b:=$01;
     for i2:=1 to ilen do
       begin
      hider:=''; s:='';
      hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($58)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($20)+chr(0);
      s:=hider;
      SetLength(s,Length(s)+$2000);
      Ms.read(s[Length(hider)+1],$2000);
      s:=s+chr(0)+chr(0);
      framelen:=Length(s)-6;
      word((@s[5])^):=framelen;
      WordSwap(@s[5]);
      Dword((@s[13])^):=sessionkey;
      DwordSwap(@s[13]);
      s[9]:=chr(b);
      b:=b+$01;
      FbusRunLongCommand(@s[1],Length(s));
     // Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
       if (fbusansb[9]=$59) and (fbusansb[10]=$00) then Application.ProcessMessages
       else begin
        // form1._msg('BLK write error!!!');
         result:=false;
         case info of
         1: Form1.pb1.Progress:=0;
         2: Form1.pbsm1.Progress:=0;
         3: Application.ProcessMessages;
         end;
		 ms.free;
         exit;
         end;
       Application.ProcessMessages;
        case info of
        1: Form1.pb1.Progress:=Form1.pb1.Progress+1;
        2: Form1.pbsm1.Progress:=Form1.pbsm1.Progress+1;
        3: Application.ProcessMessages;
        end;
        Application.ProcessMessages;
      end;
      if ost>0 then begin
      hider:=''; s:='';
      hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($58)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0);
      s:=hider;
      SetLength(s,Length(s)+ost);
      Ms.read(s[Length(hider)+1],ost);
      s:=s+chr(0)+chr(0);
      framelen:=Length(s)-6;
      word((@s[5])^):=framelen;
      WordSwap(@s[5]);
      Dword((@s[13])^):=sessionkey;
      DwordSwap(@s[13]);
      s[9]:=chr(b);
      word((@s[19])^):=ost;
      wordswap(@s[19]);
      b:=b+$01;
      FbusRunLongCommand(@s[1], Length(s));
       //Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
        if (fbusansb[9]=$59) and (fbusansb[10]=$00) then Application.ProcessMessages
        else begin
        // form1._msg('BLK write error!!!');
         result:=false;
         case info of
         1: Form1.pb1.Progress:=0;
         2: Form1.pbsm1.Progress:=0;
         3: Application.ProcessMessages;
         end;
		     ms.free;
         exit;
         end;
       Application.ProcessMessages;
        case info of
        1: Form1.pb1.Progress:=Form1.pb1.Progress+1;
        2: Form1.pbsm1.Progress:=Form1.pbsm1.Progress+1;
        3: Application.ProcessMessages;
        end;
        Application.ProcessMessages;
      end;
      Application.ProcessMessages;
      Ms.Free;
      hider:='';
      hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($66)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr(0);
      framelen:=Length(hider)-6;
      word((@hider[5])^):=framelen;
      WordSwap(@hider[5]);
      Dword((@hider[13])^):=sessionkey;
      DwordSwap(@hider[13]);
      hider[9]:=chr(b);
      FbusRunLongCommand(@hider[1], Length(hider));
      Application.ProcessMessages;
       //Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
       hider[10]:=chr($74);
       hider[9]:=chr(b+1);
       FbusRunLongCommand(@hider[1], Length(hider));
      //Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
       result:=true;
       Application.ProcessMessages;
        form1.pbsm1.Progress:=0;
     end
     else begin
    if info=1 then   form1._msg('Will write 1 block...');
       Application.ProcessMessages;
       b:=$01;
      hider:=''; s:='';
      hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($58)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0);
      s:=hider;
      SetLength(s,Length(s)+ost);
      Ms.read(s[Length(hider)+1],ost);
      s:=s+chr(0)+chr($01)+chr(0);
      framelen:=Length(s)-6;
      word((@s[5])^):=framelen;
      WordSwap(@s[5]);
      Dword((@s[13])^):=sessionkey;
      DwordSwap(@s[13]);
      s[9]:=chr(b);
      word((@s[19])^):=ost;
       wordswap(@s[19]);
       b:=b+$01;
       FbusRunLongCommand(@s[1], Length(s));
      // Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
        if (fbusansb[9]=$59) and (fbusansb[10]=$00) then Application.ProcessMessages
        else begin
         //form1._msg('BLK write error!!!');
         result:=false;
         case info of
         1: Form1.pb1.Progress:=0;
         2: Form1.pbsm1.Progress:=0;
         3: Application.ProcessMessages;
         end;
		     ms.free;
         exit;
         end;
       Application.ProcessMessages;
        case info of
        1: Form1.pb1.Progress:=Form1.pb1.Progress+1;
        2: Form1.pbsm1.Progress:=Form1.pbsm1.Progress+1;
        3: Application.ProcessMessages;
        end;
        Application.ProcessMessages;
       Ms.Free;
      hider:='';
      hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($66)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr(0)+chr($01)+chr(0);
      framelen:=Length(hider)-6;
      word((@hider[5])^):=framelen;
      WordSwap(@hider[5]);
      Dword((@hider[13])^):=sessionkey;
      DwordSwap(@hider[13]);
      hider[9]:=chr(b);
      FbusRunLongCommand(@hider[1], Length(hider));
      Application.ProcessMessages;
     //  Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
       hider[10]:=chr($74);
       hider[9]:=chr(b+1);
       FbusRunLongCommand(@hider[1], Length(hider));
     // Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
       result:=true;
       Application.ProcessMessages;
       form1.pbsm1.Progress:=0;
     end;
  except
  result:=False;
  form1.pbsm1.Progress:=0;
  end;
end;


function fbuschngrigths40(level:Word;filepath:string):Boolean;
var
 s,hider,s2:string;
  i2:integer;
  pathlen,framelen:Word;
begin
  FbusSendSynk;
  hider:=''; s:=''; s2:=''; result:=false;
  ///1E 00 10 6D 00 64 00 12 05 6E 00 2B 00 00 00 60    looks like it be a hider
  s2:=Copy(PathConv(filepath),3,Length(PathConv(filepath))-4);
  hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($12)+chr(0)+chr($6E)+chr(0)+chr(Length(filepath)+1)+chr(0)+chr(0)+chr(0)+chr(0);
  hider:=hider+s2+chr(0)+chr(0)+chr($01)+chr($00);
  //wordswap(@hider[15]);
  Word((@hider[16])^):=level;
  framelen:=Length(hider)-6;
  word((@hider[5])^):=framelen;
  WordSwap(@hider[5]);
   FbusRunlongCommand(@hider[1], Length(hider));
   if fbusansb[10]=$00 then  result:=True  else result:=false;
   //Form1._msg(BufToHexStr(@fbusstr[1], Length(FbusStr)));
   //Form1._msg(Byte2Str(fbusansb[9])+Byte2Str(fbusansb[10]));
end;

function FKBstest():Boolean;
begin
  FbusSendSynk;
  result:=False;
  FbusRunCommand(@S40KeybSt,Length(S40KeybSt));
  //form1._msg(BufToHexstr(@Fbusstr[1],Length(fbusstr)));
  if FbusAnsB[9]=$16 then begin
  if FbusAnsB[10]=$00 then result:=True else result:=False;
 end
 else result:=false;
  end;

function FKBtestEnd():Boolean;
begin
  result:=False;
  fbussendsynk;
  FbusRunCommand(@s40KeyBend,Length(s40KeyBend));
   //form1._msg(BufToHexstr(@Fbusstr[1],Length(fbusstr)));
    if fbusansb[10]=$00 then
    begin
    form1._msg('Released Ok!');
    result:=true;
    end;
   end;

function s40getKbstatus():Boolean;
var
  keycnt,i,i2:Integer;
  data,key,len:Word;
begin
 result:=False;
   fbussendsynk;
   FbusRunCommand(@s40checkkeys,Length(s40checkkeys));
   //form1._msg(BufToHexstr(@Fbusstr[1],Length(fbusstr)));
 if fbusansb[11]=$01 then begin
                keycnt:=HexToInt(Byte2Str(fbusansb[19]));
                Form1._msg('Total pressed keys : '+inttostr(keycnt));
                  if keycnt>0 then begin
                   i2:=20;
                   Form1._msg('');
                   for i:=1 to keycnt do
                   begin
                  WordSwap(@fbusansb[i2]);
                  key:=word((@fbusansb[i2])^);
                  WordSwap(@fbusansb[i2+2]);
                  data:=word((@fbusansb[i2+2])^);
                  form1._msg(getkeystatus(data)+' : '+getkeycode(key));
                  i2:=i2+4;
                   end;
                  Form1._msg('');
                  end else Form1._msg('No any key was pressed :(');
              result:=True;
        end
           else begin
            Form1._msg('No any key was pressed :(');
            Exit;
           end;

end;

function F60startkeybtest () : Boolean;
begin
 result:=false;
 fbussendsynk;
 FbusRunCommand(@Fbs60keybtststart, Length(Fbs60keybtststart));
 //form1._msg(BufToHexstr(@Fbusstr[1],Length(fbusstr)));
 FbusRunCommand(@Fbs60keybTst2nd, Length(Fbs60keybTst2nd));
 //form1._msg(BufToHexstr(@Fbusstr[1],Length(fbusstr)));
  if FbusAnsB[9]=$01 then result:=true;
end;

function FBcheckkeys60 () : Boolean;
var
  keycnt,i,i2:Integer;
  data,key,len:Word;
begin
 fbussendsynk;
 FbusRunCommand(@Fbs60keybCheck, Length(Fbs60keybCheck));
 //form1._msg(BufToHexstr(@Fbusstr[1],Length(fbusstr)));
        if FbusAnsB[14]=$01 then begin
                keycnt:=HexToInt(Byte2Str(FbusAnsB[15]));
                Form1._msg('Total pressed keys : '+inttostr(keycnt));
                if keycnt>0 then begin
                   i2:=16;
                   Form1._msg('');
                   for i:=1 to keycnt do
                   begin
                  WordSwap(@FbusAnsB[i2]);
                  key:=word((@FbusAnsB[i2])^);
                  WordSwap(@FbusAnsB[i2+2]);
                  data:=word((@FbusAnsB[i2+2])^);
                  form1._msg(getkeystatus(data)+' : '+getkeycode(key));
                  i2:=i2+4;
                   end;
                  Form1._msg('');
                  end else Form1._msg('No any key was pressed :(');
              result:=True;
                end;
end;

function FBfinkeybtests60 () : Boolean;
begin
  FbusSendSynk;
  result:=False;
 FbusRunCommand(@FBs60keytestfree, Length(FBs60keytestfree));
 //form1._msg(BufToHexstr(@Fbusstr[1],Length(fbusstr)));
 FbusRunCommand(@FBs60keybtststart, Length(FBs60keybtststart));
 //form1._msg(BufToHexstr(@Fbusstr[1],Length(fbusstr)));
  result:=true;
end;

function FbusS40CreateDir(fullpath:string):byte;
var
  hider,s,s2:string;
  framelen:Word;
  i:integer;
  res:string;
begin
 FbusSendSynk;
 s:='';  hider:='';
hider:=chr($1E)+chr(0)+chr($10)+chr($6D)+chr(0)+chr(0)+chr(0)+chr($05)+chr($10)+chr($64);
hider:=hider+PathConv(fullpath)+chr(0)+chr(0)+chr($01)+chr(0);
framelen:=Length(hider)-6;
 word((@hider[5])^):=framelen;
 WordSwap(@hider[5]);
FbusRunLongCommand(@hider[1],Length(hider));
result:=fbusansb[10];
end;

function FbusreadPBcount():DWORD;
begin
  FbusSendSynk;
  FbusRunCommand(@FgetPBcount,Length(FgetPBcount));
  Form1._msg(BufToHexStr(@Fbusstr[1], 32));

end;

function WriteSLDataSL2(key:string):Boolean;
var
  comand_buf : array [0..2000] of Byte;
  i,i2      : Integer;
begin
  result:=false;
  BufCopy(@FwriteSimLock[0],@comand_buf[0], 12);
  i:=StrToBufHex(key,@comand_buf[114]);
  if i>800 then i:=800;
  for i2:=12 to 111 do comand_buf[i2]:=$55;
  word((@comand_buf[112])^):=i;
  Wordswap(@comand_buf[112]);
  Word((@comand_buf[4])^):=i+108;
  WordSwap(@comand_buf[4]);
  //form1._msg(buftohexstr(@comand_buf[0],i+114));
  FbusRunLongCommand(@comand_buf[0],i+116);
  if (FbusAnsb[9]=$19) and (FbusAnsb[10]=$00) then result:=True;
end;

function WriteSLkeySL2(Dkey:string):Boolean;
var
  comandbuf : array [0..400] of Byte;
  i,i2      : Integer;
begin
  result:=false;
  BufCopy(@FWriteSlkeys2[0],@comandbuf[0], 12);
  i:=StrToBufHex(Dkey,@comandbuf[12]);
  //if i<>100 then exit;
  comandbuf[i+12]:=$00;
  comandbuf[i+13]:=$90;
  for i2:=114 to 257 do comandbuf[i2]:=$FF;
  Word((@comandbuf[4])^):=252;
  WordSwap(@comandbuf[4]);
  //form1._msg(buftohexstr(@comandbuf[0],258));
  comandbuf[258]:=$01;
  comandbuf[259]:=$06;
  FbusRunLongCommand(@comandbuf[0],260);
  if (FbusAnsb[9]=$19) and (FbusAnsb[10]=$00) then result:=True;
end;


function FWriteSDkeySLx(Dkey:string):Boolean;
var
  comandbuf : array [0..400] of Byte;
  i,i2      : Integer;
begin
  result:=false;
  BufCopy(@FwriteSD[0],@comandbuf[0], 16);
  i:=StrToBufHex(Dkey,@comandbuf[16]);
  Word((@comandbuf[14])^):=i;
  WordSwap(@comandbuf[14]);
  if i<>$60 then Exit;
  word((@comandbuf[4])^):=i+$0C;
  WordSwap(@comandbuf[4]);
  comandbuf[i+$10]:=$01;
  //Form1._msg(BufTohexstr(@comandbuf[0],i+$12));
  FbusRunLongCommand(@comandbuf[0],i+$12);
  if (FbusAnsb[9]=$18) and (Fbusansb[10]=$01) and(Fbusansb[11]=$00) then result:=true;
end;

function stopfbusop():Boolean;
begin
  //stop1
  FbusRunCommand(@Fstop1, Length(fstop1));
  //Form1._msg(BufToHexStr(@Fbusstr[1],12));
  //stop2
  FbusRunCommand(@Fstop2, Length(fstop2));
  //Form1._msg(BufToHexStr(@Fbusstr[1],12));
end;

function GetInfoDct4():Boolean;
begin
  result:=True;
  try
    PhInfoRecord.MCUSW:=FbusReadMcuSw;
    PhInfoRecord.IMEIPlain:=FbusReadIMEIPl;
    PhInfoRecord.ProductCode:= FbusReadProductCode;
    PhInfoRecord.DSP:= FbusReadDSP;
    PhInfoRecord.PPMInfo:= FbusReadPPMversioninfo;
    PhInfoRecord.CNT:= FbusReadCNTInfo;
    PhInfoRecord.BisicPrdCode:= FbusReadBasicProductionCode;
    PhInfoRecord.ModuleCode:= FbusReadMcode;
    PhInfoRecord.HWID:= FbusReadHWID;
    PhInfoRecord.LCD:= FbusReadLCD;
  except
    result:=False;
  end;
end;

end.
