Release 1.3.0

This commit is contained in:
2021-08-26 12:33:15 +02:00
commit 9bb72f0207
1148 changed files with 92133 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
lib/**/*.js
homehub_iformicarium/**/*.js

View File

@@ -0,0 +1,26 @@
{
"extends": [
"@bthlabs",
"plugin:react/recommended",
"plugin:react-hooks/recommended"
],
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module",
"ecmaFeatures": {
"jsx": true,
"modules": true
}
},
"globals": {
"PRODUCTION": "readonly"
},
"settings": {
"react": {
"version": "detect"
}
},
"rules": {
"react/prop-types": "off"
}
}

69
packages/homehub_iformicarium/.gitignore vendored Executable file
View File

@@ -0,0 +1,69 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.envrc
# next.js build output
.next
# homehub_frontend
/build/
/dist/
/lib/
/homehub_iformicarium.egg-info/
test-results.xml

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1 @@
include LICENSE.txt NOTICE.txt README.md requirements.txt

View File

@@ -0,0 +1,23 @@
PHONY: clean dev lint test build publish
clean:
rm -rf build/ dist/ lib/ homehub_iformicarium.egg-info/
dev:
yarn dev
lint:
yarn lint
flake8
test:
yarn test --single-run
pytest -v --disable-warnings
build: clean
yarn build
python setup.py build sdist bdist_wheel
publish:
npm publish
twine upload --repository pypi-hosted.nexus.bthlabs.pl --skip-existing dist/*

View File

@@ -0,0 +1,31 @@
BTHLabs HomeHub - iFormicarium Integration
Copyright 2021-present BTHLabs <contact@bthlabs.pl> (https://bthlabs.pl/)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---
BTHLabs HomeHub - iFormicarium Integration includes the following third party
software
classnames
Copyright (c) 2017 Jed Watson
Licensed under terms of the MIT License
lodash
Copyright JS Foundation and other contributors
Licensed under terms of the MIT License
luxon
Copyright 2019 JS Foundation and other contributors
Licensed under terms of the MIT License

View File

@@ -0,0 +1,3 @@
# homehub_iformicarium
BTHLabs HomeHub - Torflix Deployment

View File

@@ -0,0 +1,22 @@
module.exports = {
'presets': [
[
'@babel/preset-env', {
'targets': {
'chrome': 81,
'edge': 18,
'firefox': 75,
'ie': 11,
'opera': 68,
'safari': 13,
},
'modules': 'commonjs',
},
],
'@babel/preset-react',
],
'plugins': [
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-export-default-from',
],
};

View File

@@ -0,0 +1 @@
__version__ = '1.3.0'

View File

@@ -0,0 +1 @@
kServiceIFormicarium = 'kServiceIFormicarium'

View File

@@ -0,0 +1,76 @@
# -*- coding: utf8 -*-
import datetime
import json
import logging
import uuid
import gmqtt
from homehub_backend.lib.services import BaseService, ServiceData
from homehub_iformicarium.defs import kServiceIFormicarium
LOGGER = logging.getLogger('homehub.tradfri.services')
class iFormicariumService(BaseService):
KIND = kServiceIFormicarium
def __init__(self, app, instance, characteristics):
super(iFormicariumService, self).__init__(
app, instance, characteristics,
)
self._current_data = None
self.client = None
async def current_data(self):
if self._current_data is None:
return ServiceData()
return self._current_data
def on_client_connect(self, client, flags, rc, properties):
LOGGER.debug('iFormicariumService.on_client_connect()')
client.subscribe(self.characteristics['topic'])
def on_client_disconnect(self, client, packet, exc=None):
LOGGER.debug(
'iFormicariumService.on_client_disconnect()', exc_info=exc,
)
async def on_client_message(self, client, topic, payload, qos, properties):
LOGGER.debug('iFormicariumService.on_client_message() {topic} "{payload}"'.format(
topic=topic,
payload=payload,
))
result = ServiceData()
should_notify = True
try:
message = json.loads(payload)
should_notify = message['name'] == self.characteristics['name']
result.data = message
result.data['dt'] = datetime.datetime.now().timestamp()
except Exception as exc:
LOGGER.error('Unhandled exception!', exc_info=exc)
result.exception = exc
if should_notify:
self._current_data = result
await self.notify()
async def start(self):
if not self.client:
self.client = gmqtt.Client(str(uuid.uuid4()))
self.client.set_config({'reconnect_retries': 10})
self.client.on_connect = self.on_client_connect
self.client.on_disconnect = self.on_client_disconnect
self.client.on_message = self.on_client_message
await self.client.connect(self.characteristics['mqtt'])
async def stop(self):
if self.client and self.client.is_connected:
await self.client.disconnect()

View File

@@ -0,0 +1 @@
state.json

View File

@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
import os
DEBUG = False
TESTING = True
STATE_PATH = os.path.join(os.path.dirname(__file__), 'state.json')

View File

@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
from homehub_backend.app import create_app
import pytest
@pytest.fixture
def homehub_app(loop):
return create_app(loop=loop)

View File

@@ -0,0 +1,273 @@
# -*- coding: utf-8 -*-
import datetime
import json
from unittest import mock
from homehub_backend.lib.services import ServiceData
import gmqtt
import pytest
from homehub_iformicarium import services
@pytest.fixture
def mock_mqtt_client():
return mock.Mock(spec=gmqtt.Client)
class Test_iFormicariumService:
def _valid_characteristics(self):
return {
'mqtt': 'thisisntright.local',
'name': 'iformicarium',
'topic': 'iformicarium',
}
def _valid_payload(self, **update):
payload = {
'name': 'iformicarium',
'uptime': 123,
'heap': 65535,
'dht': {
'0': {
'name': 'dht1',
'humi': 69,
'temp': 25,
},
},
'fan': 1,
}
payload.update(update)
return json.dumps(payload)
def test_init(self, homehub_app):
# Given
service = services.iFormicariumService(
homehub_app, 'testing', self._valid_characteristics(),
)
# Then
assert service._current_data is None
assert service.client is None
async def test_current_data(self, homehub_app):
# Given
service = services.iFormicariumService(
homehub_app, 'testing', self._valid_characteristics(),
)
service._current_data = ServiceData(data='spam')
# When
result = await service.current_data()
# Then
assert result is service._current_data
async def test_current_data_empty(self, homehub_app):
# Given
service = services.iFormicariumService(
homehub_app, 'testing', self._valid_characteristics(),
)
# When
result = await service.current_data()
# Then
assert result != service._current_data
assert result.data is None
assert result.exception is None
def test_on_client_connect(self, homehub_app, mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
# When
service.on_client_connect(
mock_mqtt_client, 'flags', 'rc', 'properties',
)
# Then
mock_mqtt_client.subscribe.assert_called_with(
characteristics['topic'],
)
@pytest.mark.skip()
def test_on_client_disconnect(self, homehub_app):
pass
async def test_on_client_message_json_decode_error(self, homehub_app,
mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
with mock.patch.object(service, 'notify') as mock_notify:
# When
await service.on_client_message(
mock_mqtt_client,
characteristics['topic'],
'',
None,
None,
)
# Then
assert mock_notify.called
assert service._current_data.data is None
assert isinstance(service._current_data.exception, BaseException)
async def test_on_client_message_name_mismatch(self, homehub_app,
mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
fake_payload = self._valid_payload(name='otherinstance')
with mock.patch.object(service, 'notify') as mock_notify:
# When
await service.on_client_message(
mock_mqtt_client,
characteristics['topic'],
fake_payload,
None,
None,
)
# Then
assert not mock_notify.called
assert service._current_data is None
@mock.patch('datetime.datetime')
async def test_on_client_message(self, mock_datetime, homehub_app,
mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
fake_payload = self._valid_payload()
fake_now = datetime.datetime(1987, 10, 3, 8, 0, 0)
mock_datetime.now.return_value = fake_now
with mock.patch.object(service, 'notify') as mock_notify:
# When
await service.on_client_message(
mock_mqtt_client,
characteristics['topic'],
fake_payload,
None,
None,
)
# Then
assert mock_notify.called
assert service._current_data is not None
assert service._current_data.exception is None
data = json.loads(fake_payload)
assert service._current_data.data['name'] == data['name']
assert service._current_data.data['uptime'] == data['uptime']
assert service._current_data.data['heap'] == data['heap']
assert service._current_data.data['dht'] == data['dht']
assert service._current_data.data['dt'] == fake_now.timestamp()
async def test_start_already_started(self, homehub_app, mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
service.client = mock_mqtt_client
fake_other_client = mock.Mock(spec=gmqtt.Client)
with mock.patch.object(gmqtt, 'Client') as mock_client:
mock_client.return_value = fake_other_client
# When
await service.start()
# Then
assert service.client == mock_mqtt_client
assert not mock_client.called
async def test_start(self, homehub_app, mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
with mock.patch.object(gmqtt, 'Client') as mock_client:
mock_client.return_value = mock_mqtt_client
# When
await service.start()
# Then
assert service.client == mock_mqtt_client
assert service.client.on_connect == service.on_client_connect
assert service.client.on_disconnect == service.on_client_disconnect
assert service.client.on_message == service.on_client_message
assert mock_client.called
mock_mqtt_client.set_config.assert_called_with({
'reconnect_retries': 10,
})
mock_mqtt_client.connect.assert_called_with(
characteristics['mqtt'],
)
async def test_stop_not_started(self, homehub_app, mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
# When
await service.stop()
# Then
assert not mock_mqtt_client.disconnect.called
async def test_stop_not_connected(self, homehub_app, mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
service.client = mock_mqtt_client
service.client.is_connected = False
# When
await service.stop()
# Then
assert not mock_mqtt_client.disconnect.called
async def test_stop(self, homehub_app, mock_mqtt_client):
# Given
characteristics = self._valid_characteristics()
service = services.iFormicariumService(
homehub_app, 'testing', characteristics,
)
service.client = mock_mqtt_client
service.client.is_connected = True
# When
await service.stop()
# Then
assert mock_mqtt_client.disconnect.called

View File

@@ -0,0 +1,70 @@
var path = require('path');
const CONTEXT = path.resolve(__dirname);
const SCSS_DIR = path.resolve(CONTEXT, 'scss');
const PROJECT_DIR = path.resolve(CONTEXT, 'src');
const TESTS_DIR = path.resolve(CONTEXT, 'tests');
const ENTRY_POINT = path.resolve(TESTS_DIR, '__entry__.js');
module.exports = function (config) {
config.set({
basePath: '.',
browsers: ['jsdom'],
frameworks: ['jasmine'],
files: [ENTRY_POINT],
junitReporter: {
outputDir: '',
outputFile: 'test-results.xml',
suite: 'homehub_frontend',
useBrowserName: false,
},
mochaReporter: {
ignoreSkipped: true,
},
preprocessors: {
[ENTRY_POINT]: ['webpack', 'sourcemap'],
},
reporters: ['mocha'],
singleRun: false,
webpack: {
mode: 'development',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.js?/,
include: PROJECT_DIR,
use: ['babel-loader'],
},
{
test: /\.js$/,
include: TESTS_DIR,
use: ['babel-loader'],
},
{
test: /\.scss$/,
use: ['null-loader'],
},
{
test: /\.(png|svg)$/,
use: ['null-loader'],
},
],
},
resolve: {
alias: {
'scss': SCSS_DIR,
'src': PROJECT_DIR,
'tests': TESTS_DIR,
},
},
externals: {
'cheerio': 'window',
'react/addons': 'react',
'react/lib/ExecutionEnvironment': 'react',
'react/lib/ReactContext': 'react',
},
},
});
};

View File

@@ -0,0 +1,75 @@
{
"name": "@bthlabs/homehub-iformicarium",
"version": "1.3.0",
"description": "BTHLabs HomeHub - iFormicarium Integration",
"main": "lib/index.js",
"author": "BTHLabs <contact@bthlabs.pl>",
"license": "Apache-2.0",
"scripts": {
"build": "NODE_ENV=production npx webpack-cli",
"dev": "npx webpack-cli",
"start": "npx webpack-cli --watch",
"lint": "npx eslint src/ tests/ *.js",
"test": "npx karma start",
"test:dist": "npx karma start --single-run --reporters junit"
},
"files": [
"lib/"
],
"publishConfig": {
"registry": "https://nexus.bthlabs.pl/repository/npm-hosted/"
},
"peerDependencies": {
"@bthlabs/homehub-components": ">=1.3.0",
"@bthlabs/homehub-core": ">=1.3.0",
"@bthlabs/homehub-icons": ">=1.3.0",
"react": ">=16.11.0",
"react-bootstrap": "1.0.1",
"react-dom": ">=16.11.0"
},
"devDependencies": {
"@babel/core": "7.7.2",
"@babel/plugin-proposal-class-properties": "7.8.3",
"@babel/plugin-proposal-export-default-from": "7.5.2",
"@babel/preset-env": "7.7.1",
"@babel/preset-react": "7.7.0",
"@bthlabs/eslint-config": "1.0.3",
"@bthlabs/homehub-components": ">=1.2.0",
"@bthlabs/homehub-core": ">=1.2.0",
"@bthlabs/homehub-icons": ">=1.2.0",
"babel-eslint": "10.0.3",
"babel-loader": "8.0.6",
"classnames": "2.2.6",
"clean-webpack-plugin": "3.0.0",
"css-loader": "3.5.3",
"enzyme": "3.10.0",
"enzyme-adapter-react-16": "1.15.1",
"eslint": "6.6.0",
"eslint-plugin-react": "7.20.4",
"eslint-plugin-react-hooks": "4.0.8",
"jasmine-core": "3.5.0",
"jsdom": "16.4.0",
"lodash": "4.17.15",
"luxon": "1.24.1",
"karma": "4.4.1",
"karma-jasmine": "2.0.1",
"karma-jsdom-launcher": "9.0.0",
"karma-junit-reporter": "2.0.1",
"karma-mocha-reporter": "2.2.5",
"karma-sourcemap-loader": "0.3.7",
"karma-webpack": "4.0.2",
"node-sass": "4.14.1",
"null-loader": "4.0.0",
"prop-types": "15.7.2",
"react": "16.11.0",
"react-bootstrap": "1.0.1",
"react-dom": "16.11.0",
"react-svg-loader": "3.0.3",
"regenerator-runtime": "0.13.5",
"sass-loader": "8.0.2",
"style-loader": "1.2.1",
"underscore": "1.9.1",
"webpack": "4.41.2",
"webpack-cli": "3.3.11"
}
}

View File

@@ -0,0 +1,9 @@
-r requirements.txt
flake8==3.8.3
flake8-commas==2.0.0
pycodestyle==2.6.0
pytest==6.0.1
pytest-aiohttp==0.3.0
pytest-asyncio==0.14.0
pytest-env==0.6.2
twine==2.0.0

View File

@@ -0,0 +1,2 @@
gmqtt==0.6.7
homehub_backend>=1.3.0

View File

@@ -0,0 +1,10 @@
[flake8]
exclude = build/,lib/,node_modules/
ignore = E402
max-line-length = 120
[tool:pytest]
testpaths =
homehub_iformicarium/tests
env =
HOMEHUB_SETTINGS_MODULE=homehub_iformicarium.testing.settings

View File

@@ -0,0 +1,53 @@
import io
import re
from setuptools import find_packages
from setuptools import setup
def _process_requirements(requirements):
return list(
filter(lambda x: x != '', map(lambda x: x.strip(), requirements)),
)
def _process_packages(packages):
return list(
map(lambda x: 'homehub_iformicarium.{package}'.format(package=x), packages),
)
with io.open('README.md', 'rt', encoding='utf8') as f:
readme = f.read()
with io.open('requirements.txt', 'rt', encoding='utf8') as f:
requirements = _process_requirements(f.read().split('\n'))
with io.open('homehub_iformicarium/__init__.py', 'rt', encoding='utf8') as f:
version = re.search(r"""__version__ = '(.*?)'""", f.read()).group(1)
packages = ['homehub_iformicarium']
packages.extend(_process_packages(find_packages(
'homehub_iformicarium', exclude=[
'testing', 'testing.*', 'tests', 'tests.*',
],
)))
setup(
name='homehub_iformicarium',
version=version,
license='Apache License Version 2.0',
author='BTHLabs',
author_email='contact@bthlabs.pl',
maintainer='BTHLabs',
maintainer_email='contact@bthlabs.pl',
description='BTHLabs HomeHub - iFormicarium Integration',
long_description=readme,
classifiers=[
'License :: OSI Approved :: Apache Software License',
],
packages=packages,
include_package_data=True,
python_requires='>=3.7',
install_requires=requirements,
)

View File

@@ -0,0 +1,41 @@
import {API, BaseService} from '@bthlabs/homehub-core';
import isEqual from 'lodash/isEqual';
import {kServiceIFormicarium, kWidgetIFormicarium} from './defs';
export class IFormicariumService extends BaseService {
static kind = kServiceIFormicarium;
static widget = kWidgetIFormicarium;
static emptyCharacteristics () {
return {
name: '',
mqtt: '',
topic: 'iformicarium',
};
}
async start () {
const result = await API.Services.start(
kServiceIFormicarium, this.instance, this.characteristics
);
this.notify(result);
}
async stop () {
return API.Services.stop(kServiceIFormicarium, this.instance);
}
setCharacteristics (newCharacteristics) {
const shouldRestart = Object.keys(
IFormicariumService.emptyCharacteristics()
).some(
(key) => {
return !isEqual(this.characteristics[key], newCharacteristics[key]);
}
);
super.setCharacteristics(newCharacteristics);
if (shouldRestart) {
this.restart();
}
}
}

View File

@@ -0,0 +1,158 @@
import {FatalError, Widget} from '@bthlabs/homehub-components';
import {
IconArrowsRotate, IconBasicElaborationTabletCloud, Icon,
} from '@bthlabs/homehub-icons';
import ClassName from 'classnames';
import {DateTime} from 'luxon';
import React from 'react';
import {Form} from 'react-bootstrap';
import './IFormicariumWidgetView.scss';
export const IFormicariumWidgetSettingsView = (props) => {
const onMQTTInputChange = React.useCallback(
(event) => {
props.setNextCharacteristics({
...props.nextCharacteristics,
mqtt: event.target.value,
});
},
[props]
);
const onNameInputChange = React.useCallback(
(event) => {
props.setNextCharacteristics({
...props.nextCharacteristics,
name: event.target.value,
});
},
[props]
);
const onTopicInputChange = React.useCallback(
(event) => {
props.setNextCharacteristics({
...props.nextCharacteristics,
topic: event.target.value,
});
},
[props]
);
if (!props.nextCharacteristics) {
return null;
}
return (
<Form>
<Form.Group controlId="input-mqtt">
<Form.Label>MQTT Host</Form.Label>
<Form.Control
size="sm"
value={props.nextCharacteristics.mqtt}
onChange={onMQTTInputChange}
/>
</Form.Group>
<Form.Group controlId="input-name">
<Form.Label>Instance Name</Form.Label>
<Form.Control
size="sm"
value={props.nextCharacteristics.name}
onChange={onNameInputChange}
/>
</Form.Group>
<Form.Group controlId="input-topic">
<Form.Label>MQTT Topic</Form.Label>
<Form.Control
size="sm"
value={props.nextCharacteristics.topic}
onChange={onTopicInputChange}
/>
</Form.Group>
</Form>
);
};
export const IFormicariumWidgetView = (props) => {
if (props.serviceState === null) {
return null;
}
let data = null;
let lastUpdateDt = null;
if (props.serviceState.hasData()) {
data = props.serviceState.data();
lastUpdateDt = DateTime.fromSeconds(data.dt);
}
const className = ClassName('IFormicariumWidgetView', {
'is-loading': (
props.serviceState.isLoading() || props.serviceState.hasFatalError()
),
});
return (
<Widget className={className} {...props}>
{props.serviceState.isLoading() &&
<Icon
_hint="Loader"
className="animation-loading loader"
icon={IconArrowsRotate}
size={78}
/>
}
{props.serviceState.hasData() &&
<div _hint="InstanceInfo">
<h5 _hint="InstanceName" className="text-center">
{data.name}
</h5>
<div _hint="InstanceMetrics" className="metrics">
{Object.values(data.dht).map((metric) => {
return (
<div
_hint="InstanceDHTMetric"
key={`dht-${metric.name}`}
className="metric"
>
<p>{metric.name}</p>
<p>Temp: {metric.temp}&deg;</p>
<p>Humi: {metric.humi}%</p>
</div>
);
})}
<div _hint="InstanceFanMetric" className="metric">
<p>Fan</p>
<p>{data.fan * 25}%</p>
</div>
</div>
<p className="meta">
<small _hint="LastUpdate">
Last update {lastUpdateDt.toLocaleString(DateTime.TIME_SIMPLE)}
</small>
</p>
</div>
}
{props.serviceState.hasFatalError() &&
<FatalError
service={props.service}
serviceState={props.serviceState}
/>
}
</Widget>
);
};
IFormicariumWidgetView.defaultLayout = {
h: 4,
w: 6,
};
IFormicariumWidgetView.icon = IconBasicElaborationTabletCloud;
IFormicariumWidgetView.layoutConstraints = {
minH: 4,
minW: 6,
};
IFormicariumWidgetView.settingsView = IFormicariumWidgetSettingsView;
IFormicariumWidgetView.title = 'iFormicarium';

View File

@@ -0,0 +1,43 @@
.IFormicariumWidgetView {
color: white;
.widget-content {
display: flex;
flex-direction: column;
height: 100%;
.metrics {
display: flex;
flex: 1;
flex-direction: row;
.metric {
width: calc(33% - 8px);
p {
margin-bottom: 0.3rem;
&:first-child {
font-weight: bold;
text-align: center;
}
}
}
}
.meta {
bottom: 0px;
left: 0.2rem;
line-height: 1rem;
position: absolute;
}
}
&.is-loading {
.widget-content {
align-items: center;
flex-wrap: nowrap;
justify-content: center;
}
}
}

View File

@@ -0,0 +1,2 @@
export const kServiceIFormicarium = 'kServiceIFormicarium';
export const kWidgetIFormicarium = 'kWidgetIFormicarium';

View File

@@ -0,0 +1,17 @@
/*!
* BTHLabs HomeHub - iFormicarium Integration (https://bthlabs.pl/)
* Copyright 2021-present BTHLabs
* Apache License Version 2.0
*/
import * as defs from './defs';
import {IFormicariumService} from './IFormicariumService';
import {IFormicariumWidgetView} from './IFormicariumWidgetView';
export const WIDGETS = {
[defs.kWidgetIFormicarium]: IFormicariumWidgetView,
};
export const SERVICES = {
[defs.kServiceIFormicarium]: IFormicariumService,
};

View File

@@ -0,0 +1,389 @@
import {FatalError, Widget} from '@bthlabs/homehub-components';
import {ServiceState} from '@bthlabs/homehub-core';
import {DateTime} from 'luxon';
import {shallow} from 'enzyme';
import React from 'react';
import {Form} from 'react-bootstrap';
import {IFormicariumService} from 'src/IFormicariumService';
import * as IFormicariumWidgetView from 'src/IFormicariumWidgetView';
import {IFormicariumDataFactory} from 'tests/__fixtures__/iformicarium';
describe('src/widgets/IFormicariumWidgetView', () => {
describe('IFormicariumWidgetSettingsView', () => {
let fakeNextCharacteristics = null;
let mockSetNextCharacteristics = null;
beforeEach(() => {
fakeNextCharacteristics = {
mqtt: '',
name: '',
topic: '',
};
mockSetNextCharacteristics = jasmine.createSpy();
});
it('calls the setNextCharacteristics callback when mqtt input changes', () => {
// Given
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetSettingsView
nextCharacteristics={fakeNextCharacteristics}
setNextCharacteristics={mockSetNextCharacteristics}
/>
);
// When
component.find(Form.Control).at(0).simulate('change', {
target: {value: 'thisisntright.local'},
});
// Then
expect(mockSetNextCharacteristics).toHaveBeenCalledWith({
...fakeNextCharacteristics,
mqtt: 'thisisntright.local',
});
});
it('calls the setNextCharacteristics callback when name input changes', () => {
// Given
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetSettingsView
nextCharacteristics={fakeNextCharacteristics}
setNextCharacteristics={mockSetNextCharacteristics}
/>
);
// When
component.find(Form.Control).at(1).simulate('change', {
target: {value: 'iformicarium'},
});
// Then
expect(mockSetNextCharacteristics).toHaveBeenCalledWith({
...fakeNextCharacteristics,
name: 'iformicarium',
});
});
it('calls the setNextCharacteristics callback when topic input changes', () => {
// Given
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetSettingsView
nextCharacteristics={fakeNextCharacteristics}
setNextCharacteristics={mockSetNextCharacteristics}
/>
);
// When
component.find(Form.Control).at(2).simulate('change', {
target: {value: 'iformicarium'},
});
// Then
expect(mockSetNextCharacteristics).toHaveBeenCalledWith({
...fakeNextCharacteristics,
topic: 'iformicarium',
});
});
it('renders empty when nextCharacteristics is empty', () => {
// Given
fakeNextCharacteristics = null;
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetSettingsView
nextCharacteristics={fakeNextCharacteristics}
setNextCharacteristics={mockSetNextCharacteristics}
/>
);
// Then
expect(component.isEmptyRender()).toBe(true);
});
it('configures and renders the city input', () => {
// Given
fakeNextCharacteristics = {
...fakeNextCharacteristics,
mqtt: 'thisisntright.local',
name: 'iformicarium',
topic: 'iformicarium',
};
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetSettingsView
nextCharacteristics={fakeNextCharacteristics}
setNextCharacteristics={mockSetNextCharacteristics}
/>
);
// When
const input = component.find(Form.Control).at(0);
// Then
expect(input.exists()).toBe(true);
expect(input.prop('value')).toEqual(fakeNextCharacteristics.mqtt);
});
it('configures and renders the name input', () => {
// Given
fakeNextCharacteristics = {
...fakeNextCharacteristics,
mqtt: 'thisisntright.local',
name: 'iformicarium',
topic: 'iformicarium',
};
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetSettingsView
nextCharacteristics={fakeNextCharacteristics}
setNextCharacteristics={mockSetNextCharacteristics}
/>
);
// When
const input = component.find(Form.Control).at(1);
// Then
expect(input.exists()).toBe(true);
expect(input.prop('value')).toEqual(fakeNextCharacteristics.name);
});
it('configures and renders the topic input', () => {
// Given
fakeNextCharacteristics = {
...fakeNextCharacteristics,
mqtt: 'thisisntright.local',
name: 'iformicarium',
topic: 'iformicarium',
};
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetSettingsView
nextCharacteristics={fakeNextCharacteristics}
setNextCharacteristics={mockSetNextCharacteristics}
/>
);
// When
const input = component.find(Form.Control).at(2);
// Then
expect(input.exists()).toBe(true);
expect(input.prop('value')).toEqual(fakeNextCharacteristics.topic);
});
});
describe('IFormicariumWidgetView', () => {
let fakeAppearance = null;
let fakeDateTime = null;
let fakeService = null;
let fakeServiceState = null;
let fakeData = null;
beforeEach(() => {
fakeAppearance = {color: 'red'};
fakeDateTime = DateTime.local(1987, 10, 3, 8, 0, 0);
fakeService = new IFormicariumService({
instance: 'testing',
layout: {x: 0, y: 0, h: 1, w: 1},
});
fakeData = IFormicariumDataFactory();
fakeServiceState = new ServiceState({
data: fakeData,
});
spyOn(DateTime, 'fromSeconds').and.returnValue(fakeDateTime);
spyOn(fakeDateTime, 'toLocaleString').and.returnValue(
'Formatted DateTime'
);
});
it('defines the widget attributes', () => {
// Then
expect(IFormicariumWidgetView.IFormicariumWidgetView.defaultLayout).toEqual({
h: jasmine.any(Number),
w: jasmine.any(Number),
});
expect(IFormicariumWidgetView.IFormicariumWidgetView.icon).toBeDefined();
expect(IFormicariumWidgetView.IFormicariumWidgetView.layoutConstraints).toEqual({
minH: jasmine.any(Number),
minW: jasmine.any(Number),
});
expect(IFormicariumWidgetView.IFormicariumWidgetView.settingsView).toEqual(
IFormicariumWidgetView.IFormicariumWidgetSettingsView
);
expect(IFormicariumWidgetView.IFormicariumWidgetView.title).toEqual('iFormicarium');
});
it('renders empty when service state is null', () => {
// Given
fakeServiceState = null;
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetView
appearance={fakeAppearance}
service={fakeService}
serviceState={fakeServiceState}
/>
);
// Then
expect(component.isEmptyRender()).toBe(true);
});
it('configures and renders the Widget', () => {
// Given
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetView
appearance={fakeAppearance}
service={fakeService}
serviceState={fakeServiceState}
/>
);
// When
const widget = component.find(Widget).at(0);
// Then
expect(widget.exists()).toBe(true);
expect(widget.prop('appearance')).toEqual(fakeAppearance);
});
it('renders the loader when state is loading', () => {
// Given
spyOn(fakeServiceState, 'isLoading').and.returnValue(true);
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetView
appearance={fakeAppearance}
service={fakeService}
serviceState={fakeServiceState}
/>
);
// When
const loader = component.find('Icon[_hint="Loader"]').at(0);
// Then
expect(loader.exists()).toBe(true);
expect(loader.prop('icon')).toBeDefined();
});
it('does not render the loader when state is not loading', () => {
// Given
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetView
appearance={fakeAppearance}
service={fakeService}
serviceState={fakeServiceState}
/>
);
// When
const loader = component.find('Icon[_hint="Loader"]').at(0);
// Then
expect(loader.exists()).toBe(false);
});
it('does not compute and render instance info when service state has no data', () => {
// Given
spyOn(fakeServiceState, 'hasData').and.returnValue(false);
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetView
appearance={fakeAppearance}
service={fakeService}
serviceState={fakeServiceState}
/>
);
// When
const instanceInfo = component.find('div[_hint="InstanceInfo"]').at(0);
// Then
expect(instanceInfo.exists()).toBe(false);
});
it('computes and renders instance info when service state has data', () => {
// Given
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetView
appearance={fakeAppearance}
service={fakeService}
serviceState={fakeServiceState}
/>
);
// When
const instanceInfo = component.find('div[_hint="InstanceInfo"]').at(0);
// Then
expect(instanceInfo.exists()).toBe(true);
const instanceName = component.find('h5[_hint="InstanceName"]').at(0);
expect(instanceName.exists()).toBe(true);
expect(instanceName.text()).toEqual(fakeData.name);
const instanceMetrics = component.find('div[_hint="InstanceMetrics"]').at(0);
expect(instanceMetrics.exists()).toBe(true);
const instanceDHTMetric = instanceMetrics.find('div[_hint="InstanceDHTMetric"]').at(0);
expect(instanceDHTMetric.exists()).toBe(true);
expect(instanceDHTMetric.find('p').at(0).text()).toEqual(
fakeData.dht['0'].name
);
expect(instanceDHTMetric.find('p').at(1).text()).toContain(
`Temp: ${fakeData.dht['0'].temp}`
);
expect(instanceDHTMetric.find('p').at(2).text()).toEqual(
`Humi: ${fakeData.dht['0'].humi}%`
);
const instanceFanMetric = instanceMetrics.find('div[_hint="InstanceFanMetric"]').at(0);
expect(instanceFanMetric.exists()).toBe(true);
expect(instanceFanMetric.find('p').at(1).text()).toEqual('25%');
const lastUpdate = component.find('small[_hint="LastUpdate"]').at(0);
expect(lastUpdate.exists()).toBe(true);
expect(lastUpdate.text()).toContain('Formatted DateTime');
expect(DateTime.fromSeconds).toHaveBeenCalledWith(fakeData.dt);
expect(fakeDateTime.toLocaleString).toHaveBeenCalledWith(
DateTime.TIME_SIMPLE
);
});
it('does not render FatalError if service state has no fatal error', () => {
// Given
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetView
appearance={fakeAppearance}
service={fakeService}
serviceState={fakeServiceState}
/>
);
// When
const fatalError = component.find(FatalError).at(0);
// Then
expect(fatalError.exists()).toBe(false);
});
it('configures and renders FatalError if service state has fatal error', () => {
// Given
spyOn(fakeServiceState, 'hasFatalError').and.returnValue(true);
const component = shallow(
<IFormicariumWidgetView.IFormicariumWidgetView
appearance={fakeAppearance}
service={fakeService}
serviceState={fakeServiceState}
/>
);
// When
const fatalError = component.find(FatalError).at(0);
// Then
expect(fatalError.exists()).toBe(true);
expect(fatalError.prop('service')).toEqual(fakeService);
expect(fatalError.prop('serviceState')).toEqual(fakeServiceState);
});
});
});

View File

@@ -0,0 +1,6 @@
require('regenerator-runtime');
require('tests/__setup__/enzyme.setup.js');
let testsContext = require.context('.', true, /\.spec\.js$/);
testsContext.keys().forEach(testsContext);

View File

@@ -0,0 +1,16 @@
export const IFormicariumDataFactory = () => {
return {
name: 'iformicarium',
uptime: 123,
heap: 65535,
dht: {
'0': {
name: 'dht1',
humi: 69,
temp: 25,
},
},
fan: 1,
dt: 560242800,
};
};

View File

@@ -0,0 +1,7 @@
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({
adapter: new Adapter(),
disableLifecycleMethods: true,
});

View File

@@ -0,0 +1,155 @@
import * as HomeHubCore from '@bthlabs/homehub-core';
import * as IFormicariumService from 'src/IFormicariumService';
import {IFormicariumDataFactory} from 'tests/__fixtures__/iformicarium';
describe('src/IFormicariumService', () => {
describe('IFormicariumService', () => {
let fakeCharacteristics = null;
let fakeResult = null;
beforeEach(() => {
fakeCharacteristics = {
mqtt: 'thisisntright.local',
name: 'iformicarium',
topic: 'iformicarium',
};
fakeResult = IFormicariumDataFactory();
spyOn(HomeHubCore.API.Services, 'start').and.returnValue(fakeResult);
spyOn(HomeHubCore.API.Services, 'stop').and.returnValue('ok');
});
describe('emptyCharacteristics', () => {
it('returns empty characteristics', () => {
// Given
const result = IFormicariumService.IFormicariumService.emptyCharacteristics();
// Then
expect(result).toEqual({
name: '',
mqtt: '',
topic: 'iformicarium',
});
});
});
describe('start', () => {
it('notifies subscribers with the result of start service API call', async () => {
// Given
const service = new IFormicariumService.IFormicariumService({
instance: 'testing',
characteristics: fakeCharacteristics,
});
spyOn(service, 'notify');
// When
await service.start();
// Then
expect(HomeHubCore.API.Services.start).toHaveBeenCalledWith(
service.kind, 'testing', fakeCharacteristics
);
expect(service.notify).toHaveBeenCalledWith(fakeResult);
});
});
describe('stop', () => {
it('calls the stop service API method', async () => {
// Given
const service = new IFormicariumService.IFormicariumService({
instance: 'testing',
characteristics: fakeCharacteristics,
});
// When
await service.stop();
// Then
expect(HomeHubCore.API.Services.stop).toHaveBeenCalledWith(
service.kind, 'testing'
);
});
});
describe('setCharacteristics', () => {
it('updates the service characteristics', () => {
// Given
const newCharacteristics = {
mqtt: 'thisisntrighttoo.local',
name: 'iformicarium2',
topic: 'iformicarium2',
};
const service = new IFormicariumService.IFormicariumService({
instance: 'testing',
characteristics: fakeCharacteristics,
});
spyOn(service, 'restart');
// When
service.setCharacteristics(newCharacteristics);
// Then
expect(service.characteristics).toEqual(newCharacteristics);
});
it('restarts the service if mqtt characteristic changed', () => {
// Given
const newCharacteristics = {
...fakeCharacteristics,
mqtt: 'thisisntrighttoo.local',
};
const service = new IFormicariumService.IFormicariumService({
instance: 'testing',
characteristics: fakeCharacteristics,
});
spyOn(service, 'restart');
// When
service.setCharacteristics(newCharacteristics);
// Then
expect(service.restart).toHaveBeenCalled();
});
it('restarts the service if name characteristic changed', () => {
// Given
const newCharacteristics = {
...fakeCharacteristics,
name: 'iformicarium2',
};
const service = new IFormicariumService.IFormicariumService({
instance: 'testing',
characteristics: fakeCharacteristics,
});
spyOn(service, 'restart');
// When
service.setCharacteristics(newCharacteristics);
// Then
expect(service.restart).toHaveBeenCalled();
});
it('restarts the service if topic characteristic changed', () => {
// Given
const newCharacteristics = {
...fakeCharacteristics,
topic: 'iformicarium2',
};
const service = new IFormicariumService.IFormicariumService({
instance: 'testing',
characteristics: fakeCharacteristics,
});
spyOn(service, 'restart');
// When
service.setCharacteristics(newCharacteristics);
// Then
expect(service.restart).toHaveBeenCalled();
});
});
});
});

View File

@@ -0,0 +1,110 @@
const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const webpack = require('webpack');
const CONTEXT = path.resolve(__dirname);
const SCSS_DIR = path.resolve(CONTEXT, 'scss');
const PROJECT_DIR = path.resolve(CONTEXT, 'src');
const OUTPUT_DIR = path.resolve(CONTEXT, 'lib');
const IS_PRODUCTION = (process.env['NODE_ENV'] === 'production');
const config = {
mode: 'development',
devtool: 'source-map',
context: CONTEXT,
entry: {
index: './src/index.js',
},
output: {
path: OUTPUT_DIR,
filename: '[name].js',
library: 'homehub_iformicarium',
libraryTarget: 'umd',
umdNamedDefine: true,
},
module: {
rules: [
{
test: /\.js?$/,
include: PROJECT_DIR,
use: [
'babel-loader',
],
},
{
test: /\.scss?$/,
include: PROJECT_DIR,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
{
test: /\.css?$/,
use: [
'style-loader',
'css-loader',
],
},
{
test: /\.(svg)$/,
include: PROJECT_DIR,
use: [
{
loader: 'babel-loader',
},
{
loader: 'react-svg-loader',
options: {
jsx: true,
},
},
],
},
{
test: /\.(png)$/,
include: PROJECT_DIR,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
],
},
{
test: /\.scss$/,
include: SCSS_DIR,
use: [
'null-loader',
],
},
],
},
resolve: {
alias: {
'scss': SCSS_DIR,
'src': PROJECT_DIR,
},
},
externals: {
'@bthlabs/homehub-components': '@bthlabs/homehub-components',
'@bthlabs/homehub-core': '@bthlabs/homehub-core',
'@bthlabs/homehub-icons': '@bthlabs/homehub-icons',
react: 'react',
'react-bootstrap': 'react-bootstrap',
'react-dom': 'react-dom',
},
plugins: [
new CleanWebpackPlugin(),
new webpack.DefinePlugin({
PRODUCTION: IS_PRODUCTION,
}),
],
};
module.exports = config;

File diff suppressed because it is too large Load Diff