Skip to content

Commit

Permalink
improve show robot picture, lock db writes
Browse files Browse the repository at this point in the history
  • Loading branch information
mootw committed Feb 20, 2024
1 parent 1ee2552 commit 3337e8d
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 47 deletions.
29 changes: 14 additions & 15 deletions app/lib/screens/match_recorder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import 'package:app/providers/data_provider.dart';
import 'package:app/widgets/fieldwidget.dart';
import 'package:app/style.dart';
import 'package:app/scouting_tools/scouting_tool.dart';
import 'package:app/widgets/image_view.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:photo_view/photo_view.dart';
import 'package:provider/provider.dart';
import 'package:snout_db/config/matcheventconfig.dart';
import 'package:snout_db/event/matchevent.dart';
Expand Down Expand Up @@ -347,7 +349,7 @@ class _MatchRecorderPageState extends State<MatchRecorderPage> {
}

Widget _statusAndToolBar() {
Widget? robotPicture;
Image? robotPicture;
final pictureData = context
.watch<DataProvider>()
.event
Expand All @@ -366,7 +368,9 @@ class _MatchRecorderPageState extends State<MatchRecorderPage> {
tooltip: "Rotate Map",
onPressed: () => setState(() {
_rotateField = !_rotateField;
context.read<LocalConfigProvider>().setFlipFieldImage(_rotateField);
context
.read<LocalConfigProvider>()
.setFlipFieldImage(_rotateField);
}),
icon: const Icon(Icons.rotate_right)),
const SizedBox(width: 8),
Expand All @@ -376,19 +380,14 @@ class _MatchRecorderPageState extends State<MatchRecorderPage> {
if (robotPicture != null)
Center(
child: TextButton(
onPressed: () => showDialog(
context: context,
builder: (bc) {
return AlertDialog(
content: robotPicture!,
actions: [
TextButton(
onPressed: () => Navigator.pop(bc),
child: const Text("Okay")),
],
);
}),
child: const Text("Show Robot")),
onPressed: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(),
body: PhotoView(
imageProvider: robotPicture!.image,
),
))),
child: const Text("Robot Picture")),
),
const SizedBox(width: 8),
FilledButton.icon(
Expand Down
75 changes: 43 additions & 32 deletions server/bin/server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:snout_db/patch.dart';
import 'package:snout_db/snout_db.dart';
import 'package:synchronized/synchronized.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'edit_lock.dart';
Expand All @@ -21,9 +22,13 @@ import 'edit_lock.dart';
final env = DotEnv(includePlatformEnvironment: true)..load();
int serverPort = 6749;
Map<String, EventData> loadedEvents = {};

//To keep things simple we will just have 1 edit lock for all loaded events.
EditLock editLock = EditLock();

// used to prevent the server from writing the database multiple times at once
final Lock dbWriteLock = Lock();

final app = Router();

final Logger logger = Logger("snout-scout-server");
Expand Down Expand Up @@ -182,38 +187,44 @@ void main(List<String> args) async {
}
});

app.put("/events/<eventID>", (Request request, String eventID) async {
final File? f = loadedEvents[eventID]?.file;
if (f == null || await f.exists() == false) {
return Response.notFound("Event not found");
}
final event = SnoutDB.fromJson(
json.decode(await f.readAsString()) as Map<String, dynamic>,
);
//Uses UTF-8 by default
final String content = await request.readAsString();
try {
final Patch patch = Patch.fromJson(json.decode(content) as Map);

event.addPatch(patch);

logger.fine('added patch: ${json.encode(patch)}');

//Successful patch, send this update to all listeners
for (final WebSocketChannel listener
in loadedEvents[eventID]?.listeners ?? []) {
listener.sink.add(json.encode(patch));
}

//Write the new DB to disk
await f.writeAsString(json.encode(event));

return Response.ok("");
} catch (e, s) {
logger.severe('failed to accept patch: $content', e, s);
return Response.internalServerError(body: e);
}
});
app.put(
"/events/<eventID>",
(Request request, String eventID) async {
// Require all writes to start with reading the file, only one at a time and do a full disk flush
return dbWriteLock.synchronized(() async {
final File? f = loadedEvents[eventID]?.file;
if (f == null || await f.exists() == false) {
return Response.notFound("Event not found");
}
final event = SnoutDB.fromJson(
json.decode(await f.readAsString()) as Map<String, dynamic>,
);
//Uses UTF-8 by default
final String content = await request.readAsString();
try {
final Patch patch = Patch.fromJson(json.decode(content) as Map);

event.addPatch(patch);

logger.fine('added patch: ${json.encode(patch)}');

//Successful patch, send this update to all listeners
for (final WebSocketChannel listener
in loadedEvents[eventID]?.listeners ?? []) {
listener.sink.add(json.encode(patch));
}

//Write the new DB to disk
await f.writeAsString(json.encode(event), flush: true);

return Response.ok("");
} catch (e, s) {
logger.severe('failed to accept patch: $content', e, s);
return Response.internalServerError(body: e);
}
});
},
);

final handler = const Pipeline()
.addMiddleware(logRequests())
Expand Down
8 changes: 8 additions & 0 deletions server/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.2.0"
synchronized:
dependency: "direct main"
description:
name: synchronized
sha256: "539ef412b170d65ecdafd780f924e5be3f60032a1128df156adad6c5b373d558"
url: "https://pub.dev"
source: hosted
version: "3.1.0+1"
term_glyph:
dependency: transitive
description:
Expand Down
1 change: 1 addition & 0 deletions server/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ dependencies:
snout_db:
path: ../snout_db

synchronized: ^3.1.0+1
web_socket_channel: ^2.4.0

dev_dependencies:
Expand Down

0 comments on commit 3337e8d

Please sign in to comment.