Updated angular

This commit is contained in:
Zakary Timson 2021-06-19 19:52:10 -04:00
parent 655a43ade4
commit 110ca07adc
59 changed files with 15455 additions and 779 deletions

17
.browserslistrc Normal file
View File

@ -0,0 +1,17 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# For the full list of supported browsers by the Angular framework, please see:
# https://angular.io/guide/browser-support
# You can see what browsers were selected by your queries by running:
# npx browserslist
last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.

View File

@ -1,13 +0,0 @@
# Editor configuration, see http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false

6
.gitignore vendored
View File

@ -4,10 +4,15 @@
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events*.json
# IDEs and editors
/.idea
.project
@ -23,6 +28,7 @@
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache

View File

@ -1,5 +1,27 @@
# HomeFront
# Homefront
[See Live](https://homefront.app)
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 12.0.1.
This is an Angular + Firebase app that is used in conjunction with my [BMS software](https://github.com/ztimson/HomeFront-Battery) to display and graph battery module's voltage & tempature for an offgrid solar system. It also provides the weather and I have future plans to add the TPLink Kasa, Philips Hue, & Nano Leaf API's so I can also control all the autmoated parts of my house from one interface.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.

View File

@ -3,138 +3,116 @@
"version": 1,
"newProjectRoot": "projects",
"projects": {
"HomeFront": {
"root": "",
"sourceRoot": "src",
"Homefront": {
"projectType": "application",
"prefix": "app",
"schematics": {
"@schematics/angular:component": {
"styleext": "scss"
"inlineTemplate": true,
"inlineStyle": true,
"style": "scss",
"skipTests": true
},
"@schematics/angular:class": {
"skipTests": true
},
"@schematics/angular:directive": {
"skipTests": true
},
"@schematics/angular:guard": {
"skipTests": true
},
"@schematics/angular:interceptor": {
"skipTests": true
},
"@schematics/angular:pipe": {
"skipTests": true
},
"@schematics/angular:service": {
"skipTests": true
},
"@schematics/angular:application": {
"strict": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/HomeFront",
"outputPath": "dist/Homefront",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets",
"src/manifest.json"
"src/manifest.webmanifest"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
"scripts": [],
"serviceWorker": true,
"ngswConfigPath": "ngsw-config.json"
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
],
"serviceWorker": true
}
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "HomeFront:build"
},
"configurations": {
"production": {
"browserTarget": "HomeFront:build:production"
}
"browserTarget": "Homefront:build:production"
},
"development": {
"browserTarget": "Homefront:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "HomeFront:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.scss"
],
"scripts": [],
"assets": [
"src/assets",
"src/manifest.json"
]
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"HomeFront-e2e": {
"root": "e2e/",
"projectType": "application",
"prefix": "",
"architect": {
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "HomeFront:serve"
},
"configurations": {
"production": {
"devServerTarget": "HomeFront:serve:production"
}
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
"browserTarget": "Homefront:build"
}
}
}
}
},
"defaultProject": "HomeFront"
"defaultProject": "Homefront"
}

View File

@ -1,28 +0,0 @@
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.e2e.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};

View File

@ -1,14 +0,0 @@
import { AppPage } from './app.po';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('Welcome to HomeFront!');
});
});

View File

@ -1,11 +0,0 @@
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get('/');
}
getParagraphText() {
return element(by.css('app-root h1')).getText();
}
}

View File

@ -1,13 +0,0 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}

View File

@ -1,16 +0,0 @@
{
"hosting": {
"public": "dist/HomeFront",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}

View File

@ -1,4 +1,5 @@
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
@ -6,18 +7,22 @@
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.json",
"/*.css",
"/*.js"
]
}
}, {
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
"/assets/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
]
}
}

14958
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,60 +1,41 @@
{
"name": "home-front",
"version": "0.2.0",
"version": "0.3.0",
"scripts": {
"ng": "ng",
"start": "ng serve --host=0.0.0.0",
"build": "ng build --configuration=production",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"start": "ng serve --host=0.0.0.0 -o",
"build": "ng build --configuration production",
"watch": "ng build --watch --configuration production",
"deploy": "firebase deploy --token \"${FIREBASE_TOKEN}\""
},
"private": true,
"dependencies": {
"@angular/animations": "~7.0.0",
"@angular/cdk": "^7.0.4",
"@angular/common": "~7.0.0",
"@angular/compiler": "~7.0.0",
"@angular/core": "~7.0.0",
"@angular/fire": "^5.2.1",
"@angular/forms": "~7.0.0",
"@angular/http": "~7.0.0",
"@angular/material": "^7.0.4",
"@angular/platform-browser": "~7.0.0",
"@angular/platform-browser-dynamic": "~7.0.0",
"@angular/pwa": "^0.10.5",
"@angular/router": "~7.0.0",
"@angular/service-worker": "~7.0.0",
"angular-gauge": "^3.1.2",
"chart.js": "^2.9.3",
"core-js": "^2.5.4",
"firebase": "^5.5.8",
"hammerjs": "^2.0.8",
"ng2-charts": "2.2.3",
"rxjs": "~6.3.3",
"zone.js": "~0.8.26"
"@angular/animations": "~12.0.1",
"@angular/cdk": "^12.0.5",
"@angular/common": "~12.0.1",
"@angular/compiler": "~12.0.1",
"@angular/core": "~12.0.1",
"@angular/fire": "^6.1.5",
"@angular/forms": "~12.0.1",
"@angular/material": "^12.0.5",
"@angular/platform-browser": "~12.0.1",
"@angular/platform-browser-dynamic": "~12.0.1",
"@angular/router": "~12.0.1",
"@angular/service-worker": "~12.0.1",
"angular-gauge": "^4.0.0",
"chart.js": "^2.9.4",
"firebase": "^8.6.8",
"ng2-charts": "^2.4.2",
"rxjs": "~6.6.0",
"tslib": "^2.1.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.10.0",
"@angular/cli": "~7.0.5",
"@angular/compiler-cli": "~7.0.0",
"@angular/language-service": "~7.0.0",
"@types/jasmine": "~2.8.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^10.12.7",
"codelyzer": "~4.5.0",
"@angular-devkit/build-angular": "~12.0.1",
"@angular/cli": "~12.0.1",
"@angular/compiler-cli": "~12.0.1",
"@types/node": "^12.11.1",
"firebase-tools": "^6.1.0",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~3.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~1.1.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.1.6"
"typescript": "~4.2.3"
}
}

View File

@ -1,74 +1,81 @@
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {environment} from '../environments/environment';
import {AppRoutes} from './app.routes';
import {AdminGuard} from './guards/admin.guard';
import {GuestGuard} from './guards/guest.guard';
import {LoginGuard} from './guards/login.guard';
import {MaterialModule} from './material.module';
import {AppComponent} from './views/app/app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {FormsModule} from '@angular/forms';
import {
MatButtonModule, MatButtonToggleModule,
MatCardModule,
MatDividerModule, MatFormFieldModule,
MatIconModule, MatInputModule,
MatListModule, MatProgressSpinnerModule,
MatSidenavModule,
MatToolbarModule
} from '@angular/material';
import {DashboardComponent} from './dashboard/dashboard.component';
import {BatteryComponent} from './battery/battery.component';
import {WeatherComponent} from './weather/weather.component';
import {SecurityComponent} from './security/security.component';
import {DashboardComponent} from './views/dashboard/dashboard.component';
import {BatteryComponent} from './views/battery/battery.component';
import {WeatherComponent} from './views/weather/weather.component';
import {SecurityComponent} from './views/security/security.component';
import {HttpClientModule} from '@angular/common/http';
import {LoginComponent} from './login/login.component';
import {LoginComponent} from './views/login/login.component';
import {ServiceWorkerModule} from '@angular/service-worker';
import {RoundPipe} from './round.pipe';
import {BatteryWidgetComponent} from './battery/widget/batteryWidget.component';
import {WeatherWidgetComponent} from './weather/widget/weatherWidget.component';
import {RoundPipe} from './pipes/round.pipe';
import {BatteryWidgetComponent} from './components/battery-widget/batteryWidget.component';
import {WeatherWidgetComponent} from './components/weather-widget/weatherWidget.component';
import {AngularFireAuthModule} from '@angular/fire/auth';
import {environment} from '../environments/environment';
import {AngularFireModule} from '@angular/fire';
import {AngularFirestoreModule} from '@angular/fire/firestore';
import {GaugeModule} from 'angular-gauge';
import {ChartsModule} from 'ng2-charts';
const APP_COMPONENTS = [
BatteryWidgetComponent,
WeatherWidgetComponent
];
const APP_GUARDS = [
AdminGuard,
GuestGuard,
LoginGuard
];
const APP_PIPES = [
RoundPipe
];
const APP_VIEWS = [
AppComponent,
BatteryComponent,
DashboardComponent,
LoginComponent,
SecurityComponent,
WeatherComponent
];
@NgModule({
declarations: [
AppComponent,
BatteryWidgetComponent,
DashboardComponent,
BatteryComponent,
WeatherComponent,
SecurityComponent,
LoginComponent,
RoundPipe,
WeatherWidgetComponent
APP_COMPONENTS,
APP_PIPES,
APP_VIEWS
],
imports: [
AngularFireAuthModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
AppRoutingModule,
AppRoutes,
BrowserModule,
BrowserAnimationsModule,
ChartsModule,
FormsModule,
GaugeModule.forRoot(),
HttpClientModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatDividerModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatListModule,
MatProgressSpinnerModule,
MatSidenavModule,
MatToolbarModule,
MaterialModule,
ServiceWorkerModule.register('ngsw-worker.js', {enabled: false}),
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production,
// Register the ServiceWorker as soon as the app is stable
// or after 30 seconds (whichever comes first).
registrationStrategy: 'registerWhenStable:30000'
}),
],
providers: [],
providers: [APP_GUARDS],
bootstrap: [AppComponent]
})
export class AppModule {
}
export class AppModule { }

View File

@ -1,11 +1,11 @@
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {DashboardComponent} from './dashboard/dashboard.component';
import {WeatherComponent} from './weather/weather.component';
import {SecurityComponent} from './security/security.component';
import {BatteryComponent} from './battery/battery.component';
import {LoginComponent} from './login/login.component';
import {LoginGuard} from './login/login.guard';
import {DashboardComponent} from './views/dashboard/dashboard.component';
import {WeatherComponent} from './views/weather/weather.component';
import {SecurityComponent} from './views/security/security.component';
import {BatteryComponent} from './views/battery/battery.component';
import {LoginComponent} from './views/login/login.component';
import {LoginGuard} from './guards/login.guard';
const routes: Routes = [
{path: 'battery', component: BatteryComponent, canActivate: [LoginGuard]},
@ -20,4 +20,4 @@ const routes: Routes = [
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
export class AppRoutes { }

View File

@ -1,17 +0,0 @@
import {CanActivate, Router} from '@angular/router';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {filter, map, tap} from 'rxjs/operators';
import {AuthService} from '../auth.service';
@Injectable({
providedIn: 'root'
})
export class LoginGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): Observable<boolean> {
return this.auth.user.pipe(filter((user: any) => user != null), map(user => user && !user.isAnonymous), tap(auth => auth ? null : this.router.navigate(['/login'])));
}
}

View File

@ -1,5 +1,5 @@
import {Component} from '@angular/core';
import {BatteryService} from '../battery.service';
import {BatteryService} from '../../services/battery.service';
@Component({
selector: 'battery-widget',

View File

@ -1,5 +1,5 @@
import {Component} from '@angular/core';
import {WeatherService} from '../weather.service';
import {WeatherService} from '../../services/weather.service';
@Component({
selector: 'weather-widget',

View File

@ -1,15 +1,15 @@
import {CanActivate, Router} from '@angular/router';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {filter, map, tap} from 'rxjs/operators';
import {AuthService} from '../auth.service';
import {filter, map} from 'rxjs/operators';
import {AuthService} from '../services/auth.service';
@Injectable({
providedIn: 'root'
})
export class AdminGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
constructor(private auth: AuthService) {}
canActivate(): Observable<boolean> {
return this.auth.user.pipe(filter((user: any) => user != null), map(user => user && user.isAdmin));

View File

@ -2,7 +2,7 @@ import {CanActivate, Router} from '@angular/router';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {filter, map, tap} from 'rxjs/operators';
import {AuthService} from '../auth.service';
import {AuthService} from '../services/auth.service';
@Injectable({
providedIn: 'root'

View File

@ -8,10 +8,10 @@ import {AngularFireAuth} from '@angular/fire/auth';
providedIn: 'root'
})
export class LoginGuard implements CanActivate {
loggedIn?;
loggedIn?: any;
constructor(private auth: AngularFireAuth, private router: Router) {
this.auth.auth.onAuthStateChanged(user => this.loggedIn = !!user);
this.auth.onAuthStateChanged(user => this.loggedIn = !!user);
}
canActivate(): Observable<boolean> {

View File

@ -0,0 +1,32 @@
import {NgModule} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {MatButtonToggleModule} from '@angular/material/button-toggle';
import {MatCardModule} from '@angular/material/card';
import {MatDividerModule} from '@angular/material/divider';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatIconModule} from '@angular/material/icon';
import {MatInputModule} from '@angular/material/input';
import {MatListModule} from '@angular/material/list';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatToolbarModule} from '@angular/material/toolbar';
const MATERIAL_MODULES = [
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatDividerModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatListModule,
MatProgressSpinnerModule,
MatSidenavModule,
MatToolbarModule
];
@NgModule({
imports: MATERIAL_MODULES,
exports: MATERIAL_MODULES
})
export class MaterialModule { }

View File

@ -1,4 +1,4 @@
export interface Battery {
export interface IBattery {
ampHours: number;
avgCellVoltage: number;
capacity: number;

View File

@ -1,7 +1,8 @@
import {User as FirebaseUser} from "firebase"
import {AngularFirestoreDocument} from '@angular/fire/firestore';
import firebase from 'firebase';
import User = firebase.User;
export interface User extends FirebaseUser {
export interface IUser extends User {
ref?: AngularFirestoreDocument;
isAdmin: boolean;

View File

@ -1,4 +1,4 @@
export interface Weather {
export interface IWeather {
cloudCover: number;
current: number;
date: Date;

View File

@ -1,19 +1,18 @@
import {Injectable} from "@angular/core";
import firebase from 'firebase';
import {BehaviorSubject, from} from "rxjs";
import {AngularFirestore} from "@angular/fire/firestore";
import {AngularFireAuth} from "@angular/fire/auth";
import {auth} from 'firebase';
import {Router} from "@angular/router";
import {flatMap, map, skip} from 'rxjs/operators';
import {User} from './user';
import {IUser} from '../models/user';
import GoogleAuthProvider = firebase.auth.GoogleAuthProvider;
@Injectable({
providedIn: 'root'
})
@Injectable({providedIn: 'root'})
export class AuthService {
readonly collection = 'Users';
user = new BehaviorSubject<User>(null);
user = new BehaviorSubject<IUser>(null);
constructor(private afAuth: AngularFireAuth, private router: Router, private db: AngularFirestore) {
this.afAuth.user.pipe(
@ -22,16 +21,16 @@ export class AuthService {
let ref = this.db.collection(this.collection).doc(user.uid);
return ref.valueChanges().pipe(map(dbUser => Object.assign({ref: ref}, user, dbUser)))
})
).subscribe(user => this.user.next(<User>user));
).subscribe(user => this.user.next(<IUser>user));
}
async loginWithGoogle() {
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
this.afAuth.signInWithPopup(new GoogleAuthProvider());
return this.user.pipe(skip(1));
}
async logout() {
await this.afAuth.auth.signOut();
await this.afAuth.signOut();
return this.router.navigate(['/']);
}
}

View File

@ -1,14 +1,14 @@
import {Injectable} from '@angular/core';
import {AngularFirestore} from '@angular/fire/firestore';
import {Battery} from './battery';
import {IBattery} from '../models/battery';
import {BehaviorSubject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BatteryService {
data = new BehaviorSubject<Battery[]>([]);
last: Battery = <Battery>{};
data = new BehaviorSubject<IBattery[]>([]);
last: IBattery = <IBattery>{};
modules = [];
get charging() {
@ -29,7 +29,7 @@ export class BatteryService {
let afterDate = new Date();
afterDate.setDate(afterDate.getDate() - 1);
this.firestore.collection('Battery').doc('170614D').collection<Battery>('data', ref => ref.where('timestamp', '>=', afterDate.getTime()).orderBy('timestamp')).valueChanges().subscribe(data => {
this.firestore.collection('Battery').doc('170614D').collection<IBattery>('data', ref => ref.where('timestamp', '>=', afterDate.getTime()).orderBy('timestamp')).valueChanges().subscribe(data => {
this.modules = data.reduce((acc: any, row) => {
Object.keys(row.modules).forEach(module => {
if(!acc[module]) acc[module] = [];

View File

@ -2,17 +2,15 @@ import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Subscription, timer} from 'rxjs';
import {environment} from '../../environments/environment';
import {Weather} from './weather';
import {WeatherIcons} from './weatherIcons';
import {IWeather} from '../models/weather';
import {WeatherIcons} from '../models/weatherIcons';
@Injectable({
providedIn: 'root'
})
@Injectable({providedIn: 'root'})
export class WeatherService {
locationKey: string;
metric = true;
sub: Subscription;
weather: Weather[] = [];
weather: IWeather[] = [];
get icon() {
if(!this.weather.length) return '';

View File

@ -1,9 +1,9 @@
<mat-toolbar *ngIf="!hide" [@collapseUp]="!hide" [@expandDown]="!hide" class="bg-primary">
<mat-icon *ngIf="mobile" class="mr-2" (click)="open = !open">menu</mat-icon>
<img src="assets/icon.png" class="mr-2" height="24px" width="auto">
<img src="../../../assets/icon.png" class="mr-2" height="24px" width="auto">
<span>
<span style="font-weight: 500;">Home Front</span>
<small class="text-muted ml-2">v{{environment.version}}</small>
<small class="text-muted ml-2">v{{version}}</small>
</span>
</mat-toolbar>
<mat-drawer-container class="fill-height" [hasBackdrop]="false">

View File

@ -1,12 +1,12 @@
import {Component} from '@angular/core';
import {BatteryService} from './battery/battery.service';
import {BatteryService} from '../../services/battery.service';
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';
import {environment} from '../environments/environment';
import {collapseUp, expandDown, routerTransition} from './animations';
import {collapseUp, expandDown, routerTransition} from '../../animations';
import {ActivatedRoute, NavigationEnd, Router} from '@angular/router';
import {filter} from 'rxjs/operators';
import {WeatherService} from './weather/weather.service';
import {WeatherService} from '../../services/weather.service';
import {AngularFireAuth} from '@angular/fire/auth';
import packageJson from 'package.json';
@Component({
selector: 'app-root',
@ -18,11 +18,11 @@ export class AppComponent {
mobile = true; // Mobile or desktop size
noTransition = false; // Stop router transitions
open = false; // Side nav open
environment = environment; // Environment ref
version = packageJson.version;
constructor(private auth: AngularFireAuth, private router: Router, public batteryService: BatteryService, public weatherService: WeatherService, route: ActivatedRoute, breakpointObserver: BreakpointObserver) {
constructor(private auth: AngularFireAuth, private router: Router, private route: ActivatedRoute, public batteryService: BatteryService, public weatherService: WeatherService, breakpointObserver: BreakpointObserver) {
router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe(() => {
this.hide = !!route.root.firstChild.snapshot.data.hide;
this.hide = !!route.root.firstChild?.snapshot.data.hide;
this.open = !this.hide && !this.mobile;
});
@ -34,11 +34,11 @@ export class AppComponent {
async logout() {
this.noTransition = true;
await this.auth.auth.signOut();
await this.auth.signOut();
return this.router.navigate(['/login']).then(() => this.noTransition = false);
}
transition(outlet) {
transition(outlet: any) {
if(!outlet.isActivated || !!outlet.activatedRouteData.noAnimation || this.noTransition) return '';
return outlet.activatedRoute;
}

View File

@ -1,7 +1,8 @@
<div class="fill-height p-3" style="background-color: #b52e3c !important; overflow-y: scroll">
<!-- Header -->
<div class="ml-2 d-flex align-items-center">
<div class="d-none d-sm-inline pr-2">
<img src="assets/tesla.png" height="85px" width="auto">
<div class="d-inline pr-2">
<img src="../../../assets/tesla.png" height="85px" width="auto">
</div>
<div>
<h1 class="mb-0">Powerwall: {{batteryService.last.voltage | number : '1.1-1'}} V</h1>
@ -9,14 +10,14 @@
<h6 class="mb-0">Uptime: {{batteryService.last.uptime}}</h6>
</div>
</div>
<div class="w-100 mt-5">
<div class="d-inline-block col-12 col-md-3 px-1">
<mat-card class="d-inline-block col-6 col-md-12 m-0 m-md-2">
<div class="mt-3 d-flex flex-column flex-md-row">
<div class="d-flex flex-md-column flex-row flex-wrap">
<mat-card style="margin: 10px; min-width: 200px; width: 200px; height: 200px;">
<canvas id="netPower" class="w-100"></canvas>
<h5 class="text-center text-muted"><strong>Power: </strong>{{batteryService.last.power | number : '1.1-1'}} Watts</h5>
<h5 class="text-center text-muted"><strong>Current: </strong>{{batteryService.last.current | number : '1.1-1'}} Amps</h5>
</mat-card>
<mat-card class="d-inline-block col-6 col-md-12 m-0 m-md-2">
<mat-card style="margin: 10px; min-width: 200px; width: 200px; height: 200px;">
<mwl-gauge
[max]="100"
[color]="color"
@ -29,8 +30,8 @@
</mwl-gauge>
</mat-card>
</div>
<div class="d-inline-block col-12 col-md-9 px-1">
<mat-card class="h-100">
<div class="flex-grow-1" style="overflow: hidden; margin: 10px">
<mat-card class="w-100">
<canvas baseChart
[datasets]="socData"
[labels]="socLabels"
@ -41,6 +42,7 @@
</mat-card>
</div>
</div>
<!-- Battery Cells -->
<div class="d-flex flex-wrap mt-5">
<div class="p-2 col-12 col-sm-6 col-lg-3" *ngFor="let battery of batteries; let i = index">
<mat-card>

View File

@ -1,19 +1,19 @@
import {Component, HostListener, OnInit} from '@angular/core';
import {BatteryService} from './battery.service';
import {AppComponent} from '../app.component';
import {Component, OnInit} from '@angular/core';
import {BatteryService} from '../../services/battery.service';
import {AppComponent} from '../app/app.component';
declare const Gauge;
declare const Gauge: any;
@Component({
selector: 'app-batterys',
selector: 'app-batteries',
templateUrl: './battery.component.html',
styles: [`.selected { background-color: rgba(0, 0, 0, 0.1); }`]
})
export class BatteryComponent implements OnInit {
batteries = [];
gauge;
socData = [];
socLabels = [];
batteries: any[] = [];
gauge: any;
socData: any[] = [];
socLabels: string[] = [];
socOptions = {
responsive: true,
scales: {
@ -21,15 +21,15 @@ export class BatteryComponent implements OnInit {
yAxes: [{
ticks: {
min: 0,
max: 1,
max: 1.2,
step: 0.1,
callback: (label) => this.percent(Math.round(label * 100))
callback: (label: any) => this.percent(Math.round(label * 100))
}
}]
},
tooltips: {
callbacks: {
label: (tooltipItem, data) => `SOC: ${this.percent(tooltipItem.yLabel * 100)}`
label: (tooltipItem: any) => `SOC: ${this.percent(tooltipItem.yLabel * 100)}`
}
}
};
@ -39,7 +39,7 @@ export class BatteryComponent implements OnInit {
this.socLabels = data.filter(row => new Date(row.timestamp).getMinutes() % 15 == 0).map(row => this.dateFormat(new Date(row.timestamp)));
this.socData = [{label: 'SOC', fill: false, data: data.filter(row => new Date(row.timestamp).getMinutes() % 15 == 0).map(row => row.soc)}];
if(this.gauge) this.gauge.set(batteryService.last.power || 0);
this.batteries = Object.keys(this.batteryService.modules).map(key => {
this.batteries = Object.keys(this.batteryService.modules).map((key: string) => {
return {
name: `Module ${key}`,
negativeTemperature: this.batteryService.modules[key][this.batteryService.modules[key].length - 1].negativeTemperature,
@ -51,7 +51,9 @@ export class BatteryComponent implements OnInit {
}
ngOnInit() {
let canvas = document.getElementById('netPower');
const canvas = document.getElementById('netPower');
if(!canvas) return;
canvas.style.height = canvas.style.width;
this.gauge = new Gauge(canvas).setOptions({
angle: 0.2, // The span of the gauge arc
@ -95,7 +97,7 @@ export class BatteryComponent implements OnInit {
return '#4f55b6';
}
percent(val) {
percent(val: number) {
return `${Math.round(val)}%`;
}

View File

@ -5,7 +5,7 @@
<h1 class="d-inline text-white">Home Front</h1>
</div>
<div class="mt-5">
<img src="assets/icon-inv.png" width="275px" height="auto">
<img src="../../../assets/icon-inv.png" width="275px" height="auto">
</div>
</div>
<div class="off-center" *ngIf="show" [@fadeOut]="true" [@expandDown]="animate">

View File

@ -1,8 +1,9 @@
import {Component, NgZone, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import * as firebase from 'firebase';
import {expandDown, fadeIn, fadeOut} from '../animations';
import firebase from 'firebase';
import {expandDown, fadeIn, fadeOut} from '../../animations';
import {AngularFireAuth} from '@angular/fire/auth';
import GoogleAuthProvider = firebase.auth.GoogleAuthProvider;
@Component({
selector: 'app-login',
@ -17,7 +18,7 @@ export class LoginComponent implements OnInit {
constructor(private auth: AngularFireAuth, private ngZone: NgZone, public router: Router) { }
ngOnInit() {
this.auth.auth.onAuthStateChanged(user => {
this.auth.onAuthStateChanged(user => {
if(!!user) {
this.show = false;
setTimeout(() => {
@ -31,7 +32,7 @@ export class LoginComponent implements OnInit {
async login() {
this.loading = true;
await this.auth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
await this.auth.signInWithPopup(new GoogleAuthProvider());
this.loading = false;
}
}

View File

@ -1,5 +1,5 @@
import {Component, OnInit} from '@angular/core';
import {WeatherService} from './weather.service';
import {WeatherService} from '../../services/weather.service';
import {timer} from 'rxjs';
import {filter} from 'rxjs/operators';
@ -29,6 +29,7 @@ export class WeatherComponent implements OnInit {
const c = <HTMLCanvasElement>document.getElementById('myCanvas');
if (c) {
const ctx = c.getContext('2d');
if(!ctx) return;
// All the points in 2D space we care about
const width = c.width;

View File

@ -1,11 +0,0 @@
# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
#
# For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11

View File

@ -8,6 +8,5 @@ export const environment = {
storageBucket: "homefront-2ccb4.appspot.com",
messagingSenderId: "482384317544"
},
production: true,
version: require('../../package.json').version
production: true
};

View File

@ -8,6 +8,5 @@ export const environment = {
storageBucket: "homefront-2ccb4.appspot.com",
messagingSenderId: "482384317544"
},
production: false,
version: require('../../package.json').version
production: false
};

View File

@ -10,11 +10,13 @@
<link rel="icon" type="image/x-icon" href="assets/icon.png">
<link rel="stylesheet" type="text/css" href="assets/bootstrap.min.css">
<link rel="manifest" href="manifest.json">
<link rel="manifest" href="src/manifest.json">
<script src="https://bernii.github.io/gauge.js/dist/gauge.min.js"></script>
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#1976d2">
</head>
<body style="background-color: #2F323A;">
<body style="background-color: #2F323A;" class="mat-typography">
<app-root>
<div style="position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%);">
<div class="text-center">

View File

@ -1,31 +0,0 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};

View File

@ -1,11 +1,12 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import 'hammerjs';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));

View File

@ -18,61 +18,46 @@
* BROWSER POLYFILLS
*/
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';
/**
* If the application will be indexed by Google Search, the following is required.
* Googlebot uses a renderer based on Chrome 41.
* https://developers.google.com/search/docs/guides/rendering
**/
// import 'core-js/es6/array';
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
* IE11 requires the following for NgClass support on SVG elements
*/
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/** IE10 and IE11 requires the following for the Reflect API. */
// import 'core-js/es6/reflect';
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
**/
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
*/
// (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
// (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
// (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
/*
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
// (window as any).__Zone_enable_cross_context_check = true;
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
import 'zone.js'; // Included with Angular CLI.
/***************************************************************************************************

View File

@ -1,5 +1,5 @@
/* You can add global styles to this file, and also import other style files */
@import url('https://fonts.googleapis.com/css?family=Archivo|Material+Icons');
@import url('https://fonts.googleapis.com/css?family=Roboto|Material+Icons');
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
@import url('https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.9/css/weather-icons.min.css');
@import url('https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.9/css/weather-icons-wind.min.css');
@ -153,3 +153,6 @@ html, body {
height: calc(100vh - 56px);
}
}
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }

View File

@ -1,20 +0,0 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: any;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

View File

@ -1,11 +0,0 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": ["node"]
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}

View File

@ -1,18 +0,0 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"test.ts",
"polyfills.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": "../tslint.json",
"rules": {
"directive-selector": [
true,
"attribute",
"app",
"camelCase"
],
"component-selector": [
true,
"element",
"app",
"kebab-case"
]
}
}

15
tsconfig.app.json Normal file
View File

@ -0,0 +1,15 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}

View File

@ -1,21 +1,34 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitReturns": false,
"noImplicitAny": false,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"downlevelIteration": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"moduleResolution": "node",
"importHelpers": true,
"target": "es2017",
"module": "es2020",
"strictNullChecks": false,
"lib": [
"es2018",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@ -1,131 +0,0 @@
{
"rulesDirectory": [
"node_modules/codelyzer"
],
"rules": {
"arrow-return-shorthand": true,
"callable-types": true,
"class-name": true,
"comment-format": [
true,
"check-space"
],
"curly": true,
"deprecation": {
"severity": "warn"
},
"eofline": true,
"forin": true,
"import-blacklist": [
true,
"rxjs/Rx"
],
"import-spacing": true,
"indent": [
true,
"spaces"
],
"interface-over-type-literal": true,
"label-position": true,
"max-line-length": [
true,
140
],
"member-access": false,
"member-ordering": [
true,
{
"order": [
"static-field",
"instance-field",
"static-method",
"instance-method"
]
}
],
"no-arg": true,
"no-bitwise": true,
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-construct": true,
"no-debugger": true,
"no-duplicate-super": true,
"no-empty": false,
"no-empty-interface": true,
"no-eval": true,
"no-inferrable-types": [
true,
"ignore-params"
],
"no-misused-new": true,
"no-non-null-assertion": true,
"no-redundant-jsdoc": true,
"no-shadowed-variable": true,
"no-string-literal": false,
"no-string-throw": true,
"no-switch-case-fall-through": true,
"no-trailing-whitespace": true,
"no-unnecessary-initializer": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-var-keyword": true,
"object-literal-sort-keys": false,
"one-line": [
true,
"check-open-brace",
"check-catch",
"check-else",
"check-whitespace"
],
"prefer-const": true,
"quotemark": [
true,
"single"
],
"radix": true,
"semicolon": [
true,
"always"
],
"triple-equals": [
true,
"allow-null-check"
],
"typedef-whitespace": [
true,
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}
],
"unified-signatures": true,
"variable-name": false,
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
],
"no-output-on-prefix": true,
"use-input-property-decorator": true,
"use-output-property-decorator": true,
"use-host-property-decorator": true,
"no-input-rename": true,
"no-output-rename": true,
"use-life-cycle-interface": true,
"use-pipe-transform-interface": true,
"component-class-suffix": true,
"directive-class-suffix": true
}
}