blob: 5a51bdbf41c70041d510c3c0ded62735b536b40a [file] [log] [blame]
package com.fairphone.hiccup.app;
import android.util.Log;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
/**
* Copyright 2016 Fairphone B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class BoardDate {
/* The board date is stored in an ingenious format:
* Read the binary data of the file, convert it to hex
* and you get the decimal representation of the date.
* Speechless.
*/
private static final String BOARD_DATE_FILE = "/persist/board_date.bin";
private static Date boardDate = null;
private static final String TAG = "HICCUP";
public static Date getBoardDate() {
if (boardDate== null) {
boardDate = readBoardDate();
}
return boardDate;
}
private static Date readBoardDate() {
long startTime = 0;
try {
byte[] boardFile = getBoardDateFileInByteArray();
String strDate = bytesToHex(boardFile);
startTime = getTimeInMilliseconds(strDate);
} catch (Exception e) {
Log.e(TAG,"Unknown error while reading board date; using default", e);
}
return new Date(startTime);
}
private static byte[] getBoardDateFileInByteArray()
{
File file = new File(BOARD_DATE_FILE);
byte[] fileData = new byte[(int) file.length()];
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream(file));
dis.read(fileData);
dis.close();
} catch (FileNotFoundException e) {
Log.e(TAG,"BoardDateFile not found", e);
} catch (IOException e) {
Log.e(TAG, "BoardDateFile IOException", e);
}
finally {
return fileData;
}
}
public static String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static long getTimeInMilliseconds(String date)
{
Calendar cal = Calendar.getInstance();
try {
cal.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
cal.set(Calendar.MONTH, Integer.parseInt(date.substring(4, 6)));
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date.substring(6, 8)));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
}
catch (NumberFormatException e) {
Log.e(TAG, "Parse Exception", e);
return 0;
}
return cal.getTimeInMillis();
}
}