sendControl static method
Implementation
static Future<String> sendControl(ScpDevice device, String action) async {
// get NVCN
print('Fetching NVCN');
var nvcnResponse = await fetchNVCN(device);
if (nvcnResponse == null) {
return ScpStatus.RESULT_ERROR;
}
if (nvcnResponse.statusCode != 200 || nvcnResponse.bodyBytes == 0) {
return ScpStatus.RESULT_ERROR;
}
ScpResponseFetchNvcn parsedNvcnResponse =
await ScpResponseParser.parseNvcnResponse(nvcnResponse);
String nvcn = parsedNvcnResponse.getNVCN();
//send control command
// <salt> + ":" + "control" + ":" + <device ID> + ":" + <NVCN> + ":" + action
String salt = ScpCrypto().generatePassword();
String payload = "$salt:control:${device.deviceId}:$nvcn:$action";
ScpJson scpJson =
await ScpCrypto().encryptThenEncode(device.knownPassword, payload);
String query = "nonce=${urlEncode(scpJson.encryptedPayload.base64Nonce)}";
query += "&payload=${urlEncode(scpJson.encryptedPayload.base64Data)}";
query += "&payloadLength=${scpJson.encryptedPayload.dataLength}";
query += "&mac=${urlEncode(scpJson.encryptedPayload.base64Mac)}";
// await response
print('Send control command: $action');
Uri url = Uri.dataFromString(
'http://${device.ipAddress}:$PORT/secure-control?$query');
var controlResponse = await http
.get(url)
.timeout(const Duration(seconds: CONTROL_TIMEOUT))
.catchError((e) {
print(e);
});
if (controlResponse.bodyBytes != null) {
if (controlResponse.statusCode == 200) {
ScpResponseControl parsedResponse =
await ScpResponseParser.parseControlResponse(
controlResponse, device.knownPassword);
if (parsedResponse.isValid()) {
if (parsedResponse.getResult() == ScpStatus.RESULT_SUCCESS &&
action == parsedResponse.getAction()) {
print('Successfully controlled device.');
return ScpStatus.RESULT_SUCCESS;
} else if (parsedResponse.getResult() == ScpStatus.RESULT_ERROR ||
action != parsedResponse.getAction()) {
print('Failed controlling device.');
return ScpStatus.RESULT_ERROR;
}
}
} else {
print('Status code not 200: ${controlResponse.statusCode}');
}
}
return ScpStatus.RESULT_ERROR;
}