currently working on an app that gives real time data visualization based on a thingsboard back-end. I'm connecting to thingsboard over Websockets for which I first need to fetch a token from thingsboard. this token let's me then set-up the websocket channel. Next up I send a JSON to the server by which I get a response. I'm using the websocket-channel package. I've succeed in setting up the connecting, adding the request with sink.add and reading the response by channel.stream.listen. However my question is now how can I visualize this data, incoming in the channel.stream.listen with i.e. the streambuilder widget?
class websocket_2 extends StatefulWidget {
final int patientID;
websocket_2(this.patientID);
@override
createState() => _websocket_2State(this.patientID);
}
class _websocket_2State extends State<websocket_2> {
final int patientID;
Patient patient = Patient.blank();
List<dynamic> hranalys = [];
//List<String> paramatt = [];
late WebSocketChannel _paramWebsocket;
late Stream<dynamic> stream = Stream.empty();
_websocket_2State(this.patientID);
@override
void initState() {
print('setchannel');
stream = _setchannel();
print('loadData');
loadData();
super.initState();
}
@override
void dispose() {
closestream();
super.dispose();
}
loadData() async {
final patient = MockPatient.fetchByID(
patientID); //await Patient.fetchByID(this.patientID);
if (mounted) {
setState(() {
this.patient = patient;
});
}
}
Future<String> getthingboardAPI() async {
final check = await Token.requestMethod();
print('$check');
print('check token: ${check.token}');
//Websocket credentials
final String thingsBoardApiEndpoint =
'wss://demo.thingsboard.io/api/ws/plugins/telemetry?token=${check.token}';
print(thingsBoardApiEndpoint);
return thingsBoardApiEndpoint;
}
Stream _setchannel() async* {
/// Create the WebSocket channel
print('creating WebSocket channel');
WebSocketChannel channel =
WebSocketChannel.connect(Uri.parse(await getthingboardAPI()));
_sendstreamBody();
_streamlisten();
_paramWebsocket = channel;
/*Timer(Duration(seconds: 3), () {
print('opening stream');
});*/
stream = channel.stream;
yield stream;
}
void _sendstreamBody() {
var body = jsonEncode(<String, dynamic>{
'tsSubCmds': [
{
'entityType': "DEVICE",
'entityId': '5a36ce90-14ed-11ee-9079-75f587c23e37',
'scope': "LATEST_TELEMETRY",
'cmdId': '10'
}
],
'historyCmds': [],
'attrSubCmds': []
});
print('body: $body');
_paramWebsocket.sink.add(body);
}
void _streamlisten() async {
stream.listen(
(data) {
//print('data:${data.data}');
final Map<String, dynamic> itemMap = json.decode(data);
var data_check = Parameters.fromJson(itemMap);
print('${data_check.data['HR'][0][1]}');
print('${data_check.data['RR'][0][1]}');
print('${data_check.data['temp'][0][1]}');
},
onError: (error) => print(error),
);
}
void closestream() {
_paramWebsocket.sink.close();
}
Token model and function to retrieve token:
@JsonSerializable(includeIfNull: false)
class Token {
final String token;
final String refreshToken;
final String? scope;
Token({required this.token, required this.refreshToken, required this.scope});
factory Token.fromJson(Map<String, dynamic> json) => _$TokenFromJson(json);
static Future<Token> requestMethod() async {
//HTPP request to get JWT token
var uri = Uri.parse('https://demo.thingsboard.io/api/auth/login');
var body = jsonEncode(<String, String>{
'username': 'gs@h3cares.be',
'password': 'G94121827381s'
});
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
final response = await http.post(uri, body: body, headers: headers);
final responseJson = json.decode(response.body);
print(responseJson);
final Map<String, dynamic> itemMap = json.decode(response.body);
return Token.fromJson(itemMap);
}
}
Parameter model
@JsonSerializable(includeIfNull: false)
class Parameters {
final int? subscriptionID;
final int? errorCode;
final String? errorMSG;
final Map<String, dynamic> data;
Parameters(
{required this.subscriptionID,
required this.errorCode,
required this.errorMSG,
required this.data});
factory Parameters.fromJson(Map<String, dynamic> json) =>
_$ParametersFromJson(json);
What I've tried you can see in the code above.