startHeartBeat method
Implementation
Future<void> startHeartBeat() async {
if (_stateDataObs.isJoinClassSuccess) {
if (_config.classId.toString().isEmpty) {
TCICLog.error(
'classId is empty, please check the classId',
actionModule: ActionModule.tcicController.name,
actionName: ActionName.startHeartBeat.name,
);
return;
}
final stateReport = json.encode({
"RtcInfos": {"userId": _config.userId},
"Role": getRole().name,
"Time": DateTime.now().toIso8601String(),
"Seq": heartBeatSeq,
});
TCICLog.info(
"$stateReport, heartBeatInterval: $heartBeatInterval ms",
actionModule: ActionModule.tcicController.name,
actionName: ActionName.startHeartBeat.name,
);
// 如果 networkService.sendHeartBeat 3 秒内没有返回,则直接 return
try {
final data = await networkService
.sendHeartBeat(
HeartbeatBody(classId: _config.classId, stateReport: stateReport),
)
.timeout(
const Duration(seconds: 3),
onTimeout: () {
TCICLog.error(
'sendHeartBeat 超时(3秒未返回)',
actionModule: ActionModule.tcicController.name,
actionName: ActionName.startHeartBeat.name,
);
return null;
},
);
if (data == null) {
return;
} else {
if (data.errorCode == 0) {
heartBeatSeq++;
if (data.interval != 0) {
final currentInterval = (data.interval);
if (currentInterval != heartBeatInterval) {
heartBeatInterval = currentInterval;
TCICLog.info(
'heartBeatInterval changed: $heartBeatInterval',
actionModule: ActionModule.tcicController.name,
actionName: ActionName.startHeartBeat.name,
);
}
}
} else {
if (_handleHeartBeatResult(data)) {
return;
}
}
}
} catch (e) {
TCICLog.error(
'sendHeartBeat 异常: $e',
actionModule: ActionModule.tcicController.name,
actionName: ActionName.startHeartBeat.name,
);
return;
}
cancelHeartBeatTimer();
_heartBeatTimer = Timer.periodic(
Duration(milliseconds: heartBeatInterval),
(timer) {
startHeartBeat();
},
);
}
}