60 Commits
Author SHA1 Message Date
Marcus Handte 4d21dea4cd Release 1.0.29
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-11 11:46:36 +01:00
Marcus Handte e4603a231e Add obfuscator for data release.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-08 08:30:51 +01:00
Marcus Handte 316df58af6 Added docs for data release.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-08 08:28:33 +01:00
Marcus Handte 35516af52b Update to 1.0.29-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 17:35:44 +01:00
Marcus Handte 3bded2af7a Release 1.0.28
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 17:12:48 +01:00
Marcus Handte 2c788e3329 Add weather station configuration to ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 16:47:26 +01:00
Marcus Handte af2409a16d Improve handling of intent.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-01 18:25:01 +01:00
Marcus Handte 7e390ed56f Fix navigation graph issues.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-01 17:41:25 +01:00
Marcus Handte 756a816abb Add app updates and paper evaluation.
LocationBasedServices/mowesta/pipeline/head This commit looks good
Add fix for iOS app contained in release 1.1.
Add support for Android 13 to Android app.
Add tools for PerCom paper evaluation.
2022-11-01 17:11:21 +01:00
handte 1e174f77f7 Upgrade to 1.0.28-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-08-03 14:21:27 +02:00
handte ae8e1ddb82 Release 1.0.27
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 19:03:10 +02:00
handte 9381065cf2 Fix touch bug in android, resubmit ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 16:20:30 +02:00
handte 98b4ee71ae Reduce debug output, fix ordering of favorites.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 14:05:05 +02:00
handte 1b84c6fc15 Finish gradient view and prepare app store submission.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 12:27:20 +02:00
handte ad9fb99205 Fix bugs and optimize (somewhat) for tablets.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-23 17:48:09 +02:00
handte 4fdbf10054 Add 2-way (background) synchronization and favorites.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-23 16:58:25 +02:00
handte 3505c379cf Finish ios ui.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-22 17:37:02 +02:00
handte 6322022f47 Backup ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-21 22:46:49 +02:00
handte adf60f289b Backup ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-20 23:34:43 +02:00
handte 27ccac205b Fix bug in android timezone, backup ios.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-17 19:28:10 +02:00
handte 664a7d4cea Update to 1.0.27-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 22:00:04 +02:00
handte 49137e111b Release 1.0.26
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 21:56:38 +02:00
handte c834551c52 Improve layouts for tablets.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 21:52:11 +02:00
handte 91d5a7be50 Fix android app, logging and add export tool.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 21:00:23 +02:00
braun 552c2215c3 Changed recycler item width on tablets for cities and stations list fragments.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-01 12:05:23 +02:00
handte 2e9597f34d Continue iOS implementation.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-29 23:01:56 +02:00
handte ec6f25e11b Started implementation of iOS app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-28 23:33:05 +02:00
handte f871761e48 Increase debug level for file sync.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-25 14:08:00 +02:00
Marcus Handte 60bbfceb7e Update to 1.0.26-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 17:10:24 +02:00
Marcus Handte 0ce1657c0a Release 1.0.25
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 16:58:04 +02:00
Marcus Handte 035aebe741 Update to 1.0.25-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 15:53:49 +02:00
Marcus Handte a829aa01df Release 1.0.24
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 15:52:17 +02:00
Marcus Handte 76315eedc3 Remove deployment to beta.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-05-23 15:18:34 +02:00
handte 108df0d614 Remove unused robolectric tests.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-23 15:00:34 +02:00
Marcus Handte 449e128373 Prepare android app for upgrade.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-23 14:47:37 +02:00
handte be53bc8cfa Upgrade Android libraries and Swagger generators.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-22 19:32:37 +02:00
handte 70f8c27341 Upgrade project and dependencies.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2022-05-22 13:26:49 +02:00
handte f27c43bf92 Add monitoring script for experiments.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-16 11:53:43 +01:00
handte 5a9e73b72f Update to 1.0.24-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-14 11:36:12 +01:00
handte f2c98815ff Release 1.0.23
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-14 11:21:13 +01:00
handte 99abe5e86e Change library for Sepehr, change widget for Bijan.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-10 16:31:52 +01:00
handte 55a8c55aba Upgrade Android plugin. 2021-12-10 12:25:37 +01:00
handte 16c31df0bf Add workaround for design issue. 2021-12-10 12:01:52 +01:00
handte 10feb5d6aa Update to 1.0.23-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-01 15:14:11 +01:00
handte f8371a4b0a Release 1.0.22
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-01 14:50:22 +01:00
handte f8ed7dfac4 Generate android bundle during releases.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-01 14:45:56 +01:00
handte 5b0f0bef32 Add ad for Eiszeit, add model builder, add esp schematics.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-12-01 13:38:44 +01:00
handte c207f5470a Properly model build step dependencies.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-10-09 08:16:55 +02:00
handte 1002351f2d Fix missing generation of swagger api docs.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-10-08 10:39:16 +02:00
handte dd4cc41740 Update to 1.0.22-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-09-20 16:24:51 +02:00
handte 3f43df52e9 Release 1.0.21
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-09-20 16:11:20 +02:00
handte de8ad98f8d Improve robustness of SDK service on lower Android version.
LocationBasedServices/mowesta/pipeline/head This commit looks good
Move buffer and upload task to serial queue.
Increase GPS timeout to 90 seconds on pre-24 devices.
Schedule restart of SDK service, if service is shutdown by Android.
Update Android Gradle plugin.
2021-09-20 15:47:07 +02:00
handte 0fc0605a85 Update to 1.0.21-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-30 19:13:14 +02:00
handte 326e56a24c Release 1.0.20
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-30 19:10:44 +02:00
handte 6f388520f5 Add advertisement, fix permissions and bugs.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-30 17:39:16 +02:00
handte c8a52eec58 Fix crash due to to nested nav graph.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-16 13:39:35 +02:00
handte e568f43dd7 Add Arduino code for BME and BMP.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-08 21:07:16 +02:00
handte 22ccdd21ac Update to 1.0.20-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-08 12:45:11 +02:00
handte 6137fface2 Release 1.0.19
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-08 12:33:53 +02:00
handte 4588941a40 Update to 1.0.19-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-08-08 12:11:58 +02:00
514 changed files with 24076 additions and 12401 deletions
-485
View File
@@ -1,485 +0,0 @@
<code_scheme name="DefaultIntelliJCodeStyleCST" version="173">
<option name="OTHER_INDENT_OPTIONS">
<value>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</value>
</option>
<option name="LINE_SEPARATOR" value="&#xA;" />
<option name="GENERATE_FINAL_PARAMETERS" value="true" />
<option name="RIGHT_MARGIN" value="200" />
<option name="HTML_KEEP_LINE_BREAKS" value="false" />
<option name="HTML_KEEP_LINE_BREAKS_IN_TEXT" value="false" />
<option name="HTML_INLINE_ELEMENTS" value="a,abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,kbd,label,q,s,samp,select,span,strike,strong,sub,sup,textarea,tt,u,var" />
<AndroidXmlCodeStyleSettings>
<option name="USE_CUSTOM_SETTINGS" value="true" />
</AndroidXmlCodeStyleSettings>
<CssCodeStyleSettings>
<option name="HEX_COLOR_LOWER_CASE" value="true" />
<option name="HEX_COLOR_LONG_FORMAT" value="true" />
</CssCodeStyleSettings>
<HTMLCodeStyleSettings>
<option name="HTML_KEEP_LINE_BREAKS" value="false" />
<option name="HTML_KEEP_LINE_BREAKS_IN_TEXT" value="false" />
<option name="HTML_INLINE_ELEMENTS" value="abbr,acronym,b,basefont,bdo,big,br,cite,cite,code,dfn,em,font,i,img,kbd,q,s,samp,span,strike,strong,sub,sup,textarea,tt,u,var" />
</HTMLCodeStyleSettings>
<JavaeeCodeStyleSettings>
<option name="ENTITY_VO_SUFFIX" value="DTO" />
</JavaeeCodeStyleSettings>
<Objective-C-extensions>
<file>
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" />
</file>
<class>
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" />
</class>
<extensions>
<pair source="cpp" header="hpp" fileNamingConvention="LOWERCASE" />
<pair source="c" header="h" fileNamingConvention="NONE" />
</extensions>
</Objective-C-extensions>
<Properties>
<option name="KEEP_BLANK_LINES" value="true" />
</Properties>
<TypeScriptCodeStyleSettings version="0">
<option name="FORCE_SEMICOLON_STYLE" value="true" />
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
<option name="OBJECT_LITERAL_WRAP" value="1" />
</TypeScriptCodeStyleSettings>
<XML>
<option name="XML_TEXT_WRAP" value="0" />
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
<codeStyleSettings language="CFML">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="CMake">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="CSS">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="CoffeeScript">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="8" />
<option name="TAB_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="DB2">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Derby">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="ECMA Script Level 4">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="GSP">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Gherkin">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Groovy">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="H2">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="HAML">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="HSQLDB">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="HTML">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Haml">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="WHILE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="ALIGN_MULTILINE_CHAINED_METHODS" value="true" />
<option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
<option name="METHOD_CALL_CHAIN_WRAP" value="5" />
<option name="WRAP_COMMENTS" value="true" />
<option name="ENUM_CONSTANTS_WRAP" value="1" />
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
<arrangement>
<groups>
<group>
<type>GETTERS_AND_SETTERS</type>
<order>KEEP</order>
</group>
<group>
<type>OVERRIDDEN_METHODS</type>
<order>KEEP</order>
</group>
<group>
<type>DEPENDENT_METHODS</type>
<order>DEPTH_FIRST</order>
</group>
</groups>
<rules>
<section>
<rule>
<match>
<AND>
<FIELD>true</FIELD>
<FINAL>true</FINAL>
<STATIC>true</STATIC>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<FIELD>true</FIELD>
<STATIC>true</STATIC>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<FIELD>true</FIELD>
<FINAL>true</FINAL>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<FIELD>true</FIELD>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<INITIALIZER_BLOCK>true</INITIALIZER_BLOCK>
<STATIC>true</STATIC>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<INITIALIZER_BLOCK>true</INITIALIZER_BLOCK>
</match>
</rule>
</section>
<section>
<rule>
<match>
<CONSTRUCTOR>true</CONSTRUCTOR>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<METHOD>true</METHOD>
<NAME>main</NAME>
<PUBLIC>true</PUBLIC>
<STATIC>true</STATIC>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<ABSTRACT>true</ABSTRACT>
<METHOD>true</METHOD>
<visibility />
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<ABSTRACT>false</ABSTRACT>
<METHOD>true</METHOD>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<METHOD>true</METHOD>
<STATIC>true</STATIC>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<ENUM>true</ENUM>
</match>
</rule>
</section>
<section>
<rule>
<match>
<INTERFACE>true</INTERFACE>
</match>
</rule>
</section>
<section>
<rule>
<match>
<CLASS>true</CLASS>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<CLASS>true</CLASS>
<STATIC>true</STATIC>
</AND>
</match>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="JSON">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JSP">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JSPX">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JavaScript">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="LESS">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="MySQL">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="ObjectiveC">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Oracle">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="PostgreSQL">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Puppet">
<indentOptions>
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="RHTML">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="8" />
<option name="TAB_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SASS">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SCSS">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SQL">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SQLite">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Stylus">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Sybase">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="TSQL">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="TypeScript">
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="TERNARY_OPERATION_WRAP" value="1" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="ruby">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="8" />
<option name="TAB_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="true" />
<option name="KEEP_INDENTS_ON_EMPTY_LINES" value="true" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
Vendored
+5 -4
View File
@@ -49,14 +49,15 @@ node {
if (env.BRANCH_NAME == "master" && release) {
echo "Deploying to production server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
// sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
sh 'scp -i $KEYFILE android-app/build/outputs/apk/prod/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
sh 'scp -i $KEYFILE android-app/build/outputs/bundle/prodRelease/*.aab wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
}
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feat/auth") {
echo "Deploying to beta server ..."
} else if (env.BRANCH_NAME == "master") {
/* echo "Deploying to beta server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-dev.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear'
}
} */
} else {
echo "Skipping deployment for non-master branch."
}
@@ -2,7 +2,7 @@ plugins {
id 'org.hidetake.swagger.generator' version '2.18.2'
}
description = "Mowesta Android Feign"
description = "MoWeSta Android Api"
// downgrade jackson for Android, since versions > 2.9
// will contain module-info.class files that will result
@@ -33,7 +33,7 @@ swaggerSources {
language = 'java'
configFile = file('config.json')
components = [ models: true, apis: 'Default']
rawOptions = [ '--import-mappings', 'Geometry=org.geojson.Geometry']
rawOptions = [ '--import-mappings', 'Geometry=org.geojson.Geometry']
}
}
+40 -36
View File
@@ -2,14 +2,8 @@ apply plugin: 'org.handte.gradle-android-eclipse'
apply plugin: 'com.android.application'
apply plugin: 'com.google.android.gms.oss-licenses-plugin'
description = "Mowesta Android App"
description = "MoWeSta Android App"
// remove project version to workaround bugs in
// oss-license-plugin that detects local libraries
// by checking for a version called "unspecified"
// see DependencyTask.groovy on GitHub at
// https://github.com/google/play-services-plugins
project.version = "unspecified"
ext {
// android app dependencies
@@ -19,27 +13,36 @@ ext {
versionAndroidXRecycler = '1.2.1'
versionAndroidXPaging = '2.1.2'
versionAndroidXCard = '1.0.0'
versionAndroidXCoordinator = '1.1.0'
versionAndroidXConstraint = '2.1.0'
versionAndroidXNavigation = '2.3.5'
versionAndroidXLifecycle = '2.3.1'
versionAndroidXSecurity = '1.1.0-alpha03'
versionAndroidXCoordinator = '1.2.0'
versionAndroidXConstraint = '2.1.4'
versionAndroidXNavigation = '2.5.3'
versionAndroidXLifecycle = '2.5.1'
versionAndroidXSecurity = '1.0.0'
versionAndroidXViewpager = '1.0.0'
versionGoogleMaterial = '1.4.0'
versionAndroidXWork = '2.7.1'
versionGoogleMaterial = '1.7.0'
versionAndroidXSwipeRefresh = '1.1.0'
versionAndroidXWebkit = '1.4.0'
versionExoPlayer = '2.14.2'
versionAndroidXWebkit = '1.5.0'
versionExoPlayer = '2.18.1'
versionApp = project.version
}
// remove project version to workaround bugs in
// oss-license-plugin that detects local libraries
// by checking for a version called "unspecified"
// see DependencyTask.groovy on GitHub at
// https://github.com/google/play-services-plugins
project.version = "unspecified"
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation project(":android-sdk")
implementation "javax.xml.bind:jaxb-api:${versionJaxb}"
implementation "androidx.appcompat:appcompat:${versionAndroidXAppcompat}"
implementation "androidx.work:work-runtime:${versionAndroidXWork}"
implementation "com.google.android.material:material:${versionGoogleMaterial}"
implementation "androidx.preference:preference:${versionAndroidXPreference}"
implementation "androidx.cardview:cardview:${versionAndroidXCard}"
@@ -81,25 +84,24 @@ dependencies {
testImplementation "junit:junit:${versionJunit}"
testImplementation "androidx.test:core:${versionAndroidXTest}"
testImplementation "androidx.arch.core:core-testing:${versionAndroidXCoreTest}"
testImplementation "org.robolectric:robolectric:${versionRobolectric}"
}
configurations {
all {
exclude group: 'com.google.auto.service', module: 'auto-service'
}
all {
exclude group: 'com.google.auto.service', module: 'auto-service'
exclude group: 'androidx.lifecycle', module: 'lifecycle-viewmodel-ktx'
}
}
android {
compileSdkVersion 30
compileSdkVersion 33
defaultConfig {
applicationId "com.mowesta.android.app"
minSdkVersion 19
targetSdkVersion 30
versionCode 18
versionName "${version}"
targetSdkVersion 33
versionCode 29
versionName "${versionApp}"
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
resValue "string", "application_long", "MoWeSta"
@@ -141,7 +143,8 @@ android {
beta {
dimension "backend"
applicationIdSuffix ".beta"
resValue "string", "mowesta_url_default", "https://beta.mowesta.com/api"
resValue "string", "mowesta_url_default", "https://www.mowesta.com/api"
// resValue "string", "mowesta_url_default", "https://beta.mowesta.com/api"
resValue "string", "application_long", "B-MoWeSta"
}
prod {
@@ -159,19 +162,17 @@ android {
includeAndroidResources = true
}
}
lintOptions {
// FragmentTagUsage: replacing fragment with FragmentContainerView breaks Navigation library
// RelativeOverlayp: occurs in video frame which is what we want
// VectorPath: our map and logo representations are very long vectors (consider compressing)
disable 'RelativeOverlap', 'FragmentTagUsage', 'VectorPath'
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lint {
abortOnError false
disable 'RelativeOverlap', 'FragmentTagUsage', 'VectorPath'
}
namespace 'com.mowesta.android.app'
}
@@ -198,4 +199,7 @@ eclipse {
}
}
if (System.properties['android.keystore.password'] != null) {
build.dependsOn "bundle"
}
+6 -13
View File
@@ -1,16 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.mowesta.android.app">
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
@@ -28,11 +29,10 @@
android:supportsRtl="true"
android:fullBackupContent="@xml/backup">
<activity
android:launchMode="singleTask"
android:launchMode="singleTop"
android:name=".MowestaActivity"
android:windowSoftInputMode="adjustResize"
android:exported="true"
android:label="@string/application_long">
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -80,13 +80,6 @@
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget_measure" />
</receiver>
<receiver
android:name=".widget.WidgetReceiver"
android:exported="true"/>
<service android:name=".MowestaService" />
<service
android:name=".widget.WidgetService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"/>
<service android:name=".MowestaService" android:exported="true"/>
</application>
</manifest>
Binary file not shown.
@@ -1,11 +1,17 @@
package com.mowesta.android.app;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.HttpResponseCache;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
@@ -14,8 +20,14 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.DialogFragment;
import androidx.navigation.NavBackStackEntry;
import androidx.navigation.NavController;
import androidx.navigation.NavDirections;
import androidx.navigation.NavOptionsBuilder;
import androidx.navigation.Navigation;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.snackbar.Snackbar;
import com.mowesta.android.app.database.FavoriteDatabase;
import com.mowesta.android.app.repository.UserCredentials;
@@ -23,7 +35,10 @@ import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.app.task.RefreshTask;
import com.mowesta.android.app.task.SyncTask;
import com.mowesta.android.app.util.PermissionUtil;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import com.mowesta.android.feign.api.DefaultApi;
import com.mowesta.android.sdk.SdkRepository;
import com.mowesta.android.sdk.task.ClearTask;
import java.io.File;
import java.io.IOException;
@@ -48,9 +63,19 @@ public class MowestaActivity extends AppCompatActivity {
private static final int DELAY_REFRESH = 15 * 60 * 1000;
/**
* The code used to request the permissions.
* Requests the permission to issue notifications.
*/
private static final int CODE_REQUEST_PERMISSIONS = 3334;
public static final int CODE_REQUEST_POST_NOTIFICATION = 3333;
/**
* The code used to request the permission for localizing in the foreground.
*/
public static final int CODE_REQUEST_FOREGROUND_PERMISSIONS = 3334;
/**
* The code used to request the permission for localizing in the background.
*/
private static final int CODE_REQUEST_BACKGROUND_PERMISSIONS = 3335;
/**
* The preferences.
@@ -96,7 +121,9 @@ public class MowestaActivity extends AppCompatActivity {
private OnSharedPreferenceChangeListener preferenceListener = (prefs, key) -> {
if (MowestaSettings.PRIVACY_MEASURE.equals(key)) {
if (settings.isPrivacyMeasure()) {
if (!PermissionUtil.hasBackgroundPermissions(this)) requestPermissions();
if (!PermissionUtil.hasBackgroundPermissions(this) ||
!PermissionUtil.hasNotificationPermission(this))
requestPermissions(false);
else MowestaService.startService(this);
} else {
MowestaService.stopService(this);
@@ -121,15 +148,46 @@ public class MowestaActivity extends AppCompatActivity {
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// got to navigation drawer when user presses notification
setIntent(intent);
Navigation.findNavController(this, R.id.navigation_app).navigate(R.id.action_drawer);
}
// got to navigation drawer when user presses notification
private void handleNotificationIntent() {
Intent intent = getIntent();
if (intent.hasExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name))) {
String value = intent.getStringExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name));
if (value != null && value.equals(getString(R.string.mowesta_sdk_notification_activity_extra_value))) {
NavController controller = Navigation.findNavController(this, R.id.navigation_app);
if (controller.getGraph().getId() == R.id.navigation_core) {
controller.navigate(R.id.action_drawer);
} else {
boolean hasDrawer = false;
for (NavBackStackEntry entry: controller.getBackQueue()) {
if (entry.getDestination().getId() == R.id.destination_drawer) {
hasDrawer = true;
}
}
if (hasDrawer) {
controller.navigate(R.id.action_drawer);
} else {
controller.navigate(R.id.action_core);
}
}
}
}
}
@Override
protected void onResume() {
super.onResume();
settings.getPreferences().registerOnSharedPreferenceChangeListener(preferenceListener);
handleNotificationIntent();
}
@Override
protected void onPostResume() {
super.onPostResume();
MowestaService.startService(this);
}
@Override
@@ -172,18 +230,15 @@ public class MowestaActivity extends AppCompatActivity {
/**
* Method to request location permission for the app.
*/
public void requestPermissions() {
public void requestPermissions(boolean skipNotification) {
Log.d(TAG, "Requesting permissions.");
requestPermissions(PermissionUtil.getNonGrantedBackgroundPermissions(this));
}
/**
* Requests the permissions.
*
* @param permissions The permissions to request.
*/
public void requestPermissions(String[] permissions) {
ActivityCompat.requestPermissions(this, permissions, CODE_REQUEST_PERMISSIONS);
if (!skipNotification && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !PermissionUtil.hasNotificationPermission(this)) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, CODE_REQUEST_POST_NOTIFICATION);
} else if (!PermissionUtil.hasPermissions(this, PermissionUtil.getForegroundPermissions(this))) {
ActivityCompat.requestPermissions(this, PermissionUtil.getForegroundPermissions(this), CODE_REQUEST_BACKGROUND_PERMISSIONS);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_BACKGROUND_LOCATION }, CODE_REQUEST_BACKGROUND_PERMISSIONS);
}
}
/**
@@ -197,7 +252,14 @@ public class MowestaActivity extends AppCompatActivity {
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CODE_REQUEST_PERMISSIONS: {
case CODE_REQUEST_POST_NOTIFICATION: {
if (!PermissionUtil.hasBackgroundPermissions(this))
requestPermissions(true);
else MowestaService.startService(this);
break;
}
case CODE_REQUEST_BACKGROUND_PERMISSIONS:
case CODE_REQUEST_FOREGROUND_PERMISSIONS: {
boolean granted = true;
StringBuilder b = new StringBuilder();
for (int i = 0, s = Math.min(permissions.length, grantResults.length); i < s; i++) {
@@ -208,9 +270,11 @@ public class MowestaActivity extends AppCompatActivity {
Log.d(TAG, "Permission result: " + b.toString());
if (!granted) {
settings.setPrivacyMeasure(false);
showMissingPermission();
showMissingPermission(requestCode == CODE_REQUEST_FOREGROUND_PERMISSIONS);
} else {
MowestaService.startService(this);
if (!PermissionUtil.hasBackgroundPermissions(this))
settings.setPrivacyMeasure(false);
else MowestaService.startService(this);
}
break;
}
@@ -222,22 +286,59 @@ public class MowestaActivity extends AppCompatActivity {
/**
* Shows a snackbar indicating a missing permission.
*/
public void showMissingPermission() {
View coordinator = findViewById(R.id.layout_coordinator);
Snackbar.make(coordinator, R.string.message_no_permission, Snackbar.LENGTH_LONG )
.setAction(R.string.button_configure, (view) -> {
// go to app settings
public void showMissingPermission(boolean foreground) {
PermissionDialogFragment pdf = PermissionDialogFragment.newInstance(foreground);
pdf.show(getSupportFragmentManager(), "permissions");
}
/**
* A dialog fragment to explain the need for permissions.
*
* @author Marcus
*/
public static class PermissionDialogFragment extends DialogFragment {
private static final String KEY_FOREGROUND = "foreground";
public static PermissionDialogFragment newInstance(boolean foreground) {
PermissionDialogFragment f = new PermissionDialogFragment();
Bundle b = new Bundle();
b.putBoolean(KEY_FOREGROUND, foreground);
f.setArguments(b);
return f;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
MaterialAlertDialogBuilder b = new MaterialAlertDialogBuilder(getActivity());
b.setTitle(R.string.message_permission_title);
b.setMessage(isForeground()?R.string.message_permission_foreground:R.string.message_permission_background);
b.setIcon(R.drawable.ic_gps_off_normal_24);
b.setNeutralButton(R.string.button_configure, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
try {
startActivity(intent);
} catch (Exception e) {
View coordinator = getActivity().findViewById(R.id.layout_coordinator);
Snackbar.make(coordinator, R.string.message_configure_failed,
Snackbar.LENGTH_SHORT).show();
}
}).show();
}
});
return b.show();
}
private boolean isForeground() {
Bundle b = getArguments();
return b.getBoolean(KEY_FOREGROUND, false);
}
}
}
@@ -4,16 +4,18 @@ import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
import com.google.android.exoplayer2.database.StandaloneDatabaseProvider;
import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.mowesta.android.app.database.Widget;
import com.mowesta.android.app.repository.ClientFactory;
import com.mowesta.android.app.repository.DeviceRepository;
import com.mowesta.android.app.repository.FavoriteRepository;
@@ -22,7 +24,7 @@ import com.mowesta.android.app.repository.WidgetRepository;
import com.mowesta.android.app.widget.AbstractWidgetProvider;
import com.mowesta.android.app.widget.ForecastWidgetProvider;
import com.mowesta.android.app.widget.MeasureWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import java.io.File;
@@ -34,6 +36,9 @@ import java.io.File;
*/
public class MowestaApp extends Application implements IApp {
/** The log tag. */
public static final String TAG = "MowestaApp";
/**
* The widget providers of the app.
*/
@@ -81,9 +86,8 @@ public class MowestaApp extends Application implements IApp {
deviceRepository = new DeviceRepository.Builder().setTrace(false).build(this);
favoriteRepository = new FavoriteRepository(this);
widgetRepository = new WidgetRepository(this);
MowestaService.startService(this);
WidgetReceiver.updateWidgets(this);
WidgetReceiver.scheduleUpdates(this);
PeriodicWidgetWorker.updateWidgets(this);
PeriodicWidgetWorker.scheduleUpdates(this);
//if(BuildConfig.DEBUG)
// StrictMode.enableDefaults();
}
@@ -91,8 +95,9 @@ public class MowestaApp extends Application implements IApp {
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "Configuration change detected.");
for (int i = widgetProviders.length - 1; i >= 0; i--) {
widgetProviders[i].triggerUpdates(this, false);
widgetProviders[i].triggerUpdates(MowestaApp.this, false);
}
}
@@ -135,7 +140,7 @@ public class MowestaApp extends Application implements IApp {
if (mediaCache == null) {
mediaCache = new SimpleCache(new File(this.getCacheDir(), "videos"),
new LeastRecentlyUsedCacheEvictor(25 * 1000 * 1000),
new ExoDatabaseProvider(getContext()));
new StandaloneDatabaseProvider(getContext()));
}
return mediaCache;
}
@@ -5,9 +5,11 @@ import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.mowesta.android.app.IApp;
@@ -41,7 +43,6 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
public void onCreate(@Nullable Bundle savedInstanceState) {
settings = ((IApp)getContext().getApplicationContext()).getSettings();
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
@@ -64,25 +65,29 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
public abstract void onRefreshDiagram();
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_unit, menu);
}
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_unit, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_unit_system) {
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
system.show(getChildFragmentManager(), "system");
return true;
} else if (itemId == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
return true;
}
return super.onOptionsItemSelected(item);
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_unit_system) {
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
system.show(getChildFragmentManager(), "system");
return true;
} else if (itemId == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
return true;
}
return false;
}
}, getViewLifecycleOwner());
}
}
@@ -11,6 +11,7 @@ import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import com.mowesta.android.app.R;
@@ -44,12 +45,6 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
*/
protected abstract AbstractPlaceViewModel getPlaceViewModel();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
@@ -58,45 +53,46 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
model.getCoordinate().observe(getViewLifecycleOwner(), (v) -> getActivity().invalidateOptionsMenu());
model.getFavorite().observe(getViewLifecycleOwner(), (v) -> getActivity().invalidateOptionsMenu());
model.getWikipedia().observe(getViewLifecycleOwner() ,(v) -> getActivity().invalidateOptionsMenu());
}
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_place, menu);
AbstractPlaceViewModel model = getPlaceViewModel();
Boolean favorite = model.getFavorite().getValue();
if (favorite == null || favorite) {
menu.removeItem(R.id.action_favorite_add);
}
if (favorite == null || !favorite) {
menu.removeItem(R.id.action_favorite_remove);
}
if (model.getWikipedia().getValue() == null) {
menu.removeItem(R.id.action_wikipedia);
}
if (model.getCoordinate().getValue() == null) {
menu.removeItem(R.id.action_google_maps);
}
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_place, menu);
AbstractPlaceViewModel model = getPlaceViewModel();
Boolean favorite = model.getFavorite().getValue();
if (favorite == null || favorite) {
menu.removeItem(R.id.action_favorite_add);
}
if (favorite == null || !favorite) {
menu.removeItem(R.id.action_favorite_remove);
}
if (model.getWikipedia().getValue() == null) {
menu.removeItem(R.id.action_wikipedia);
}
if (model.getCoordinate().getValue() == null) {
menu.removeItem(R.id.action_google_maps);
}
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_favorite_add) {
getPlaceViewModel().addFavorite();
return true;
} else if (itemId == R.id.action_favorite_remove) {
getPlaceViewModel().removeFavorite();
return true;
} else if (itemId == R.id.action_wikipedia) {
openWikipedia();
return true;
} else if (itemId == R.id.action_google_maps) {
openGoogleMaps();
return true;
}
return false;
}
}, getViewLifecycleOwner());
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_favorite_add) {
getPlaceViewModel().addFavorite();
return true;
} else if (itemId == R.id.action_favorite_remove) {
getPlaceViewModel().removeFavorite();
return true;
} else if (itemId == R.id.action_wikipedia) {
openWikipedia();
return true;
} else if (itemId == R.id.action_google_maps) {
openGoogleMaps();
return true;
}
return false;
}
/**
@@ -0,0 +1,98 @@
package com.mowesta.android.app.fragment;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.preference.PreferenceManager;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.snackbar.Snackbar;
import com.mowesta.android.app.R;
import com.mowesta.android.app.databinding.DialogAdvertiseBinding;
import com.mowesta.android.app.model.AdvertiseViewModel;
public class AdvertiseDialogFragment extends BottomSheetDialogFragment {
public static final String KEY_ADVERTISEMENT = "advertisement";
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
BottomSheetDialog d = (BottomSheetDialog) dialog;
FrameLayout bottomSheet = (FrameLayout) d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
return dialog;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
DialogAdvertiseBinding binding = DataBindingUtil.inflate(inflater, R.layout.dialog_advertise, container, false);
AdvertiseViewModel model = new ViewModelProvider(this).get(AdvertiseViewModel.class);
binding.setModel(model);
binding.setLifecycleOwner(getViewLifecycleOwner());
binding.videoView.setPlayer(model.getExoPlayer());
binding.videoView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
model.getClose().observe(getViewLifecycleOwner(), (v) -> { if (v) this.dismiss(); } );
model.getOpen().observe(getViewLifecycleOwner(), (v) -> {
if (v) {
String url = "https://www.mowesta.com/2022/05/23/fair-experiment-bei-das-fest-in-karlsruhe/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Snackbar.make(getView(), R.string.message_no_browser, Snackbar.LENGTH_SHORT).show();
}
model.getOpen().setValue(Boolean.FALSE);
}
});
return binding.getRoot();
}
public boolean shouldShow(Context context) {
long time = System.currentTimeMillis();
if (time > 1658700000000l) return false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
long last = prefs.getLong(KEY_ADVERTISEMENT, 0);
return (time - last > 7 * 24* 60 * 60 * 1000);
}
@Override
public void onDismiss(@NonNull DialogInterface dialog) {
super.onDismiss(dialog);
Context context = getActivity();
if (context != null) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor e = prefs.edit();
e.putLong(KEY_ADVERTISEMENT, System.currentTimeMillis());
e.apply();
}
}
}
@@ -1,5 +1,6 @@
package com.mowesta.android.app.fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
@@ -18,6 +19,9 @@ import com.mowesta.android.app.adapter.CityEntryPagedListAdapter;
import com.mowesta.android.app.model.AbstractNetworkViewModel;
import com.mowesta.android.app.model.CitiesViewModel;
import com.mowesta.android.app.model.StateViewModel;
import com.mowesta.android.app.util.TabletUtil;
import org.jetbrains.annotations.NotNull;
/**
@@ -26,6 +30,7 @@ import com.mowesta.android.app.model.StateViewModel;
* @author Marcus
*/
public class CitiesFragment extends AbstractNetworkFragment {
private RecyclerView recyclerView;
@Override
protected AbstractNetworkViewModel getNetworkViewModel() {
@@ -38,10 +43,27 @@ public class CitiesFragment extends AbstractNetworkFragment {
return inflater.inflate(R.layout.fragment_cities, container, false);
}
private void applyGridWidth() {
if (!TabletUtil.isTablet(requireContext())) {
return;
}
int width = requireContext().getResources().getInteger(R.integer.RecyclerWidth);
TabletUtil.setGridLayout(recyclerView, width);
}
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
applyGridWidth();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = view.findViewById(R.id.recycler);
recyclerView = view.findViewById(R.id.recycler);
applyGridWidth();
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
CityEntryPagedListAdapter adapter = new CityEntryPagedListAdapter(getViewLifecycleOwner(), (city) -> {
if (city != null) {
@@ -12,6 +12,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuProvider;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
@@ -71,30 +72,6 @@ public class CityFragment extends AbstractPlaceFragment {
return getView().findViewById(R.id.bottom_navigation);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_customize, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_customize) {
getChildFragmentManager()
.beginTransaction()
.add(new CustomizeDialogFragment(), "customize")
.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -126,5 +103,26 @@ public class CityFragment extends AbstractPlaceFragment {
return root;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_customize, menu);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_customize) {
getChildFragmentManager()
.beginTransaction()
.add(new CustomizeDialogFragment(), "customize")
.commit();
return true;
}
return false;
}
}, getViewLifecycleOwner());
}
}
@@ -55,11 +55,6 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
*/
private TimeUtils timeUtils = new TimeUtils(System.currentTimeMillis(), null);
/**
* The view pager of the parent.
*/
private ViewPager2 pager;
/**
* The date formatter.
*/
@@ -94,8 +89,6 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
dateFormatter = new DateFormatter(getContext());
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_gradient, container, false);
// this is quite ugly, but we need to disable the view pager and collapse the toolbar
pager = getActivity().findViewById(R.id.pager);
AppBarLayout layout = getActivity().findViewById(R.id.layout_appbar);
binding.gradientProgress1.setMax(TIMEOUT_REMOVER);
binding.gradientProgress2.setMax(TIMEOUT_REMOVER);
animator = ValueAnimator.ofInt(TIMEOUT_REMOVER, 0);
@@ -110,34 +103,7 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
binding.gradientText.setAlpha(Math.min(1, Math.max(0, value / 1000f)));
}
});
binding.gradientScroll.setOnTouchListener(binding.gradientTouch.createOnTouchListener(new TimeView.OnSlideListener() {
@Override
public void onSlide(float relative) {
if (!hasData()) return;
animator.cancel();
binding.gradientProgress1.setProgress(TIMEOUT_REMOVER);
binding.gradientProgress2.setProgress(TIMEOUT_REMOVER);
binding.gradientText.setAlpha(1);
handler.removeCallbacks(remover);
if (!closed) {
layout.setExpanded(false, true);
closed = true;
}
pager.setUserInputEnabled(false);
updateSelection(relative);
updateCondition(relative);
binding.gradientText.setVisibility(View.VISIBLE);
updateGuide(relative);
}
@Override
public void onSlideEnd() {
pager.setUserInputEnabled(true);
closed = false;
animator.start();
handler.postDelayed(remover, TIMEOUT_REMOVER);
}
}));
binding.setLifecycleOwner(getViewLifecycleOwner());
binding.gradientText.setVisibility(View.GONE);
@@ -278,7 +244,53 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
public void onPause() {
handler.removeCallbacks(remover);
remover.run();
binding.gradientScroll.setOnTouchListener(null);
super.onPause();
}
@Override
public void onResume() {
super.onResume();
AppBarLayout layout = getActivity().findViewById(R.id.layout_appbar);
ViewPager2 pager = getActivity().findViewById(R.id.pager);
binding.gradientScroll.setOnTouchListener(binding.gradientTouch.createOnTouchListener(new TimeView.OnSlideListener() {
@Override
public void onSlide(float relative) {
if (!hasData()) return;
animator.cancel();
binding.gradientProgress1.setProgress(TIMEOUT_REMOVER);
binding.gradientProgress2.setProgress(TIMEOUT_REMOVER);
binding.gradientText.setAlpha(1);
handler.removeCallbacks(remover);
if (!closed) {
if (layout != null)
layout.setExpanded(false, true);
closed = true;
}
if (pager != null)
pager.setUserInputEnabled(false);
updateSelection(relative);
updateCondition(relative);
binding.gradientText.setVisibility(View.VISIBLE);
updateGuide(relative);
}
@Override
public void onSlideEnd() {
if (pager != null)
pager.setUserInputEnabled(true);
closed = false;
animator.start();
handler.postDelayed(remover, TIMEOUT_REMOVER);
}
}));
}
@Override
public void onDestroyView() {
binding.gradientTouch.setOnTouchListener(null);
super.onDestroyView();
}
}
@@ -10,6 +10,7 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
@@ -39,12 +40,6 @@ public class DevicesFragment extends AbstractNetworkFragment {
return new ViewModelProvider(this).get(DevicesViewModel.class);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -55,6 +50,22 @@ public class DevicesFragment extends AbstractNetworkFragment {
Bundle bundle = new Bundle();
controller.navigate(R.id.destination_setup, bundle, opts.build());
});
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_refresh, menu);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
DevicesViewModel model = new ViewModelProvider(DevicesFragment.this).get(DevicesViewModel.class);
model.reload();
return true;
}
return false;
}
}, getViewLifecycleOwner());
return binding.getRoot();
}
@@ -84,21 +95,6 @@ public class DevicesFragment extends AbstractNetworkFragment {
swipeRefreshLayout.setOnRefreshListener(() -> model.reload());
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_refresh, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
DevicesViewModel model = new ViewModelProvider(this).get(DevicesViewModel.class);
model.reload();
return true;
}
return false;
}
}
@@ -9,6 +9,8 @@ import android.database.AbstractCursor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
@@ -26,6 +28,7 @@ import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuProvider;
import androidx.cursoradapter.widget.CursorAdapter;
import androidx.customview.widget.Openable;
import androidx.databinding.DataBindingUtil;
@@ -76,28 +79,12 @@ public class DrawerFragment extends AbstractNetworkFragment {
return new ViewModelProvider(this).get(DrawerViewModel.class);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
preventSplashScreen();
handleNotificationIntent();
}
/**
* Prevent going back to the splash screen if opened through deep link.
*/
private void preventSplashScreen() {
NavController nav = Navigation.findNavController(getActivity().findViewById(R.id.navigation_app));
if (nav.getGraph().getId() != R.id.navigation_core) {
nav.setGraph(R.navigation.navigation_core);
}
}
/**
* Checks if the intent was generated by the background service and
@@ -108,8 +95,8 @@ public class DrawerFragment extends AbstractNetworkFragment {
if (intent.hasExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name))) {
String value = intent.getStringExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name));
if (value != null && value.equals(getString(R.string.mowesta_sdk_notification_activity_extra_value))) {
Navigation.findNavController(getView().findViewById(R.id.navigation_drawer)).navigate(R.id.destination_settings);
getActivity().setIntent(new Intent());
Navigation.findNavController(getView().findViewById(R.id.navigation_drawer)).navigate(R.id.destination_settings);
}
}
}
@@ -121,48 +108,52 @@ public class DrawerFragment extends AbstractNetworkFragment {
Toolbar toolbar = view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
loadingProgressBar = view.findViewById(R.id.progress_bar);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
menuInflater.inflate(R.menu.menu_search, menu);
SearchView search = (SearchView)menu.findItem(R.id.action_search).getActionView();
search.setQueryHint(getString(R.string.action_search));
SearchView.SearchAutoComplete complete = search.findViewById(androidx.appcompat.R.id.search_src_text);
complete.setDropDownBackgroundResource(R.color.bg_search);
final DrawerViewModel model = new ViewModelProvider(DrawerFragment.this).get(DrawerViewModel.class);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
model.setTerm(newText);
return true;
}
});
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
showLocation(model, position);
return true;
}
@Override
public boolean onSuggestionClick(int position) {
showLocation(model, position);
return true;
}
});
search.setSuggestionsAdapter(new LocationCursorAdapter(getContext(), model.getResults()));
AppBarLayout appbar = getView().findViewById(R.id.layout_appbar);
search.setOnSearchClickListener((v)->appbar.setExpanded(false, true));
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
return false;
}
}, getViewLifecycleOwner());
return view;
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_search, menu);
SearchView search = (SearchView)menu.findItem(R.id.action_search).getActionView();
search.setQueryHint(getString(R.string.action_search));
SearchView.SearchAutoComplete complete = search.findViewById(androidx.appcompat.R.id.search_src_text);
complete.setDropDownBackgroundResource(R.color.bg_search);
final DrawerViewModel model = new ViewModelProvider(this).get(DrawerViewModel.class);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
model.setTerm(newText);
return true;
}
});
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
showLocation(model, position);
return true;
}
@Override
public boolean onSuggestionClick(int position) {
showLocation(model, position);
return true;
}
});
search.setSuggestionsAdapter(new LocationCursorAdapter(getContext(), model.getResults()));
AppBarLayout appbar = getView().findViewById(R.id.layout_appbar);
search.setOnSearchClickListener((v)->appbar.setExpanded(false, true));
}
private void showLocation(DrawerViewModel model, int position) {
LocationHierarchyPage page = model.getResults().getValue();
LocationHierarchy dest = page.getElements().get(position);
@@ -10,6 +10,7 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
@@ -40,23 +41,53 @@ import java.util.List;
*/
public class FavoritesFragment extends Fragment {
private static final String TAG_ADVERTISEMENT = "ad";
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// possibly show the ad for eiszeit
AdvertiseDialogFragment adf = new AdvertiseDialogFragment();
if (adf.shouldShow(getContext()) && getChildFragmentManager().findFragmentByTag(TAG_ADVERTISEMENT) == null) {
adf.show(getChildFragmentManager(), TAG_ADVERTISEMENT);
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_favorites, container, false);
View view = inflater.inflate(R.layout.fragment_favorites, container, false);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_unit, menu);
inflater.inflate(R.menu.menu_refresh, menu);
// remove this item, since it would not have an effect here
MenuItem item = menu.findItem(R.id.action_unit_system);
if (item != null) item.setVisible(false);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
model.refresh();
return true;
} else if (item.getItemId() == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
}
return false;
}
}, getViewLifecycleOwner());
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = view.findViewById(R.id.recycler);
TabletUtil.setGridLayout(recyclerView, 300);
TabletUtil.setGridLayout(recyclerView, 350);
SwipeRefreshLayout swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
model.getRefreshing().observe(getViewLifecycleOwner(), (refreshing) -> {
@@ -140,29 +171,6 @@ public class FavoritesFragment extends Fragment {
});
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_unit, menu);
inflater.inflate(R.menu.menu_refresh, menu);
// remove this item, since it would not have an effect here
MenuItem item = menu.findItem(R.id.action_unit_system);
if (item != null) item.setVisible(false);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
model.refresh();
return true;
} else if (item.getItemId() == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
}
return false;
}
/**
* The view holder for favorites.
*
@@ -4,9 +4,7 @@ import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -28,8 +26,7 @@ import com.mowesta.android.app.model.ColorViewModel;
import com.mowesta.android.app.model.ForecastWidgetViewModel;
import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.app.widget.ForecastWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.WidgetService;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import com.mowesta.android.feign.model.City;
/**
@@ -150,7 +147,8 @@ public class ForecastWidgetFragment extends AbstractNetworkFragment {
activity.finish();
}
});
WidgetReceiver.scheduleUpdates(app);
PeriodicWidgetWorker.scheduleUpdates(app);
int id = getWidgetId();
task.execute(id, ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
Intent resultValue = new Intent();
@@ -34,7 +34,7 @@ import com.mowesta.android.app.model.ColorViewModel;
import com.mowesta.android.app.model.MeasureWidgetViewModel;
import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.app.widget.MeasureWidgetProvider;
import com.mowesta.android.app.widget.WidgetReceiver;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import com.mowesta.android.feign.model.Device;
import java.util.ArrayList;
@@ -223,7 +223,7 @@ public class MeasureWidgetFragment extends AbstractNetworkFragment {
activity.finish();
}
});
WidgetReceiver.scheduleUpdates(app);
PeriodicWidgetWorker.scheduleUpdates(app);
int id = getWidgetId();
task.execute(id, ((IApp)activity.getApplicationContext()).getWidgetRepository().getDatabase());
Intent resultValue = new Intent();
@@ -26,6 +26,7 @@ import android.content.Intent;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
@@ -200,8 +201,6 @@ public class SettingsFragment extends PreferenceFragmentCompat {
*/
private void updateBuild() {
try {
ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(getActivity().getPackageName(), 0);
PackageInfo pi = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
String summary = getResources().getString(R.string.setting_about_build_summary);
summary = summary.replace("$version$", BuildConfig.VERSION_NAME);
summary = summary.replace("$code$", "" + BuildConfig.VERSION_CODE);
@@ -17,6 +17,7 @@ import android.view.animation.OvershootInterpolator;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
@@ -66,7 +67,7 @@ public class SetupFragment extends Fragment {
SetupViewModel.GpsStatus status = model.registerGpsReceiver();
switch (status) {
case PROHIBITED:
((MowestaActivity)getActivity()).requestPermissions(PermissionUtil.getForegroundPermissions(getActivity()));
ActivityCompat.requestPermissions(getActivity(), PermissionUtil.getForegroundPermissions(getActivity()), MowestaActivity.CODE_REQUEST_FOREGROUND_PERMISSIONS);
break;
case DISABLED:
Snackbar.make(container, R.string.setup_error_gps_disabled, Snackbar.LENGTH_LONG).setAction(R.string.button_configure, (v) -> {
@@ -1,5 +1,6 @@
package com.mowesta.android.app.fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
@@ -23,14 +24,33 @@ import com.mowesta.android.app.databinding.FragmentStationsBinding;
import com.mowesta.android.app.databinding.ViewStationEntryBinding;
import com.mowesta.android.app.model.AbstractNetworkViewModel;
import com.mowesta.android.app.model.StationsViewModel;
import com.mowesta.android.app.util.TabletUtil;
import com.mowesta.android.feign.model.WeatherStation;
import org.jetbrains.annotations.NotNull;
/**
* Shows a list of the available stations.
*
* @author Marcus
*/
public class StationsFragment extends AbstractNetworkFragment {
private RecyclerView recyclerView;
private void applyGridWidth() {
if (!TabletUtil.isTablet(requireContext())) {
return;
}
int width = requireContext().getResources().getInteger(R.integer.RecyclerWidth);
TabletUtil.setGridLayout(recyclerView, width);
}
@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
applyGridWidth();
}
@Override
protected AbstractNetworkViewModel getNetworkViewModel() {
@@ -50,7 +70,9 @@ public class StationsFragment extends AbstractNetworkFragment {
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recycler = view.findViewById(R.id.recycler);
recyclerView = view.findViewById(R.id.recycler);
applyGridWidth();
StationsViewModel model = new ViewModelProvider(this).get(StationsViewModel.class);
NavController controller = Navigation.findNavController(getActivity(), R.id.navigation_app);
StationEntryPagedListAdapter adapter = new StationEntryPagedListAdapter(getViewLifecycleOwner(), (station) -> {
@@ -65,7 +87,7 @@ public class StationsFragment extends AbstractNetworkFragment {
model.getStations().observe(getViewLifecycleOwner(), (list) -> {
adapter.submitList(list);
});
recycler.setAdapter(adapter);
recyclerView.setAdapter(adapter);
}
/**
@@ -141,7 +163,7 @@ public class StationsFragment extends AbstractNetworkFragment {
* Creates a new paged list adapter that will inform
* the listener about click events.
*
* @param owner The lifecycle owner.
* @param owner The lifecycle owner.
* @param listener The listener.
*/
public StationEntryPagedListAdapter(@NonNull LifecycleOwner owner, @NonNull StationsViewModel.OnStationSelectedListener listener) {
@@ -26,14 +26,13 @@ import androidx.preference.PreferenceManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.MowestaSettings;
@@ -187,7 +186,7 @@ public class VideoFragment extends AbstractNetworkFragment {
/**
* The player.
*/
private PlayerView player;
private StyledPlayerView player;
/**
* The weather video to compute the timings.
@@ -237,7 +236,7 @@ public class VideoFragment extends AbstractNetworkFragment {
model = new ViewModelProvider(this).get(ExoPlayerViewModel.class);
ImageButton zoomButton = view.findViewById(R.id.video_zoom);
player = view.findViewById(R.id.video_view);
player.setShowBuffering(PlayerView.SHOW_BUFFERING_ALWAYS);
player.setShowBuffering(StyledPlayerView.SHOW_BUFFERING_ALWAYS);
overlay = view.findViewById(R.id.video_time);
View frame = LayoutInflater.from(view.getContext()).inflate(R.layout.view_marker, player.getOverlayFrameLayout(), true);
marker = frame.findViewById(R.id.video_marker);
@@ -272,7 +271,7 @@ public class VideoFragment extends AbstractNetworkFragment {
timeUtils = new TimeUtils(System.currentTimeMillis(), timezone);
formatter = new DateFormatter(getContext());
if (model.exoPlayer == null) {
model.exoPlayer = new SimpleExoPlayer.Builder(getContext()).build();
model.exoPlayer = new ExoPlayer.Builder(getContext()).build();
model.scaler.setContent(video.getWidth(), video.getHeight());
IApp app = (IApp)getActivity().getApplication();
DefaultHttpDataSource.Factory hf = new DefaultHttpDataSource.Factory();
@@ -0,0 +1,65 @@
package com.mowesta.android.app.model;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.upstream.AssetDataSource;
import com.google.android.exoplayer2.upstream.DataSource;
public class AdvertiseViewModel extends AndroidViewModel {
private ExoPlayer exoPlayer;
private MutableLiveData<Boolean> close = new MutableLiveData<>(Boolean.FALSE);
private MutableLiveData<Boolean> open = new MutableLiveData<>(Boolean.FALSE);
public AdvertiseViewModel(Application app) {
super(app);
ExoPlayer.Builder builder = new ExoPlayer.Builder(app);
exoPlayer = builder.build();
DataSource.Factory df = new DataSource.Factory() {
@Override
public DataSource createDataSource() {
return new AssetDataSource(app);
}
};
MediaSource videoSource = new ProgressiveMediaSource.Factory(df)
.createMediaSource(MediaItem.fromUri("android_assets:///dasfest.mp4"));
exoPlayer.setRepeatMode(ExoPlayer.REPEAT_MODE_ALL);
exoPlayer.setMediaSource(videoSource);
exoPlayer.prepare();
exoPlayer.setPlayWhenReady(true);
}
public MutableLiveData<Boolean> getClose() {
return close;
}
public MutableLiveData<Boolean> getOpen() {
return open;
}
public void close() {
close.setValue(Boolean.TRUE);
}
public void open() {
open.setValue(Boolean.TRUE);
}
public ExoPlayer getExoPlayer() {
return exoPlayer;
}
@Override
protected void onCleared() {
exoPlayer.stop();
}
}
@@ -196,7 +196,7 @@ public class DeviceViewModel extends AbstractNetworkViewModel {
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<DiagramEntry<Measurement>> callback) {
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(id, 0l, now, params.requestedStartPosition, params.requestedLoadSize ); },
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(now, id, 0l, params.requestedStartPosition, params.requestedLoadSize ); },
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()), params.requestedStartPosition, page.getTotal())); },
(id, status) -> { finishRequest(requestCode, true); });
if (isCurrentRequest(requestCode)) {
@@ -211,7 +211,7 @@ public class DeviceViewModel extends AbstractNetworkViewModel {
@Override
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<DiagramEntry<Measurement>> callback) {
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(id, 0l, now, params.startPosition, params.loadSize ); },
ApiTask<Long, MeasurementPage> task = new ApiTask<>((id, client) -> { return client.getDeviceMeasurements(now, id, 0l, params.startPosition, params.loadSize ); },
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()))); },
(id, status) -> { finishRequest(requestCode, true); });
if (id != null && credentials != null && isCurrentRequest(requestCode)) {
@@ -57,7 +57,7 @@ public class DrawerViewModel extends AbstractNetworkViewModel {
* The task to perform the search.
*/
private ApiTask<RequestParameter<String>, LocationHierarchyPage> searchTask = new ApiTask<>((input, client) -> {
return client.searchLocations(getLanguage(), input.getValue(), 0, 10, null);
return client.searchLocations(getLanguage(), input.getValue(), null,0, 10);
}, (input, result) -> {
completeRequest(input, () -> {
results.setValue(result);
@@ -68,7 +68,7 @@ public class ForecastWidgetViewModel extends AbstractNetworkViewModel {
private ApiTask<RequestParameter<String>, CityPage> searchTask = new ApiTask<>(
(input, client) -> {
CityPage cities = client.searchCities(getApplication().getString(R.string.language_code), input.getValue(), 0, 20, null);
CityPage cities = client.searchCities(getApplication().getString(R.string.language_code), input.getValue(), null, 0, 20);
return cities;
},
(input, result) -> {
@@ -355,16 +355,22 @@ public class SetupViewModel extends AndroidViewModel {
private Double parseValue(String value) {
if (value == null) return null;
value = value.trim();
LocaleListCompat c = ConfigurationCompat.getLocales(getApplication().getResources().getConfiguration());
for (int i = 0; i < c.size(); i++) {
Locale l = c.get(i);
NumberFormat f = NumberFormat.getNumberInstance(l);
try {
return ((Number)f.parseObject(value.trim())).doubleValue();
return ((Number)f.parseObject(value)).doubleValue();
} catch (ParseException e) {
Log.d(TAG, "Failed to parse double from: " + value);
}
}
try {
return Double.parseDouble(value.replace(',', '.'));
} catch (NumberFormatException e) {
Log.d(TAG, "Failed to parse double, giving up: " + value);
}
return null;
}
@@ -201,7 +201,7 @@ public class StationViewModel extends AbstractNetworkViewModel {
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<DiagramEntry<WeatherReport>> callback) {
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(id, 0l, now, params.requestedStartPosition, params.requestedLoadSize ); },
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(now, id, 0l, params.requestedStartPosition, params.requestedLoadSize ); },
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()), params.requestedStartPosition, page.getTotal())); },
(id, status) -> { finishRequest(requestCode, true); });
if (id != null && isCurrentRequest(requestCode)) {
@@ -212,7 +212,7 @@ public class StationViewModel extends AbstractNetworkViewModel {
@Override
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<DiagramEntry<WeatherReport>> callback) {
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(id, 0l, now, params.startPosition, params.loadSize ); },
ApiTask<Long, WeatherReportPage> task = new ApiTask<>((id, client) -> { return client.getStationReports(now, id, 0l, params.startPosition, params.loadSize ); },
(id, page) -> { completeRequest(requestCode, () -> callback.onResult(toEntries(page.getElements()))); },
(id, status) -> { finishRequest(requestCode, true); });
if (id != null && isCurrentRequest(requestCode)) {
@@ -150,7 +150,7 @@ public class StationsViewModel extends AbstractNetworkViewModel {
@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<WeatherStation> callback) {
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(term,0, params.requestedLoadSize ); },
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(0, params.requestedLoadSize, term); },
(v, page) -> { completeRequest(requestCode, () -> callback.onResult(page.getElements(), 0, page.getTotal())); },
(v, status) -> { finishRequest(requestCode, true); });
if (isCurrentRequest(requestCode)) {
@@ -161,7 +161,7 @@ public class StationsViewModel extends AbstractNetworkViewModel {
@Override
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<WeatherStation> callback) {
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(term, params.startPosition, params.loadSize); },
ApiTask<Void, WeatherStationPage> task = new ApiTask<>((v, client) -> { return client.getStations(params.startPosition, params.loadSize, term); },
(v, page) -> { completeRequest(requestCode, () -> callback.onResult(page.getElements())); },
(v, status) -> { finishRequest(requestCode, true);});
if (isCurrentRequest(requestCode)) {
@@ -8,7 +8,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.security.crypto.EncryptedFile;
import androidx.security.crypto.MasterKey;
import androidx.security.crypto.MasterKeys;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -281,9 +281,8 @@ public class FileStoreObserver<T> implements Observer<T> {
* be setup.
*/
@NonNull EncryptedFile getEncryptedFile() throws IOException, GeneralSecurityException {
MasterKey.Builder b = new MasterKey.Builder(context);
b.setKeyScheme(MasterKey.KeyScheme.AES256_GCM);
return new EncryptedFile.Builder(context, getFile(), b.build(),
String keySpec = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
return new EncryptedFile.Builder(getFile(), context, keySpec,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB).build();
}
@@ -96,4 +96,18 @@ public class PermissionUtil {
return new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION };
}
/**
* Determines whether the app has the post notification permission.
*
* @param context The context.
* @return True if the app may post notifications.
*/
public static boolean hasNotificationPermission(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return hasPermissions(context, new String[] { Manifest.permission.POST_NOTIFICATIONS });
} else {
return true;
}
}
}
@@ -1,10 +1,6 @@
package com.mowesta.android.app.util;
import android.content.Context;
import android.content.res.Resources;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.os.ConfigurationCompat;
import com.mowesta.android.app.R;
@@ -17,7 +13,7 @@ import java.util.List;
import java.util.TimeZone;
/**
* A utiltiy class to comptue times when aggregating weather
* A utility class to computes times when aggregating weather
* conditions into weather summaries.
*
* @author Marcus
@@ -44,15 +40,15 @@ public class TimeUtils {
* @param tz The time zone.
*/
public TimeUtils(long now, String tz) {
if (tz != null) {
c.setTimeZone(TimeZone.getTimeZone(tz));
}
c.setTimeInMillis(now);
update(today);
c.add(Calendar.DAY_OF_MONTH, -1);
update(yesterday);
c.add(Calendar.DAY_OF_MONTH, 2);
update(tomorrow);
if (tz != null) {
c.setTimeZone(TimeZone.getTimeZone(tz));
}
}
/**
@@ -133,7 +133,7 @@ public abstract class AbstractWidgetProvider extends AppWidgetProvider {
* @param id The id.
*/
public void triggerUpdate(Context context, int id, boolean schedule) {
if (schedule) WidgetService.scheduleUpdate(context, type, id);
if (schedule) OnetimeWidgetWorker.updateWidget(context, type, id);
Log.d(TAG, "Start database query for widget " + id + ".");
DatabaseTask<WidgetDatabase, Integer, Widget> task = new DatabaseTask<WidgetDatabase, Integer, Widget>((input, database)-> {
List<Widget> widgets = database.getAccessor().get(type, input);
@@ -157,6 +157,7 @@ public abstract class AbstractWidgetProvider extends AppWidgetProvider {
* @return An int array containing the width and height.
*/
protected int[] getWidgetDimensions(Context context, int id) {
Log.d(TAG, "Requesting app widget manager options.");
AppWidgetManager manager = AppWidgetManager.getInstance(context);
Bundle options = manager.getAppWidgetOptions(id);
if (options == null) return new int[] { 0, 0 };
@@ -74,6 +74,7 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
@Override
public void updateWidget(Context context, Widget widget) {
Log.d(TAG, "Performing forecast widget update "+ widget.getReference() + ".");
City city = widget.getData(City.class);
if (city == null) {
Log.d(TAG, "Ignoring update without for widget " + widget.getReference() + " without city.");
@@ -92,6 +93,7 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
}
days = a.getDays();
}
Log.d(TAG, "Building remote views.");
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_forecast);
// set color
@@ -118,6 +120,7 @@ public class ForecastWidgetProvider extends AbstractWidgetProvider {
}
}
float scale = context.getResources().getDisplayMetrics().scaledDensity / context.getResources().getDisplayMetrics().density;
Log.d(TAG, "Building remote views done.");
int[] widgetDimension = getWidgetDimensions(context, widget.getReference());
int width = widgetDimension[0];
int height = widgetDimension[1];
@@ -59,6 +59,7 @@ public class MeasureWidgetProvider extends AbstractWidgetProvider {
@Override
public void updateWidget(Context context, Widget widget) {
Log.d(TAG, "Performing measure widget update "+ widget.getReference() + ".");
Device device = widget.getData(Device.class);
if (device == null) {
Log.d(TAG, "Ignoring update without for widget " + widget.getReference() + " without device.");
@@ -92,11 +93,6 @@ public class MeasureWidgetProvider extends AbstractWidgetProvider {
Measurement measurement = widget.getContent(Measurement.class);
if (measurement != null) {
List<RemoteViews> items = new ArrayList<>();
Date dateTime = new Date(measurement.getTime());
String date = android.text.format.DateFormat.getDateFormat(context).format(dateTime);
createItemView(items, context, R.drawable.ic_calendar_today_normal_24, R.string.widget_measure_date, UnitUtils.toSpanned(date), widget.getColor());
String time = android.text.format.DateFormat.getTimeFormat(context).format(dateTime);
createItemView(items, context, R.drawable.ic_alarm_normal_24, R.string.widget_measure_time , UnitUtils.toSpanned(time), widget.getColor());
if (measurement.getTemperature() != null) {
createItemView(items, context, R.drawable.ic_thermometer_normal_24, R.string.label_temperature, UnitUtils.toSpanned(UnitUtils.getTemperature(context, measurement.getTemperature(), unit)), widget.getColor());
}
@@ -114,6 +110,11 @@ public class MeasureWidgetProvider extends AbstractWidgetProvider {
}
}
}
Date dateTime = new Date(measurement.getTime());
String date = android.text.format.DateFormat.getDateFormat(context).format(dateTime);
createItemView(items, context, R.drawable.ic_calendar_today_normal_24, R.string.widget_measure_date, UnitUtils.toSpanned(date), widget.getColor());
String time = android.text.format.DateFormat.getTimeFormat(context).format(dateTime);
createItemView(items, context, R.drawable.ic_alarm_normal_24, R.string.widget_measure_time , UnitUtils.toSpanned(time), widget.getColor());
int max = Math.min(items.size(), (int)((height - (HEIGHT_DEVICE * scale)) / (HEIGHT_ITEM * scale)));
for (int i = 0; i < max; i++) {
views.addView(R.id.widget_container_item, items.get(i));
@@ -2,14 +2,17 @@ package com.mowesta.android.app.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.OutOfQuotaPolicy;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.mowesta.android.app.IApp;
import com.mowesta.android.app.database.Widget;
@@ -21,22 +24,32 @@ import com.mowesta.android.feign.model.Device;
import com.mowesta.android.feign.model.Measurement;
import com.mowesta.android.feign.model.MeasurementPage;
import com.mowesta.android.feign.model.WeatherForecast;
import com.mowesta.android.sdk.task.AbstractTask;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* The service that updates the forecast widgets.
*
* @author Marcus
* A worker that updates a widget. The widget reference
* is passed as a parameter to the job.
*/
public class WidgetService extends JobIntentService {
public class OnetimeWidgetWorker extends Worker {
/**
* The worker to update the widget.
*/
public static final String TAG = "OnetimeWidgetWorker";
/**
* The extra containing the reference.
*/
public static final String EXTRA_WIDGET_REFERENCE = "reference";
/**
* The extra containing the widget type.
*/
public static final String EXTRA_WIDGET_TYPE = "type";
/**
* The delay to update the data.
*/
@@ -45,85 +58,64 @@ public class WidgetService extends JobIntentService {
/**
* The delay to update the content.
*/
private static final int DELAY_CONTENT = 1 * 60 * 60 * 1000;
private static final int DELAY_CONTENT = 30 * 60 * 1000;
/** The widget type. */
private int type;
/** The widget reference. */
private int reference;
/** The handler. */
private Handler handler;
/** The app. */
private IApp app;
public OnetimeWidgetWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
app = (IApp)context.getApplicationContext();
handler = new Handler(Looper.getMainLooper());
type = params.getInputData().getInt(EXTRA_WIDGET_TYPE, Widget.TYPE_INVALID);
reference = params.getInputData().getInt(EXTRA_WIDGET_REFERENCE, AppWidgetManager.INVALID_APPWIDGET_ID);
}
public static void updateWidget(Context context, int type, int reference) {
Log.d(TAG, "Scheduling update for widget " + type + " " + reference + ".");
WorkManager workManager = WorkManager.getInstance(context);
OneTimeWorkRequest.Builder builder = new OneTimeWorkRequest.Builder(OnetimeWidgetWorker.class);
builder.setInputData(OnetimeWidgetWorker.createData(type, reference));
builder.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST);
OneTimeWorkRequest request = builder.build();
workManager.beginWith(request).enqueue();
}
/**
* The extra containing the widget type.
*/
public static final String EXTRA_WIDGET_TYPE = "type";
/**
* The id for the service.
*/
private static final int SERVICE_ID = 1111;
/**
* The log tag.
*/
private static final String TAG = "WidgetService";
/**
* A handler to perform work on the ui thread.
*/
private Handler handler = new Handler(Looper.getMainLooper());
/**
* Schedules an update for a particular widget referenced by its type and its
* local id.
* Creates the data for scheduling the worker.
*
* @param context Tthe context.
* @param reference The widget reference.
* @param type The widget type.
* @param type The type.
* @param reference The reference.
* @return The data.
*/
public static void scheduleUpdate(Context context, int type, int reference) {
Log.d(TAG, "Schedule background update for widget " + reference + " type " + type + ".");
Intent intent = new Intent();
intent.setClass(context, JobIntentService.class);
intent.putExtra(EXTRA_WIDGET_TYPE, type);
intent.putExtra(EXTRA_WIDGET_REFERENCE, reference);
// schedule background execution with proper locks
enqueueWork(context, WidgetService.class, SERVICE_ID, intent);
// and also execute immediately, if we are on > o
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Handler handler = new Handler(Looper.getMainLooper());
IApp app = (IApp)context.getApplicationContext();
new AbstractTask<Void>(true) {
@Override
protected Void doInBackground() {
updateWidget(app, handler, type, reference);
return null;
}
}.execute();
}
public static Data createData(int type, int reference) {
Data.Builder b = new Data.Builder();
b.putInt(EXTRA_WIDGET_TYPE, type);
b.putInt(EXTRA_WIDGET_REFERENCE, reference);
return b.build();
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
int type = intent.getIntExtra(EXTRA_WIDGET_TYPE, Widget.TYPE_INVALID);
int reference = intent.getIntExtra(EXTRA_WIDGET_REFERENCE, AppWidgetManager.INVALID_APPWIDGET_ID);
IApp app = (IApp)getApplicationContext();
updateWidget(app, handler, type, reference);
}
/**
* Updates the data contained in the widget and requests a ui update.
*
* @param app The app.
* @param handler A handler to trigger a refresh.
* @param type The type.
* @param reference The reference.
*/
public static void updateWidget(IApp app, Handler handler, int type, int reference) {
public Result doWork() {
Log.d(TAG, "Performing update for widget " + type + " " + reference + ".");
if (type == Widget.TYPE_INVALID || reference == AppWidgetManager.INVALID_APPWIDGET_ID) {
Log.d(TAG, "Received an invalid request for type " + type + " and reference " + reference + ".");
return;
return Result.success();
}
WidgetDatabase database = app.getWidgetRepository().getDatabase();
WidgetAccessor accessor = database.getAccessor();
List<Widget> widgets = accessor.get(type, reference);
if (widgets.isEmpty()) {
Log.d(TAG, "Received a request for removed widget with type " + type + " and reference " + reference + ".");
return;
return Result.success();
}
Widget widget = widgets.get(0);
if (type == Widget.TYPE_FORECAST) {
@@ -174,7 +166,7 @@ public class WidgetService extends JobIntentService {
Measurement[] content = new Measurement[] { widget.getContent(Measurement.class) };
long[] contentTime = new long[] { widget.getContentTime() };
if (content[0] == null || time - contentTime[0] > DELAY_CONTENT) {
MeasurementPage page = api.getDeviceMeasurements(widget.getDataId(), 0l, time, 0, 1);
MeasurementPage page = api.getDeviceMeasurements(time, widget.getDataId(), 0l, 0, 1);
if (page.getElements().size() > 0) {
content[0] = page.getElements().get(0);
contentTime[0] = time;
@@ -200,6 +192,7 @@ public class WidgetService extends JobIntentService {
});
}
}
// Indicate whether the work finished successfully with the Result
return Result.success();
}
}
@@ -0,0 +1,95 @@
package com.mowesta.android.app.widget;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.mowesta.android.app.database.Widget;
import java.util.concurrent.TimeUnit;
/**
* A widget worker that is scheduled for periodic
* execution and triggers immediate one-time updates
* for all widgets.
*
* @author Marcus
*/
public class PeriodicWidgetWorker extends Worker {
public static final String TAG = "PeriodicWidgetWorker";
private static final String WORK_TAG = "widget_refresh";
public PeriodicWidgetWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
updateWidgets(getApplicationContext());
return Result.success();
}
/**
* Schedules periodic updates to all widgets.
*
* @param context The context.
*/
public static void scheduleUpdates(Context context) {
Log.d(TAG, "Scheduling periodic widget updates.");
PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(PeriodicWidgetWorker.class, 15, TimeUnit.MINUTES);
WorkManager.getInstance(context).enqueueUniquePeriodicWork(WORK_TAG, ExistingPeriodicWorkPolicy.KEEP, builder.build());
}
/**
* Updates all widgets one time.
*
* @param context The context.
*/
public static void updateWidgets(Context context) {
Log.d(TAG, "Received widget update request.");
boolean hasWidgets = updateWidgets(context, ForecastWidgetProvider.class, Widget.TYPE_FORECAST);
hasWidgets |= updateWidgets(context, MeasureWidgetProvider.class, Widget.TYPE_MEASURE);
if (!hasWidgets) cancelUpdates(context);
}
/**
* Updates all widgets of a particular provider and returns whether anything
* has been scheduled.
*
* @param context The context.
* @param provider The widget provider class.
* @param type The widget type.
* @return True if any update has been scheduled.
*/
private static boolean updateWidgets(Context context, Class<?> provider, int type) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, provider));
WorkManager workManager = WorkManager.getInstance(context);
for (int id: ids) {
OnetimeWidgetWorker.updateWidget(context, type, id);
}
return ids.length > 0;
}
/**
* Removes the scheduled periodic update.
*
* @param context The context.
*/
public static void cancelUpdates(Context context) {
WorkManager.getInstance(context).cancelUniqueWork(WORK_TAG);
}
}
@@ -1,113 +0,0 @@
package com.mowesta.android.app.widget;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import com.mowesta.android.app.database.Widget;
/**
* The receiver that is called periodically by the alarm
* manager to perform widget updates every x minutes.
*
* @author Marcus
*/
public class WidgetReceiver extends BroadcastReceiver {
/**
* The log tag.
*/
private static final String TAG = "WidgetReceiver";
/**
* The request code.
*/
private static final int REQuEST_CODE = 2298;
/**
* The initial scheduling delay.
*/
private static final int DELAY_START = 60000;
/**
* The periodic update rate.
*/
private static final int DELAY_PERIOD = 15 * 60000;
@Override
public void onReceive(Context context, Intent intent) {
updateWidgets(context);
}
/**
* Updates all widgets.
*
* @param context The context.
*/
public static void updateWidgets(Context context) {
Log.d(TAG, "Received widget update request.");
boolean hasWidgets = updateWidgets(context, ForecastWidgetProvider.class, Widget.TYPE_FORECAST);
hasWidgets |= updateWidgets(context, MeasureWidgetProvider.class, Widget.TYPE_MEASURE);
if (!hasWidgets) cancelUpdates(context);
}
/**
* Updates all widgets of a particular provider and returns whether anything
* has been scheduled.
*
* @param context The context.
* @param provider The widget provider class.
* @param type The widget type.
* @return True if any update has been scheduled.
*/
private static boolean updateWidgets(Context context, Class<?> provider, int type) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, provider));
for (int id: ids) {
WidgetService.scheduleUpdate(context, type, id);
}
return ids.length > 0;
}
/**
* Schedules periodic widget updates.
*
* @param context The context.
*/
public static void scheduleUpdates(Context context) {
Log.d(TAG, "Scheduling periodic widget updates.");
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + DELAY_START, DELAY_PERIOD, createIntent(context));
}
/**
* Creates a pending intent for the updates.
*
* @param context The context.
* @return The pending intent.
*/
private static PendingIntent createIntent(Context context) {
Intent intent = new Intent(context, WidgetReceiver.class);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) flags = flags | PendingIntent.FLAG_IMMUTABLE;
return PendingIntent.getBroadcast(context, REQuEST_CODE, intent, flags);
}
/**
* Cancels the period widget updates.
*
* @param context The context.
*/
public static void cancelUpdates(Context context) {
Log.d(TAG, "Canceling periodic widget updates.");
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(createIntent(context));
}
}
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M20.94,11c-0.46,-4.17 -3.77,-7.48 -7.94,-7.94L13,1h-2v2.06c-1.13,0.12 -2.19,0.46 -3.16,0.97l1.5,1.5C10.16,5.19 11.06,5 12,5c3.87,0 7,3.13 7,7 0,0.94 -0.19,1.84 -0.52,2.65l1.5,1.5c0.5,-0.96 0.84,-2.02 0.97,-3.15L23,13v-2h-2.06zM3,4.27l2.04,2.04C3.97,7.62 3.25,9.23 3.06,11L1,11v2h2.06c0.46,4.17 3.77,7.48 7.94,7.94L11,23h2v-2.06c1.77,-0.2 3.38,-0.91 4.69,-1.98L19.73,21 21,19.73 4.27,3 3,4.27zM16.27,17.54C15.09,18.45 13.61,19 12,19c-3.87,0 -7,-3.13 -7,-7 0,-1.61 0.55,-3.09 1.46,-4.27l9.81,9.81z"/>
</vector>
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-6h2v6zM13,9h-2L11,7h2v2z"/>
</vector>
@@ -9,7 +9,7 @@
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation_view"
android:layout_width="210dp"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:itemTextAppearance="?attr/textAppearanceBody1"
@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="model"
type="com.mowesta.android.app.model.AdvertiseViewModel" />
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/header"
android:background="@color/accent"
tools:targetApi="21"
android:elevation="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Space
android:layout_width="@dimen/space_medium"
android:layout_height="wrap_content"/>
<ImageView
android:contentDescription="@null"
android:layout_width="48dp"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
app:tint="@color/fg_accent"
app:srcCompat="@drawable/ic_info_normal_24"/>
<TextView
android:layout_weight="1"
android:layout_marginStart="@dimen/space_medium"
android:layout_marginEnd="@dimen/space_medium"
android:layout_gravity="center_vertical"
style="@style/TextAppearance.MaterialComponents.Subtitle1"
android:text="@string/advertise_header"
android:textColor="@color/fg_accent"
android:singleLine="true"
android:ellipsize="end"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<ImageButton
android:contentDescription="@string/button_close"
android:layout_width="48dp"
app:tint="@color/fg_accent"
android:layout_height="wrap_content"
android:onClick="@{ () -> model.close() }"
style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
app:srcCompat="@drawable/ic_close_normal_24" />
</LinearLayout>
<RelativeLayout
android:clickable="true"
android:focusable="true"
android:onClick="@{ () -> model.open() }"
android:layout_width="match_parent"
android:layout_height="180dp">
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="@+id/video_view"
android:layout_alignParentBottom="true"
app:use_controller="false"
app:resize_mode="zoom"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/ad_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:padding="8dp"
android:text="@string/advertise_title"
android:textAppearance="?attr/textAppearanceHeadline3"
android:textColor="@color/white" />
<TextView
android:text="@string/advertise_more"
android:textAppearance="?attr/textAppearanceBody1"
android:layout_centerInParent="true"
android:paddingTop="16dp"
android:paddingBottom="8dp"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:gravity="center"
android:textStyle="bold"
android:textColor="@color/accent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/ad_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:padding="8dp"
android:text="@string/advertise_description"
android:textAppearance="?attr/textAppearanceBody2"
android:textColor="@color/white"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
</layout>
@@ -8,7 +8,7 @@
android:layout_height="match_parent">
<com.google.android.exoplayer2.ui.PlayerView
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="@+id/video_view"
android:layout_centerInParent="true"
app:resize_mode="zoom"
@@ -41,7 +41,7 @@
android:layout_height="wrap_content"
tools:text="Sony Xperia Foo"
android:gravity="end"
android:lines="1"
android:maxLines="2"
android:ellipsize="end"
android:id="@+id/view_header_device"
android:textAppearance="?android:attr/textAppearanceSmallInverse" />
@@ -87,4 +87,11 @@
app:destination="@id/navigation_core" />
</fragment>
<action
android:id="@+id/action_core"
app:popUpTo="@id/destination_splash"
app:popUpToInclusive="true"
app:launchSingleTop="true"
app:destination="@id/navigation_core" />
</navigation>
@@ -87,6 +87,7 @@
android:id="@+id/action_drawer"
app:popUpTo="@id/destination_drawer"
app:popUpToInclusive="true"
app:launchSingleTop="true"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
app:destination="@id/destination_drawer" />
+10 -2
View File
@@ -16,9 +16,11 @@
<string name="button_yes">Ja</string>
<string name="button_no">Nein</string>
<string name="message_no_browser">Dein Webbrowser konnte nicht geöffnet werden.</string>
<string name="message_no_permission">Der App fehlt eine notwendige Berechtigung.</string>
<string name="message_permission_title">Fehlende Berechtigung</string>
<string name="message_permission_background">Um automatisch Messungen zu erfassen, benötigt MoWeSta die Berechtigung auf den Gerätestandort im Hintergrund zugreifen zu können.</string>
<string name="message_permission_foreground">Um den Standort automatisch zu bestimmen, benötigt MoWeSta die Berechtigung auf den Gerätestandort zugreifen zu können.</string>
<string name="message_configure_failed">Die Einstellungen konnten nicht geöffnet werden.</string>
<string name="button_configure">An-\npassen</string>
<string name="button_configure">Einstellungen anpasssen</string>
<!-- video controls -->
<string name="button_fit_screen">Anzeige anpasen</string>
@@ -318,4 +320,10 @@
<string name="color_dialog_blue">Blau</string>
<string name="color_dialog_green">Grün</string>
<string name="advertise_header">Veranstaltungshinweis</string>
<string name="advertise_description">Mach mit beim FAIR Experiment bei DAS FEST vom 21. bis zum 24. Juli in Karlsruhe</string>
<string name="advertise_more">Mehr erfahren…</string>
<string name="advertise_title">DAS FEST</string>
</resources>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="match_parent_limit">
<item name="android:layout_width">390dp</item>
<item name="android:layout_width">340dp</item>
</style>
</resources>
@@ -1,6 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<integer name="RecyclerWidth">375</integer>
<declare-styleable name="DataView">
<attr name="direction" format="enum">
<enum name="HORIZONTAL" value="0" />
+9 -2
View File
@@ -16,9 +16,11 @@
<string name="button_yes">Yes</string>
<string name="button_no">No</string>
<string name="message_no_browser">Unable to open your web browser.</string>
<string name="message_no_permission">The app is missing a required permission.</string>
<string name="message_permission_title">Missing Permission</string>
<string name="message_permission_background">To automatically collect measurements, MoWeSta needs your permission to locate your device in the background.</string>
<string name="message_permission_foreground">To automatically set the location, MoWeSta needs your permission to locate your device.</string>
<string name="message_configure_failed">Could not open the app settings.</string>
<string name="button_configure">Con-\nfigure</string>
<string name="button_configure">Configure settings</string>
<!-- video controls -->
<string name="button_fit_screen">Match screen</string>
@@ -322,4 +324,9 @@
<string name="color_dialog_red">Red</string>
<string name="color_dialog_blue">Blue</string>
<string name="color_dialog_green">Green</string>
<string name="advertise_header">Event note</string>
<string name="advertise_description">Join the FAIR Experiment at DAS FEST from July 21th to 24th in Karlsruhe</string>
<string name="advertise_more">Read more…</string>
<string name="advertise_title">DAS FEST</string>
</resources>
@@ -1,41 +0,0 @@
package com.mowesta.android.app.test;
import androidx.test.core.app.ApplicationProvider;
import com.mowesta.android.app.R;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
/**
* Runs a simple roboelectric test.
*
* @author Marcus
*/
@RunWith(RobolectricTestRunner.class)
// you can use the @Config annotation here to configure
// various aspects of the test such as the SDK version,
// the resource type to be loaded (e.g. "en-port" for
// english resources in portrait mode, etc.
// @Config(qualifiers = "en-port", sdk = 18)
@Config(manifest = "AndroidManifest.xml")
public class MainActivityTest {
@Test
public void test() {
// if you do not have an activity or a context, you can get access
// to the application class through the "RuntimeEnvironment" object
String name = ApplicationProvider.getApplicationContext().getResources().getString(R.string.application_long);
System.out.println("The application name is: " + name);
// create an activity
// TODO: fix test failures caused by MainActivity
// Activity activity = Robolectric.setupActivity(MainActivity.class);
// String expectedTitle = activity.getResources().getString(R.string.application_short);
// Assert.assertEquals("Title should match resource.", expectedTitle, activity.getTitle());
// fumble around in the layout
// Assert.assertNotNull("MapView should be loaded.", activity.findViewById(R.id.map));
}
}
@@ -1,62 +0,0 @@
package com.mowesta.android.app.test;
import android.view.View;
import android.widget.Button;
import com.mowesta.android.app.R;
import com.mowesta.android.app.fragment.SplashFragment;
import com.mowesta.android.app.fragment.TermsFragment;
import com.mowesta.android.app.test.util.FragmentActivity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
import static org.robolectric.Shadows.shadowOf;
/**
* Runs a simple roboelectric test for start activity.
*
* @author sarah
*/
@RunWith(RobolectricTestRunner.class)
// you can use the @Config annotation here to configure
// various aspects of the test such as the SDK version,
// the resource type to be loaded (e.g. "en-port" for
// english resources in portrait mode, etc.
// @Config(qualifiers = "en-port", sdk = 18)
@Config(manifest = "AndroidManifest.xml")
public class StartActivityTest {
@Test
public void test() {
/*
// create start activity and show logo
ActivityController<FragmentActivity> ac = Robolectric.buildActivity(FragmentActivity.class);
FragmentActivity activity = ac.create().start().visible().resume().get();
final SplashFragment logoFragment = new SplashFragment();
activity.showFragment(logoFragment);
// change to T&Cs
final TermsFragment termsFragment = new TermsFragment();
activity.showFragment(termsFragment);
Assert.assertNotNull("WebView should be present.", activity.findViewById(R.id.web_view));
Assert.assertNotNull("Accept & continue button should be present.", activity.findViewById(R.id.start_button_continue));
// continue to main activity
Button buttonContinue = (Button) activity.findViewById(R.id.start_button_continue);
final boolean[] clicked = new boolean[1];
termsFragment.setOnContinueListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clicked[0] = true;
}
});
buttonContinue.performClick();
Assert.assertTrue("Button click should call continue.", clicked[0]);
*/
}
}
@@ -1,48 +0,0 @@
package com.mowesta.android.app.test.util;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.FrameLayout;
/**
* An activity showing a single fragment. This
* is useful for standalone fragment testing.
*
* @author Marcus
*/
public class FragmentActivity extends AppCompatActivity {
/**
* The id of the view. Somewhat hacky.
*/
public static final int FRAME_ID = 1;
/**
* Creates the fragment with a single frame layout.
*
* @param savedInstanceState The instance state.
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout view = new FrameLayout(this);
view.setId(FRAME_ID);
this.setContentView(view);
}
/**
* Replaces any fragment on the main view with the
* specified fragment.
*
* @param fragment The fragment.
*/
public void showFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(FRAME_ID, fragment).commit();
}
@Override
public void invalidateOptionsMenu() {
super.invalidateOptionsMenu();
}
}
@@ -1,151 +0,0 @@
package com.mowesta.android.app.test.util;
import com.mowesta.android.feign.api.DefaultApi;
import feign.QueryMap;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* A simple proxy generator that enables us to emulate the
* mowesta server locally while testing. If only one method
* is required, you can use the createApiProxy(String,Object)
* method to create a proxy that will return the specified
* object in response to a call to the specified method.
*
* @author Marcus
*/
public class ProxyGenerator {
/**
* An interface for a method filter.
*/
public interface IMethodFilter {
/**
* Returns true if the method is acceptable.
*
* @param m The method.
* @return True if accepted, false otherwise.
*/
boolean accept(Method m);
}
/**
* A method filter that filters out the generated
* methods of the feign library which contain a
* query param annotation (or app should not call
* these methods as it would become dependent on
* the feign library).
*/
public static final IMethodFilter QUERY_PARAM_FILTER = new IMethodFilter() {
@Override
public boolean accept(Method m) {
for (Annotation[] annos: m.getParameterAnnotations()) {
for (Annotation a: annos) {
if (a instanceof QueryMap) {
return false;
}
}
}
return true;
}
};
/**
* Creates a proxy for a in interface that will return the predefined
* values as result of every method call.
*
* @param type The type of the interface to implement.
* @param results The mapping between methods and results.
* @param <T> The interface type to implement.
* @return The proxy for the interface.
*/
@SuppressWarnings("unchecked")
public static <T> T createProxy(Class<T> type, final Map<Method, Object> results) {
return (T)Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (results.containsKey(method)) {
return results.get(method);
} else {
throw new RuntimeException("Method not proxied (fix your test case).");
}
}
});
}
/**
* Finds a method in an interface type and returns the associated method object.
*
* @param type The interface type.
* @param name The name of the method.
* @param filters A set of filters to apply during search.
* @return The method.
* @throws RuntimeException Thrown if the type does not contain the method or
* if the type specifies multiple methods with the same name.
*/
public static Method findMethod(Class<?> type, String name, IMethodFilter[] filters) {
Set<Method> candidates = new HashSet<>();
method: for (Method m: type.getMethods()) {
if (m.getName().equals(name)) {
for (IMethodFilter f: filters) {
if (! f.accept(m)) continue method;
}
candidates.add(m);
}
}
if (candidates.size() == 0) {
throw new RuntimeException("Cannot find method " + name + " in " + type.getName() + ".");
} else if (candidates.size() > 1) {
throw new RuntimeException("Found " + candidates.size() + " methods for " + name + " in " + type.getName() + ".");
} else {
return candidates.iterator().next();
}
}
/**
* Finds an api method by name.
*
* @param name The name of the method.
* @return The method.
* @throws RuntimeException Thrown if the type does not contain the method or
* if the type specifies multiple methods with the same name.
*/
public static Method findApiMethod(String name) {
return findMethod(DefaultApi.class, name, new IMethodFilter[] { QUERY_PARAM_FILTER });
}
/**
* Creates an api proxy that implements the methods specified by
* the map with the specified result.
*
* @param results The results.
* @return The proxy.
*/
public static DefaultApi createApiProxy(Map<Method, Object> results) {
return createProxy(DefaultApi.class, results);
}
/**
* Creates a simple api proxy that implements the method with the specified name
* using the specified result.
*
* @param method The method.
* @param result The result.
* @return The proxy.
*/
public static DefaultApi createApiProxy(String method, Object result) {
Map<Method, Object> results = new HashMap<>();
results.put(findApiMethod(method), result);
return createApiProxy(results);
}
}
+9 -9
View File
@@ -1,6 +1,6 @@
apply plugin: 'com.android.library'
description = "Mowesta Android SDK"
description = "MoWeSta Android SDK"
// remove project version to workaround bugs in
// oss-license-plugin that detects local libraries
@@ -10,11 +10,11 @@ description = "Mowesta Android SDK"
project.version = "unspecified"
android {
compileSdkVersion 30
compileSdkVersion 33
defaultConfig {
minSdkVersion 19
targetSdkVersion 30
targetSdkVersion 33
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
@@ -28,17 +28,17 @@ android {
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
lintOptions {
quiet true
}
lint {
quiet true
}
namespace 'com.mowesta.android.sdk'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
api project(":android-feign")
api project(":android-api")
implementation "androidx.appcompat:appcompat:${versionAndroidXAppcompat}"
implementation "androidx.preference:preference:${versionAndroidXPreference}"
implementation "androidx.room:room-runtime:${versionAndroidXRoom}"
@@ -49,4 +49,4 @@ dependencies {
testImplementation "androidx.test:core:${versionAndroidXTest}"
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mowesta.android.sdk">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- permission for wifi scanning (used for caching) -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
@@ -1,6 +1,11 @@
package com.mowesta.android.sdk;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@@ -87,6 +92,7 @@ public abstract class SdkService extends Service {
private BroadcastReceiver timeTickReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
debugLog("Time tick received");
onStartCommand(null, 0, 0);
}
};
@@ -98,7 +104,9 @@ public abstract class SdkService extends Service {
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
debugLog("Location changed");
if (isLocationAccurate(location)) {
debugLog("Location is accurate enough");
setLocation(location);
}
}
@@ -124,7 +132,11 @@ public abstract class SdkService extends Service {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
setScan(wifiManager.getScanResults());
try {
setScan(wifiManager.getScanResults());
} catch (SecurityException e) {
// will never happen
}
}
}
};
@@ -137,6 +149,7 @@ public abstract class SdkService extends Service {
private boolean initialized = false;
@Override
public void onChanged(Boolean uploading) {
debugLog("Uploading is " + uploading);
if (currentState == State.IDLE) {
if (uploading) {
channelManager.updateNotification(R.string.mowesta_sdk_notification_content_upload);
@@ -220,6 +233,7 @@ public abstract class SdkService extends Service {
@Override
@SuppressWarnings("deprecation")
public void onCreate() {
debugLog("Creating service");
Log.d(TAG, "Creating sdk service.");
super.onCreate();
channelManager = new ChannelManager(getApplication());
@@ -238,6 +252,10 @@ public abstract class SdkService extends Service {
@Override
public void onDestroy() {
debugLog("Destroying service in state: " + currentState);
if (currentState != State.IDLE) {
scheduleExecution(this, measurementTime);
}
Log.d(TAG, "Destroying sdk service.");
switch (currentState) {
case MEASURE:
@@ -260,9 +278,9 @@ public abstract class SdkService extends Service {
}
repository.getUploading().removeObserver(uploadListener);
unregisterReceiver(timeTickReceiver);
stopForeground(true);
Log.d(TAG, "Releasing wake lock.");
if (wakeLock != null && wakeLock.isHeld()) wakeLock.release();
stopForeground(true);
super.onDestroy();
}
@@ -295,6 +313,7 @@ public abstract class SdkService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!isEnabled()) {
debugLog("Service not enabled, stopping");
Log.d(TAG, "Stopping since the service is not enabled.");
cancelExecution(this);
stopSelf();
@@ -305,12 +324,15 @@ public abstract class SdkService extends Service {
if (currentState == State.IDLE) {
if (now - measurementTime > repository.getConstants().TIMEOUT_MEASUREMENT) {
Log.d(TAG, "Starting state machine since timeout has expired.");
debugLog("Starting state machine since timeout has expired.");
changeState();
} else {
Log.d(TAG, "Ignoring start request while timeout has not expired.");
debugLog("Ignoring start request while timeout has not expired.");
scheduleExecution(this, measurementTime);
}
} else {
debugLog("Ignoring start request while service is " + currentState + ".");
Log.d(TAG, "Ignoring start request while service is " + currentState + ".");
}
return START_STICKY;
@@ -321,6 +343,7 @@ public abstract class SdkService extends Service {
*/
private void changeState() {
Log.d(TAG, "Changing state from " + currentState);
debugLog("Changing state from " + currentState);
switch (currentState) {
case IDLE: {
// acquire a wake lock to keep the cpu running
@@ -404,6 +427,7 @@ public abstract class SdkService extends Service {
* an unrecoverable failure.
*/
private void resetState(boolean success) {
debugLog("Reset state with succes: " + success);
currentState = State.IDLE;
channelManager.updateNotification(R.string.mowesta_sdk_notification_content_idle);
currentNetworks = null;
@@ -435,6 +459,7 @@ public abstract class SdkService extends Service {
* Starts the measurement.
*/
private void startMeasure() {
debugLog("Starting measurement.");
Log.d(TAG, "Starting measurement.");
currentState = State.MEASURE;
channelManager.updateNotification(R.string.mowesta_sdk_notification_content_measure);
@@ -457,6 +482,8 @@ public abstract class SdkService extends Service {
*/
private void startGps() {
Log.d(TAG, "Starting gps localization.");
debugLog("Starting gps localization.");
currentState = State.GPS;
channelManager.updateNotification(R.string.mowesta_sdk_notification_content_gps);
if (capabilityManager.hasLocationPermissions()) {
@@ -466,6 +493,7 @@ public abstract class SdkService extends Service {
@Override
public void run() {
Log.d(TAG, "Aborting gps localization.");
debugLog("Aborting gps localization (timeout).");
changeState();
}
};
@@ -473,9 +501,11 @@ public abstract class SdkService extends Service {
return;
} catch (SecurityException e) {
Log.d(TAG, "Security exception while accessing location.", e);
debugLog("Security exception while accessing location.");
}
}
Log.d(TAG, "Location permissions missing, changing state.");
debugLog("Location permissions missing, changing state.");
changeState();
}
@@ -484,6 +514,7 @@ public abstract class SdkService extends Service {
*/
private void startNet() {
Log.d(TAG, "Starting network localization.");
debugLog("Starting network localization.");
channelManager.updateNotification(R.string.mowesta_sdk_notification_content_net);
currentState = State.NET;
if (capabilityManager.hasLocationPermissions()) {
@@ -493,6 +524,8 @@ public abstract class SdkService extends Service {
@Override
public void run() {
Log.d(TAG, "Aborting network localization.");
debugLog("Aborting network localization (timeout).");
changeState();
}
};
@@ -500,9 +533,12 @@ public abstract class SdkService extends Service {
return;
} catch (SecurityException e) {
Log.d(TAG, "Security exception while accessing location.", e);
debugLog("Security exception while accessing location.");
}
}
Log.d(TAG, "Location permissions missing, changing state.");
debugLog("Location permissions missing, changing state.");
changeState();
}
@@ -512,8 +548,10 @@ public abstract class SdkService extends Service {
@SuppressWarnings("deprecation")
private void startWifi() {
Log.d(TAG, "Acquiring wifi lock.");
debugLog("Acquiring wifi lock");
wifiLock.acquire();
Log.d(TAG, "Starting wifi scan.");
debugLog("Starting wifi scan.");
channelManager.updateNotification(R.string.mowesta_sdk_notification_content_wifi);
currentState = State.WIFI;
registerReceiver(wifiListener, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
@@ -521,6 +559,7 @@ public abstract class SdkService extends Service {
@Override
public void run() {
Log.d(TAG, "Aborting wifi scan.");
debugLog("Aborting wifi scan (timeout).");
changeState();
}
};
@@ -533,19 +572,22 @@ public abstract class SdkService extends Service {
*/
private void startCache() {
Log.d(TAG, "Starting cache lookup.");
debugLog("Starting cache lookup.");
currentState = State.CACHE;
channelManager.updateNotification(R.string.mowesta_sdk_notification_content_cache);
lookupTask = new LookupTask(repository, currentNetworks, new LookupTask.OnCompletionListener() {
@Override
public void onCompletion(@Nullable LocationEntity entity) {
Log.d(TAG, "Cache lookup complete.");
Log.d(TAG, "Cache lookup complete with cached result.");
if (entity != null) {
debugLog("Cache lockup success");
Coordinate c = new Coordinate();
c.setLatitude(entity.getLatitude());
c.setLongitude(entity.getLongitude());
measurement.setCoordinate(c);
resetState(true);
} else {
debugLog("Cache lockup without cached result.");
changeState();
}
}
@@ -625,6 +667,7 @@ public abstract class SdkService extends Service {
}
this.currentNetworks = networks;
Log.d(TAG, "Found " + this.currentNetworks.size() + " wifi networks.");
debugLog("Found " + this.currentNetworks.size() + " wifi networks.");
changeState();
}
@@ -634,6 +677,7 @@ public abstract class SdkService extends Service {
* @param location The location.
*/
private void setLocation(Location location) {
debugLog("Set location");
// cleanup based on type
if (currentState == State.GPS) cleanupGps();
if (currentState == State.NET) cleanupNet();
@@ -647,6 +691,7 @@ public abstract class SdkService extends Service {
measurement.setCoordinate(c);
// store location in cache
if (hasMinimumNetworks()) {
debugLog("Store in cache");
LocationEntity entity = new LocationEntity();
entity.setAccuracy((double)location.getAccuracy());
entity.setLatitude(location.getLatitude());
@@ -694,6 +739,7 @@ public abstract class SdkService extends Service {
long now = SystemClock.elapsedRealtime();
long next = Math.max(5000, (lastTime + service.repository.getConstants().TIMEOUT_MEASUREMENT) - now);
Log.d(TAG, "Updating alarm to execute in " + next + " ms.");
service.debugLog("Updating alarm to execute in " + next + " ms.");
PendingIntent pending = createIntent(service);
manager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + next, service.repository.getConstants().TIMEOUT_MEASUREMENT, pending);
}
@@ -715,14 +761,16 @@ public abstract class SdkService extends Service {
* @return The pending intent.
*/
public static PendingIntent createIntent(SdkService service) {
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
Intent intent = new Intent();
intent.setClassName(service, service.getClass().getName());
intent.putExtra(EXTRA_ALARM, true);
int code = service.getResources().getInteger(R.integer.mowesta_sdk_alarm_request_code);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return PendingIntent.getService(service, code, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return PendingIntent.getService(service, code, intent, flags);
} else {
return PendingIntent.getForegroundService(service, code, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) flags |= PendingIntent.FLAG_MUTABLE;
return PendingIntent.getForegroundService(service, code, intent, flags);
}
}
@@ -774,4 +822,30 @@ public abstract class SdkService extends Service {
}
/**
* Performs logging to a local file to debug issues with the service.
* This code and all calls to it can be removed safely, once the app
* is robust, until then we keep it to swap it in quickly.
*
* @param string The string to log.
*/
private void debugLog(String string) {
// uncomment to enable file-based debug log
/*
synchronized (SdkService.class) {
try {
long now = System.currentTimeMillis();
String message = now + " :: " + new Date(now).toString() + " :: " + string + "\n";
File dest = new File(getFilesDir(), "debug.log");
BufferedWriter w = new BufferedWriter(new FileWriter(dest.getAbsolutePath(), true));
w.write(message);
w.flush();
w.close();
} catch (IOException e) {
// nothing
}
}
*/
}
}
@@ -57,7 +57,7 @@ public class BufferTask extends AbstractTask<Void> {
* @param listener The listener to signal the completion.
*/
public BufferTask(@NonNull SdkRepository repository, @NonNull Measurement measurement, @NonNull OnCompletionListener listener) {
super(true);
super(false);
this.repository = repository;
this.measurement = measurement;
this.listener = listener;
@@ -62,7 +62,7 @@ public class UploadTask extends AbstractTask<Void> {
* @param client The api client to use.
*/
public UploadTask(@NonNull SdkRepository repository, @NonNull DefaultApi client) {
super(true);
super(false);
this.repository = repository;
this.client = client;
}
@@ -91,17 +91,18 @@ public class ChannelManager {
* @return The notification.
*/
public Notification createNotification(int res) {
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) flags |= PendingIntent.FLAG_MUTABLE;
NotificationCompat.Builder builder = new NotificationCompat.Builder(application, getChannelId())
.setContentTitle(application.getString(R.string.mowesta_sdk_notification_title))
.setContentText(application.getString(res))
.setOngoing(true)
.setContentIntent(PendingIntent.getActivity(application, getNotificationRequestCode(), createNotificationIntent(), PendingIntent.FLAG_UPDATE_CURRENT))
.setContentIntent(PendingIntent.getActivity(application, getNotificationRequestCode(), createNotificationIntent(), flags))
.setSmallIcon(R.drawable.mowesta_sdk_ic_notification_small)
.setLargeIcon(BitmapFactory.decodeResource(application.getResources(), R.drawable.mowesta_sdk_ic_notification_large));
return builder.build();
}
/**
* Returns the request code used for the pending intent.
*
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- The maximum time to wait for a gps location. Depends on the user's position (indoor/outdoor). -->
<integer name="mowesta_sdk_service_gps_timeout">60000</integer>
</resources>
+1 -1
View File
@@ -46,7 +46,7 @@
<!-- The maximum time to wait for a network location. Depends on the network connection. -->
<integer name="mowesta_sdk_service_network_timeout">45000</integer>
<!-- The maximum time to wait for a gps location. Depends on the user's position (indoor/outdoor). -->
<integer name="mowesta_sdk_service_gps_timeout">60000</integer>
<integer name="mowesta_sdk_service_gps_timeout">90000</integer>
<!-- The minimum location accuracy in meters required to use a gps or network position. -->
<integer name="mowesta_sdk_service_minimum_location_accuracy">75</integer>
<!-- The maximum age in milliseconds that we will use a cached location before we validate the cache. -->
@@ -0,0 +1,480 @@
#define ARDUINOJSON_USE_LONG_LONG 1
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <EEPROM.h>
#include "Adafruit_Sensor.h"
#include "Adafruit_BME280.h"
#include "ArduinoJson.h"
// Hardware setup
#define BUTTON_PIN D5
#define VOLTAGE_PIN A0
#define VOLTAGE_MULTIPLIER 11
#define VOLTAGE_DIVIDER 255.0
#define EEPROM_SIZE 512
#define BUTTON_OUT D7
#define BME_OUT D6
#define VOLTAGE_OUT D8
//Credentials for the Access Point
#define WLAN_AP_SSID "MoWeSta - WiFi"
#define WLAN_AP_PASSWORD "mowesta123456wifi"
// API-URL where measurements will be uploaded to
#define MOWESTA_UPLOAD_URL "https://www.mowesta.com/api/devices/current/measurements/now"
// #define MOWESTA_UPLOAD_URL "https://beta.mowesta.com/api/devices/current/measurements/now"
#define MOWESTA_SOFTWARE_VERSION 2
// memory for json document
#define JSON_BUFFER_SIZE 1000
// deep sleep period between measurements (us = 1e-6)
#define DEEP_SLEEP_PERIOD 600000000
// timeout to wait for the wifi connection in ms
#define TIMEOUT_WIFI 20000
// timeout to wait for the ntp sync in ms
#define TIMEOUT_NTP 20000
// timeout to wait for the setup data in sec
#define TIMEOUT_READ 40
// Let's encrypt root cert (valid until June 4, 2035)
const char certificate_anchors[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";
X509List certificates(certificate_anchors);
// Access point config
IPAddress ip_address_local(192, 168, 4, 1);
IPAddress ip_address_gateway(192, 168, 4, 1);
IPAddress ip_subnet_mask(255, 255, 255, 0);
WiFiServer wifi_server(8080);
// Variables set to data values received from the app
String* setting_wlan_ssid;
String* setting_wlan_password;
String* setting_device_id;
String* setting_device_token;
String* setting_longitude;
String* setting_latitude;
// Flag to store mode
bool mode_setup = false;
// Store boot time for timeout
long time_boot;
// Sensor to gather measurements
Adafruit_BME280 sensor_bme;
// eeprom reading and writing
void eeprom_write_string(int* add, String* data);
String* eeprom_read_string(int* add);
// settings reading, writing, printing and validation
void settings_read();
void settings_write();
void settings_print();
bool settings_valid();
// device setup via mobile app or netcat
bool setup_process_connection(WiFiClient*);
bool setup_process_data(String);
// measurement and upload
void measurement_capture();
void setup() {
//Open serial port to display data and set baudrate
Serial.begin(115200);
// Wait for serial port to be initialized
while (!Serial);
Serial.println();
// power the voltage divider
pinMode(VOLTAGE_OUT, OUTPUT);
digitalWrite(VOLTAGE_OUT, LOW);
// power the bme sensor
pinMode(BME_OUT, OUTPUT);
digitalWrite(BME_OUT, LOW);
// power the button
pinMode(BUTTON_OUT, OUTPUT);
digitalWrite(BUTTON_OUT, LOW);
// Initialize EEPROM with complete size
// Configure the button to enter setup
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Configure the LED to indicate setup
pinMode(LED_BUILTIN, OUTPUT);
// Read the settings from eeprom
EEPROM.begin(EEPROM_SIZE);
settings_read();
// Check if button is pressed to enter setup
mode_setup = (digitalRead(BUTTON_PIN) == LOW);
time_boot = millis();
if (mode_setup) {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Entering setup mode.");
WiFi.softAPConfig(ip_address_local, ip_address_gateway, ip_subnet_mask);
WiFi.softAP(WLAN_AP_SSID, WLAN_AP_PASSWORD);
IPAddress ip_address = WiFi.softAPIP();
Serial.print("IP address is: '");
Serial.print(ip_address);
Serial.println("'");
wifi_server.begin();
} else if (settings_valid()){
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("Connecting to WiFi network '");
Serial.print(*setting_wlan_ssid);
Serial.println("'");
WiFi.begin(setting_wlan_ssid->c_str(), setting_wlan_password->c_str());
} else {
Serial.println("Invalid settings, setup required.");
settings_print();
}
}
void loop() {
if (mode_setup) {
// setup mode, keeps handling incoming clients until successful setup
WiFiClient client = wifi_server.available();
if (client) {
digitalWrite(LED_BUILTIN, HIGH);
if (setup_process_connection(&client)) {
WiFi.softAPdisconnect(true);
delay(5000);
ESP.restart();
} else {
digitalWrite(LED_BUILTIN, LOW);
}
}
} else if (settings_valid()) {
// measurement mode, captures and uploads a measurement when wifi is up
if (WiFi.status() == WL_CONNECTED) {
if (sensor_bme.begin(0x76)) {
measurement_capture();
} else {
Serial.println("Failed to activate sensor.");
}
WiFi.disconnect();
delay(1000);
Serial.end();
ESP.deepSleep(DEEP_SLEEP_PERIOD);
} else {
// check for excessive waiting time
long time_now = millis();
long time_delta = (time_now > time_boot) ? (time_now - time_boot) : time_boot - time_now;
if (time_delta > TIMEOUT_WIFI) {
Serial.println("Failed to activate wifi.");
WiFi.disconnect();
delay(1000);
Serial.end();
ESP.deepSleep(DEEP_SLEEP_PERIOD);
}
delay(500);
}
} else {
// blink to indicate missing config
for(int i = 0; i < 10; i++){
digitalWrite(LED_BUILTIN, LOW);
delay(50);
digitalWrite(LED_BUILTIN, HIGH);
delay(50);
}
Serial.end();
ESP.deepSleep(DEEP_SLEEP_PERIOD);
}
}
/**
* Writes a String in EEPROM memory starting at a defined address.
*
* @param add In/out parameter with the address.
* @param data The string to write.
*/
void eeprom_write_string(int* add, String* data) {
int s = data->length();
if (*add + s + 1 < EEPROM_SIZE) {
for (int i = 0; i < s; i++) {
EEPROM.write(*add + i, (*data)[i]);
}
EEPROM.write(*add + s, '\0');
}
*add += s + 1;
}
/**
* Reads a String from EEPROM memory starting at a defined address.
* Reads until a terminating null character.
*
* @param add In/out parameter with the address.
* @return A pointer to the string.
*/
String* eeprom_read_string(int* add) {
char data[EEPROM_SIZE + 1];
int limit = EEPROM_SIZE - *add;
limit = limit < 0 ? 0 : limit;
int len = 0;
unsigned char k;
if (limit > 0) {
k = EEPROM.read(*add);
while (k != '\0' && len < limit)
{
k = EEPROM.read(*add + len);
data[len] = k;
len++;
}
}
data[len] = '\0';
*add += len;
return new String(data);
}
/**
* Reads the settings from the eeprom to memory.
*/
void settings_read() {
int address = 0;
setting_wlan_ssid = eeprom_read_string(&address);
setting_wlan_password = eeprom_read_string(&address);
setting_device_id = eeprom_read_string(&address);
setting_device_token = eeprom_read_string(&address);
setting_longitude = eeprom_read_string(&address);
setting_latitude = eeprom_read_string(&address);
}
/**
* Writes the settings from memory to the eeprom.
*/
void settings_write() {
int address = 0;
eeprom_write_string(&address, setting_wlan_ssid);
eeprom_write_string(&address, setting_wlan_password);
eeprom_write_string(&address, setting_device_id);
eeprom_write_string(&address, setting_device_token);
eeprom_write_string(&address, setting_longitude);
eeprom_write_string(&address, setting_latitude);
EEPROM.commit();
}
/**
* Prints the settings onto the serial console.
*/
void settings_print() {
Serial.print("WLAN SSID: ");
Serial.println(*setting_wlan_ssid);
Serial.print("WLAN Password: ");
Serial.println(*setting_wlan_password);
Serial.print("Device ID: ");
Serial.println(*setting_device_id);
Serial.print("Device Token: ");
Serial.println(*setting_device_token);
Serial.print("Longitude: ");
Serial.println(*setting_longitude);
Serial.print("Latitude: ");
Serial.println(*setting_latitude);
}
/**
* Determines whether the settings are valid. This is
* done by making sure that every string has a non-zero length.
*
* @return True if the settings are valid, false otherwise.
*/
bool settings_valid() {
return setting_wlan_ssid->length() > 0 &&
setting_wlan_password->length() > 0 &&
setting_device_id->length() > 0 &&
setting_device_token->length() > 0 &&
setting_longitude->length() > 0 &&
setting_latitude->length() > 0;
}
/**
* Parses the client data and stores the relevant information in flash memory.
* It is assumed that the client data is in json format.
*
* @param data The data received from the client.
* @return True if the data seems ok and has been stored to flash, false otherwise.
*/
bool setup_process_data(String data) {
StaticJsonDocument<JSON_BUFFER_SIZE> doc; //Memory pool
Serial.print("Received settings: ");
Serial.println(data);
DeserializationError error = deserializeJson(doc, data);
if (error) {
Serial.print("Deserialization failed with code ");
Serial.println(error.c_str());
return false;
} else {
delete setting_wlan_ssid;
delete setting_wlan_password;
delete setting_device_id;
delete setting_device_token;
delete setting_longitude;
delete setting_latitude;
setting_wlan_ssid = new String(doc["ssid"]);
setting_wlan_password = new String(doc["password"]);
setting_device_id = new String(doc["id"]);
setting_device_token = new String(doc["token"]);
setting_longitude = new String(doc["longitude"]);
setting_latitude = new String(doc["latitude"]);
settings_print();
if (settings_valid()) {
Serial.println("Storing valid settings.");
settings_write();
return true;
} else {
Serial.println("Ignoring invalid settings.");
return false;
}
}
}
/**
* Performs the setup data exchange with the app and returns
* whether the arduino has successfully received a new configuration.
*
* @param client The wifi client that represents the connection.
* @return True if the setup data has been retrieved successfully.
*/
bool setup_process_connection(WiFiClient *client) {
Serial.println("Client connection established.");
String data = "";
bool didRead = true;
client->setTimeout(TIMEOUT_READ);
while (client->connected() && didRead) {
String chunk = client->readStringUntil('\n');
didRead = chunk.length() > 0; // if line is empty, break immediately
data += chunk;
}
if (data.length() > 0) {
if(setup_process_data(data)) {
client->println("Success\n"); // Notify client
client->flush();
// Wait for client to close connection, since we will
// be disabling the accesspoint directly afterwards
while (client->connected());
client->stop();
Serial.println("Success, client disconnected.");
return true;
} else {
client->println("Error\n"); //Notify client
client->flush();
client->stop();
Serial.println("Error, client disconnected.");
return false;
}
} else {
client->println("Timeout\n"); //Notify client
client->flush();
client->stop();
Serial.println("Timeout, client disconnected.");
return false;
}
}
/**
* Synchronizes the time with an ntp server, captures a measurement,
* generates a json document and uploads it to the mowesta backend.
*/
void measurement_capture() {
WiFiClientSecure wifi;
HTTPClient http;
StaticJsonDocument<JSON_BUFFER_SIZE> doc;
// set trusted root certificates and perform ntp time sync for https
configTime(0, 0, "time2-1.uni-duisburg-essen.de", "time2-3.uni-duisburg-essen.de", "pool.ntp.org");
Serial.print("Waiting for NTP time sync: ");
time_t now = time(nullptr);
// check that time is after January 1st, 2021
int max_wait = TIMEOUT_NTP;
while (now < 1606694400) {
if (max_wait < 0) {
Serial.println("Timeout");
return;
}
delay(500);
max_wait -= 500;
now = time(nullptr);
}
Serial.println(now);
wifi.setTrustAnchors(&certificates);
// create json document for upload
doc["id"] = 0;
doc["creationTime"] = 0;
doc["modificationTime"] = 0;
doc["deleted"] = "false";
JsonObject coordinate = doc.createNestedObject("coordinate");
coordinate["latitude"] = setting_latitude->toDouble();
coordinate["longitude"] = setting_longitude->toDouble();
doc["time"] = now * 1000;
doc["device"] = atol(setting_device_id->c_str());
doc["version"] = MOWESTA_SOFTWARE_VERSION;
doc["temperature"] = (char*)0;
doc["pressure"] = (char*)0;
doc["humidity"] = (char*)0;
JsonObject data = doc.createNestedObject("data");
data["SENSOR_TEMPERATURE"] = String(sensor_bme.readTemperature());
data["SENSOR_PRESSURE"] = String(sensor_bme.readPressure() / 100);
data["SENSOR_HUMIDITY"] = String(sensor_bme.readHumidity());
data["BATTERY_VOLTAGE"] = String((analogRead(VOLTAGE_PIN) / VOLTAGE_DIVIDER) * VOLTAGE_MULTIPLIER);
// print measurement
serializeJsonPretty(doc, Serial);
Serial.println();
// upload measurement
String body;
serializeJson(doc, body);
http.begin(wifi, MOWESTA_UPLOAD_URL);
http.addHeader("Accept", "application/json");
http.addHeader("Authorization", "Bearer " + *setting_device_token);
http.addHeader("Content-Type", "application/json");
int code = http.POST(body);
if (code / 100 == 2) {
Serial.println("Upload successful.");
} else {
Serial.print("Upload failed: ");
Serial.println(code);
}
http.end();
}
@@ -0,0 +1,482 @@
#define ARDUINOJSON_USE_LONG_LONG 1
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <EEPROM.h>
#include <Adafruit_BMP280.h>
#include "ArduinoJson.h"
// Hardware setup
#define BUTTON_PIN D5
#define VOLTAGE_PIN A0
#define VOLTAGE_MULTIPLIER 11
#define VOLTAGE_DIVIDER 255.0
#define EEPROM_SIZE 512
#define BUTTON_OUT D7
#define EXTERNAL_OUT D8
//Credentials for the Access Point
#define WLAN_AP_SSID "MoWeSta - WiFi"
#define WLAN_AP_PASSWORD "mowesta123456wifi"
// API-URL where measurements will be uploaded to
#define MOWESTA_UPLOAD_URL "https://www.mowesta.com/api/devices/current/measurements/now"
//#define MOWESTA_UPLOAD_URL "https://beta.mowesta.com/api/devices/current/measurements/now"
#define MOWESTA_SOFTWARE_VERSION 2
// memory for json document
#define JSON_BUFFER_SIZE 1000
// deep sleep period between measurements (us = 1e-6)
#define DEEP_SLEEP_PERIOD 600000000
// timeout to wait for the wifi connection in ms
#define TIMEOUT_WIFI 20000
// timeout to wait for the ntp sync in ms
#define TIMEOUT_NTP 20000
// timeout to wait for the setup data in sec
#define TIMEOUT_READ 40
// Let's encrypt root cert (valid until June 4, 2035)
const char certificate_anchors[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";
X509List certificates(certificate_anchors);
// Access point config
IPAddress ip_address_local(192, 168, 4, 1);
IPAddress ip_address_gateway(192, 168, 4, 1);
IPAddress ip_subnet_mask(255, 255, 255, 0);
WiFiServer wifi_server(8080);
// Variables set to data values received from the app
String* setting_wlan_ssid;
String* setting_wlan_password;
String* setting_device_id;
String* setting_device_token;
String* setting_longitude;
String* setting_latitude;
// Flag to store mode
bool mode_setup = false;
// Store boot time for timeout
long time_boot;
// Sensor to gather measurements
Adafruit_BMP280 sensor_bmp;
// eeprom reading and writing
void eeprom_write_string(int* add, String* data);
String* eeprom_read_string(int* add);
// settings reading, writing, printing and validation
void settings_read();
void settings_write();
void settings_print();
bool settings_valid();
// device setup via mobile app or netcat
bool setup_process_connection(WiFiClient*);
bool setup_process_data(String);
// measurement and upload
void measurement_capture();
void setup() {
//Open serial port to display data and set baudrate
Serial.begin(115200);
// Wait for serial port to be initialized
while (!Serial);
Serial.println();
// power the button, voltage divider and sensor
pinMode(BUTTON_OUT, OUTPUT);
digitalWrite(BUTTON_OUT, LOW);
// set out to in, since it is connected directly to GND
pinMode(EXTERNAL_OUT, INPUT);
// Initialize EEPROM with complete size
// Configure the button to enter setup
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Configure the LED to indicate setup
pinMode(LED_BUILTIN, OUTPUT);
// Read the settings from eeprom
EEPROM.begin(EEPROM_SIZE);
settings_read();
// Check if button is pressed to enter setup
mode_setup = (digitalRead(BUTTON_PIN) == LOW);
time_boot = millis();
if (mode_setup) {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Entering setup mode.");
WiFi.softAPConfig(ip_address_local, ip_address_gateway, ip_subnet_mask);
WiFi.softAP(WLAN_AP_SSID, WLAN_AP_PASSWORD);
IPAddress ip_address = WiFi.softAPIP();
Serial.print("IP address is: '");
Serial.print(ip_address);
Serial.println("'");
wifi_server.begin();
} else if (settings_valid()){
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("Connecting to WiFi network '");
Serial.print(*setting_wlan_ssid);
Serial.println("'");
WiFi.begin(setting_wlan_ssid->c_str(), setting_wlan_password->c_str());
} else {
Serial.println("Invalid settings, setup required.");
settings_print();
}
}
void loop() {
if (mode_setup) {
// setup mode, keeps handling incoming clients until successful setup
WiFiClient client = wifi_server.available();
if (client) {
digitalWrite(LED_BUILTIN, HIGH);
if (setup_process_connection(&client)) {
WiFi.softAPdisconnect(true);
delay(5000);
ESP.restart();
} else {
digitalWrite(LED_BUILTIN, LOW);
}
}
} else if (settings_valid()) {
// measurement mode, captures and uploads a measurement when wifi is up
if (WiFi.status() == WL_CONNECTED) {
if (sensor_bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID)) {
// Setup with default settings from datasheet.
sensor_bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, // Operating Mode.
Adafruit_BMP280::SAMPLING_X16, // Temp. oversampling
Adafruit_BMP280::SAMPLING_X16, // Pressure oversampling
Adafruit_BMP280::FILTER_X16, // Filtering.
Adafruit_BMP280::STANDBY_MS_500); // Standby time.
measurement_capture();
} else {
Serial.println("Failed to activate sensor.");
}
WiFi.disconnect();
delay(1000);
Serial.end();
ESP.deepSleep(DEEP_SLEEP_PERIOD);
} else {
// check for excessive waiting time
long time_now = millis();
long time_delta = (time_now > time_boot) ? (time_now - time_boot) : time_boot - time_now;
if (time_delta > TIMEOUT_WIFI) {
Serial.println("Failed to activate wifi.");
WiFi.disconnect();
delay(1000);
Serial.end();
ESP.deepSleep(DEEP_SLEEP_PERIOD);
}
delay(500);
}
} else {
// blink to indicate missing config
for(int i = 0; i < 10; i++){
digitalWrite(LED_BUILTIN, LOW);
delay(50);
digitalWrite(LED_BUILTIN, HIGH);
delay(50);
}
Serial.end();
ESP.deepSleep(DEEP_SLEEP_PERIOD);
}
}
/**
* Writes a String in EEPROM memory starting at a defined address.
*
* @param add In/out parameter with the address.
* @param data The string to write.
*/
void eeprom_write_string(int* add, String* data) {
int s = data->length();
if (*add + s + 1 < EEPROM_SIZE) {
for (int i = 0; i < s; i++) {
EEPROM.write(*add + i, (*data)[i]);
}
EEPROM.write(*add + s, '\0');
}
*add += s + 1;
}
/**
* Reads a String from EEPROM memory starting at a defined address.
* Reads until a terminating null character.
*
* @param add In/out parameter with the address.
* @return A pointer to the string.
*/
String* eeprom_read_string(int* add) {
char data[EEPROM_SIZE + 1];
int limit = EEPROM_SIZE - *add;
limit = limit < 0 ? 0 : limit;
int len = 0;
unsigned char k;
if (limit > 0) {
k = EEPROM.read(*add);
while (k != '\0' && len < limit)
{
k = EEPROM.read(*add + len);
data[len] = k;
len++;
}
}
data[len] = '\0';
*add += len;
return new String(data);
}
/**
* Reads the settings from the eeprom to memory.
*/
void settings_read() {
int address = 0;
setting_wlan_ssid = eeprom_read_string(&address);
setting_wlan_password = eeprom_read_string(&address);
setting_device_id = eeprom_read_string(&address);
setting_device_token = eeprom_read_string(&address);
setting_longitude = eeprom_read_string(&address);
setting_latitude = eeprom_read_string(&address);
}
/**
* Writes the settings from memory to the eeprom.
*/
void settings_write() {
int address = 0;
eeprom_write_string(&address, setting_wlan_ssid);
eeprom_write_string(&address, setting_wlan_password);
eeprom_write_string(&address, setting_device_id);
eeprom_write_string(&address, setting_device_token);
eeprom_write_string(&address, setting_longitude);
eeprom_write_string(&address, setting_latitude);
EEPROM.commit();
}
/**
* Prints the settings onto the serial console.
*/
void settings_print() {
Serial.print("WLAN SSID: ");
Serial.println(*setting_wlan_ssid);
Serial.print("WLAN Password: ");
Serial.println(*setting_wlan_password);
Serial.print("Device ID: ");
Serial.println(*setting_device_id);
Serial.print("Device Token: ");
Serial.println(*setting_device_token);
Serial.print("Longitude: ");
Serial.println(*setting_longitude);
Serial.print("Latitude: ");
Serial.println(*setting_latitude);
}
/**
* Determines whether the settings are valid. This is
* done by making sure that every string has a non-zero length.
*
* @return True if the settings are valid, false otherwise.
*/
bool settings_valid() {
return setting_wlan_ssid->length() > 0 &&
setting_wlan_password->length() > 0 &&
setting_device_id->length() > 0 &&
setting_device_token->length() > 0 &&
setting_longitude->length() > 0 &&
setting_latitude->length() > 0;
}
/**
* Parses the client data and stores the relevant information in flash memory.
* It is assumed that the client data is in json format.
*
* @param data The data received from the client.
* @return True if the data seems ok and has been stored to flash, false otherwise.
*/
bool setup_process_data(String data) {
StaticJsonDocument<JSON_BUFFER_SIZE> doc; //Memory pool
Serial.print("Received settings: ");
Serial.println(data);
DeserializationError error = deserializeJson(doc, data);
if (error) {
Serial.print("Deserialization failed with code ");
Serial.println(error.c_str());
return false;
} else {
delete setting_wlan_ssid;
delete setting_wlan_password;
delete setting_device_id;
delete setting_device_token;
delete setting_longitude;
delete setting_latitude;
setting_wlan_ssid = new String(doc["ssid"]);
setting_wlan_password = new String(doc["password"]);
setting_device_id = new String(doc["id"]);
setting_device_token = new String(doc["token"]);
setting_longitude = new String(doc["longitude"]);
setting_latitude = new String(doc["latitude"]);
settings_print();
if (settings_valid()) {
Serial.println("Storing valid settings.");
settings_write();
return true;
} else {
Serial.println("Ignoring invalid settings.");
return false;
}
}
}
/**
* Performs the setup data exchange with the app and returns
* whether the arduino has successfully received a new configuration.
*
* @param client The wifi client that represents the connection.
* @return True if the setup data has been retrieved successfully.
*/
bool setup_process_connection(WiFiClient *client) {
Serial.println("Client connection established.");
String data = "";
bool didRead = true;
client->setTimeout(TIMEOUT_READ);
while (client->connected() && didRead) {
String chunk = client->readStringUntil('\n');
didRead = chunk.length() > 0; // if line is empty, break immediately
data += chunk;
}
if (data.length() > 0) {
if(setup_process_data(data)) {
client->println("Success\n"); // Notify client
client->flush();
// Wait for client to close connection, since we will
// be disabling the accesspoint directly afterwards
while (client->connected());
client->stop();
Serial.println("Success, client disconnected.");
return true;
} else {
client->println("Error\n"); //Notify client
client->flush();
client->stop();
Serial.println("Error, client disconnected.");
return false;
}
} else {
client->println("Timeout\n"); //Notify client
client->flush();
client->stop();
Serial.println("Timeout, client disconnected.");
return false;
}
}
/**
* Synchronizes the time with an ntp server, captures a measurement,
* generates a json document and uploads it to the mowesta backend.
*/
void measurement_capture() {
WiFiClientSecure wifi;
HTTPClient http;
StaticJsonDocument<JSON_BUFFER_SIZE> doc;
sensors_event_t temperature_event, pressure_event;
// set trusted root certificates and perform ntp time sync for https
configTime(0, 0, "time2-1.uni-duisburg-essen.de", "time2-3.uni-duisburg-essen.de", "pool.ntp.org");
Serial.print("Waiting for NTP time sync: ");
time_t now = time(nullptr);
// check that time is after January 1st, 2021
int max_wait = TIMEOUT_NTP;
while (now < 1606694400) {
if (max_wait < 0) {
Serial.println("Timeout");
return;
}
delay(500);
max_wait -= 500;
now = time(nullptr);
}
Serial.println(now);
wifi.setTrustAnchors(&certificates);
// capture sensor data
sensor_bmp.getTemperatureSensor()->getEvent(&temperature_event);
sensor_bmp.getPressureSensor()->getEvent(&pressure_event);
// create json document for upload
doc["id"] = 0;
doc["creationTime"] = 0;
doc["modificationTime"] = 0;
doc["deleted"] = "false";
JsonObject coordinate = doc.createNestedObject("coordinate");
coordinate["latitude"] = setting_latitude->toDouble();
coordinate["longitude"] = setting_longitude->toDouble();
doc["time"] = now * 1000;
doc["device"] = atol(setting_device_id->c_str());
doc["version"] = MOWESTA_SOFTWARE_VERSION;
doc["temperature"] = (char*)0;
doc["pressure"] = (char*)0;
doc["humidity"] = (char*)0;
JsonObject data = doc.createNestedObject("data");
data["SENSOR_TEMPERATURE"] = String(temperature_event.temperature);
data["SENSOR_PRESSURE"] = String(pressure_event.pressure);
data["BATTERY_VOLTAGE"] = String((analogRead(VOLTAGE_PIN) / VOLTAGE_DIVIDER) * VOLTAGE_MULTIPLIER);
// print measurement
serializeJsonPretty(doc, Serial);
Serial.println();
// upload measurement
String body;
serializeJson(doc, body);
http.begin(wifi, MOWESTA_UPLOAD_URL);
http.addHeader("Accept", "application/json");
http.addHeader("Authorization", "Bearer " + *setting_device_token);
http.addHeader("Content-Type", "application/json");
int code = http.POST(body);
if (code / 100 == 2) {
Serial.println("Upload successful.");
} else {
Serial.print("Upload failed: ");
Serial.println(code);
}
http.end();
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+15 -13
View File
@@ -5,10 +5,10 @@ apply plugin: 'maven-publish'
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:7.0.0'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.4'
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
classpath "org.openbakery:xcode-plugin:0.19.1"
classpath 'com.android.tools.build:gradle:7.3.1'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.4'
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
classpath "gradle.plugin.org.openbakery:plugin:0.21.0"
}
repositories {
maven {
@@ -24,7 +24,7 @@ allprojects {
// set version for our project
group = 'com.mowesta'
version = '1.0.18'
version = '1.0.29'
// set versions for our libraries
ext {
@@ -44,7 +44,7 @@ allprojects {
// built-in infinispan dependency
versionInfinispan = '9.4.20.Final'
// testing dependencies
versionJunit = '4.13.1'
versionJunit = '4.13.2'
versionArquillianContainer = '2.2.0.Final'
versionArquillianJunit = '1.5.0.Final'
// thorntail dependencies
@@ -54,13 +54,15 @@ allprojects {
mapstructVersion = '1.3.1.Final'
// shared android dependencies
versionAndroidXTest = '1.4.0'
versionAndroidXAppcompat = '1.3.1'
versionAndroidXRoom = '2.3.0'
versionAndroidXPreference = '1.1.1'
versionRobolectric = '4.5'
// locoslab libraries and code
versionGeometry = '1.1.4'
versionCarta = '1.1.4'
versionAndroidXAppcompat = '1.5.1'
versionAndroidXRoom = '2.4.3'
versionAndroidXPreference = '1.2.0'
versionRobolectric = '4.9'
// locoslab libraries and code
versionGeometry = '1.1.4'
versionCarta = '1.1.4'
// tools
versionCli = '1.4'
}
+5 -2
View File
@@ -1,8 +1,8 @@
plugins {
id 'com.benjaminsproule.swagger' version '1.0.6'
id 'com.benjaminsproule.swagger' version '1.0.14'
}
description = 'Mowesta Common Api'
description = 'MoWeSta Common Api'
dependencies {
api "javax.xml.bind:jaxb-api:${versionJaxb}"
@@ -75,6 +75,9 @@ swagger {
}
}
build.dependsOn("generateSwaggerDocumentation")
publish.dependsOn("generateSwaggerDocumentation")
// add the swagger defintion to the artifacts published by this module
publishing {
publications {
@@ -1,14 +1,12 @@
package com.mowesta.api.location;
import javax.annotation.security.PermitAll;
import javax.enterprise.inject.Default;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -64,6 +62,7 @@ public interface ILocationService {
* Searches for a particular city by name.
*
* @param pageConfig The page configuration.
* @param context The search context.
* @param term The search term.
* @return The page of cities.
*/
+64
View File
@@ -0,0 +1,64 @@
![](header.png)
# MoWeSta Datensatz
Die beigefügte Datei im CSV Format enthält anonymsierte Batterietemperaturmessungen von Android-Geräten im Außenbereich, die mit Hilfe des [MoWeSta Diensts](https://www.mowesta.com) im Rahmen des vom Bundesministerium für Digitales und Verkehr geförderten [Forschungsprojekts FAIR](https://www.fair-opendata.de) durch Freiwillige erfasst wurden.
## Zeitraum
Der Zeitraum umfasst Messungen die zwischen Januar 2020 und September 2022 erfolgt sind.
## Abdeckung
Die örtliche Abdeckung ist begrenzt auf Deutschland, da hierfür die Basistemperaturwerte des Deutschen Wetterdiensts verfügbar sind.
## Vorverarbeitung
Im o.g. Zeitraum wurden mit Hilfe des MoWeSta Diensts rund 6,2 Millionen Batterietemperaturmessungen erfasst. Die meisten Messungen sind für die Bestimmung der Außentemperatur jedoch nicht geeignet, da sie in Innenräumen erfolgt sind. Darüber hinaus enthalten die in MoWeSta gespeicherten Messungen genaue Standortinformationen, womit sie als personenbezogene Daten gelten, die nicht ohne Einwilligung der Nutzer weitergegeben werden dürfen. Aus diesem Grund wurden die Daten vorverarbeitet, um eine uneingeschränkte Weitergabe an Dritte zu ermöglichen.
### Datenselektion
Um sicherzustellen, dass die Batterietemperaturmessunen im Außenbereich erfolgt sind, wurden zunächst die Messungen identifiziert, bei denen sich das jeweilige Gerät mindestens 5 Minuten lang im Freien befand. Hierzu wurden zunächst anhand der Standortdaten einzelner Geräte alle zurückgelegten Wegstrecken berechnet. Von diesen Wegstrecken wurden diejenigen ausgewählt, bei denen die Bewegungsgeschwindigkeit unter 2 m/s lag. Jede Zeile in der beigefügten Datei repräsentiert eine solche Wegstrecke. Aufgrund der Geschwindigkeitsbeschränkung kann davon ausgegangen werden, dass die Wegstrecke zu Fuß (und damit im Freien) zurückgelegt wurde.
### Außentemperatur
Zur Entwicklung von weiteren Modellen zur Abbildung der Batterietemperaturwerte auf die Außentempeatur wurde jeder Wegstrecke die vorherschende Außentemperatur zugewiesen. Dazu wurde anhand des Gerätestandorts zunächst die nächste synoptische Messstation des DWD identifiziert. Anhand der Startzeit wurde daraufhin die gemessene Außentemperatur der Station abgerufen und der Wegstrecke zugewiesen.
### Pseudonymisierung
Für jedes Gerät wird der Hersteller und die Modellbezeichnung aufgeführt.
Zur Entfernung von nutzerspezifischen Informationen wurde jedem Gerät anstelle der im MoWeSta Dienst verwendeten Kennung eine fortlaufende Nummer zugewiesen.
### Standortverschleierung
Zur Anonymisierung der Standortinformationen wurden der genaue Standort für jedes Gerät verscheiert. Zu diesem Zweck wurde der GPS Standort zunächst mit Hilfe einer sphärischen Mercatorprojektion auf eine [Kachel der Zoomstufe 10](https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames) abgebildet und durch das Zentrum der Kachel (mit Angabe der resultierender maximalen Ungenauigkeit) ersetzt. Darüber hinaus wurden die von MoWeSta erfassten Zeitstempel unter Beibehaltung des Monats durch relative Angaben ersetzt. Abschließend wurden die Messdaten nach Außentemperatur geornet, womit alle zeitlichen Zusammenhänge zwischen Standort und Messzeitpunkt aus dem Datensatz entfernt sind.
## Struktur
Die beigefügte Datei im CSV Format nutzt Strichpunkte als Zellenseparator und Kommas zur Repräsentation von Dezimalzahlen. Damit kann Sie direkt in Microsoft Excel mit deutschen Einstellungen geöffnet werden. Da jede Zeile eine Wegstrecke repräsentiert, ist die Zahl der Spalten variabel und kann sich von Zeile zu Zeile in Abhängigkeit von der Zahl der Messungen pro Strecke unterscheiden. Im Folgenden werden die einzelnen Spalten kurz beschrieben:
- **Gerät:** Eine fortlaufende Nummer, die Wegstrecken des selben Geräts identifiziert.
- **Hersteller:** Der Name des Geräteherstellers.
- **Model:** Die herstellerspezifische Angabe des Gerätemodells.
- **Monat:** Der Monat der Messung (1=Januar, 12=Dezember)
- **Temperatur in °C (DWD):** Die gemessene Außentemperatur (in einer Höhe von 2 Metern) der nächstgelegenen synoptischen Station des Deutschen Wetterdiensts.
- **Latitude (WGS84):** Die Breite des Zentrums der Kachel (auf Zoomstufe 10), die den Standort enthält.
- **Longitude (WGS84):** Die Länge des Zentrums der Kachel (auf Zoomstufe 10), die den Standort enthält.
- **Verschleierung (m):** Die maximale Ungenauigkeit in Metern, die sich durch die Abbildung des Standorts auf das Zentrum der Kachel ergibt.
- **Aufenthaltsdauer im Freien (ms):** Die relative Aufenthaltsdauer im Freien seit Beginn der Bewegung in Millisekunden.
- **Batterietemperatur in °C:** Die gemessene Batterietemperatur des Geräts zum zuvor genannten Zeitpunkt
- **Gerät aktiv:** Ein boolscher Wert (Ja/Nein), der angibt ob sich das Gerät während der Messung der Batterietemperatur im aktiven Zustand befand (ein Indiz für Nutzeraktivität).
Die letzten 3 Spalten können sich beliebig häufig in einer Zeile wiederholen, um mehrere Messungen während der Wegstrecke darzustellen.
## Kontakt
Für Fragen zum beiliegenden Datensatz oder zur Vorverarbeitung wenden Sie sich bitte an [Dr. Marcus Handte](mailto:marcus.handte@uni-due.de). Weitere Kontaktinformationen finden Sie auf der [Homepage des Lehrstuhls Networked Embedded Systems](https://www.nes.uni-due.de) der [Universität Duisburg-Essen](https://www.uni-due.de).
&nbsp;
&nbsp;
![](footer.png)
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+51
View File
@@ -0,0 +1,51 @@
---
Titel: "MoWeSta Datensatz"
Publikationsdatum: "2022-11-07"
Kurzbeschreibung: "Der MoWeSta Datensatz enthält anonymsierte Batterietemperaturmessungen von Android-Geräten im Außenbereich, die mit Hilfe des MoWeSta Diensts im Rahmen des vom Bundesministerium für Digitales und Verkehr geförderten Forschungsprojekts FAIR durch Freiwillige erfasst wurden.\n
\n
Viele der mit MoWeSta erfassten Messungen sind für die Bestimmung der Außentemperatur jedoch nicht geeignet, da sie in Innenräumen erfolgt sind. Darüber hinaus enthalten die in MoWeSta gespeicherten Messungen genaue Standortinformationen, womit sie als personenbezogene Daten gelten, die nicht ohne Einwilligung der Nutzer weitergegeben werden dürfen. Aus diesem Grund wurden die Daten vorverarbeitet, um eine uneingeschränkte Weitergabe an Dritte zu ermöglichen.\n
\n
- Datenselektion: Um sicherzustellen, dass die Batterietemperaturmessunen im Außenbereich erfolgt sind, wurden zunächst die Messungen identifiziert, bei denen sich das jeweilige Gerät mindestens 5 Minuten lang im Freien befand. Hierzu wurden zunächst anhand der Standortdaten einzelner Geräte alle zurückgelegten Wegstrecken berechnet. Von diesen Wegstrecken wurden diejenigen ausgewählt, bei denen die Bewegungsgeschwindigkeit unter 2 m/s lag. Jede Zeile in der beigefügten Datei repräsentiert eine solche Wegstrecke. Aufgrund der Geschwindigkeitsbeschränkung kann davon ausgegangen werden, dass die Wegstrecke zu Fuß (und damit im Freien) zurückgelegt wurde.\n
- Außentemperatur: Zur Entwicklung von weiteren Modellen zur Abbildung der Batterietemperaturwerte auf die Außentempeatur wurde jeder Wegstrecke die vorherschende Außentemperatur zugewiesen. Dazu wurde anhand des Gerätestandorts zunächst die nächste synoptische Messstation des DWD identifiziert. Anhand der Startzeit wurde daraufhin die gemessene Außentemperatur der Station abgerufen und der Wegstrecke zugewiesen.\n
- Pseudonymisierung: Für jedes Gerät wird der Hersteller und die Modellbezeichnung aufgeführt. Zur Entfernung von nutzerspezifischen Informationen wurde jedem Gerät anstelle der im MoWeSta Dienst verwendeten Kennung eine fortlaufende Nummer zugewiesen.\n
- Standortverschleierung: Zur Anonymisierung der Standortinformationen wurden der genaue Standort für jedes Gerät verscheiert. Zu diesem Zweck wurde der GPS Standort zunächst mit Hilfe einer sphärischen Mercatorprojektion auf eine Kachel der Zoomstufe 10 abgebildet und durch das Zentrum der Kachel (mit Angabe der resultierender maximalen Ungenauigkeit) ersetzt. Darüber hinaus wurden die von MoWeSta erfassten Zeitstempel unter Beibehaltung des Monats durch relative Angaben ersetzt. Abschließend wurden die Messdaten nach Außentemperatur geornet, womit alle zeitlichen Zusammenhänge zwischen Standort und Messzeitpunkt aus dem Datensatz entfernt sind.\n
\n
Der Datensatz ist im CSV Format gespeichert und nutzt Strichpunkte als Zellenseparator und Kommas zur Repräsentation von Dezimalzahlen. Damit kann Sie direkt in Microsoft Excel mit deutschen Einstellungen geöffnet werden. Da jede Zeile eine Wegstrecke repräsentiert, ist die Zahl der Spalten variabel und kann sich von Zeile zu Zeile in Abhängigkeit von der Zahl der Messungen pro Strecke unterscheiden. Im Folgenden werden die einzelnen Spalten kurz beschrieben:\n
\n
- Gerät: Eine fortlaufende Nummer, die Wegstrecken des selben Geräts identifiziert.\n
- Hersteller: Der Name des Geräteherstellers.\n
- Model: Die herstellerspezifische Angabe des Gerätemodells.\n
- Monat: Der Monat der Messung (1=Januar, 12=Dezember)\n
- Temperatur in °C (DWD): Die gemessene Außentemperatur (in einer Höhe von 2 Metern) der nächstgelegenen synoptischen Station des Deutschen Wetterdiensts.\n
- Latitude (WGS84): Die Breite des Zentrums der Kachel (auf Zoomstufe 10), die den Standort enthält.\n
- Longitude (WGS84): Die Länge des Zentrums der Kachel (auf Zoomstufe 10), die den Standort enthält.\n
- Verschleierung (m): Die maximale Ungenauigkeit in Metern, die sich durch die Abbildung des Standorts auf das Zentrum der Kachel ergibt.\n
- Aufenthaltsdauer im Freien (ms): Die relative Aufenthaltsdauer im Freien seit Beginn der Bewegung in Millisekunden.\n
- Batterietemperatur in °C: Die gemessene Batterietemperatur des Geräts zum zuvor genannten Zeitpunkt.\n
- Gerät aktiv: Ein boolscher Wert (Ja/Nein), der angibt ob sich das Gerät während der Messung der Batterietemperatur im aktiven Zustand befand (ein Indiz für Nutzeraktivität).\n
\n
Die letzten 3 Spalten können sich beliebig häufig in einer Zeile wiederholen, um mehrere Messungen während der Wegstrecke darzustellen.
"
Zeitliche_Ausdehnung:
Anfangszeitpunkt: "2020-01-18"
Endzeitpunkt: "2022-09-07"
Geographisches_Begrenzungsrechteck:
Westen: "5.80077"
Osten: "13.88672"
Süden: "46.92011"
Norden: "54.67371"
Format:
- "CSV"
Online-Ressource:
- URL: "https://www.mowesta.com/data/measure/mowesta-dataset-20221107.zip"
Protokoll: "WWW:DOWNLOAD-1.0-http--download"
Bezeichnung: "MoWeSta Datensatz"
Beschreibung:
Funktion: "Download"
Herkunft_Erläuterung: "Der MoWeSta Datensatz enthält anonymsierte Batterietemperaturmessungen von Android-Geräten im Außenbereich, die mit Hilfe des MoWeSta Diensts im Rahmen des vom Bundesministerium für Digitales und Verkehr geförderten Forschungsprojekts FAIR durch Freiwillige erfasst wurden."
Referenzsystem:
- EPSG: "4326"
Name: "WGS 84"
Zusätzlicher_Metadatenkontakt:
- Organisation: "Universität Duisburg-Essen (WiWi > ICB > NES)"
E-Mail: "marcus.handte@uni-due.de"
+3 -3
View File
@@ -1,6 +1,6 @@
#Sat Nov 07 15:10:18 CET 2020
#Mon May 23 12:33:06 CEST 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
zipStoreBase=GRADLE_USER_HOME
-19
View File
@@ -1,19 +0,0 @@
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "MowestaApi",
products: [
.library(name: "MowestaApi", targets: ["MowestaApi"]),
],
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.1")
],
targets: [
.target(
name: "MowestaApi",
dependencies: ["Alamofire"],
path: "./"
)
]
)
-26
View File
@@ -1,26 +0,0 @@
plugins {
id 'org.hidetake.swagger.generator' version '2.18.2'
}
description = "Mowesta IOS Alamofire"
dependencies {
swaggerCodegen 'io.swagger:swagger-codegen-cli:2.4.11'
}
swaggerSources {
mowesta {
inputFile = file(project(':common-api:').buildDir.path + '/swagger/mowesta.json')
code {
outputDir = file("${project.buildDir}/swagger")
language = 'swift5'
rawOptions = ['--import-mappings', 'LocationHierarchy=LocationHierarchy']
}
}
}
// require api build to access swagger definition
tasks.register("build") { }
tasks['resolveSwaggerTemplate'].dependsOn(project(':common-api').tasks['build'])
// require swagger code gen before compilation
build.dependsOn('generateSwaggerCode')
@@ -1,61 +0,0 @@
//
// LocationHierarchy.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Represents a hierarchy of locations. */
public class LocationHierarchy: Codable {
public enum ModelType: String, Codable {
case country = "COUNTRY"
case state = "STATE"
case city = "CITY"
}
/** The unique identifier of the data. */
public var _id: Int64?
/** The time stamp when the data was created. */
public var creationTime: Int64?
/** The time stamp when the data was created. */
public var modificationTime: Int64?
/** A flag to indicate whether the data was deleted. */
public var deleted: Bool?
/** The coordinate of the location. */
public var coordinate: Coordinate
/** The type of the location. */
public var type: ModelType
/** The parent of the location (country for states, country or state for cities, null for countries). */
public var parent: LocationHierarchy?
/** The names of the location by language code. */
public var names: [String:String]
public init(_id: Int64?, creationTime: Int64?, modificationTime: Int64?, deleted: Bool?, coordinate: Coordinate, type: ModelType, parent: LocationHierarchy?, names: [String:String]) {
self._id = _id
self.creationTime = creationTime
self.modificationTime = modificationTime
self.deleted = deleted
self.coordinate = coordinate
self.type = type
self.parent = parent
self.names = names
}
public enum CodingKeys: String, CodingKey {
case _id = "id"
case creationTime
case modificationTime
case deleted
case coordinate
case type
case parent
case names
}
}
+19
View File
@@ -0,0 +1,19 @@
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "MoWeStaApi",
products: [
.library(name: "MoWeStaApi", targets: ["MoWeStaApi"]),
],
dependencies: [
.package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"),
],
targets: [
.target(
name: "MoWeStaApi",
dependencies: ["AnyCodable", ],
path: "./build/swagger/OpenAPIClient/Classes/OpenAPIs"
)
]
)
+43
View File
@@ -0,0 +1,43 @@
plugins {
id 'org.openapi.generator' version '6.0.1'
}
description = "MoWeSta iOS Api"
openApiGenerate {
generatorName = "swift5"
inputSpec = project(':common-api:').buildDir.path + '/swagger/mowesta.json'
outputDir = "${project.buildDir}/swagger"
configOptions = [
removeMigrationProjectNameClass: "true",
useClasses: "true"
]
}
task clean(type: Delete) {
delete "${project.buildDir}"
}
task fixApiClient() {
doLast {
ant.replaceregexp(match:'Optional<T>.none as! T', replace:'E.init(nilLiteral: ()) as! T', flags:'g', byline:true) {
fileset(dir: 'build/swagger/OpenAPIClient/Classes/OpenAPIs', includes: 'URLSessionImplementations.swift')
}
ant.replaceregexp(match:'if T.self is ExpressibleByNilLiteral.Type', replace:'if let E = T.self as? ExpressibleByNilLiteral.Type', flags:'g', byline:true) {
fileset(dir: 'build/swagger/OpenAPIClient/Classes/OpenAPIs', includes: 'URLSessionImplementations.swift')
}
}
}
// require api build to access swagger definition
tasks.register("build") { }
tasks['openApiGenerate'].dependsOn(project(':common-api').tasks['build'])
// require swagger code gen before compilation
build.dependsOn('openApiGenerate')
fixApiClient.dependsOn('openApiGenerate')
build.dependsOn('fixApiClient')
@@ -1,16 +0,0 @@
//
// CDDataDictionary+CoreDataClass.swift
// app
//
// Created by Sebastian Pobel on 08.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
@objc(CDDataDictionary)
public class CDDataDictionary: NSManagedObject {
}
@@ -1,39 +0,0 @@
//
// CDDataDictionary+CoreDataProperties.swift
// app
//
// Created by Sebastian Pobel on 08.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
extension CDDataDictionary {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDDataDictionary> {
return NSFetchRequest<CDDataDictionary>(entityName: "CDDataDictionary")
}
@NSManaged public var key: String?
@NSManaged public var value: String?
@NSManaged public var measurement: CDMeasurement?
}
enum MeasurementDataContext: String {
case BatteryCharging = "BATTERY_CHARGING"
case CpuFrequency = "CPU_FREQUENCY"
case ScreenEnabled = "SCREEN_ENABLED"
case BatteryTemperature = "BATTERY_TEMPERATURE"
case CpuTemperature = "CPU_TEMPERATURE"
case SensorTemperature = "SENSOR_TEMPERATURE"
case SensorPressure = "SENSOR_PRESSURE"
case SensorHumidity = "SENSOR_HUMIDITY"
case BatteryVoltage = "BATTERY_VOLTAGE"
case SolarVoltage = "SOLAR_VOLTAGE"
}
@@ -1,19 +0,0 @@
//
// CDPlacemarkLocation+CoreDataClass.swift
// app
//
// Created by Sebastian Pobel on 09.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
//The first decimal place is worth up to 11.1 km: it can distinguish the position of one large city from a neighboring large city.
//The second decimal place is worth up to 1.1 km: it can separate one village from the next.
//The third decimal place is worth up to 110 m: it can identify a large agricultural field or institutional campus.
@objc(CDPlacemarkLocation)
public class CDPlacemarkLocation: NSManagedObject {
}
@@ -1,33 +0,0 @@
//
// CDPlacemarkLocation+CoreDataProperties.swift
// app
//
// Created by Sebastian Pobel on 09.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
//The first decimal place is worth up to 11.1 km: it can distinguish the position of one large city from a neighboring large city.
//The second decimal place is worth up to 1.1 km: it can separate one village from the next.
//The third decimal place is worth up to 110 m: it can identify a large agricultural field or institutional campus.
extension CDPlacemarkLocation {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDPlacemarkLocation> {
return NSFetchRequest<CDPlacemarkLocation>(entityName: "CDPlacemarkLocation")
}
@nonobjc public class func fetchRequestFor(latitude: Int, longitude: Int) -> NSFetchRequest<CDPlacemarkLocation> {
let fetchRequest = NSFetchRequest<CDPlacemarkLocation>(entityName: "CDPlacemarkLocation")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \CDPlacemarkLocation.latitude, ascending: false)]
fetchRequest.predicate = NSPredicate(format: "latitude == %lld AND longitude == %lld", latitude, longitude)
return fetchRequest
}
@NSManaged public var name: String
@NSManaged public var longitude: Int64
@NSManaged public var latitude: Int64
}
-28
View File
@@ -1,28 +0,0 @@
//
// CDevice+CoreDataClass.swift
// app
//
// Created by Sebastian Pobel on 01.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
import MowestaApi
@objc(CDevice)
public class CDevice: NSManagedObject {
convenience init(context: NSManagedObjectContext, device: Device) {
self.init(context: context)
self.id = device._id!
self.creationTime = device.creationTime ?? -1000
self.device = device.device
self.manufacturer = device.manufacturer
self.markedDeleted = device.deleted ?? false
self.model = device.model
self.modificationTime = device.modificationTime ?? -1000
self.os = device.os.name
}
}
-81
View File
@@ -1,81 +0,0 @@
//
// CDevice+CoreDataProperties.swift
// app
//
// Created by Sebastian Pobel on 01.02.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
extension CDevice {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDevice> {
let fetchRequest = NSFetchRequest<CDevice>(entityName: "CDevice")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \CDevice.id, ascending: true)]
return fetchRequest
}
@nonobjc public class func fetchRequestWithout(id: Int64) -> NSFetchRequest<CDevice> {
let fetchRequest = NSFetchRequest<CDevice>(entityName: "CDevice")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \CDevice.id, ascending: true)]
fetchRequest.predicate = NSPredicate(format: "id != %lld", id)
return fetchRequest
}
@nonobjc public class func fetchRequestBy(id: Int64) -> NSFetchRequest<CDevice> {
let fetchRequest = NSFetchRequest<CDevice>(entityName: "CDevice")
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \CDevice.id, ascending: true)]
fetchRequest.predicate = NSPredicate(format: "id == %lld", id)
return fetchRequest
}
@NSManaged public var creationTime: Int64
@NSManaged public var device: String?
@NSManaged public var id: Int64
@NSManaged public var manufacturer: String?
@NSManaged public var markedDeleted: Bool
@NSManaged public var model: String?
@NSManaged public var modificationTime: Int64
@NSManaged public var os: String?
@NSManaged public var measurements: NSOrderedSet?
}
// MARK: Generated accessors for measurements
extension CDevice {
@objc(insertObject:inMeasurementsAtIndex:)
@NSManaged public func insertIntoMeasurements(_ value: CDMeasurement, at idx: Int)
@objc(removeObjectFromMeasurementsAtIndex:)
@NSManaged public func removeFromMeasurements(at idx: Int)
@objc(insertMeasurements:atIndexes:)
@NSManaged public func insertIntoMeasurements(_ values: [CDMeasurement], at indexes: NSIndexSet)
@objc(removeMeasurementsAtIndexes:)
@NSManaged public func removeFromMeasurements(at indexes: NSIndexSet)
@objc(replaceObjectInMeasurementsAtIndex:withObject:)
@NSManaged public func replaceMeasurements(at idx: Int, with value: CDMeasurement)
@objc(replaceMeasurementsAtIndexes:withMeasurements:)
@NSManaged public func replaceMeasurements(at indexes: NSIndexSet, with values: [CDMeasurement])
@objc(addMeasurementsObject:)
@NSManaged public func addToMeasurements(_ value: CDMeasurement)
@objc(removeMeasurementsObject:)
@NSManaged public func removeFromMeasurements(_ value: CDMeasurement)
@objc(addMeasurements:)
@NSManaged public func addToMeasurements(_ values: NSOrderedSet)
@objc(removeMeasurements:)
@NSManaged public func removeFromMeasurements(_ values: NSOrderedSet)
}
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1130"
LastUpgradeVersion = "1340"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -14,10 +14,10 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846D02372F44300766694"
BlueprintIdentifier = "2C163306283A27D300F78CEE"
BuildableName = "MoWeSta.app"
BlueprintName = "app"
ReferencedContainer = "container:app.xcodeproj">
BlueprintName = "App"
ReferencedContainer = "container:App.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@@ -32,20 +32,20 @@
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846E62372F44500766694"
BuildableName = "appTests.xctest"
BlueprintName = "appTests"
ReferencedContainer = "container:app.xcodeproj">
BlueprintIdentifier = "2C16331B283A27D600F78CEE"
BuildableName = "AppTests.xctest"
BlueprintName = "AppTests"
ReferencedContainer = "container:App.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846F12372F44500766694"
BuildableName = "appUITests.xctest"
BlueprintName = "appUITests"
ReferencedContainer = "container:app.xcodeproj">
BlueprintIdentifier = "2C163325283A27D600F78CEE"
BuildableName = "AppUITests.xctest"
BlueprintName = "AppUITests"
ReferencedContainer = "container:App.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
@@ -64,10 +64,10 @@
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846D02372F44300766694"
BlueprintIdentifier = "2C163306283A27D300F78CEE"
BuildableName = "MoWeSta.app"
BlueprintName = "app"
ReferencedContainer = "container:app.xcodeproj">
BlueprintName = "App"
ReferencedContainer = "container:App.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
@@ -81,10 +81,10 @@
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2C7846D02372F44300766694"
BlueprintIdentifier = "2C163306283A27D300F78CEE"
BuildableName = "MoWeSta.app"
BlueprintName = "app"
ReferencedContainer = "container:app.xcodeproj">
BlueprintName = "App"
ReferencedContainer = "container:App.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
@@ -2,13 +2,9 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.associated-domains</key>
<array>
<string>webcredentials:mowesta.com</string>
</array>
<key>com.apple.developer.networking.HotspotConfiguration</key>
<true/>
<key>com.apple.developer.networking.networkextension</key>
<array/>
<key>com.apple.developer.networking.wifi-info</key>
<true/>
</dict>
</plist>
-96
View File
@@ -1,96 +0,0 @@
//
// AppDelegate.swift
// app
//
// Created by Marcus Handte on 06.11.19.
// Copyright © 2019 Marcus Handte. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
NSLog("didLaunchApplication")
BackgroundService.shared.registerMeasurementService()
WeatherForecastService.shared.registerWeatherforecastBackgroundService()
let userDefaults = UserDefaults.standard
if !userDefaults.bool(forKey: KeychainKeys.hasRunBefore) {
UserData.shared.reset()
DeviceData.shared.reset() {}
// Update the flag indicator
userDefaults.set(true, forKey: KeychainKeys.hasRunBefore)
}
//let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
//print(urls[urls.count-1] as URL)
return true
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
NSLog("new scene session created");
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
NSLog("user discards scene session");
}
func applicationDidEnterBackground(_ application: UIApplication) {
WeatherForecastService.shared.scheduleWeatherforecastBackgroundService()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Mowesta")
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
-29
View File
@@ -1,29 +0,0 @@
//
// AppRootView.swift
// app
//
// Created by Tobias Stottrop on 02.03.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import SwiftUI
struct AppRootView: View {
@EnvironmentObject var user: UserData
var body: some View {
return Group {
if (user.agreedToS) {
MainTabView()
} else {
TermsRootView()
}
}
}
}
struct AppRootView_Previews: PreviewProvider {
static var previews: some View {
AppRootView()
}
}

Some files were not shown because too many files have changed in this diff Show More