Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Home selection #16

Merged
merged 2 commits into from
Oct 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions app/watt_wizard/lib/homescreen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:watt_wizard/profile.dart';

import 'leaderboard.dart';
import 'widgets/users_leaderboard.dart';
import 'widgets/homes_leaderboard.dart';

class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
Expand Down Expand Up @@ -113,7 +114,19 @@ class _HomeScreenState extends State<HomeScreen> {
} else {}
},
child: const Text("Turn Bluetooth On"),
)
),
// Center(
// child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// SizedBox(
// width: sizedBoxWidth,
// height: sizedBoxHeight,
// child: UserList(),
// )
// ],
// ),
// ),
],
),
),
Expand All @@ -129,7 +142,18 @@ class _HomeScreenState extends State<HomeScreen> {
],
),
),
const Center(child: Text("hello"))
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: sizedBoxWidth,
height: sizedBoxHeight,
child: HomeList(),
)
],
),
),
],
),
),
Expand Down
17 changes: 17 additions & 0 deletions app/watt_wizard/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'homescreen.dart';

final db = FirebaseFirestore.instance;

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
Expand Down Expand Up @@ -49,6 +52,20 @@ class MyHomePage extends StatelessWidget {
void _signInWithGitHub() async {
GithubAuthProvider githubProvider = GithubAuthProvider();
await FirebaseAuth.instance.signInWithProvider(githubProvider);
if (FirebaseAuth.instance.currentUser != null) {
var userUID = await db.collection('users').doc(FirebaseAuth.instance.currentUser?.uid).get();
if (!userUID.exists) {
await db.collection('users').doc(FirebaseAuth.instance.currentUser?.uid).set(
{
'devices': [],
'friends': [],
'home': "",
'name': FirebaseAuth.instance.currentUser?.displayName,
'pfp': 'https://m.media-amazon.com/images/I/612-e1vHBAL._AC_SL1145_.jpg'
},
);
}
}
}

@override
Expand Down
30 changes: 25 additions & 5 deletions app/watt_wizard/lib/profile.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:watt_wizard/widgets/connected_device_tile.dart';
import 'package:watt_wizard/widgets/scan_result_tile.dart';
import 'package:watt_wizard/utils/extra.dart';

final db = FirebaseFirestore.instance;

class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key, required this.username});

Expand Down Expand Up @@ -40,8 +44,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
_scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) {
List<ScanResult> result = [];
for (ScanResult r in results) {
if (r.device.platformName == "Light Control" &&
!_connectedDevices.contains(r.device)) {
if (r.device.platformName == "Light Control" && !_connectedDevices.contains(r.device)) {
result.add(r);
}
}
Expand Down Expand Up @@ -71,9 +74,27 @@ class _ProfileScreenState extends State<ProfileScreen> {
FlutterBluePlus.stopScan();
}

void onConnectPressed(BluetoothDevice device) {
void onConnectPressed(BluetoothDevice device) async {
device.connectAndUpdateStream();
_connectedDevices.add(device);

var userDoc = await db.collection('users').doc(FirebaseAuth.instance.currentUser?.uid).get();
List<dynamic> devices = await userDoc.get('devices');

int deviceHash = device.hashCode;

if (!devices.any((element) => element['id'] == deviceHash)) {
await db.collection('users').doc(FirebaseAuth.instance.currentUser?.uid).update({
'devices': FieldValue.arrayUnion([
{
'id': deviceHash,
'name': device.platformName,
'power': []
}
])
});
}

setState(() {});
}

Expand Down Expand Up @@ -119,8 +140,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
child: const Icon(Icons.stop),
);
} else {
return FloatingActionButton(
onPressed: onScanPressed, child: const Text("SCAN"));
return FloatingActionButton(onPressed: onScanPressed, child: const Text("SCAN"));
}
}

Expand Down
178 changes: 178 additions & 0 deletions app/watt_wizard/lib/widgets/homes_leaderboard.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// ignore_for_file: prefer_const_constructors_in_immutables,unnecessary_const,library_private_types_in_public_api,avoid_print
// Copyright 2021, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import '../firebase_options.dart';

// Future<void> main() async {
// WidgetsFlutterBinding.ensureInitialized();
// await Firebase.initializeApp(options: defaultFirebaseOptions);
// }

final _db = FirebaseFirestore.instance;

/// A reference to the list of movies.
/// We are using `withConverter` to ensure that interactions with the collection
/// are type-safe.
final _homesRef = _db.collection('homes').withConverter<_Home>(
fromFirestore: (snapshots, _) => _Home.fromJson(snapshots.data()!, snapshots.id),
toFirestore: (home, _) => home.toJson(),
);

/// Holds all example app films
class HomeList extends StatefulWidget {
const HomeList({Key? key}) : super(key: key);

@override
_HomeListState createState() => _HomeListState();
}

class _HomeListState extends State<HomeList> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<QuerySnapshot<_Home>>(
stream: _homesRef.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
}

if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}

final data = snapshot.requireData;

return ListView.builder(
itemCount: data.size,
itemBuilder: (context, index) {
return _HomeItem(
data.docs[index].data(),
data.docs[index].reference,
);
},
);
},
),
);
}
}

Future<void> updateHome(_Home home) async {
String userUID = FirebaseAuth.instance.currentUser!.uid;

var userSnapshot = await _db.collection('users').doc(userUID).get();
String userHome = userSnapshot.get('home') as String;

await _db.collection('users').doc(userUID).update({
'home': home.id,
});

await _db.collection('homes').doc(userHome).update({
'users': FieldValue.arrayRemove([
userUID
])
}).onError((error, stackTrace) => null);

await _db.collection('homes').doc(home.id).update({
'users': FieldValue.arrayUnion([
userUID
])
});
}

/// A single movie row.
class _HomeItem extends StatelessWidget {
_HomeItem(this.home, this.reference);

final _Home home;
final DocumentReference<_Home> reference;

/// Returns the movie poster.
Widget get pfp {
return SizedBox(
width: 100,
child: Image.network(home.pfp),
);
}

/// Returns user details.
Widget get details {
return Padding(
padding: const EdgeInsets.only(left: 8, right: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
name,
],
),
);
}

// Return the home name.
Widget get name {
return Text(
'${home.name}',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
);
}

Widget updateHomeButton(BuildContext context, _Home home) {
return FloatingActionButton(
onPressed: () async {
await updateHome(home);
},
child: const Text("SELECT"),
);
}

@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 4, top: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
pfp,
Flexible(child: details),
updateHomeButton(context, home),
],
),
);
}
}

@immutable
class _Home {
_Home({required this.pfp, required this.users, required this.name, required this.id});

_Home.fromJson(Map<String, Object?> json, String id)
: this(
pfp: json['pfp']! as String,
users: json['users']! as List<dynamic>,
name: json['name']! as String,
id: id,
);

final String pfp;
final List<dynamic> users;
final String name;
final String id;

Map<String, Object?> toJson() {
return {
'users': users,
'pfp': pfp,
'name': name,
};
}
}
Loading
Loading