commit 14556b226a6113aac0e6f5d1005e84432c633dbd Author: Mikko Ahlroth Date: Sun Nov 7 11:01:39 2021 +0200 Hackfest diff --git a/.formatter.exs b/.formatter.exs new file mode 100644 index 0000000..4761678 --- /dev/null +++ b/.formatter.exs @@ -0,0 +1,4 @@ +[ + import_deps: [:phoenix], + inputs: ["*.{ex,exs}", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c5b7809 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where 3rd-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Ignore package tarball (built via "mix hex.build"). +geo_therminator-*.tar + +# Ignore assets that are produced by build tools. +/priv/static/assets/ + +# Ignore digested assets cache. +/priv/static/cache_manifest.json + +# In case you use Node.js/npm, you want to ignore these. +npm-debug.log +/assets/node_modules/ + +.env diff --git a/.tool-versions b/.tool-versions new file mode 100644 index 0000000..df5f7db --- /dev/null +++ b/.tool-versions @@ -0,0 +1,2 @@ +elixir 1.12.3-otp-24 +erlang 24.0.6 diff --git a/README.md b/README.md new file mode 100644 index 0000000..68a31d2 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# GeoTherminator + +To start your Phoenix server: + + * Install dependencies with `mix deps.get` + * Start Phoenix endpoint with `mix phx.server` or inside IEx with `iex -S mix phx.server` + +Now you can visit [`localhost:4000`](http://localhost:4000) from your browser. + +Ready to run in production? Please [check our deployment guides](https://hexdocs.pm/phoenix/deployment.html). + +## Learn more + + * Official website: https://www.phoenixframework.org/ + * Guides: https://hexdocs.pm/phoenix/overview.html + * Docs: https://hexdocs.pm/phoenix + * Forum: https://elixirforum.com/c/phoenix-forum + * Source: https://github.com/phoenixframework/phoenix diff --git a/assets/css/app.css b/assets/css/app.css new file mode 100644 index 0000000..72fb781 --- /dev/null +++ b/assets/css/app.css @@ -0,0 +1,121 @@ +/* This file is for your main application CSS */ +@import "./phoenix.css"; + +/* Alerts and form errors used by phx.new */ +.alert { + padding: 15px; + margin-bottom: 20px; + border: 1px solid transparent; + border-radius: 4px; +} +.alert-info { + color: #31708f; + background-color: #d9edf7; + border-color: #bce8f1; +} +.alert-warning { + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #faebcc; +} +.alert-danger { + color: #a94442; + background-color: #f2dede; + border-color: #ebccd1; +} +.alert p { + margin-bottom: 0; +} +.alert:empty { + display: none; +} +.invalid-feedback { + color: #a94442; + display: block; + margin: -1rem 0 2rem; +} + +/* LiveView specific classes for your customization */ +.phx-no-feedback.invalid-feedback, +.phx-no-feedback .invalid-feedback { + display: none; +} + +.phx-click-loading { + opacity: 0.5; + transition: opacity 1s ease-out; +} + +.phx-disconnected{ + cursor: wait; +} +.phx-disconnected *{ + pointer-events: none; +} + +.phx-modal { + opacity: 1!important; + position: fixed; + z-index: 1; + left: 0; + top: 0; + width: 100%; + height: 100%; + overflow: auto; + background-color: rgb(0,0,0); + background-color: rgba(0,0,0,0.4); +} + +.phx-modal-content { + background-color: #fefefe; + margin: 15vh auto; + padding: 20px; + border: 1px solid #888; + width: 80%; +} + +.phx-modal-close { + color: #aaa; + float: right; + font-size: 28px; + font-weight: bold; +} + +.phx-modal-close:hover, +.phx-modal-close:focus { + color: black; + text-decoration: none; + cursor: pointer; +} + +.gthm-logo { + min-width: 300px; + margin: 1rem; + display: block; +} +.gthm-logo img { + width: auto; + display: block; + max-height: 100px; +} + +.main-view-component { + position: relative; +} + +.pump-overlay-btn { + opacity: 0; + + position: absolute; + width: 60px; + height: 61px; + top: 384px; +} + +#pump-dec-btn { + left: 25px; +} + +#pump-inc-btn { + left: 115px; +} diff --git a/assets/css/phoenix.css b/assets/css/phoenix.css new file mode 100644 index 0000000..cb99aa8 --- /dev/null +++ b/assets/css/phoenix.css @@ -0,0 +1,78 @@ +/* Includes some default style for the starter application. + * This can be safely deleted to start fresh. + */ + +/* Milligram v1.4.1 https://milligram.github.io + * Copyright (c) 2020 CJ Patoilo Licensed under the MIT license + */ + +*,*:after,*:before{box-sizing:inherit}html{box-sizing:border-box;font-size:62.5%}body{color:#000000;font-family:'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;font-size:1.6em;font-weight:300;letter-spacing:.01em;line-height:1.6}blockquote{border-left:0.3rem solid #d1d1d1;margin-left:0;margin-right:0;padding:1rem 1.5rem}blockquote *:last-child{margin-bottom:0}.button,button,input[type='button'],input[type='reset'],input[type='submit']{background-color:#0069d9;border:0.1rem solid #0069d9;border-radius:.4rem;color:#fff;cursor:pointer;display:inline-block;font-size:1.1rem;font-weight:700;height:3.8rem;letter-spacing:.1rem;line-height:3.8rem;padding:0 3.0rem;text-align:center;text-decoration:none;text-transform:uppercase;white-space:nowrap}.button:focus,.button:hover,button:focus,button:hover,input[type='button']:focus,input[type='button']:hover,input[type='reset']:focus,input[type='reset']:hover,input[type='submit']:focus,input[type='submit']:hover{background-color:#606c76;border-color:#606c76;color:#fff;outline:0}.button[disabled],button[disabled],input[type='button'][disabled],input[type='reset'][disabled],input[type='submit'][disabled]{cursor:default;opacity:.5}.button[disabled]:focus,.button[disabled]:hover,button[disabled]:focus,button[disabled]:hover,input[type='button'][disabled]:focus,input[type='button'][disabled]:hover,input[type='reset'][disabled]:focus,input[type='reset'][disabled]:hover,input[type='submit'][disabled]:focus,input[type='submit'][disabled]:hover{background-color:#0069d9;border-color:#0069d9}.button.button-outline,button.button-outline,input[type='button'].button-outline,input[type='reset'].button-outline,input[type='submit'].button-outline{background-color:transparent;color:#0069d9}.button.button-outline:focus,.button.button-outline:hover,button.button-outline:focus,button.button-outline:hover,input[type='button'].button-outline:focus,input[type='button'].button-outline:hover,input[type='reset'].button-outline:focus,input[type='reset'].button-outline:hover,input[type='submit'].button-outline:focus,input[type='submit'].button-outline:hover{background-color:transparent;border-color:#606c76;color:#606c76}.button.button-outline[disabled]:focus,.button.button-outline[disabled]:hover,button.button-outline[disabled]:focus,button.button-outline[disabled]:hover,input[type='button'].button-outline[disabled]:focus,input[type='button'].button-outline[disabled]:hover,input[type='reset'].button-outline[disabled]:focus,input[type='reset'].button-outline[disabled]:hover,input[type='submit'].button-outline[disabled]:focus,input[type='submit'].button-outline[disabled]:hover{border-color:inherit;color:#0069d9}.button.button-clear,button.button-clear,input[type='button'].button-clear,input[type='reset'].button-clear,input[type='submit'].button-clear{background-color:transparent;border-color:transparent;color:#0069d9}.button.button-clear:focus,.button.button-clear:hover,button.button-clear:focus,button.button-clear:hover,input[type='button'].button-clear:focus,input[type='button'].button-clear:hover,input[type='reset'].button-clear:focus,input[type='reset'].button-clear:hover,input[type='submit'].button-clear:focus,input[type='submit'].button-clear:hover{background-color:transparent;border-color:transparent;color:#606c76}.button.button-clear[disabled]:focus,.button.button-clear[disabled]:hover,button.button-clear[disabled]:focus,button.button-clear[disabled]:hover,input[type='button'].button-clear[disabled]:focus,input[type='button'].button-clear[disabled]:hover,input[type='reset'].button-clear[disabled]:focus,input[type='reset'].button-clear[disabled]:hover,input[type='submit'].button-clear[disabled]:focus,input[type='submit'].button-clear[disabled]:hover{color:#0069d9}code{background:#f4f5f6;border-radius:.4rem;font-size:86%;margin:0 .2rem;padding:.2rem .5rem;white-space:nowrap}pre{background:#f4f5f6;border-left:0.3rem solid #0069d9;overflow-y:hidden}pre>code{border-radius:0;display:block;padding:1rem 1.5rem;white-space:pre}hr{border:0;border-top:0.1rem solid #f4f5f6;margin:3.0rem 0}input[type='color'],input[type='date'],input[type='datetime'],input[type='datetime-local'],input[type='email'],input[type='month'],input[type='number'],input[type='password'],input[type='search'],input[type='tel'],input[type='text'],input[type='url'],input[type='week'],input:not([type]),textarea,select{-webkit-appearance:none;background-color:transparent;border:0.1rem solid #d1d1d1;border-radius:.4rem;box-shadow:none;box-sizing:inherit;height:3.8rem;padding:.6rem 1.0rem .7rem;width:100%}input[type='color']:focus,input[type='date']:focus,input[type='datetime']:focus,input[type='datetime-local']:focus,input[type='email']:focus,input[type='month']:focus,input[type='number']:focus,input[type='password']:focus,input[type='search']:focus,input[type='tel']:focus,input[type='text']:focus,input[type='url']:focus,input[type='week']:focus,input:not([type]):focus,textarea:focus,select:focus{border-color:#0069d9;outline:0}select{background:url('data:image/svg+xml;utf8,') center right no-repeat;padding-right:3.0rem}select:focus{background-image:url('data:image/svg+xml;utf8,')}select[multiple]{background:none;height:auto}textarea{min-height:6.5rem}label,legend{display:block;font-size:1.6rem;font-weight:700;margin-bottom:.5rem}fieldset{border-width:0;padding:0}input[type='checkbox'],input[type='radio']{display:inline}.label-inline{display:inline-block;font-weight:normal;margin-left:.5rem}.container{margin:0 auto;max-width:112.0rem;padding:0 2.0rem;position:relative;width:100%}.row{display:flex;flex-direction:column;padding:0;width:100%}.row.row-no-padding{padding:0}.row.row-no-padding>.column{padding:0}.row.row-wrap{flex-wrap:wrap}.row.row-top{align-items:flex-start}.row.row-bottom{align-items:flex-end}.row.row-center{align-items:center}.row.row-stretch{align-items:stretch}.row.row-baseline{align-items:baseline}.row .column{display:block;flex:1 1 auto;margin-left:0;max-width:100%;width:100%}.row .column.column-offset-10{margin-left:10%}.row .column.column-offset-20{margin-left:20%}.row .column.column-offset-25{margin-left:25%}.row .column.column-offset-33,.row .column.column-offset-34{margin-left:33.3333%}.row .column.column-offset-40{margin-left:40%}.row .column.column-offset-50{margin-left:50%}.row .column.column-offset-60{margin-left:60%}.row .column.column-offset-66,.row .column.column-offset-67{margin-left:66.6666%}.row .column.column-offset-75{margin-left:75%}.row .column.column-offset-80{margin-left:80%}.row .column.column-offset-90{margin-left:90%}.row .column.column-10{flex:0 0 10%;max-width:10%}.row .column.column-20{flex:0 0 20%;max-width:20%}.row .column.column-25{flex:0 0 25%;max-width:25%}.row .column.column-33,.row .column.column-34{flex:0 0 33.3333%;max-width:33.3333%}.row .column.column-40{flex:0 0 40%;max-width:40%}.row .column.column-50{flex:0 0 50%;max-width:50%}.row .column.column-60{flex:0 0 60%;max-width:60%}.row .column.column-66,.row .column.column-67{flex:0 0 66.6666%;max-width:66.6666%}.row .column.column-75{flex:0 0 75%;max-width:75%}.row .column.column-80{flex:0 0 80%;max-width:80%}.row .column.column-90{flex:0 0 90%;max-width:90%}.row .column .column-top{align-self:flex-start}.row .column .column-bottom{align-self:flex-end}.row .column .column-center{align-self:center}@media (min-width: 40rem){.row{flex-direction:row;margin-left:-1.0rem;width:calc(100% + 2.0rem)}.row .column{margin-bottom:inherit;padding:0 1.0rem}}a{color:#0069d9;text-decoration:none}a:focus,a:hover{color:#606c76}dl,ol,ul{list-style:none;margin-top:0;padding-left:0}dl dl,dl ol,dl ul,ol dl,ol ol,ol ul,ul dl,ul ol,ul ul{font-size:90%;margin:1.5rem 0 1.5rem 3.0rem}ol{list-style:decimal inside}ul{list-style:circle inside}.button,button,dd,dt,li{margin-bottom:1.0rem}fieldset,input,select,textarea{margin-bottom:1.5rem}blockquote,dl,figure,form,ol,p,pre,table,ul{margin-bottom:2.5rem}table{border-spacing:0;display:block;overflow-x:auto;text-align:left;width:100%}td,th{border-bottom:0.1rem solid #e1e1e1;padding:1.2rem 1.5rem}td:first-child,th:first-child{padding-left:0}td:last-child,th:last-child{padding-right:0}@media (min-width: 40rem){table{display:table;overflow-x:initial}}b,strong{font-weight:bold}p{margin-top:0}h1,h2,h3,h4,h5,h6{font-weight:300;letter-spacing:-.1rem;margin-bottom:2.0rem;margin-top:0}h1{font-size:4.6rem;line-height:1.2}h2{font-size:3.6rem;line-height:1.25}h3{font-size:2.8rem;line-height:1.3}h4{font-size:2.2rem;letter-spacing:-.08rem;line-height:1.35}h5{font-size:1.8rem;letter-spacing:-.05rem;line-height:1.5}h6{font-size:1.6rem;letter-spacing:0;line-height:1.4}img{max-width:100%}.clearfix:after{clear:both;content:' ';display:table}.float-left{float:left}.float-right{float:right} + +/* General style */ +h1{font-size: 3.6rem; line-height: 1.25} +h2{font-size: 2.8rem; line-height: 1.3} +h3{font-size: 2.2rem; letter-spacing: -.08rem; line-height: 1.35} +h4{font-size: 1.8rem; letter-spacing: -.05rem; line-height: 1.5} +h5{font-size: 1.6rem; letter-spacing: 0; line-height: 1.4} +h6{font-size: 1.4rem; letter-spacing: 0; line-height: 1.2} +pre{padding: 1em;} + +.container{ + margin: 0 auto; + max-width: 80.0rem; + padding: 0 2.0rem; + position: relative; + width: 100% +} +select { + width: auto; +} + + +/* Headers */ +header { + width: 100%; + background: #fdfdfd; + border-bottom: 1px solid #eaeaea; + margin-bottom: 2rem; +} +header section { + align-items: center; + display: flex; + flex-direction: column; + justify-content: space-between; +} +header section :first-child { + order: 2; +} +header section :last-child { + order: 1; +} +header nav ul, +header nav li { + margin: 0; + padding: 0; + display: block; + text-align: right; + white-space: nowrap; +} +header nav ul { + margin: 1rem; + margin-top: 0; +} +header nav a { + display: block; +} + +@media (min-width: 40.0rem) { /* Small devices (landscape phones, 576px and up) */ + header section { + flex-direction: row; + } + header nav ul { + margin: 1rem; + } + .phx-logo { + flex-basis: 527px; + margin: 2rem 1rem; + } +} diff --git a/assets/js/app.js b/assets/js/app.js new file mode 100644 index 0000000..9eabcff --- /dev/null +++ b/assets/js/app.js @@ -0,0 +1,44 @@ +// We import the CSS which is extracted to its own file by esbuild. +// Remove this line if you add a your own CSS build pipeline (e.g postcss). +import "../css/app.css" + +// If you want to use Phoenix channels, run `mix help phx.gen.channel` +// to get started and then uncomment the line below. +// import "./user_socket.js" + +// You can include dependencies in two ways. +// +// The simplest option is to put them in assets/vendor and +// import them using relative paths: +// +// import "./vendor/some-package.js" +// +// Alternatively, you can `npm install some-package` and import +// them using a path starting with the package name: +// +// import "some-package" +// + +// Include phoenix_html to handle method=PUT/DELETE in forms and buttons. +import "phoenix_html" +// Establish Phoenix Socket and LiveView configuration. +import {Socket} from "phoenix" +import {LiveSocket} from "phoenix_live_view" +import topbar from "../vendor/topbar" + +let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") +let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) + +// Show progress bar on live navigation and form submits +topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) +window.addEventListener("phx:page-loading-start", info => topbar.show()) +window.addEventListener("phx:page-loading-stop", info => topbar.hide()) + +// connect if there are any LiveViews on the page +liveSocket.connect() + +// expose liveSocket on window for web console debug logs and latency simulation: +// >> liveSocket.enableDebug() +// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session +// >> liveSocket.disableLatencySim() +window.liveSocket = liveSocket diff --git a/assets/mainview.drawio b/assets/mainview.drawio new file mode 100644 index 0000000..50ceefe --- /dev/null +++ b/assets/mainview.drawio @@ -0,0 +1 @@ +7Vxdk6I4FP01PmpBQvh4nLZndqp2dmdqu7Z25jFCVGpQLMRW59dv+BSSiEEJTNvaVV0SIMRzTm7uvQkZwenq8EeEN8u/Qo8EI6B5hxF8HgFgWBr9nxQcswIEUFawiHwvK9JPBS/+L5IX5vctdr5HtrUL4zAMYn9TL3TD9Zq4ca0MR1G4r182D4P6Uzd4QbiCFxcHfOl/vhcv81KgaacTn4m/WBaPNoszK1xcnRdsl9gL95Ui+HEEp1EYxtm31WFKggS8Apjsvk9nzpYti8g6lrnBeFpiuIc/Z8/Wl5W/H8M/t2DsZLW84mCX/+K8sfGxgGARhbsN/7D8+a8kislBxAWeFTWcfi2VCQlXJI6O9LpCIzk+xxLB7Hh/wruEe1mBGhXA4pzjRVn1CQX6JQeiBSjWZVAoJmuPJJVoI/i0X/oxedlgNzm7px2Bli3jFX3os06/zv0gmIZBGKX3wjlK/mj5No7Cn6Ryxkw/9Mwiwp5Poa6cm6V/9BxPRSOzLD88D8MBbV8G+gK0eLvJuv3cPyR0dI9OftasqxTxIrUF0NkdIKf/s3/59/nXR+vr7PP209/4x+fFclxQUoFu7FDdTvXRFIyetCkHJP2dcR27uvzW4ZowWvXIHO+C5C4c+Is1LYmyn/aU4OZTK/khL1/5npc8SNgT6n1lHq7j3M5DozjOm6mdYUWWUFn2IODp04HF82fYqvgDXdsYFlYpHlXhrbN4GxzeUNBdDGXdBV6Gm6y9D4nHQI/cAG+3vltHuFnGFK3o+D0/mR78SA4mqDh8PlRPPh/zo6wZxOPcEDkDFuNoQeKmX35m8K0wgUQ2Py+LSIBj/7XeOBE9+RO+hT5tdqkDyOjAMOo1bMNd5JL8pqrvwtRj1+sBDlNPBgNXT6qV8kdfLx9kSMgnCKhTes4GNg1ZTV03cRfox7YFnZdzH6AJHeip7NbIqvtqkLejon4NVfVrhB7EpP0D1XkZmhYJD/qSuWXBd3fRa2p99Vut5lDGkBkUS1+7rTE0L9Sj2hjyXvvY0R6up5zrqVsm1zf7dT0RH/OPOcpOwOm3+Z7U+nmY2HO3QqVL8SSROMy1CDaJJgyOXZvM5gqNKKgb0dIbrTBlCqyDqcqKmnyMNwJPSqma2y5xZamiTM3SbAVH1cxGBtIUUqXrw3ElbK4u4ur8iJdbvLPRBTn4cRpMTADKD39UTp1iieSgCCUyGoo0ZRO7lwgT5PmywakBAUs4Jg811jIBg84SLzvWlrmvvCI2Qj0z1lKe8bFy2Sa5YHu+uY7wKSdBZvVdO4yLFSuRgbhKsVaHii2HjkujwdtXrA6ciVP91AXMCu9aAeuS3mJbBeuO+DlqNdwurSOrYb0q4JOeB9Dwb6JNAJu0CU1nolU+oBulQugoUSpEGtv8xnZx18Pa9YqULZNxulXZNwr7FnfiTQgbsAq8VsrA6kfKALaTctEutVI2H0Z6eC2bUFNhpE1F7gSrVBNqje3iru/F/WiX5nwYaRXCRtemUVkpI0WxHStNpLWTMuo4GhTmmgT5i7Fjvo+kbvPCD2jZdToGT+AKfMOxgx5cCbjSB+eKd37GyeT1gyuWK1jIejiu+OF87MC3zxV88ld4QT4U09unCdROCQTFZPxwBIpmJsHbJ7B7roYfwwSTkI7+oIqnavAhzJBIslbWiEsvCG8DCmATF4JF4kVcUAXF0VSBol8G5XdZv9nA6lnAUT3IEkyvGoKAT1cGt8T0agcabANUVXkCKJQpD0oseVMFxZm1pIUHJ+iTfa6XgBI589+6T2bUnsV36E4IwX3jK1g12Su+4F71eziLr+idGWX2AcgsFpZP17LoZnU1rklthVpPyVUm2QgmqF6FbDqVqchi61G8KhV0O8t0H+TCrsiFA5Pb7UTLfZBrdEWuMTC5Em+Bvjty2Tmgq8lFA5Mr8YL5uyOXfZf4anLNYcktRoUHuRVOrK7ItQYmVyLD9e7Itbsi1x6Y3Fu95VvfzmuVXxokEmI3vbgyDhqz6YKu1luzy60bG1VfPaVmCQm81Um/Q00Z3WjK6EdTsJWmUB+aujU2uENNca//Xqcpsx9NoVaasvrQ1K0hyR1qit1f40pN2f1oymqlKacHTRkSY992iTfJVzeM1ukrtUqy9+nOeyDxuNMt94D0W7jNE/A6428IFpBYAnkq29DHkBgYegLcj4gb+2FSRvtJgkZGgl6SoHdFApvy40kQbfPRxfZtYhIkLGmx0uYLnpHgW7j1c6hmYRyHK8FSnDhkaCloXB0WyRaTkxne+u7Ei9LrZLceuHE3gUudg9l+pViIVl2z0ycxSCJ2L3vHMfBpnB7Byx1klkX0X2ZlAXZ/LtI4/+suptWQgrKMER0pnoRsZAVYdVaQZnGsGIhnRS9WXLWghR6eNvLMBpXTdqjw4/8= \ No newline at end of file diff --git a/assets/vendor/topbar.js b/assets/vendor/topbar.js new file mode 100644 index 0000000..ff7fbb6 --- /dev/null +++ b/assets/vendor/topbar.js @@ -0,0 +1,157 @@ +/** + * @license MIT + * topbar 1.0.0, 2021-01-06 + * http://buunguyen.github.io/topbar + * Copyright (c) 2021 Buu Nguyen + */ +(function (window, document) { + "use strict"; + + // https://gist.github.com/paulirish/1579671 + (function () { + var lastTime = 0; + var vendors = ["ms", "moz", "webkit", "o"]; + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + window.requestAnimationFrame = + window[vendors[x] + "RequestAnimationFrame"]; + window.cancelAnimationFrame = + window[vendors[x] + "CancelAnimationFrame"] || + window[vendors[x] + "CancelRequestAnimationFrame"]; + } + if (!window.requestAnimationFrame) + window.requestAnimationFrame = function (callback, element) { + var currTime = new Date().getTime(); + var timeToCall = Math.max(0, 16 - (currTime - lastTime)); + var id = window.setTimeout(function () { + callback(currTime + timeToCall); + }, timeToCall); + lastTime = currTime + timeToCall; + return id; + }; + if (!window.cancelAnimationFrame) + window.cancelAnimationFrame = function (id) { + clearTimeout(id); + }; + })(); + + var canvas, + progressTimerId, + fadeTimerId, + currentProgress, + showing, + addEvent = function (elem, type, handler) { + if (elem.addEventListener) elem.addEventListener(type, handler, false); + else if (elem.attachEvent) elem.attachEvent("on" + type, handler); + else elem["on" + type] = handler; + }, + options = { + autoRun: true, + barThickness: 3, + barColors: { + 0: "rgba(26, 188, 156, .9)", + ".25": "rgba(52, 152, 219, .9)", + ".50": "rgba(241, 196, 15, .9)", + ".75": "rgba(230, 126, 34, .9)", + "1.0": "rgba(211, 84, 0, .9)", + }, + shadowBlur: 10, + shadowColor: "rgba(0, 0, 0, .6)", + className: null, + }, + repaint = function () { + canvas.width = window.innerWidth; + canvas.height = options.barThickness * 5; // need space for shadow + + var ctx = canvas.getContext("2d"); + ctx.shadowBlur = options.shadowBlur; + ctx.shadowColor = options.shadowColor; + + var lineGradient = ctx.createLinearGradient(0, 0, canvas.width, 0); + for (var stop in options.barColors) + lineGradient.addColorStop(stop, options.barColors[stop]); + ctx.lineWidth = options.barThickness; + ctx.beginPath(); + ctx.moveTo(0, options.barThickness / 2); + ctx.lineTo( + Math.ceil(currentProgress * canvas.width), + options.barThickness / 2 + ); + ctx.strokeStyle = lineGradient; + ctx.stroke(); + }, + createCanvas = function () { + canvas = document.createElement("canvas"); + var style = canvas.style; + style.position = "fixed"; + style.top = style.left = style.right = style.margin = style.padding = 0; + style.zIndex = 100001; + style.display = "none"; + if (options.className) canvas.classList.add(options.className); + document.body.appendChild(canvas); + addEvent(window, "resize", repaint); + }, + topbar = { + config: function (opts) { + for (var key in opts) + if (options.hasOwnProperty(key)) options[key] = opts[key]; + }, + show: function () { + if (showing) return; + showing = true; + if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId); + if (!canvas) createCanvas(); + canvas.style.opacity = 1; + canvas.style.display = "block"; + topbar.progress(0); + if (options.autoRun) { + (function loop() { + progressTimerId = window.requestAnimationFrame(loop); + topbar.progress( + "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2) + ); + })(); + } + }, + progress: function (to) { + if (typeof to === "undefined") return currentProgress; + if (typeof to === "string") { + to = + (to.indexOf("+") >= 0 || to.indexOf("-") >= 0 + ? currentProgress + : 0) + parseFloat(to); + } + currentProgress = to > 1 ? 1 : to; + repaint(); + return currentProgress; + }, + hide: function () { + if (!showing) return; + showing = false; + if (progressTimerId != null) { + window.cancelAnimationFrame(progressTimerId); + progressTimerId = null; + } + (function loop() { + if (topbar.progress("+.1") >= 1) { + canvas.style.opacity -= 0.05; + if (canvas.style.opacity <= 0.05) { + canvas.style.display = "none"; + fadeTimerId = null; + return; + } + } + fadeTimerId = window.requestAnimationFrame(loop); + })(); + }, + }; + + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = topbar; + } else if (typeof define === "function" && define.amd) { + define(function () { + return topbar; + }); + } else { + this.topbar = topbar; + } +}.call(this, window, document)); diff --git a/config/config.exs b/config/config.exs new file mode 100644 index 0000000..79eeb0a --- /dev/null +++ b/config/config.exs @@ -0,0 +1,37 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Config module. +# +# This configuration file is loaded before any dependency and +# is restricted to this project. + +# General application configuration +import Config + +# Configures the endpoint +config :geo_therminator, GeoTherminatorWeb.Endpoint, + url: [host: "localhost"], + render_errors: [view: GeoTherminatorWeb.ErrorView, accepts: ~w(html json), layout: false], + pubsub_server: GeoTherminator.PubSub, + live_view: [signing_salt: "PC6YJv8v"] + +# Configure esbuild (the version is required) +config :esbuild, + version: "0.12.18", + default: [ + args: + ~w(js/app.js --bundle --target=es2016 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), + cd: Path.expand("../assets", __DIR__), + env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} + ] + +# Configures Elixir's Logger +config :logger, :console, + format: "$time $metadata[$level] $message\n", + metadata: [:request_id] + +# Use Jason for JSON parsing in Phoenix +config :phoenix, :json_library, Jason + +# Import environment specific config. This must remain at the bottom +# of this file so it overrides the configuration defined above. +import_config "#{config_env()}.exs" diff --git a/config/dev.exs b/config/dev.exs new file mode 100644 index 0000000..fa8ec49 --- /dev/null +++ b/config/dev.exs @@ -0,0 +1,65 @@ +import Config + +# For development, we disable any cache and enable +# debugging and code reloading. +# +# The watchers configuration can be used to run external +# watchers to your application. For example, we use it +# with esbuild to bundle .js and .css sources. +config :geo_therminator, GeoTherminatorWeb.Endpoint, + # Binding to loopback ipv4 address prevents access from other machines. + # Change to `ip: {0, 0, 0, 0}` to allow access from other machines. + http: [ip: {127, 0, 0, 1}, port: 4000], + check_origin: false, + code_reloader: true, + debug_errors: true, + secret_key_base: "iNdGHrsVxsC/iRd6ItQmU6WUOOgbs8lixEMdKIypmM2NuKb1PPrzncqR6ETXQvvR", + watchers: [ + # Start the esbuild watcher by calling Esbuild.install_and_run(:default, args) + esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]} + ] + +# ## SSL Support +# +# In order to use HTTPS in development, a self-signed +# certificate can be generated by running the following +# Mix task: +# +# mix phx.gen.cert +# +# Note that this task requires Erlang/OTP 20 or later. +# Run `mix help phx.gen.cert` for more information. +# +# The `http:` config above can be replaced with: +# +# https: [ +# port: 4001, +# cipher_suite: :strong, +# keyfile: "priv/cert/selfsigned_key.pem", +# certfile: "priv/cert/selfsigned.pem" +# ], +# +# If desired, both `http:` and `https:` keys can be +# configured to run both http and https servers on +# different ports. + +# Watch static and templates for browser reloading. +config :geo_therminator, GeoTherminatorWeb.Endpoint, + live_reload: [ + patterns: [ + ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", + ~r"priv/gettext/.*(po)$", + ~r"lib/geo_therminator_web/(live|views)/.*(ex)$", + ~r"lib/geo_therminator_web/templates/.*(eex)$" + ] + ] + +# Do not include metadata nor timestamps in development logs +config :logger, :console, format: "[$level] $message\n" + +# Set a higher stacktrace during development. Avoid configuring such +# in production as building large stacktraces may be expensive. +config :phoenix, :stacktrace_depth, 20 + +# Initialize plugs at runtime for faster development compilation +config :phoenix, :plug_init_mode, :runtime diff --git a/config/prod.exs b/config/prod.exs new file mode 100644 index 0000000..d9e2f22 --- /dev/null +++ b/config/prod.exs @@ -0,0 +1,51 @@ +import Config + +# For production, don't forget to configure the url host +# to something meaningful, Phoenix uses this information +# when generating URLs. +# +# Note we also include the path to a cache manifest +# containing the digested version of static files. This +# manifest is generated by the `mix phx.digest` task, +# which you should run after static files are built and +# before starting your production server. +config :geo_therminator, GeoTherminatorWeb.Endpoint, + url: [host: "example.com", port: 80], + cache_static_manifest: "priv/static/cache_manifest.json" + +# Do not print debug messages in production +config :logger, level: :info + +# ## SSL Support +# +# To get SSL working, you will need to add the `https` key +# to the previous section and set your `:url` port to 443: +# +# config :geo_therminator, GeoTherminatorWeb.Endpoint, +# ..., +# url: [host: "example.com", port: 443], +# https: [ +# ..., +# port: 443, +# cipher_suite: :strong, +# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), +# certfile: System.get_env("SOME_APP_SSL_CERT_PATH") +# ] +# +# The `cipher_suite` is set to `:strong` to support only the +# latest and more secure SSL ciphers. This means old browsers +# and clients may not be supported. You can set it to +# `:compatible` for wider support. +# +# `:keyfile` and `:certfile` expect an absolute path to the key +# and cert in disk or a relative path inside priv, for example +# "priv/ssl/server.key". For all supported SSL configuration +# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 +# +# We also recommend setting `force_ssl` in your endpoint, ensuring +# no data is ever sent via http, always redirecting to https: +# +# config :geo_therminator, GeoTherminatorWeb.Endpoint, +# force_ssl: [hsts: true] +# +# Check `Plug.SSL` for all available options in `force_ssl`. diff --git a/config/runtime.exs b/config/runtime.exs new file mode 100644 index 0000000..02d41e3 --- /dev/null +++ b/config/runtime.exs @@ -0,0 +1,109 @@ +import Config +import GeoTherminator.ConfigHelpers + +if config_env() == :dev do + DotenvParser.load_file(".env") +end + +config :geo_therminator, + api_timeout: 30_000, + api_username: get_env("API_USERNAME"), + api_password: get_env("API_PASSWORD"), + api_auth_url: + get_env("API_AUTH_URL", "https://thermia-auth-api.azurewebsites.net/api/v1/Jwt/login"), + api_installations_url: + get_env( + "API_INSTALLATIONS_URL", + "https://online-genesis-serviceapi.azurewebsites.net/api/v1/installationsInfo" + ), + api_device_url: + get_env( + "API_DEVICE_URL", + "https://online-genesis-serviceapi.azurewebsites.net/api/v1/installations/{id}" + ), + api_device_status_url: + get_env( + "API_DEVICE_STATUS_URL", + "https://online-genesis-serviceapi.azurewebsites.net/api/v1/installationstatus/{id}/status" + ), + api_device_register_url: + get_env( + "API_DEVICE_REGISTER_URL", + "https://online-genesis-serviceapi.azurewebsites.net/api/v1/Registers/Installations/{id}/Groups/REG_GROUP_TEMPERATURES" + ), + api_device_opstat_url: + get_env( + "API_DEVICE_OPSTAT_URL", + "https://online-genesis-serviceapi.azurewebsites.net/api/v1/Registers/Installations/{id}/Groups/REG_GROUP_OPERATIONAL_STATUS" + ), + api_opstat_mapping: %{ + # "REG_VALUE_STATUS_MANUAL" => 1, + 1 => :hand_operated, + # "REG_VALUE_STATUS_TAPWATER" => 3, + 3 => :hot_water, + # "REG_VALUE_STATUS_HEAT" => 4, + 4 => :heating, + # "REG_VALUE_STATUS_COOL" => 5, + 5 => :active_cooling, + # "REG_VALUE_STATUS_POOL" => 6, + 6 => :pool, + # "REG_VALUE_STATUS_LEGIONELLA" => 7, + 7 => :anti_legionella, + # "REG_VALUE_STATUS_PASSIVE_COOL" => 8, + 8 => :passive_cooling, + # "REG_VALUE_STATUS_STANDBY" => 98, + 98 => :standby, + # "REG_VALUE_STATUS_IDLE" => 99, + 99 => :idle, + # "REG_VALUE_STATUS_OFF" => 100 + 100 => :off + }, + api_device_reg_set_url: + get_env( + "API_DEVICE_REG_SET_URL", + "https://online-genesis-serviceapi.azurewebsites.net/api/v1/Registers/Installations/{id}/Registers" + ), + api_device_temp_set_reg_index: 3, + api_device_reg_set_client_id: get_env("API_DEVICE_REG_SET_CLIENT_ID"), + api_refresh: 10_000 + +# config/runtime.exs is executed for all environments, including +# during releases. It is executed after compilation and before the +# system starts, so it is typically used to load production configuration +# and secrets from environment variables or elsewhere. Do not define +# any compile-time configuration in here, as it won't be applied. +# The block below contains prod specific runtime configuration. +if config_env() == :prod do + # The secret key base is used to sign/encrypt cookies and other secrets. + # A default value is used in config/dev.exs and config/test.exs but you + # want to use a different value for prod and you most likely don't want + # to check this value into version control, so we use an environment + # variable instead. + secret_key_base = + System.get_env("SECRET_KEY_BASE") || + raise """ + environment variable SECRET_KEY_BASE is missing. + You can generate one by calling: mix phx.gen.secret + """ + + config :geo_therminator, GeoTherminatorWeb.Endpoint, + http: [ + # Enable IPv6 and bind on all interfaces. + # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. + # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html + # for details about using IPv6 vs IPv4 and loopback vs public addresses. + ip: {0, 0, 0, 0, 0, 0, 0, 0}, + port: String.to_integer(System.get_env("PORT") || "4000") + ], + secret_key_base: secret_key_base + + # ## Using releases + # + # If you are doing OTP releases, you need to instruct Phoenix + # to start each relevant endpoint: + # + # config :geo_therminator, GeoTherminatorWeb.Endpoint, server: true + # + # Then you can assemble a release by calling `mix release`. + # See `mix help release` for more information. +end diff --git a/config/test.exs b/config/test.exs new file mode 100644 index 0000000..8bba849 --- /dev/null +++ b/config/test.exs @@ -0,0 +1,14 @@ +import Config + +# We don't run a server during test. If one is required, +# you can enable the server option below. +config :geo_therminator, GeoTherminatorWeb.Endpoint, + http: [ip: {127, 0, 0, 1}, port: 4002], + secret_key_base: "jTM8H/r05f0LEiokDoSBgftJugkpUkfr/0wpwwISIZ6wOOM+90aKvcAF8G21pNKA", + server: false + +# Print only warnings and errors during test +config :logger, level: :warn + +# Initialize plugs at runtime for faster test compilation +config :phoenix, :plug_init_mode, :runtime diff --git a/lib/geo_therminator/application.ex b/lib/geo_therminator/application.ex new file mode 100644 index 0000000..de92c7b --- /dev/null +++ b/lib/geo_therminator/application.ex @@ -0,0 +1,46 @@ +defmodule GeoTherminator.Application do + # See https://hexdocs.pm/elixir/Application.html + # for more information on OTP Applications + @moduledoc false + + use Application + + @impl true + def start(_type, _args) do + auth_username = Application.get_env(:geo_therminator, :api_username) + auth_password = Application.get_env(:geo_therminator, :api_password) + + children = [ + {Finch, name: GeoTherminator.PumpAPI.HTTP}, + {Phoenix.PubSub, name: GeoTherminator.PumpAPI.Device.PubSub}, + {Registry, keys: :unique, name: GeoTherminator.PumpAPI.Device.Registry}, + {DynamicSupervisor, strategy: :one_for_one, name: GeoTherminator.PumpAPI.Device.Supervisor}, + {GeoTherminator.PumpAPI.Auth.Server, + %GeoTherminator.PumpAPI.Auth.Server.Options{ + server_name: GeoTherminator.PumpAPI.Auth.Server, + username: auth_username, + password: auth_password + }}, + + # Start the Telemetry supervisor + GeoTherminatorWeb.Telemetry, + # Start the PubSub system + Supervisor.child_spec({Phoenix.PubSub, name: GeoTherminator.PubSub}, id: :phoenix_pubsub), + # Start the Endpoint (http/https) + GeoTherminatorWeb.Endpoint + ] + + # See https://hexdocs.pm/elixir/Supervisor.html + # for other strategies and supported options + opts = [strategy: :one_for_one, name: GeoTherminator.Supervisor] + Supervisor.start_link(children, opts) + end + + # Tell Phoenix to update the endpoint configuration + # whenever the application is updated. + @impl true + def config_change(changed, _new, removed) do + GeoTherminatorWeb.Endpoint.config_change(changed, removed) + :ok + end +end diff --git a/lib/geo_therminator/config_helpers.ex b/lib/geo_therminator/config_helpers.ex new file mode 100644 index 0000000..8c85375 --- /dev/null +++ b/lib/geo_therminator/config_helpers.ex @@ -0,0 +1,35 @@ +defmodule GeoTherminator.ConfigHelpers do + @type config_type :: :str | :int | :bool | :json + + @doc """ + Get value from environment variable, converting it to the given type if needed. + + If no default value is given, or `:no_default` is given as the default, an error is raised if the variable is not + set. + """ + @spec get_env(String.t(), :no_default | any(), config_type()) :: any() + def get_env(var, default \\ :no_default, type \\ :str) + + def get_env(var, :no_default, type) do + System.fetch_env!(var) + |> get_with_type(type) + end + + def get_env(var, default, type) do + with {:ok, val} <- System.fetch_env(var) do + get_with_type(val, type) + else + :error -> default + end + end + + @spec get_with_type(String.t(), config_type()) :: any() + defp get_with_type(val, type) + + defp get_with_type(val, :str), do: val + defp get_with_type(val, :int), do: String.to_integer(val) + defp get_with_type("true", :bool), do: true + defp get_with_type("false", :bool), do: false + defp get_with_type(val, :json), do: Jason.decode!(val) + defp get_with_type(val, type), do: raise("Cannot convert to #{inspect(type)}: #{inspect(val)}") +end diff --git a/lib/geo_therminator/pump_api/auth/api.ex b/lib/geo_therminator/pump_api/auth/api.ex new file mode 100644 index 0000000..9ce3da8 --- /dev/null +++ b/lib/geo_therminator/pump_api/auth/api.ex @@ -0,0 +1,60 @@ +defmodule GeoTherminator.PumpAPI.Auth.API do + alias GeoTherminator.PumpAPI.HTTP + alias GeoTherminator.PumpAPI.Auth + + require Logger + + @spec auth(String.t(), String.t()) :: Auth.User.t() + def auth(username, password) do + url = Application.get_env(:geo_therminator, :api_auth_url) + + req = + HTTP.req(:post, url, [], %{ + username: username, + password: password + }) + + {:ok, response} = Finch.request(req, HTTP) + + if response.status != 200 do + raise "Request error #{response.status}: #{inspect(response.body)}" + end + + json = Jason.decode!(response.body) + + {:ok, valid_to, _} = DateTime.from_iso8601(json["tokenValidToUtc"]) + + token = %Auth.Token{ + token: json["token"], + token_valid_to: valid_to + } + + %Auth.User{ + user_name: json["userName"], + email: json["email"], + first_name: json["firstName"], + last_name: json["lastName"], + culture: json["culture"], + eula_accepted: json["eulaAccepted"], + is_authenticated: json["isAuthenticated"], + time_zone: json["timeZone"], + token: token + } + end + + @spec installations_info(Auth.User.t()) :: [Auth.InstallationInfo.t()] + def installations_info(user) do + url = Application.get_env(:geo_therminator, :api_installations_url) + + req = HTTP.authed_req(user, :get, url) + {:ok, response} = Finch.request(req, HTTP) + + json = Jason.decode!(response.body) + + Enum.map(json["installations"], fn item -> + %Auth.InstallationInfo{ + id: item["id"] + } + end) + end +end diff --git a/lib/geo_therminator/pump_api/auth/installation_info.ex b/lib/geo_therminator/pump_api/auth/installation_info.ex new file mode 100644 index 0000000..7868240 --- /dev/null +++ b/lib/geo_therminator/pump_api/auth/installation_info.ex @@ -0,0 +1,8 @@ +defmodule GeoTherminator.PumpAPI.Auth.InstallationInfo do + import GeoTherminator.TypedStruct + + deftypedstruct(%{ + id: integer() + # ... + }) +end diff --git a/lib/geo_therminator/pump_api/auth/server.ex b/lib/geo_therminator/pump_api/auth/server.ex new file mode 100644 index 0000000..0fa5377 --- /dev/null +++ b/lib/geo_therminator/pump_api/auth/server.ex @@ -0,0 +1,106 @@ +defmodule GeoTherminator.PumpAPI.Auth.Server do + use GenServer + import GeoTherminator.TypedStruct + alias GeoTherminator.PumpAPI.Auth + require Logger + + @token_check_timer 10_000 + @token_check_diff 5 * 60 + + defmodule Options do + deftypedstruct(%{ + server_name: GenServer.name(), + username: String.t(), + password: String.t() + }) + end + + defmodule State do + deftypedstruct(%{ + username: String.t(), + password: String.t(), + authed_user: {Auth.User.t() | nil, nil}, + installations_fetched: {boolean(), false}, + installations: {[Auth.InstallationInfo.t()], []} + }) + end + + @spec start_link(Options.t()) :: GenServer.on_start() + def start_link(opts) do + GenServer.start_link(__MODULE__, opts, name: opts.server_name) + end + + @impl true + def init(%Options{} = opts) do + {:ok, %State{username: opts.username, password: opts.password}, {:continue, :init}} + end + + @impl true + def handle_continue(:init, state) do + user = Auth.API.auth(state.username, state.password) + installations = Auth.API.installations_info(user) + + schedule_token_check() + + state = %State{ + state + | authed_user: user, + installations: installations, + installations_fetched: true + } + + {:noreply, state} + end + + @impl true + def handle_call(msg, from, state) + + def handle_call(:get_auth, _from, state) do + {:reply, state.authed_user, state} + end + + def handle_call(:get_installations, _from, state) do + {:reply, state.installations, state} + end + + def handle_call({:get_installation, id}, _from, state) do + {:reply, Enum.find(state.installations, &(&1.id == id)), state} + end + + @impl true + def handle_info(msg, state) + + def handle_info(:token_check, state) do + now = DateTime.utc_now() + diff = DateTime.diff(state.authed_user.token.token_valid_to, now) + + schedule_token_check() + + if diff < @token_check_diff do + Logger.debug("Renewing auth token since #{diff} < #{@token_check_diff}") + user = Auth.API.auth(state.username, state.password) + {:noreply, %State{state | authed_user: user}} + else + {:noreply, state} + end + end + + @spec get_auth(GenServer.name()) :: Auth.User.t() + def get_auth(server) do + GenServer.call(server, :get_auth) + end + + @spec get_installations(GenServer.name()) :: Auth.InstallationInfo.t() + def get_installations(server) do + GenServer.call(server, :get_installations) + end + + @spec get_installation(GenServer.name(), integer()) :: Auth.InstallationInfo.t() | nil + def get_installation(server, id) do + GenServer.call(server, {:get_installation, id}) + end + + defp schedule_token_check() do + Process.send_after(self(), :token_check, @token_check_timer) + end +end diff --git a/lib/geo_therminator/pump_api/auth/token.ex b/lib/geo_therminator/pump_api/auth/token.ex new file mode 100644 index 0000000..056979d --- /dev/null +++ b/lib/geo_therminator/pump_api/auth/token.ex @@ -0,0 +1,8 @@ +defmodule GeoTherminator.PumpAPI.Auth.Token do + import GeoTherminator.TypedStruct + + deftypedstruct(%{ + token: String.t(), + token_valid_to: DateTime.t() + }) +end diff --git a/lib/geo_therminator/pump_api/auth/user.ex b/lib/geo_therminator/pump_api/auth/user.ex new file mode 100644 index 0000000..822b75d --- /dev/null +++ b/lib/geo_therminator/pump_api/auth/user.ex @@ -0,0 +1,15 @@ +defmodule GeoTherminator.PumpAPI.Auth.User do + import GeoTherminator.TypedStruct + + deftypedstruct(%{ + user_name: String.t(), + email: String.t(), + first_name: String.t(), + last_name: String.t(), + culture: String.t(), + eula_accepted: boolean(), + is_authenticated: boolean(), + time_zone: String.t(), + token: GeoTherminator.PumpAPI.Auth.Token.t() + }) +end diff --git a/lib/geo_therminator/pump_api/device/api.ex b/lib/geo_therminator/pump_api/device/api.ex new file mode 100644 index 0000000..3c7ff3c --- /dev/null +++ b/lib/geo_therminator/pump_api/device/api.ex @@ -0,0 +1,142 @@ +defmodule GeoTherminator.PumpAPI.Device.API do + alias GeoTherminator.PumpAPI.HTTP + alias GeoTherminator.PumpAPI.Device + alias GeoTherminator.PumpAPI.Auth + + @spec device_info(Auth.User.t(), Device.InstallationInfo.t()) :: Device.t() + def device_info(user, installation) do + url = + Application.get_env(:geo_therminator, :api_device_url) + |> String.replace("{id}", to_string(installation.id)) + + req = HTTP.authed_req(user, :get, url) + + {:ok, response} = Finch.request(req, HTTP) + json = Jason.decode!(response.body) + + last_online = NaiveDateTime.from_iso8601!(json["lastOnline"]) + created_when = NaiveDateTime.from_iso8601!(json["createdWhen"]) + + %Device{ + id: json["id"], + device_id: json["deviceId"], + is_online: json["isOnline"], + last_online: last_online, + created_when: created_when, + mac_address: json["macAddress"], + name: json["name"], + model: json["model"], + retailer_access: json["retailerAccess"] + } + end + + @spec status(Auth.User.t(), Device.t()) :: Device.Status.t() + def status(user, device) do + url = + Application.get_env(:geo_therminator, :api_device_status_url) + |> String.replace("{id}", to_string(device.id)) + + req = HTTP.authed_req(user, :get, url) + + {:ok, response} = Finch.request(req, HTTP) + json = Jason.decode!(response.body) + + %Device.Status{ + heating_effect: json["heatingEffect"], + is_heating_effect_set_by_user: json["isHeatingEffectSetByUser"] + } + end + + @spec register_info(Auth.User.t(), Device.t()) :: Device.RegisterCollection.t() + def register_info(user, device) do + url = + Application.get_env(:geo_therminator, :api_device_register_url) + |> String.replace("{id}", to_string(device.id)) + + req = HTTP.authed_req(user, :get, url) + + {:ok, response} = Finch.request(req, HTTP) + json = Jason.decode!(response.body) + + registers = + Enum.map(json, fn item -> + {:ok, timestamp, _} = DateTime.from_iso8601(item["timeStamp"]) + + %Device.Register{ + register_name: item["registerName"], + register_value: item["registerValue"], + timestamp: timestamp + } + end) + + %Device.RegisterCollection{ + outdoor_temp: find_register(registers, "REG_OUTDOOR_TEMPERATURE"), + supply_out: find_register(registers, "REG_SUPPLY_LINE"), + supply_in: find_register(registers, "REG_OPER_DATA_RETURN"), + desired_supply: find_register(registers, "REG_DESIRED_SYS_SUPPLY_LINE_TEMP"), + brine_out: find_register(registers, "REG_BRINE_OUT"), + brine_in: find_register(registers, "REG_BRINE_IN"), + hot_water_temp: find_register(registers, "REG_HOT_WATER_TEMPERATURE") + } + end + + @spec opstat(Auth.User.t(), Device.t()) :: Device.OpStat.t() + def opstat(user, device) do + url = + Application.get_env(:geo_therminator, :api_device_opstat_url) + |> String.replace("{id}", to_string(device.id)) + + req = HTTP.authed_req(user, :get, url) + + {:ok, response} = Finch.request(req, HTTP) + json = Jason.decode!(response.body) + + registers = + Enum.map(json, fn item -> + {:ok, timestamp, _} = DateTime.from_iso8601(item["timeStamp"]) + + %Device.Register{ + register_name: item["registerName"], + register_value: item["registerValue"], + timestamp: timestamp + } + end) + + priority_register = find_register(registers, "REG_OPERATIONAL_STATUS_PRIO1") + mapping = Application.get_env(:geo_therminator, :api_opstat_mapping) + + %Device.OpStat{ + priority: Map.fetch!(mapping, priority_register.register_value) + } + end + + @spec set_temp(Auth.User.t(), Device.t(), integer()) :: :ok | {:error, String.t()} + def set_temp(user, device, temp) do + url = + Application.get_env(:geo_therminator, :api_device_reg_set_url) + |> String.replace("{id}", to_string(device.id)) + + register_index = Application.get_env(:geo_therminator, :api_device_temp_set_reg_index) + client_id = Application.get_env(:geo_therminator, :api_device_reg_set_client_id) + + req = + HTTP.authed_req(user, :post, url, [], %{ + registerIndex: register_index, + registerValue: temp, + clientUuid: client_id + }) + + IO.inspect(req) + {:ok, response} = Finch.request(req, HTTP) + + if response.status == 200 do + :ok + else + {:error, "Error #{response.status}: " <> response.body} + end + end + + defp find_register(registers, name) do + Enum.find(registers, &(&1.register_name == name)) + end +end diff --git a/lib/geo_therminator/pump_api/device/device.ex b/lib/geo_therminator/pump_api/device/device.ex new file mode 100644 index 0000000..3c263a6 --- /dev/null +++ b/lib/geo_therminator/pump_api/device/device.ex @@ -0,0 +1,81 @@ +defmodule GeoTherminator.PumpAPI.Device do + import GeoTherminator.TypedStruct + + deftypedstruct(%{ + id: integer(), + device_id: integer(), + is_online: boolean(), + last_online: NaiveDateTime.t(), + created_when: NaiveDateTime.t(), + mac_address: String.t(), + name: String.t(), + model: String.t(), + retailer_access: integer() + }) + + defmodule Status do + deftypedstruct(%{ + heating_effect: integer(), + is_heating_effect_set_by_user: boolean() + }) + end + + defmodule Register do + deftypedstruct(%{ + register_name: String.t(), + register_value: integer(), + timestamp: DateTime.t() + }) + end + + defmodule RegisterCollection do + deftypedstruct(%{ + outdoor_temp: Register.t(), + supply_out: Register.t(), + supply_in: Register.t(), + desired_supply: Register.t(), + brine_out: Register.t(), + brine_in: Register.t(), + hot_water_temp: Register.t() + }) + end + + defmodule OpStat do + deftypedstruct(%{ + priority: + :hand_operated + | :hot_water + | :heating + | :active_cooling + | :pool + | :anti_legionella + | :passive_cooling + | :standby + | :idle + | :off + }) + end + + @spec get_device_process(GenServer.name(), GeoTherminator.PumpAPI.Auth.InstallationInfo.t()) :: + {:ok, GenServer.name()} | :error + def get_device_process(auth_server, installation) do + case DynamicSupervisor.start_child( + __MODULE__.Supervisor, + {__MODULE__.Server, + %__MODULE__.Server.Options{ + auth_server: auth_server, + installation: installation + }} + ) do + {:ok, pid} -> + {:ok, pid} + + {:error, {:already_started, pid}} -> + {:ok, pid} + + err -> + IO.inspect(err) + :error + end + end +end diff --git a/lib/geo_therminator/pump_api/device/pub_sub.ex b/lib/geo_therminator/pump_api/device/pub_sub.ex new file mode 100644 index 0000000..7679b1a --- /dev/null +++ b/lib/geo_therminator/pump_api/device/pub_sub.ex @@ -0,0 +1,59 @@ +defmodule GeoTherminator.PumpAPI.Device.PubSub do + alias Phoenix.PubSub + + @installation_topic "installation:" + + @spec subscribe_installation(GeoTherminator.PumpAPI.Auth.InstallationInfo.t()) :: :ok + def subscribe_installation(installation) do + :ok = PubSub.subscribe(__MODULE__, @installation_topic <> to_string(installation.id)) + end + + @spec broadcast_device(GeoTherminator.PumpAPI.Device.t()) :: :ok + def broadcast_device(device) do + :ok = + PubSub.broadcast!( + __MODULE__, + @installation_topic <> to_string(device.id), + {:device, device} + ) + end + + @spec broadcast_status( + GeoTherminator.PumpAPI.Device.t(), + GeoTherminator.PumpAPI.Device.Status.t() + ) :: :ok + def broadcast_status(device, status) do + :ok = + PubSub.broadcast!( + __MODULE__, + @installation_topic <> to_string(device.id), + {:status, status} + ) + end + + @spec broadcast_registers( + GeoTherminator.PumpAPI.Device.t(), + GeoTherminator.PumpAPI.Device.RegisterCollection.t() + ) :: :ok + def broadcast_registers(device, registers) do + :ok = + PubSub.broadcast!( + __MODULE__, + @installation_topic <> to_string(device.id), + {:registers, registers} + ) + end + + @spec broadcast_opstat( + GeoTherminator.PumpAPI.Device.t(), + GeoTherminator.PumpAPI.Device.OpStat.t() + ) :: :ok + def broadcast_opstat(device, opstat) do + :ok = + PubSub.broadcast!( + __MODULE__, + @installation_topic <> to_string(device.id), + {:opstat, opstat} + ) + end +end diff --git a/lib/geo_therminator/pump_api/device/server.ex b/lib/geo_therminator/pump_api/device/server.ex new file mode 100644 index 0000000..c511483 --- /dev/null +++ b/lib/geo_therminator/pump_api/device/server.ex @@ -0,0 +1,138 @@ +defmodule GeoTherminator.PumpAPI.Device.Server do + use GenServer + import GeoTherminator.TypedStruct + alias GeoTherminator.PumpAPI.Device + alias GeoTherminator.PumpAPI.Auth.InstallationInfo + alias GeoTherminator.PumpAPI.Auth.Server, as: AuthServer + require Logger + + defmodule Options do + deftypedstruct(%{ + auth_server: GenServer.name(), + installation: InstallationInfo.t() + }) + end + + defmodule State do + deftypedstruct(%{ + auth_server: GenServer.name(), + device: {Device.t() | nil, nil}, + status: {Device.Status.t() | nil, nil}, + registers: {Device.RegisterCollection.t() | nil, nil}, + opstat: {Device.OpStat.t() | nil, nil} + }) + end + + @spec start_link(Options.t()) :: GenServer.on_start() + def start_link(opts) do + GenServer.start_link(__MODULE__, opts, + name: {:via, Registry, {Device.Registry, opts.installation.id}} + ) + end + + @impl true + def init(%Options{} = opts) do + {:ok, %State{auth_server: opts.auth_server}, {:continue, {:init, opts.installation}}} + end + + @impl true + def handle_continue({:init, installation}, state) do + user = AuthServer.get_auth(state.auth_server) + device = Device.API.device_info(user, installation) + + :ok = Device.PubSub.broadcast_device(device) + + state = + %State{state | device: device} + |> refresh_status() + + schedule_status() + {:noreply, state} + end + + @impl true + def handle_call(msg, from, state) + + def handle_call(:get_device, _from, state) do + {:reply, state.device, state} + end + + def handle_call(:get_status, _from, state) do + {:reply, state.status, state} + end + + def handle_call(:get_registers, _from, state) do + {:reply, state.registers, state} + end + + def handle_call(:get_opstat, _from, state) do + {:reply, state.opstat, state} + end + + def handle_call({:set_temp, temp}, _from, state) do + user = AuthServer.get_auth(state.auth_server) + + Logger.debug("Begin set temp to #{temp}") + resp = Device.API.set_temp(user, state.device, temp) + Logger.debug("Set temp result: #{inspect(resp)}") + {:reply, resp, state} + end + + @impl true + def handle_info(msg, state) + + def handle_info(:refresh_status, state) do + state = refresh_status(state) + schedule_status() + {:noreply, state} + end + + @spec get_device(GenServer.name()) :: Device.t() + def get_device(server) do + GenServer.call(server, :get_device) + end + + @spec get_status(GenServer.name()) :: Device.Status.t() + def get_status(server) do + GenServer.call(server, :get_status) + end + + @spec get_registers(GenServer.name()) :: Device.RegisterCollection.t() + def get_registers(server) do + GenServer.call(server, :get_registers) + end + + @spec get_opstat(GenServer.name()) :: Device.OpStat.t() + def get_opstat(server) do + GenServer.call(server, :get_opstat) + end + + @spec set_temp(GenServer.name(), integer()) :: :ok | {:error, String.t()} + def set_temp(server, temp) do + GenServer.call(server, {:set_temp, temp}) + end + + defp refresh_status(state) do + user = AuthServer.get_auth(state.auth_server) + + [status, registers, opstat] = + Task.async_stream( + [&Device.API.status/2, &Device.API.register_info/2, &Device.API.opstat/2], + & &1.(user, state.device) + ) + |> Enum.map(fn {:ok, val} -> val end) + + Device.PubSub.broadcast_status(state.device, status) + Device.PubSub.broadcast_registers(state.device, registers) + Device.PubSub.broadcast_opstat(state.device, opstat) + %State{state | status: status, registers: registers, opstat: opstat} + end + + defp schedule_status() do + Process.send_after( + self(), + :refresh_status, + Application.get_env(:geo_therminator, :api_refresh) + ) + end +end diff --git a/lib/geo_therminator/pump_api/http.ex b/lib/geo_therminator/pump_api/http.ex new file mode 100644 index 0000000..b171712 --- /dev/null +++ b/lib/geo_therminator/pump_api/http.ex @@ -0,0 +1,49 @@ +defmodule GeoTherminator.PumpAPI.HTTP do + @spec authed_req( + GeoTherminator.PumpAPI.Auth.User.t(), + Finch.Request.method(), + Finch.Request.url(), + Finch.Request.headers(), + map() | nil, + Keyword.t() + ) :: + Finch.Request.t() + def authed_req(user, method, url, headers \\ [], body \\ nil, opts \\ []) do + headers = + headers + |> List.keystore("authorization", 0, {"authorization", "Bearer #{user.token.token}"}) + + req(method, url, headers, body, opts) + end + + @spec req( + Finch.Request.method(), + Finch.Request.url(), + Finch.Request.headers(), + map() | nil, + Keyword.t() + ) :: + Finch.Request.t() + def req(method, url, headers \\ [], body \\ nil, opts \\ []) do + headers = + headers + |> List.keystore("accept", 0, {"accept", "application/json"}) + + headers = + if not is_nil(body) do + List.keystore(headers, "content-type", 0, {"content-type", "application/json"}) + else + headers + end + + opts = Keyword.put(opts, :timeout, Application.get_env(:geo_therminator, :api_timeout)) + + Finch.build( + method, + url, + headers, + if(not is_nil(body), do: Jason.encode!(body)), + opts + ) + end +end diff --git a/lib/geo_therminator/typed_struct.ex b/lib/geo_therminator/typed_struct.ex new file mode 100644 index 0000000..a61bae5 --- /dev/null +++ b/lib/geo_therminator/typed_struct.ex @@ -0,0 +1,71 @@ +defmodule GeoTherminator.TypedStruct do + @doc """ + Create typed struct with a type, default values, and enforced keys. + + Input should be a map where the key names are names of the struct keys and values are the + field information. The value can be a typespec, in which case the field will be enforced, or + a 2-tuple of `{typespec, default_value}`, making the field unenforced. + + To prevent ambiguity, a value of `{typespec, :ts_enforced}` will be interpreted as enforced, + this will allow you to typespec a 2-tuple. + + NOTE: Due to the ambiguity removal technique above, `:ts_enforced` is not allowed as a default + value. + + Example: + + ```elixir + deftypedstruct(%{ + # Enforced with simple type + foo: integer(), + + # Enforced 2-tuple typed field, written like this to remove ambiguity + bar: {{String.t(), integer()}, :ts_enforced}, + + # Non-enforced field with default value + baz: {any(), ""} + }) + ``` + """ + defmacro deftypedstruct(fields) do + fields_list = + case fields do + {:%{}, _, flist} -> flist + _ -> raise ArgumentError, "Fields must be a map!" + end + + enforced_list = + fields_list + |> Enum.filter(fn + {_, {_, :ts_enforced}} -> true + {_, {_, _}} -> false + {_, _} -> true + end) + |> Enum.map(&elem(&1, 0)) + + field_specs = + Enum.map(fields_list, fn + {field, {typespec, :ts_enforced}} -> + {field, typespec} + + {field, {typespec, _}} -> + {field, typespec} + + {field, typespec} -> + {field, typespec} + end) + + field_vals = + Enum.map(fields_list, fn + {field, {_, :ts_enforced}} -> field + {field, {_, default}} -> {field, default} + {field, _} -> field + end) + + quote do + @type t :: %__MODULE__{unquote_splicing(field_specs)} + @enforce_keys unquote(enforced_list) + defstruct unquote(field_vals) + end + end +end diff --git a/lib/geo_therminator_web/endpoint.ex b/lib/geo_therminator_web/endpoint.ex new file mode 100644 index 0000000..c1f2803 --- /dev/null +++ b/lib/geo_therminator_web/endpoint.ex @@ -0,0 +1,49 @@ +defmodule GeoTherminatorWeb.Endpoint do + use Phoenix.Endpoint, otp_app: :geo_therminator + + # The session will be stored in the cookie and signed, + # this means its contents can be read but not tampered with. + # Set :encryption_salt if you would also like to encrypt it. + @session_options [ + store: :cookie, + key: "_geo_therminator_key", + signing_salt: "j8JUzvur" + ] + + socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] + + # Serve at "/" the static files from "priv/static" directory. + # + # You should set gzip to true if you are running phx.digest + # when deploying your static files in production. + plug Plug.Static, + at: "/", + from: :geo_therminator, + gzip: false, + only: ~w(assets fonts images favicon.ico robots.txt) + + # Code reloading can be explicitly enabled under the + # :code_reloader configuration of your endpoint. + if code_reloading? do + socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket + plug Phoenix.LiveReloader + plug Phoenix.CodeReloader + end + + plug Phoenix.LiveDashboard.RequestLogger, + param_key: "request_logger", + cookie_key: "request_logger" + + plug Plug.RequestId + plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] + + plug Plug.Parsers, + parsers: [:urlencoded, :multipart, :json], + pass: ["*/*"], + json_decoder: Phoenix.json_library() + + plug Plug.MethodOverride + plug Plug.Head + plug Plug.Session, @session_options + plug GeoTherminatorWeb.Router +end diff --git a/lib/geo_therminator_web/geo_therminator_web.ex b/lib/geo_therminator_web/geo_therminator_web.ex new file mode 100644 index 0000000..1d9718a --- /dev/null +++ b/lib/geo_therminator_web/geo_therminator_web.ex @@ -0,0 +1,102 @@ +defmodule GeoTherminatorWeb do + @moduledoc """ + The entrypoint for defining your web interface, such + as controllers, views, channels and so on. + + This can be used in your application as: + + use GeoTherminatorWeb, :controller + use GeoTherminatorWeb, :view + + The definitions below will be executed for every view, + controller, etc, so keep them short and clean, focused + on imports, uses and aliases. + + Do NOT define functions inside the quoted expressions + below. Instead, define any helper function in modules + and import those modules here. + """ + + def controller do + quote do + use Phoenix.Controller, namespace: GeoTherminatorWeb + + import Plug.Conn + import GeoTherminatorWeb.Gettext + alias GeoTherminatorWeb.Router.Helpers, as: Routes + end + end + + def view do + quote do + use Phoenix.View, + root: "lib/geo_therminator_web/templates", + namespace: GeoTherminatorWeb + + # Import convenience functions from controllers + import Phoenix.Controller, + only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1] + + # Include shared imports and aliases for views + unquote(view_helpers()) + end + end + + def live_view do + quote do + use Phoenix.LiveView, + layout: {GeoTherminatorWeb.LayoutView, "live.html"} + + unquote(view_helpers()) + end + end + + def live_component do + quote do + use Phoenix.LiveComponent + + unquote(view_helpers()) + end + end + + def router do + quote do + use Phoenix.Router + + import Plug.Conn + import Phoenix.Controller + import Phoenix.LiveView.Router + end + end + + def channel do + quote do + use Phoenix.Channel + import GeoTherminatorWeb.Gettext + end + end + + defp view_helpers do + quote do + # Use all HTML functionality (forms, tags, etc) + use Phoenix.HTML + + # Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc) + import Phoenix.LiveView.Helpers + + # Import basic rendering functionality (render, render_layout, etc) + import Phoenix.View + + import GeoTherminatorWeb.ErrorHelpers + import GeoTherminatorWeb.Gettext + alias GeoTherminatorWeb.Router.Helpers, as: Routes + end + end + + @doc """ + When used, dispatch to the appropriate controller/view/etc. + """ + defmacro __using__(which) when is_atom(which) do + apply(__MODULE__, which, []) + end +end diff --git a/lib/geo_therminator_web/gettext.ex b/lib/geo_therminator_web/gettext.ex new file mode 100644 index 0000000..427154d --- /dev/null +++ b/lib/geo_therminator_web/gettext.ex @@ -0,0 +1,24 @@ +defmodule GeoTherminatorWeb.Gettext do + @moduledoc """ + A module providing Internationalization with a gettext-based API. + + By using [Gettext](https://hexdocs.pm/gettext), + your module gains a set of macros for translations, for example: + + import GeoTherminatorWeb.Gettext + + # Simple translation + gettext("Here is the string to translate") + + # Plural translation + ngettext("Here is the string to translate", + "Here are the strings to translate", + 3) + + # Domain-based translation + dgettext("errors", "Here is the error message to translate") + + See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. + """ + use Gettext, otp_app: :geo_therminator +end diff --git a/lib/geo_therminator_web/live/components/main_view.ex b/lib/geo_therminator_web/live/components/main_view.ex new file mode 100644 index 0000000..474d246 --- /dev/null +++ b/lib/geo_therminator_web/live/components/main_view.ex @@ -0,0 +1,19 @@ +defmodule GeoTherminatorWeb.Components.MainView do + use GeoTherminatorWeb, :live_component + + @impl true + def update(assigns, socket) do + {:ok, + assign(socket, + set_temp: assigns.status.heating_effect, + set_temp_active: assigns.status.is_heating_effect_set_by_user, + hot_water_temp: assigns.registers.hot_water_temp.register_value, + brine_out: assigns.registers.brine_out.register_value, + brine_in: assigns.registers.brine_in.register_value, + supply_out: assigns.registers.supply_out.register_value, + supply_in: assigns.registers.supply_in.register_value, + outdoor_temp: assigns.registers.outdoor_temp.register_value, + priority: assigns.opstat.priority + )} + end +end diff --git a/lib/geo_therminator_web/live/components/main_view.html.heex b/lib/geo_therminator_web/live/components/main_view.html.heex new file mode 100644 index 0000000..b319d74 --- /dev/null +++ b/lib/geo_therminator_web/live/components/main_view.html.heex @@ -0,0 +1,200 @@ +
+ + + + + + + + + + + + + + + + + + + + + + <%= @outdoor_temp %>°C + + + + + + + <%= if @priority == :heating do %> + + <% end %> + + <%= if @priority == :hot_water do %> + + <% end %> + + + + + + + <%= @set_temp %>°C + + + + + + - + + + + + + + + + + + + + + + + + + + <%= @brine_in %>°C + + + + + + <%= @brine_out %>°C + + + + + + <%= @supply_in %>°C + + + + + + <%= @supply_out %>°C + + + + + + <%= @hot_water_temp %>°C + + + + + + + + + + + + + + + + + + + + + + + + + Viewer does not support full SVG 1.1 + + + + + +
diff --git a/lib/geo_therminator_web/live/main/index.ex b/lib/geo_therminator_web/live/main/index.ex new file mode 100644 index 0000000..78c71da --- /dev/null +++ b/lib/geo_therminator_web/live/main/index.ex @@ -0,0 +1,13 @@ +defmodule GeoTherminatorWeb.MainLive.Index do + use GeoTherminatorWeb, :live_view + + @impl true + def mount(_params, _session, socket) do + user = GeoTherminator.PumpAPI.Auth.Server.get_auth(GeoTherminator.PumpAPI.Auth.Server) + + installations = + GeoTherminator.PumpAPI.Auth.Server.get_installations(GeoTherminator.PumpAPI.Auth.Server) + + {:ok, assign(socket, user: user, installations: installations)} + end +end diff --git a/lib/geo_therminator_web/live/main/index.html.heex b/lib/geo_therminator_web/live/main/index.html.heex new file mode 100644 index 0000000..99a38c0 --- /dev/null +++ b/lib/geo_therminator_web/live/main/index.html.heex @@ -0,0 +1,17 @@ +
+
+

Welcome, <%= @user.first_name %>!

+
+ +
+

Your available pumps

+
    + <%= for installation <- @installations do %> +
  • <%= live_redirect(installation.id, to: Routes.live_path(@socket, GeoTherminatorWeb.MainLive.Pump, installation.id)) %>
  • + <% end %> +
+
+ +
+
+
diff --git a/lib/geo_therminator_web/live/main/pump.ex b/lib/geo_therminator_web/live/main/pump.ex new file mode 100644 index 0000000..54ac600 --- /dev/null +++ b/lib/geo_therminator_web/live/main/pump.ex @@ -0,0 +1,92 @@ +defmodule GeoTherminatorWeb.MainLive.Pump do + use GeoTherminatorWeb, :live_view + alias GeoTherminator.PumpAPI.Auth + alias GeoTherminator.PumpAPI.Device + require Logger + + @impl true + def mount(%{"id" => str_id}, _session, socket) do + socket = + with {id, ""} <- Integer.parse(str_id), + %Auth.InstallationInfo{} = info <- Auth.Server.get_installation(Auth.Server, id), + :ok <- Device.PubSub.subscribe_installation(info), + {:ok, pid} <- Device.get_device_process(Auth.Server, info), + %Device{} = device <- Device.Server.get_device(pid), + %Device.Status{} = status <- Device.Server.get_status(pid), + %Device.RegisterCollection{} = registers <- Device.Server.get_registers(pid), + %Device.OpStat{} = opstat <- Device.Server.get_opstat(pid) do + assign(socket, + pid: pid, + device: device, + status: status, + registers: registers, + opstat: opstat + ) + else + err -> + Logger.debug("EXPLODY #{inspect(err)}") + assign(socket, pid: nil, device: nil, status: nil, registers: nil, opstat: nil) + end + + {:ok, socket} + end + + @impl true + def handle_event(event, unsigned_params, socket) + + def handle_event("inc_temp", _params, socket) do + if not socket.assigns.status.is_heating_effect_set_by_user do + current = socket.assigns.status.heating_effect + _ = Device.Server.set_temp(socket.assigns.pid, current + 1) + + optimistic_status = %Device.Status{ + socket.assigns.status + | is_heating_effect_set_by_user: true + } + + {:noreply, assign(socket, status: optimistic_status)} + else + {:noreply, socket} + end + end + + def handle_event("dec_temp", _params, socket) do + if not socket.assigns.status.is_heating_effect_set_by_user do + current = socket.assigns.status.heating_effect + _ = Device.Server.set_temp(socket.assigns.pid, current - 1) + + optimistic_status = %Device.Status{ + socket.assigns.status + | is_heating_effect_set_by_user: true + } + + {:noreply, assign(socket, status: optimistic_status)} + else + {:noreply, socket} + end + end + + @impl true + def handle_info(msg, socket) + + def handle_info({:device, device}, socket) do + {:noreply, assign(socket, device: device)} + end + + def handle_info({:status, status}, socket) do + {:noreply, assign(socket, status: status)} + end + + def handle_info({:registers, registers}, socket) do + {:noreply, assign(socket, registers: registers)} + end + + def handle_info({:opstat, opstat}, socket) do + {:noreply, assign(socket, opstat: opstat)} + end + + def handle_info(msg, socket) do + Logger.debug("Unknown message: #{inspect(msg)}") + {:noreply, socket} + end +end diff --git a/lib/geo_therminator_web/live/main/pump.html.heex b/lib/geo_therminator_web/live/main/pump.html.heex new file mode 100644 index 0000000..44f7b26 --- /dev/null +++ b/lib/geo_therminator_web/live/main/pump.html.heex @@ -0,0 +1,18 @@ +<%= live_redirect("« Go back", to: Routes.live_path(@socket, GeoTherminatorWeb.MainLive.Index)) %> + +<%= if is_nil(@pid) do %> + Some fail happened. +<% else %> + <%= if is_nil(@device) do %> + Loading pump data… + <% else %> + <.live_component + module={GeoTherminatorWeb.Components.MainView} + id={"pump-#{@device.id}"} + device={@device} + status={@status} + registers={@registers} + opstat={@opstat} + /> + <% end %> +<% end %> diff --git a/lib/geo_therminator_web/router.ex b/lib/geo_therminator_web/router.ex new file mode 100644 index 0000000..566e4d3 --- /dev/null +++ b/lib/geo_therminator_web/router.ex @@ -0,0 +1,44 @@ +defmodule GeoTherminatorWeb.Router do + use GeoTherminatorWeb, :router + + pipeline :browser do + plug :accepts, ["html"] + plug :fetch_session + plug :fetch_live_flash + plug :put_root_layout, {GeoTherminatorWeb.LayoutView, :root} + plug :protect_from_forgery + plug :put_secure_browser_headers + end + + pipeline :api do + plug :accepts, ["json"] + end + + scope "/", GeoTherminatorWeb do + pipe_through :browser + + live "/", MainLive.Index + live "/pump/:id", MainLive.Pump + end + + # Other scopes may use custom stacks. + # scope "/api", GeoTherminatorWeb do + # pipe_through :api + # end + + # Enables LiveDashboard only for development + # + # If you want to use the LiveDashboard in production, you should put + # it behind authentication and allow only admins to access it. + # If your application does not have an admins-only section yet, + # you can use Plug.BasicAuth to set up some basic authentication + # as long as you are also using SSL (which you should anyway). + if Mix.env() in [:dev, :test] do + import Phoenix.LiveDashboard.Router + + scope "/" do + pipe_through :browser + live_dashboard "/dashboard", metrics: GeoTherminatorWeb.Telemetry + end + end +end diff --git a/lib/geo_therminator_web/telemetry.ex b/lib/geo_therminator_web/telemetry.ex new file mode 100644 index 0000000..659425e --- /dev/null +++ b/lib/geo_therminator_web/telemetry.ex @@ -0,0 +1,48 @@ +defmodule GeoTherminatorWeb.Telemetry do + use Supervisor + import Telemetry.Metrics + + def start_link(arg) do + Supervisor.start_link(__MODULE__, arg, name: __MODULE__) + end + + @impl true + def init(_arg) do + children = [ + # Telemetry poller will execute the given period measurements + # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics + {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} + # Add reporters as children of your supervision tree. + # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} + ] + + Supervisor.init(children, strategy: :one_for_one) + end + + def metrics do + [ + # Phoenix Metrics + summary("phoenix.endpoint.stop.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.router_dispatch.stop.duration", + tags: [:route], + unit: {:native, :millisecond} + ), + + # VM Metrics + summary("vm.memory.total", unit: {:byte, :kilobyte}), + summary("vm.total_run_queue_lengths.total"), + summary("vm.total_run_queue_lengths.cpu"), + summary("vm.total_run_queue_lengths.io") + ] + end + + defp periodic_measurements do + [ + # A module, function and arguments to be invoked periodically. + # This function must call :telemetry.execute/3 and a metric must be added above. + # {GeoTherminatorWeb, :count_users, []} + ] + end +end diff --git a/lib/geo_therminator_web/templates/layout/app.html.heex b/lib/geo_therminator_web/templates/layout/app.html.heex new file mode 100644 index 0000000..169aed9 --- /dev/null +++ b/lib/geo_therminator_web/templates/layout/app.html.heex @@ -0,0 +1,5 @@ +
+ + + <%= @inner_content %> +
diff --git a/lib/geo_therminator_web/templates/layout/live.html.heex b/lib/geo_therminator_web/templates/layout/live.html.heex new file mode 100644 index 0000000..a29d604 --- /dev/null +++ b/lib/geo_therminator_web/templates/layout/live.html.heex @@ -0,0 +1,11 @@ +
+ + + + + <%= @inner_content %> +
diff --git a/lib/geo_therminator_web/templates/layout/root.html.heex b/lib/geo_therminator_web/templates/layout/root.html.heex new file mode 100644 index 0000000..b18a692 --- /dev/null +++ b/lib/geo_therminator_web/templates/layout/root.html.heex @@ -0,0 +1,30 @@ + + + + + + + <%= csrf_meta_tag() %> + <%= live_title_tag assigns[:page_title] || "Main", suffix: " · GeoTherminator" %> + + + + +
+
+ + +
+
+ <%= @inner_content %> + + diff --git a/lib/geo_therminator_web/views/error_helpers.ex b/lib/geo_therminator_web/views/error_helpers.ex new file mode 100644 index 0000000..6eee012 --- /dev/null +++ b/lib/geo_therminator_web/views/error_helpers.ex @@ -0,0 +1,47 @@ +defmodule GeoTherminatorWeb.ErrorHelpers do + @moduledoc """ + Conveniences for translating and building error messages. + """ + + use Phoenix.HTML + + @doc """ + Generates tag for inlined form input errors. + """ + def error_tag(form, field) do + Enum.map(Keyword.get_values(form.errors, field), fn error -> + content_tag(:span, translate_error(error), + class: "invalid-feedback", + phx_feedback_for: input_name(form, field) + ) + end) + end + + @doc """ + Translates an error message using gettext. + """ + def translate_error({msg, opts}) do + # When using gettext, we typically pass the strings we want + # to translate as a static argument: + # + # # Translate "is invalid" in the "errors" domain + # dgettext("errors", "is invalid") + # + # # Translate the number of files with plural rules + # dngettext("errors", "1 file", "%{count} files", count) + # + # Because the error messages we show in our forms and APIs + # are defined inside Ecto, we need to translate them dynamically. + # This requires us to call the Gettext module passing our gettext + # backend as first argument. + # + # Note we use the "errors" domain, which means translations + # should be written to the errors.po file. The :count option is + # set by Ecto and indicates we should also apply plural rules. + if count = opts[:count] do + Gettext.dngettext(GeoTherminatorWeb.Gettext, "errors", msg, msg, count, opts) + else + Gettext.dgettext(GeoTherminatorWeb.Gettext, "errors", msg, opts) + end + end +end diff --git a/lib/geo_therminator_web/views/error_view.ex b/lib/geo_therminator_web/views/error_view.ex new file mode 100644 index 0000000..4bffcab --- /dev/null +++ b/lib/geo_therminator_web/views/error_view.ex @@ -0,0 +1,16 @@ +defmodule GeoTherminatorWeb.ErrorView do + use GeoTherminatorWeb, :view + + # If you want to customize a particular status code + # for a certain format, you may uncomment below. + # def render("500.html", _assigns) do + # "Internal Server Error" + # end + + # By default, Phoenix returns the status message from + # the template name. For example, "404.html" becomes + # "Not Found". + def template_not_found(template, _assigns) do + Phoenix.Controller.status_message_from_template(template) + end +end diff --git a/lib/geo_therminator_web/views/layout_view.ex b/lib/geo_therminator_web/views/layout_view.ex new file mode 100644 index 0000000..47278a4 --- /dev/null +++ b/lib/geo_therminator_web/views/layout_view.ex @@ -0,0 +1,7 @@ +defmodule GeoTherminatorWeb.LayoutView do + use GeoTherminatorWeb, :view + + # Phoenix LiveDashboard is available only in development by default, + # so we instruct Elixir to not warn if the dashboard route is missing. + @compile {:no_warn_undefined, {Routes, :live_dashboard_path, 2}} +end diff --git a/mix.exs b/mix.exs new file mode 100644 index 0000000..14a9bba --- /dev/null +++ b/mix.exs @@ -0,0 +1,65 @@ +defmodule GeoTherminator.MixProject do + use Mix.Project + + def project do + [ + app: :geo_therminator, + version: "0.1.0", + elixir: "~> 1.12", + elixirc_paths: elixirc_paths(Mix.env()), + compilers: [:gettext] ++ Mix.compilers(), + start_permanent: Mix.env() == :prod, + aliases: aliases(), + deps: deps() + ] + end + + # Configuration for the OTP application. + # + # Type `mix help compile.app` for more information. + def application do + [ + mod: {GeoTherminator.Application, []}, + extra_applications: [:logger, :runtime_tools] + ] + end + + # Specifies which paths to compile per environment. + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + # Specifies your project dependencies. + # + # Type `mix help deps` for examples and options. + defp deps do + [ + {:phoenix, "~> 1.6.2"}, + {:phoenix_html, "~> 3.0"}, + {:phoenix_live_reload, "~> 1.2", only: :dev}, + {:phoenix_live_view, "~> 0.17.0"}, + {:floki, ">= 0.30.0", only: :test}, + {:phoenix_live_dashboard, "~> 0.6"}, + {:esbuild, "~> 0.2", runtime: Mix.env() == :dev}, + {:telemetry_metrics, "~> 0.6"}, + {:telemetry_poller, "~> 1.0"}, + {:gettext, "~> 0.18"}, + {:jason, "~> 1.2"}, + {:plug_cowboy, "~> 2.5"}, + {:dotenv_parser, "~> 1.2"}, + {:finch, "~> 0.9.0"} + ] + end + + # Aliases are shortcuts or tasks specific to the current project. + # For example, to install project dependencies and perform other setup tasks, run: + # + # $ mix setup + # + # See the documentation for `Mix` for more info on aliases. + defp aliases do + [ + setup: ["deps.get"], + "assets.deploy": ["esbuild default --minify", "phx.digest"] + ] + end +end diff --git a/mix.lock b/mix.lock new file mode 100644 index 0000000..0a8ef14 --- /dev/null +++ b/mix.lock @@ -0,0 +1,33 @@ +%{ + "castore": {:hex, :castore, "0.1.13", "ccf3ab251ffaebc4319f41d788ce59a6ab3f42b6c27e598ad838ffecee0b04f9", [:mix], [], "hexpm", "a14a7eecfec7e20385493dbb92b0d12c5d77ecfd6307de10102d58c94e8c49c0"}, + "cowboy": {:hex, :cowboy, "2.9.0", "865dd8b6607e14cf03282e10e934023a1bd8be6f6bacf921a7e2a96d800cd452", [:make, :rebar3], [{:cowlib, "2.11.0", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "2c729f934b4e1aa149aff882f57c6372c15399a20d54f65c8d67bef583021bde"}, + "cowboy_telemetry": {:hex, :cowboy_telemetry, "0.4.0", "f239f68b588efa7707abce16a84d0d2acf3a0f50571f8bb7f56a15865aae820c", [:rebar3], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7d98bac1ee4565d31b62d59f8823dfd8356a169e7fcbb83831b8a5397404c9de"}, + "cowlib": {:hex, :cowlib, "2.11.0", "0b9ff9c346629256c42ebe1eeb769a83c6cb771a6ee5960bd110ab0b9b872063", [:make, :rebar3], [], "hexpm", "2b3e9da0b21c4565751a6d4901c20d1b4cc25cbb7fd50d91d2ab6dd287bc86a9"}, + "dotenv_parser": {:hex, :dotenv_parser, "1.2.0", "f062900aeb57727b619aeb182fa4a8b1cbb7b4260ebec2b70b3d5c064885aff3", [:mix], [], "hexpm", "eddd69e7fde28618adb2e4153fa380db5c56161b32341e7a4e0530d86987c47f"}, + "esbuild": {:hex, :esbuild, "0.3.4", "416203c642eb84b207f882cf7953a1fd7bb71e23f5f86554f983bb7bad18b897", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}], "hexpm", "c472e38b37e9547113776b1e4b64b44ec540bcc7056dd252c2c3ffba41aa9793"}, + "file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"}, + "finch": {:hex, :finch, "0.9.0", "8b772324aebafcaba763f1dffaa3e7f52f8c4e52485f50f48bbb2f42219a2e87", [:mix], [{:castore, "~> 0.1", [hex: :castore, repo: "hexpm", optional: false]}, {:mint, "~> 1.3", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.3.5", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 0.2", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "a93bfcad9ca50fa3cb2d459f27667d9a87cfbb7fecf9b29b2e78a50bc2ab445d"}, + "floki": {:hex, :floki, "0.32.0", "f915dc15258bc997d49be1f5ef7d3992f8834d6f5695270acad17b41f5bcc8e2", [:mix], [{:html_entities, "~> 0.5.0", [hex: :html_entities, repo: "hexpm", optional: false]}], "hexpm", "1c5a91cae1fd8931c26a4826b5e2372c284813904c8bacb468b5de39c7ececbd"}, + "gettext": {:hex, :gettext, "0.18.2", "7df3ea191bb56c0309c00a783334b288d08a879f53a7014341284635850a6e55", [:mix], [], "hexpm", "f9f537b13d4fdd30f3039d33cb80144c3aa1f8d9698e47d7bcbcc8df93b1f5c5"}, + "html_entities": {:hex, :html_entities, "0.5.2", "9e47e70598da7de2a9ff6af8758399251db6dbb7eebe2b013f2bbd2515895c3c", [:mix], [], "hexpm", "c53ba390403485615623b9531e97696f076ed415e8d8058b1dbaa28181f4fdcc"}, + "jason": {:hex, :jason, "1.2.2", "ba43e3f2709fd1aa1dce90aaabfd039d000469c05c56f0b8e31978e03fa39052", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "18a228f5f0058ee183f29f9eae0805c6e59d61c3b006760668d8d18ff0d12179"}, + "mime": {:hex, :mime, "1.6.0", "dabde576a497cef4bbdd60aceee8160e02a6c89250d6c0b29e56c0dfb00db3d2", [:mix], [], "hexpm", "31a1a8613f8321143dde1dafc36006a17d28d02bdfecb9e95a880fa7aabd19a7"}, + "mint": {:hex, :mint, "1.4.0", "cd7d2451b201fc8e4a8fd86257fb3878d9e3752899eb67b0c5b25b180bde1212", [:mix], [{:castore, "~> 0.1.0", [hex: :castore, repo: "hexpm", optional: true]}], "hexpm", "10a99e144b815cbf8522dccbc8199d15802440fc7a64d67b6853adb6fa170217"}, + "nimble_options": {:hex, :nimble_options, "0.3.7", "1e52dd7673d36138b1a5dede183b5d86dff175dc46d104a8e98e396b85b04670", [:mix], [], "hexpm", "2086907e6665c6b6579be54ef5001928df5231f355f71ed258f80a55e9f63633"}, + "nimble_pool": {:hex, :nimble_pool, "0.2.4", "1db8e9f8a53d967d595e0b32a17030cdb6c0dc4a451b8ac787bf601d3f7704c3", [:mix], [], "hexpm", "367e8071e137b787764e6a9992ccb57b276dc2282535f767a07d881951ebeac6"}, + "phoenix": {:hex, :phoenix, "1.6.2", "6cbd5c8ed7a797f25a919a37fafbc2fb1634c9cdb12a4448d7a5d0b26926f005", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 1.0", [hex: :phoenix_view, repo: "hexpm", optional: false]}, {:plug, "~> 1.10", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.2", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7bbee475acae0c3abc229b7f189e210ea788e63bd168e585f60c299a4b2f9133"}, + "phoenix_html": {:hex, :phoenix_html, "3.1.0", "0b499df05aad27160d697a9362f0e89fa0e24d3c7a9065c2bd9d38b4d1416c09", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "0c0a98a2cefa63433657983a2a594c7dee5927e4391e0f1bfd3a151d1def33fc"}, + "phoenix_live_dashboard": {:hex, :phoenix_live_dashboard, "0.6.1", "fb94a33c077141f9ac7930b322a7a3b99f9b144bf3a08dd667b9f9aaf0319889", [:mix], [{:ecto, "~> 3.6.2 or ~> 3.7", [hex: :ecto, repo: "hexpm", optional: true]}, {:ecto_mysql_extras, "~> 0.3", [hex: :ecto_mysql_extras, repo: "hexpm", optional: true]}, {:ecto_psql_extras, "~> 0.7", [hex: :ecto_psql_extras, repo: "hexpm", optional: true]}, {:mime, "~> 1.6.0", [hex: :mime, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 0.17.1", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:telemetry_metrics, "~> 0.6.0", [hex: :telemetry_metrics, repo: "hexpm", optional: false]}], "hexpm", "6faf1373e5846c8ab68c2cf55cfa5c196c1fbbe0c72d12a4cdfaaac6ef189948"}, + "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.3.3", "3a53772a6118d5679bf50fc1670505a290e32a1d195df9e069d8c53ab040c054", [:mix], [{:file_system, "~> 0.2.1 or ~> 0.3", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "766796676e5f558dbae5d1bdb066849673e956005e3730dfd5affd7a6da4abac"}, + "phoenix_live_view": {:hex, :phoenix_live_view, "0.17.5", "63f52a6f9f6983f04e424586ff897c016ecc5e4f8d1e2c22c2887af1c57215d8", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.5.9 or ~> 1.6.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.1", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "c5586e6a3d4df71b8214c769d4f5eb8ece2b4001711a7ca0f97323c36958b0e3"}, + "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.0.0", "a1ae76717bb168cdeb10ec9d92d1480fec99e3080f011402c0a2d68d47395ffb", [:mix], [], "hexpm", "c52d948c4f261577b9c6fa804be91884b381a7f8f18450c5045975435350f771"}, + "phoenix_view": {:hex, :phoenix_view, "1.0.0", "fea71ecaaed71178b26dd65c401607de5ec22e2e9ef141389c721b3f3d4d8011", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "82be3e2516f5633220246e2e58181282c71640dab7afc04f70ad94253025db0c"}, + "plug": {:hex, :plug, "1.12.1", "645678c800601d8d9f27ad1aebba1fdb9ce5b2623ddb961a074da0b96c35187d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "d57e799a777bc20494b784966dc5fbda91eb4a09f571f76545b72a634ce0d30b"}, + "plug_cowboy": {:hex, :plug_cowboy, "2.5.2", "62894ccd601cf9597e2c23911ff12798a8a18d237e9739f58a6b04e4988899fe", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:cowboy_telemetry, "~> 0.3", [hex: :cowboy_telemetry, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "ea6e87f774c8608d60c8d34022a7d073bd7680a0a013f049fc62bf35efea1044"}, + "plug_crypto": {:hex, :plug_crypto, "1.2.2", "05654514ac717ff3a1843204b424477d9e60c143406aa94daf2274fdd280794d", [:mix], [], "hexpm", "87631c7ad914a5a445f0a3809f99b079113ae4ed4b867348dd9eec288cecb6db"}, + "poolboy": {:hex, :poolboy, "1.5.2", "392b007a1693a64540cead79830443abf5762f5d30cf50bc95cb2c1aaafa006b", [:rebar3], [], "hexpm", "dad79704ce5440f3d5a3681c8590b9dc25d1a561e8f5a9c995281012860901e3"}, + "ranch": {:hex, :ranch, "1.8.0", "8c7a100a139fd57f17327b6413e4167ac559fbc04ca7448e9be9057311597a1d", [:make, :rebar3], [], "hexpm", "49fbcfd3682fab1f5d109351b61257676da1a2fdbe295904176d5e521a2ddfe5"}, + "telemetry": {:hex, :telemetry, "1.0.0", "0f453a102cdf13d506b7c0ab158324c337c41f1cc7548f0bc0e130bbf0ae9452", [:rebar3], [], "hexpm", "73bc09fa59b4a0284efb4624335583c528e07ec9ae76aca96ea0673850aec57a"}, + "telemetry_metrics": {:hex, :telemetry_metrics, "0.6.1", "315d9163a1d4660aedc3fee73f33f1d355dcc76c5c3ab3d59e76e3edf80eef1f", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7be9e0871c41732c233be71e4be11b96e56177bf15dde64a8ac9ce72ac9834c6"}, + "telemetry_poller": {:hex, :telemetry_poller, "1.0.0", "db91bb424e07f2bb6e73926fcafbfcbcb295f0193e0a00e825e589a0a47e8453", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "b3a24eafd66c3f42da30fc3ca7dda1e9d546c12250a2d60d7b81d264fbec4f6e"}, +} diff --git a/priv/gettext/en/LC_MESSAGES/errors.po b/priv/gettext/en/LC_MESSAGES/errors.po new file mode 100644 index 0000000..cdec3a1 --- /dev/null +++ b/priv/gettext/en/LC_MESSAGES/errors.po @@ -0,0 +1,11 @@ +## `msgid`s in this file come from POT (.pot) files. +## +## Do not add, change, or remove `msgid`s manually here as +## they're tied to the ones in the corresponding POT file +## (with the same domain). +## +## Use `mix gettext.extract --merge` or `mix gettext.merge` +## to merge POT files into PO files. +msgid "" +msgstr "" +"Language: en\n" diff --git a/priv/gettext/errors.pot b/priv/gettext/errors.pot new file mode 100644 index 0000000..d6f47fa --- /dev/null +++ b/priv/gettext/errors.pot @@ -0,0 +1,10 @@ +## This is a PO Template file. +## +## `msgid`s here are often extracted from source code. +## Add new translations manually only if they're dynamic +## translations that can't be statically extracted. +## +## Run `mix gettext.extract` to bring this file up to +## date. Leave `msgstr`s empty as changing them here has no +## effect: edit them in PO (`.po`) files instead. + diff --git a/priv/repo/migrations/20211106121919_create_paskas.exs b/priv/repo/migrations/20211106121919_create_paskas.exs new file mode 100644 index 0000000..b9435b7 --- /dev/null +++ b/priv/repo/migrations/20211106121919_create_paskas.exs @@ -0,0 +1,11 @@ +defmodule GeoTherminator.Repo.Migrations.CreatePaskas do + use Ecto.Migration + + def change do + create table(:paskas) do + add :name, :string + + timestamps() + end + end +end diff --git a/priv/static/favicon.ico b/priv/static/favicon.ico new file mode 100644 index 0000000..73de524 Binary files /dev/null and b/priv/static/favicon.ico differ diff --git a/priv/static/images/geotherminator.png b/priv/static/images/geotherminator.png new file mode 100644 index 0000000..97e0c7b Binary files /dev/null and b/priv/static/images/geotherminator.png differ diff --git a/priv/static/robots.txt b/priv/static/robots.txt new file mode 100644 index 0000000..3c9c7c0 --- /dev/null +++ b/priv/static/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/test/geo_therminator/paska_test.exs b/test/geo_therminator/paska_test.exs new file mode 100644 index 0000000..c72fb11 --- /dev/null +++ b/test/geo_therminator/paska_test.exs @@ -0,0 +1,59 @@ +defmodule GeoTherminator.PaskaTest do + use GeoTherminator.DataCase + + alias GeoTherminator.Paska + + describe "paskas" do + alias GeoTherminator.Paska.Crap + + import GeoTherminator.PaskaFixtures + + @invalid_attrs %{name: nil} + + test "list_paskas/0 returns all paskas" do + crap = crap_fixture() + assert Paska.list_paskas() == [crap] + end + + test "get_crap!/1 returns the crap with given id" do + crap = crap_fixture() + assert Paska.get_crap!(crap.id) == crap + end + + test "create_crap/1 with valid data creates a crap" do + valid_attrs = %{name: "some name"} + + assert {:ok, %Crap{} = crap} = Paska.create_crap(valid_attrs) + assert crap.name == "some name" + end + + test "create_crap/1 with invalid data returns error changeset" do + assert {:error, %Ecto.Changeset{}} = Paska.create_crap(@invalid_attrs) + end + + test "update_crap/2 with valid data updates the crap" do + crap = crap_fixture() + update_attrs = %{name: "some updated name"} + + assert {:ok, %Crap{} = crap} = Paska.update_crap(crap, update_attrs) + assert crap.name == "some updated name" + end + + test "update_crap/2 with invalid data returns error changeset" do + crap = crap_fixture() + assert {:error, %Ecto.Changeset{}} = Paska.update_crap(crap, @invalid_attrs) + assert crap == Paska.get_crap!(crap.id) + end + + test "delete_crap/1 deletes the crap" do + crap = crap_fixture() + assert {:ok, %Crap{}} = Paska.delete_crap(crap) + assert_raise Ecto.NoResultsError, fn -> Paska.get_crap!(crap.id) end + end + + test "change_crap/1 returns a crap changeset" do + crap = crap_fixture() + assert %Ecto.Changeset{} = Paska.change_crap(crap) + end + end +end diff --git a/test/geo_therminator_web/controllers/page_controller_test.exs b/test/geo_therminator_web/controllers/page_controller_test.exs new file mode 100644 index 0000000..c4ec8ca --- /dev/null +++ b/test/geo_therminator_web/controllers/page_controller_test.exs @@ -0,0 +1,8 @@ +defmodule GeoTherminatorWeb.PageControllerTest do + use GeoTherminatorWeb.ConnCase + + test "GET /", %{conn: conn} do + conn = get(conn, "/") + assert html_response(conn, 200) =~ "Welcome to Phoenix!" + end +end diff --git a/test/geo_therminator_web/live/crap_live_test.exs b/test/geo_therminator_web/live/crap_live_test.exs new file mode 100644 index 0000000..7e00f51 --- /dev/null +++ b/test/geo_therminator_web/live/crap_live_test.exs @@ -0,0 +1,110 @@ +defmodule GeoTherminatorWeb.CrapLiveTest do + use GeoTherminatorWeb.ConnCase + + import Phoenix.LiveViewTest + import GeoTherminator.PaskaFixtures + + @create_attrs %{name: "some name"} + @update_attrs %{name: "some updated name"} + @invalid_attrs %{name: nil} + + defp create_crap(_) do + crap = crap_fixture() + %{crap: crap} + end + + describe "Index" do + setup [:create_crap] + + test "lists all paskas", %{conn: conn, crap: crap} do + {:ok, _index_live, html} = live(conn, Routes.crap_index_path(conn, :index)) + + assert html =~ "Listing Paskas" + assert html =~ crap.name + end + + test "saves new crap", %{conn: conn} do + {:ok, index_live, _html} = live(conn, Routes.crap_index_path(conn, :index)) + + assert index_live |> element("a", "New Crap") |> render_click() =~ + "New Crap" + + assert_patch(index_live, Routes.crap_index_path(conn, :new)) + + assert index_live + |> form("#crap-form", crap: @invalid_attrs) + |> render_change() =~ "can't be blank" + + {:ok, _, html} = + index_live + |> form("#crap-form", crap: @create_attrs) + |> render_submit() + |> follow_redirect(conn, Routes.crap_index_path(conn, :index)) + + assert html =~ "Crap created successfully" + assert html =~ "some name" + end + + test "updates crap in listing", %{conn: conn, crap: crap} do + {:ok, index_live, _html} = live(conn, Routes.crap_index_path(conn, :index)) + + assert index_live |> element("#crap-#{crap.id} a", "Edit") |> render_click() =~ + "Edit Crap" + + assert_patch(index_live, Routes.crap_index_path(conn, :edit, crap)) + + assert index_live + |> form("#crap-form", crap: @invalid_attrs) + |> render_change() =~ "can't be blank" + + {:ok, _, html} = + index_live + |> form("#crap-form", crap: @update_attrs) + |> render_submit() + |> follow_redirect(conn, Routes.crap_index_path(conn, :index)) + + assert html =~ "Crap updated successfully" + assert html =~ "some updated name" + end + + test "deletes crap in listing", %{conn: conn, crap: crap} do + {:ok, index_live, _html} = live(conn, Routes.crap_index_path(conn, :index)) + + assert index_live |> element("#crap-#{crap.id} a", "Delete") |> render_click() + refute has_element?(index_live, "#crap-#{crap.id}") + end + end + + describe "Show" do + setup [:create_crap] + + test "displays crap", %{conn: conn, crap: crap} do + {:ok, _show_live, html} = live(conn, Routes.crap_show_path(conn, :show, crap)) + + assert html =~ "Show Crap" + assert html =~ crap.name + end + + test "updates crap within modal", %{conn: conn, crap: crap} do + {:ok, show_live, _html} = live(conn, Routes.crap_show_path(conn, :show, crap)) + + assert show_live |> element("a", "Edit") |> render_click() =~ + "Edit Crap" + + assert_patch(show_live, Routes.crap_show_path(conn, :edit, crap)) + + assert show_live + |> form("#crap-form", crap: @invalid_attrs) + |> render_change() =~ "can't be blank" + + {:ok, _, html} = + show_live + |> form("#crap-form", crap: @update_attrs) + |> render_submit() + |> follow_redirect(conn, Routes.crap_show_path(conn, :show, crap)) + + assert html =~ "Crap updated successfully" + assert html =~ "some updated name" + end + end +end diff --git a/test/geo_therminator_web/views/error_view_test.exs b/test/geo_therminator_web/views/error_view_test.exs new file mode 100644 index 0000000..18c2daf --- /dev/null +++ b/test/geo_therminator_web/views/error_view_test.exs @@ -0,0 +1,14 @@ +defmodule GeoTherminatorWeb.ErrorViewTest do + use GeoTherminatorWeb.ConnCase, async: true + + # Bring render/3 and render_to_string/3 for testing custom views + import Phoenix.View + + test "renders 404.html" do + assert render_to_string(GeoTherminatorWeb.ErrorView, "404.html", []) == "Not Found" + end + + test "renders 500.html" do + assert render_to_string(GeoTherminatorWeb.ErrorView, "500.html", []) == "Internal Server Error" + end +end diff --git a/test/geo_therminator_web/views/layout_view_test.exs b/test/geo_therminator_web/views/layout_view_test.exs new file mode 100644 index 0000000..74d6230 --- /dev/null +++ b/test/geo_therminator_web/views/layout_view_test.exs @@ -0,0 +1,8 @@ +defmodule GeoTherminatorWeb.LayoutViewTest do + use GeoTherminatorWeb.ConnCase, async: true + + # When testing helpers, you may want to import Phoenix.HTML and + # use functions such as safe_to_string() to convert the helper + # result into an HTML string. + # import Phoenix.HTML +end diff --git a/test/geo_therminator_web/views/page_view_test.exs b/test/geo_therminator_web/views/page_view_test.exs new file mode 100644 index 0000000..86c51d9 --- /dev/null +++ b/test/geo_therminator_web/views/page_view_test.exs @@ -0,0 +1,3 @@ +defmodule GeoTherminatorWeb.PageViewTest do + use GeoTherminatorWeb.ConnCase, async: true +end diff --git a/test/test_helper.exs b/test/test_helper.exs new file mode 100644 index 0000000..869559e --- /dev/null +++ b/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start()