private void RecDistant_67(byte[] btFrame) {
logger.info(String.format("%s 接收到对时命令: %s", logHead(), Common.toHex(btFrame)));
byte[] bytes = Common.subBytes(btFrame, Constant.IEC104_POS_DATA_START, 7);
String s_time = Common.parseCP56Time2a(bytes);
try {
// 执行命令修改时间
String[] cmd = {"date", "-s", s_time};
logger.info(String.format("command: %s", cmd[0] + cmd[1] + cmd[2]));
Process process = Runtime.getRuntime().exec(cmd);
int exit = process.waitFor();
logger.info("命令执行结果:" + exit);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
byte[] btFrame是接收到的104帧
byte[] bytes是截取的时间值字节
需要注意这里用数组 String[] cmd = {“date”, “-s”, s_time};
如果修改不成功可能是时区或者是权限的问题
查看时区命令timedatectl
时区没问题
修改权限,普通用户不能修改系统时间
sudo chmod 4755 /bin/date
public static String parseCP56Time2a(byte[] bytes) {
String strTime = null;
try {
int milliseconds1 = bytes[0] < 0 ? 256 + bytes[0] : bytes[0];
int milliseconds2 = bytes[1] < 0 ? 256 + bytes[1] : bytes[1];
int milliseconds = milliseconds1 + milliseconds2 * 256;
int millisecond = milliseconds % 1000;
int seconds = milliseconds / 1000;
// int seconds1 = (bytes[1] << 8) + bytes[0];
// 位于 0011 1111
int minutes = bytes[2] & 0x3f;
// 位于 0001 1111
int hours = bytes[3] & 0x1f;
// 位于 0000 1111
int days = bytes[4] & 0x1f;
// 位于 0001 1111
int months = (bytes[5] & 0x0f);
// 位于 0111 1111
int years = bytes[6] & 0x7f;
strTime = String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d", years + 2000, months, days, hours, minutes,
seconds, millisecond);
} catch (Exception e) {
}
return strTime;
}
将104时间格式转为字符串
以上本人已经验证正确性