我需要开发一个连接蓝牙BLE设备的ReactNative应用。 我正在使用react-native-ble-plx库。
要做的关键事情之一是在ReactNative应用程序和蓝牙设备之间同步当前时间。
我意识到该应用应具有CTS,即当前时间服务。 如何实施CTS服务? 有提供CTS服务的图书馆吗?
答案 0 :(得分:0)
我不确定您的问题是关于在设备上创建CTS还是与具有CTS的设备进行交互。我将假设是后者,而您的问题大致是:“如何在外围BLE设备上将当前时间写入当前时间服务?”
这是我使用react-native-ble-plx库将时间写到外围设备上的CTS的方法。
constructCT = (): string => {
// Order:
// Year_LSO (byte), Year_MSO (byte), Month (byte), DayOfMonth (byte), Hours (byte), Minutes (byte), Seconds (byte), DayOfWeek (byte), Fractions (byte), AdjReason (byte)
const fullDateTime = new Date();
const year = fullDateTime.getFullYear();
const month = fullDateTime.getMonth() + 1;
const dayOfMonth = fullDateTime.getDate();
const hours = fullDateTime.getHours();
const minutes = fullDateTime.getMinutes();
const seconds = fullDateTime.getSeconds();
let dayOfWeek = fullDateTime.getDay();
if (dayOfWeek === 0) {
dayOfWeek = 7;
}
const fraction1000 = fullDateTime.getMilliseconds();
const adjustFractionDenom = 256 / 1000;
const fraction256 = Math.round(fraction1000 * adjustFractionDenom);
// TODO: Set your adjust reasons accordingly, in my case they were unnecessary
// Adjust Reasons: Manual Update, External Update, Time Zone Change, Daylight Savings Change
const adjustReasons = [true, false, false, true];
let adjustValue = 0;
for (let i = 0; i < 4; i++) {
if (adjustReasons[i]) {
adjustValue = adjustValue | (1 << i);
}
}
// console.log("Year:", year, " Month:", month, " Date:", dayOfMonth, " Hours:", hours, " Minutes:", minutes, " Seconds:", seconds, " DOW:", dayOfWeek, " MS:", fraction256, " Adjust Reason: ", adjustValue);
const yearHex = this.correctLength(year.toString(16), 4);
const yearHexMSO = yearHex.substr(0, 2);
const yearHexLSO = yearHex.substr(2, 2);
const monthHex = this.correctLength(month.toString(16), 2);
const dayOfMonthHex = this.correctLength(dayOfMonth.toString(16), 2);
const hoursHex = this.correctLength(hours.toString(16), 2);
const minutesHex = this.correctLength(minutes.toString(16), 2);
const secondsHex = this.correctLength(seconds.toString(16), 2);
const dayOfWeekHex = this.correctLength(dayOfWeek.toString(16), 2);
const fractionHex = this.correctLength(fraction256.toString(16), 2);
const adjustValueHex = this.correctLength(adjustValue.toString(16), 2);
const currentTime = yearHexLSO + yearHexMSO + monthHex + dayOfMonthHex + hoursHex + minutesHex + secondsHex + dayOfWeekHex + fractionHex + adjustValueHex;
const currentTime64 = Buffer.from(currentTime, 'hex').toString('base64');
return currentTime64;
}
correctLength = (str, dig): numFilled => {
let result = str;
while (result.length !== dig) {
result = "0" + result;
}
return result;
}
pushTimeData = () => {
const CTSValue = this.constructCT();
this.state.manager.writeCharacteristicWithResponseForDevice(this.state.deviceName, time_service, time_charac, CTSValue)
.then((charac) => {
// console.log("CHARAC VALUE: ", charac.value);
})
.catch((error) => {
console.log(JSON.stringify(error));
})
}