#include "tran_for_coder.h"
#include "debug.h"
#include "mymisc.h"
#include "mystdlib.h"
#include "board.h"
#include "dev_flash.h"
#include "prot_uc.h"
#include "coder_lib.h"
#include "PSDGenerate.h"
#include "mystring.h"
#include "coder_judge.h"
#include "JQ_UIDGenerate.h"
#include "transmit.h"
#include "elec_judge.h"
#include "elec_task_slot.h"
#include "elec_det.h"



typedef struct{
  ucport_def u;
  char uid_code[20];
  uint8_t save_code[12];
  uint8_t psw[10];
  char psw_ascii[10];
}slave_def;




static slave_def *slave_creat(void)
{
  slave_def *u=calloc(1,sizeof(slave_def));
  return u;
}



static void slave_del(ucport_def *u)
{
  slave_def *s=(slave_def *)u;
  free(u);
}



// 赋码仪 注码使用xt算法
static int code_dolater(ucport_def *u,uint8_t cmd,array_def *data,char *err_str)
{
  slave_def *s=(slave_def *)u;
  uint8_t *d=arr_data(data);
  if(d[0]!=1){
    // 只支持1个通道
    return 1;
  }
  if(check_shell_code((const char *)&d[6])==0){
    // 管壳码无效
    return 2;
  }
  if(coder_shell_to_uid((const char *)&d[1],(const char *)&d[6],s->uid_code)!=0){
    // uid校验失败
    return 3;
  }
  {
    array_def *r=arr_creat();
    arr_append(r,1);
    arr_append(r,0);
    emit tran_reply_signal(u->p,arr_temp(r));
  }
  
  coder_uid_to_save(s->uid_code,s->save_code);
  GetPasswordByUidCode((const uint8_t *)s->uid_code,s->psw);
  sprintf(s->psw_ascii,"%02X%02X%02X%02X",
    s->psw[0],s->psw[1],s->psw[2],s->psw[3]);
  array_def *uid_psw=arr_creat();
  arr_append(uid_psw,8);
  arr_append(uid_psw,4);
  arr_append(uid_psw,1);
  arr_appends(uid_psw,s->save_code,8);
  arr_appends(uid_psw,s->psw,4);
  array_def *r=elec_check_with_scheme(uid_psw);
  arr_delete(uid_psw);
  if(r){
    array_def *ret=arr_creat();
    arr_append(ret,1);
    arr_append(ret,1);
    arr_append(ret,arr_get(r,0));
    arr_appends(ret,&d[6],13);
    arr_appends(ret,s->uid_code,16);
    arr_appends(ret,s->psw_ascii,8);
    emit tran_send_signal(u->p,0x82,arr_temp(ret));
  }
  return 0;
}
static ucport_def *code(tran_def *t, uint8_t cmd,array_def *data)
{
  int ret=0;
  slave_def *u=slave_creat();
  u->u.p=t;
  u->u.del=slave_del;
  u->u.dolater=code_dolater;
  u->u.dolater(&u->u,cmd,data,"ok");
  return (ucport_def *)u;
}






transmit_export(ym_checker,0x02,code)

















