I have wrote the code for server.js and main.dart.
Functionality which I am trying to achieve is very simple but somehow I cannot make it work.
server receives an incoming request, app fetches that request from server and ring/vibrate the device.
**main.dart code
**
void main() {
runApp(MyApp());
}
String receiverDeviceId =
''; // Define and declare the receiverDeviceId variable
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.dark,
home: MyHomePage(),
);
}
}
Future<String> fetchReceiverDeviceId(String serverUrl) async {
final response =
await http.get(Uri.parse('$serverUrl/getReceiverDeviceId'));
if (response.statusCode == 200) {
final result = jsonDecode(response.body);
return result['receiverDeviceId'];
} else {
throw Exception(
'Failed to fetch receiverDeviceId from the server. Status code: ${response.statusCode}');
}
}
void sendSlap(String serverUrl, String senderDeviceId,
Function(String) onServerResponse) async {
try {
String receiverDeviceId = await fetchReceiverDeviceId(serverUrl);
final response = await http.post(
Uri.parse('$serverUrl/notifySlap'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(
{'deviceId': senderDeviceId, 'receiverDeviceId': receiverDeviceId}),
);
if (response.statusCode == 200) {
final result = jsonDecode(response.body);
if (result['success']) {
print(
'Slap notification sent from $senderDeviceId to $receiverDeviceId');
showSnackbar(
'Slap notification sent from $senderDeviceId to $receiverDeviceId');
// Notify the app that the server received the slap request
onServerResponse('Server received slap notification');
} else {
print('Error sending slap notification: ${result['message']}');
showSnackbar('Error sending slap notification: ${result['message']}');
}
} else {
print('Slap notification request failed. Please try again.');
showSnackbar('Slap notification request failed. Please try again.');
}
} catch (e) {
print('Error sending slap notification: $e');
showSnackbar('Error sending slap notification. Please try again.');
}
}
void receiveSlap(String senderDeviceId, String receiverDeviceId) {
// Logic to handle receiving a slap notification
print(
'Slap notification received from $senderDeviceId on $receiverDeviceId');
showSnackbar(
'Slap notification received from $senderDeviceId on $receiverDeviceId');
// Vibrate the device
vibrateDevice();
// Play the notification sound
playNotificationSound();
}
void playNotificationSound() async {
AudioCache player = AudioCache();
await player.load('noti/notification_sound.mp3');
}
void vibrateDevice() {
Vibration.vibrate(duration: 500); // Vibrate the device for 500 milliseconds
}
ElevatedButton(
onPressed: () async {
print('Slap button pressed'); // Add this debug statement
final response = await http
.get(Uri.parse('$serverUrl/getReceiverDeviceId'));
if (response.statusCode == 200) {
receiverDeviceId =
jsonDecode(response.body)['receiverDeviceId'];
print(
'Receiver Device ID: $receiverDeviceId'); // Add this debug statement
sendSlap(serverUrl, deviceId!, (String serverResponse) {
print(
serverResponse); // This will notify the app that the server has received the slap request
});
} else {
print(
'Failed to fetch receiverDeviceId from the server. Status code: ${response.statusCode}'); // Add this debug statement
}
},
child: Text('Slap!'),
),
**server.js code
**
fastify.post('/notifySlap', (request, reply) => {
const deviceId = request.body.deviceId;
const receiverDeviceId = request.body.receiverDeviceId;
const connectedDevicesToNotify = connectedDevices.filter(id => id !== deviceId);
if (connectedDevicesToNotify.length > 0) {
console.log(`Slap notification sent to devices: ${connectedDevicesToNotify.join(', ')}`);
sendNotificationCommandToDevices(connectedDevicesToNotify); // Send command to devices to play sound or vibrate
}
if (deviceId === receiverDeviceId) {
console.log(`Slap notification sent to device: ${deviceId}`);
// Add logic here to handle the slap received by the same device
// For example, you can play a sound or vibrate the device
}
reply.send({ success: true });
});
fastify.get('/getReceiverDeviceId', (request, reply) => {
const receiverDeviceId = generateReceiverDeviceId();
reply.send({ receiverDeviceId });
});
function sendNotificationCommandToDevices(devices) {
devices.forEach(deviceId => {
if (connectedDevices.includes(deviceId)) {
console.log(`Sending slap notification to device: ${deviceId}`);
if (isVibratingDevice(deviceId)) {
console.log(`Vibrating device: ${deviceId}`);
// Add code here to trigger device vibration
} else {
console.log(`Sending sound notification to device: ${deviceId}`);
// Add code here to play a sound notification
}
} else {
console.log(`Device ${deviceId} is not connected.`);
}
});
}
function isVibratingDevice(deviceId) {
// Add logic here to determine if the device should vibrate upon receiving a slap notification
// For example, you can check a database or a list of vibrating devices
return true; // Return true if the device should vibrate, false otherwise
}
// Add a new endpoint to fetch server logs
fastify.get('/serverLogs', (request, reply) => {
// Implement logic to fetch and return server logs here
// You can return an array of log messages from the server
const serverLogs = ['I/flutter (3471): Server received slap notification', 'Vibrating device: '];
reply.send(serverLogs);
});
I have tried to fetch the server log and make the app ring/vibrate by matching the server logs, but nothing happens.