<commit_before>var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var assert = require('assert');

var portName = "/dev/tty.usbmodem1411";

var readData = '';
var phase = 0;
var sp = new SerialPort(portName, {
  baudRate: 9600,
  dataBits: 8,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
});

function errorExit(){
  console.log("error exit.");
  sp.close();
  process.exit(1);
}

var keepAlive = null;
function sendCommand(cmd){
  console.log("Send command : " + cmd);
  sp.write(cmd, function(err, bytesWritten){
    if(err){
      console.log(err);
    }
    if(cmd.length != bytesWritten){
      console.log("Invalid send length .");
      console.log("cmd.length : " + cmd.length + ", bytesWritten : " + bytesWritten);
      errorExit();
    }
    /*
     * arduinoからのレスポンスの終わりを検出出来ないので、
     * タイムアウトしたら何らかのエラー or バグがあるのもとして
     * 受信したバッファーを出力して終了する.
     */
    keepAlive = setTimeout(function(){
      console.log("!!!!!!!!!!!!!!!!!!!!!!!!!");
      console.log("!!!!!    Timeout    !!!!!");
      console.log("!!!!!!!!!!!!!!!!!!!!!!!!!");
      console.log("Read data : ");
      console.log(readData);
      errorExit();
    }, 2000);
  });
}

function nextPhaseMsg(result){
  if(keepAlive != null){
    clearTimeout(keepAlive);
  }
  console.log("Received message : " + result);
  console.log("Phase " + phase + " is OK. Next phase.");
  console.log();
  readData = '';
  phase++;
}

sp.on('data', function (data) {
  // 改行は消される.
  readData += data;

  switch (phase){
    case 0:
      // setup
      // Arduino初期化待ち & ao writeコマンド送信.
      if(readData.indexOf("READY") >= 0){
        nextPhaseMsg(readData);
        console.log("AO write test.");
        var aoWriteTest = "ao/write/3?val=25\n";
        sendCommand(aoWriteTest);
      }
      break;
    case 1:
      // ao writeコマンド結果待ち
      var expect = {msg:"OK", port:3, val:25};
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ao/write/11\n";
        sendCommand(cmd);
      }
      break;
    case 2:
      var expect = {msg:"NG", port:11, val:-1};
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ao/write/12?geho\n";
        sendCommand(cmd);
      }
      break;
    case 3:
      var expect = {msg:"NG", port:12, val:-2};
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ao/write/12?val=aaa\n";
        sendCommand(cmd);
      }
      break;
    case 4:
      var expect = {msg:"NG", port:12, val:-3};
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ai/ref?type=INTERNAL\n";
        sendCommand(cmd);
      }
      break;
    case 5:
      var expect = {msg:"OK", type:"INTERNAL"};
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ai/ref?type=EXTERNAL\n";
        sendCommand(cmd);
      }
      break;
    case 6:
      var expect = {msg:"OK", type:"EXTERNAL"};
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ai/ref?type=DEFAULT\n";
        sendCommand(cmd);
      }
      break;
    case 7:
      var expect = {msg:"OK", type:"DEFAULT"};
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ai/ref?type=hoge\n";
        sendCommand(cmd);
      }
      break;
    case 8:
      var expect = {msg:"NG", type:"hoge"};
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ai/read/1\n";
        sendCommand(cmd);
      }
      break;
    case 9:
      var expect = {msg:"OK", port:1, val:1};
      // aiの値は不定なのでそこは無視する.
      var json = JSON.stringify(expect).split("\"val")[0];
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
        var cmd = "ai/read/aa\n";
        sendCommand(cmd);
      }
      break;
    case 10:
      var expect = {msg:"NG", port:-1, val:-1};
      // aiの値は不定なのでそこは無視する.
      var json = JSON.stringify(expect);
      if(readData.indexOf(json) >= 0){
        nextPhaseMsg(readData);
      }
      break;

  }

});

sp.on('close', function (err) {
  console.log('port closed');
});

sp.on('error', function (err) {
  console.error("error", err);
});

sp.on('open', function () {
  console.log("Wait for \"READY\" message.");
});
<commit_msg>テスト方法を改革した.<commit_after>var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var assert = require('assert');
var _ = require("underscore");
var portName = "/dev/tty.usbmodem1411";

var readData = '';
var phase = 0;
var sp = new SerialPort(portName, {
  baudRate: 9600,
  dataBits: 8,
  parity: 'none',
  stopBits: 1,
  flowControl: false,
});

function errorExit(){
  console.log("error exit.");
  sp.close();
  process.exit(1);
}

var keepAlive = null;
function startkeepAlive(){
  /*
   * arduinoからのレスポンスの終わりを検出出来ないので、
   * タイムアウトしたら何らかのエラー or バグがあるのもとして
   * 受信したバッファーを出力して終了する.
   */
  keepAlive = setTimeout(function(){
    console.log("!!!!!!!!!!!!!!!!!!!!!!!!!");
    console.log("!!!!!    Timeout    !!!!!");
    console.log("!!!!!!!!!!!!!!!!!!!!!!!!!");
    console.log("Expect           : " + tests[test_index].expect);
    console.log("Received message : " + readData);
    errorExit();
  }, 2000);
}
function clearKeepAlive(){
  if(keepAlive != null){
    clearTimeout(keepAlive);
  }
}

function sendCommand(cmdWithoutNL, cb){
  // READY待ちの時だけ例外的に扱う.
  if(cmdWithoutNL == ""){
    cb(null, 0, "");
    return;
  }
  console.log("Send command : " + cmdWithoutNL);
  var cmd = cmdWithoutNL + "\n";
  sp.write(cmd, function(err, bytesWritten, sendCmd){
    cb(err, bytesWritten, cmd)
  });
}

function successMsg(result, expect){
  console.log("Expect           : " + expect.trim());
  console.log("Received message : " + result.trim());
  console.log();
}

var tests = [
{
  name:"READY",
  cmd:"", // 初期化待ちだけ空のコマンドにする.
  expect:"READY",
  send:false
},
{
  name:"AO write test.",
  cmd:"ao/write/3?val=25",
  expect:JSON.stringify({msg:"OK", port:3, val:25}),
  send:false
},
{
  name:"AO write test. No query.",
  cmd:"ao/write/3",
  expect:JSON.stringify({msg:"NG", port:3, val:-1}),
  send:false
},
{
  name:"AO write test. Illegal query.",
  cmd:"ao/write/3?hoge",
  expect:JSON.stringify({msg:"NG", port:3, val:-2}),
  send:false
},
{
  name:"AO write test. Illegal value. ",
  cmd:"ao/write/3?val=hoge",
  expect:JSON.stringify({msg:"NG", port:3, val:-3}),
  send:false
},
{
  name:"AI Reference test. type = INTERNAL",
  cmd:"ai/ref?type=INTERNAL",
  expect:JSON.stringify({msg:"OK", type:"INTERNAL"}),
  send:false
},
{
  name:"AI Reference test. type = EXTERNAL",
  cmd:"ai/ref?type=EXTERNAL",
  expect:JSON.stringify({msg:"OK", type:"EXTERNAL"}),
  send:false
},
{
  name:"AI Reference test. type = DEFAULT",
  cmd:"ai/ref?type=DEFAULT",
  expect:JSON.stringify({msg:"OK", type:"DEFAULT"}),
  send:false
},
{
  name:"AI Reference test. Unknown type.",
  cmd:"ai/ref?type=hoge",
  expect:JSON.stringify({msg:"NG", type:"hoge"}),
  send:false
},
{
  name:"AI read test.",
  cmd:"ai/read/1",
  expect:JSON.stringify({msg:"OK", port:1, val:1}).split("\"val")[0],
  send:false
},
{
  name:"AI read test. Illegal port.",
  cmd:"ai/read/a",
  expect:JSON.stringify({msg:"NG", port:-1, val:-1}),
  send:false
}

];
var test_index = 0;
sp.on('data', function (data) {
  // 改行は消えて入ってくる.
  readData += data;
});

sp.on('close', function (err) {
  console.log('port closed');
});

sp.on('error', function (err) {
  console.error("error", err);
});

var task = null;
sp.on('open', function () {
  console.log("Wait for \"READY\" message.");
  task = setInterval(function(){
    if(test_index >= tests.length){
      clearInterval(task);
      console.log("finish");
      return;
    }

    var test_case = tests[test_index];
    if(test_case.send == false){
      // コマンド送信
      readData = "";
      console.log("**********************************");
      console.log("Start : " + test_case.name);
      console.log("**********************************");
      sendCommand(test_case.cmd, function(err, bytesWritten, cmd){
        // ちゃんと送信できたか確認.
        if(cmd.length != bytesWritten){
          console.log("Invalid send length .");
          console.log("cmd.length : " + cmd.length + ", bytesWritten : " + bytesWritten);
          errorExit();
        }
        test_case.send = true;
        startkeepAlive();
      });
    }else{
      // レスポンス待機
      // レスポンス評価
      if(readData.indexOf(test_case.expect) >= 0){
        clearKeepAlive();
        successMsg(readData, test_case.expect);
        // 次のテストに進める
        test_index++;
      }
    }

  }, 100);
});


/*
      */
{'fraction_non_alphanumeric': 0.19634499665700914, 'fraction_numerical': 0.012146200133719634, 'mean_word_length': 2.817524457677584, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3547739', 'n_tokens_mistral': 3342, 'n_tokens_neox': 3222, 'n_words': 582}