플루터 웹소켓 상태를 확인 할 수 있는 위젯 추가
1초마다 api를 호출할 때 1초마다 반복해주는 기능
_timer = Timer.periodic(Duration(seconds: 1),(timer) async {
});
상위 위젯에서 사용하여 웹소켓 연결 시에만 보이도록 설정
connectWS2(){
_webSocketStreaming.connect(_ipTextEditController.text, _passwordTextEditController.text);
setState(() {
_visibility = true;
});
_webSocketStreaming.startStreaming((data) {
// 데이터 처리
setState(() {
_imageData = data;
});
});
_webSocketStreaming.sendCommand("mecanum","off");
}
.
.
.
Visibility(
child: StatusWidget(),
visible: _visibility,
)
class StatusWidget extends StatefulWidget {
@override
_StatusWidgetState createState() => _StatusWidgetState();
}
class _StatusWidgetState extends State<StatusWidget> {
late Timer _timer;
var url = Uri.parse('https://[URL]/status');
var killMonUrl = Uri.parse('https://[URL]/killmon');
var killCamUrl = Uri.parse('https://[URL]/killcam');
var killDriveUrl = Uri.parse('https://[URL]/killdrive');
var oldStatus = "";
var monState = Colors.red;
var ipcamState = Colors.red;
var trainState = Colors.red;
_StatusWidgetState(){
_startTimer();
}
void _startTimer() {
_timer = Timer.periodic(Duration(seconds: 1),(timer) async {
var response = await http.get(url);
var body = json.decode(response.body);
if(oldStatus != response){
oldStatus = response.body;
setState(() {
if(body["mon"]=="off"){
monState = Colors.red;
}else{
monState = Colors.green;
}
if(body["ipcam"]=="off"){
ipcamState = Colors.red;
}else{
ipcamState = Colors.green;
}
if(body["drivetrain"]=="off"){
trainState = Colors.red;
}else{
trainState = Colors.green;
}
});
}
});
}
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child:
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RawMaterialButton(
onPressed: () {
http.get(killMonUrl);
},
elevation: 1.0,
fillColor: monState,
child: Icon(
Icons.monitor,
size: 15.0,
),
shape: CircleBorder(),
),
RawMaterialButton(
onPressed: () {
http.get(killCamUrl);
},
elevation: 1.0,
fillColor: ipcamState,
child: Icon(
Icons.videocam,
size: 15.0,
),
shape: CircleBorder(),
),
RawMaterialButton(
onPressed: () {
http.get(killDriveUrl);
},
elevation: 1.0,
fillColor: trainState,
child: Icon(
Icons.drive_eta,
size: 15.0,
),
shape: CircleBorder(),
),
]
),
);
}
}