You've already forked homehub
Release 1.3.0
This commit is contained in:
2
packages/homehub_tradfri/.eslintignore
Executable file
2
packages/homehub_tradfri/.eslintignore
Executable file
@@ -0,0 +1,2 @@
|
||||
lib/**/*.js
|
||||
homehub_tradfri/**/*.js
|
||||
26
packages/homehub_tradfri/.eslintrc.json
Normal file
26
packages/homehub_tradfri/.eslintrc.json
Normal 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_tradfri/.gitignore
vendored
Executable file
69
packages/homehub_tradfri/.gitignore
vendored
Executable 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_tradfri.egg-info/
|
||||
test-results.xml
|
||||
201
packages/homehub_tradfri/LICENSE.txt
Normal file
201
packages/homehub_tradfri/LICENSE.txt
Normal 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.
|
||||
1
packages/homehub_tradfri/MANIFEST.in
Normal file
1
packages/homehub_tradfri/MANIFEST.in
Normal file
@@ -0,0 +1 @@
|
||||
include LICENSE.txt NOTICE.txt README.md requirements.txt
|
||||
23
packages/homehub_tradfri/Makefile
Normal file
23
packages/homehub_tradfri/Makefile
Normal file
@@ -0,0 +1,23 @@
|
||||
PHONY: clean dev lint test build publish
|
||||
|
||||
clean:
|
||||
rm -rf build/ dist/ lib/ homehub_tradfri.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/*
|
||||
27
packages/homehub_tradfri/NOTICE.txt
Normal file
27
packages/homehub_tradfri/NOTICE.txt
Normal file
@@ -0,0 +1,27 @@
|
||||
BTHLabs HomeHub - IKEA Tradfri 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 - IKEA Tradfri Integration application 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
|
||||
3
packages/homehub_tradfri/README.md
Normal file
3
packages/homehub_tradfri/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# homehub_tradfri
|
||||
|
||||
BTHLabs HomeHub - IKEA Tradfri Integration
|
||||
22
packages/homehub_tradfri/babel.config.js
Normal file
22
packages/homehub_tradfri/babel.config.js
Normal 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',
|
||||
],
|
||||
};
|
||||
1
packages/homehub_tradfri/homehub_tradfri/__init__.py
Normal file
1
packages/homehub_tradfri/homehub_tradfri/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
__version__ = '1.3.0'
|
||||
1
packages/homehub_tradfri/homehub_tradfri/defs.py
Normal file
1
packages/homehub_tradfri/homehub_tradfri/defs.py
Normal file
@@ -0,0 +1 @@
|
||||
kServiceTradfri = 'kServiceTradfri'
|
||||
163
packages/homehub_tradfri/homehub_tradfri/services.py
Normal file
163
packages/homehub_tradfri/homehub_tradfri/services.py
Normal file
@@ -0,0 +1,163 @@
|
||||
# -*- coding: utf8 -*-
|
||||
import asyncio
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
import aiojobs.aiohttp
|
||||
from homehub_backend.lib.services import BaseService, ServiceData
|
||||
from homehub_tradfri.defs import kServiceTradfri
|
||||
import pytradfri
|
||||
import pytradfri.api.aiocoap_api
|
||||
|
||||
LOGGER = logging.getLogger('homehub.tradfri.services')
|
||||
|
||||
|
||||
class TradfriService(BaseService):
|
||||
KIND = kServiceTradfri
|
||||
|
||||
def __init__(self, app, instance, characteristics):
|
||||
super(TradfriService, self).__init__(app, instance, characteristics)
|
||||
self.api_factory = None
|
||||
self.gateway = None
|
||||
self.job = None
|
||||
self.started = False
|
||||
|
||||
def state_key(self):
|
||||
state_key = super(TradfriService, self).state_key()
|
||||
return '{state_key}.{host}.{key}'.format(
|
||||
state_key=state_key,
|
||||
host=self.characteristics['host'],
|
||||
key=self.characteristics['key'],
|
||||
)
|
||||
|
||||
async def current_data(self):
|
||||
result = ServiceData()
|
||||
|
||||
try:
|
||||
result.data = {
|
||||
'groups': await self.get_groups(),
|
||||
'lights': await self.get_lights(),
|
||||
}
|
||||
except Exception as exc:
|
||||
LOGGER.error('Unhandled exception!', exc_info=exc)
|
||||
result.exception = exc
|
||||
|
||||
return result
|
||||
|
||||
async def call_api(self, commands):
|
||||
api = self.api_factory.request
|
||||
result = await api(commands)
|
||||
|
||||
return result
|
||||
|
||||
async def get_lights(self):
|
||||
lights_command = self.gateway.get_devices()
|
||||
lights_commands = await self.call_api(lights_command)
|
||||
|
||||
result = await self.call_api(lights_commands)
|
||||
return [
|
||||
{
|
||||
'id': light.id,
|
||||
'name': light.name,
|
||||
'state': light.light_control.lights[0].state,
|
||||
'reachable': light.reachable,
|
||||
'dimmer': light.light_control.lights[0].dimmer,
|
||||
}
|
||||
for light in filter(lambda x: x.has_light_control, result)
|
||||
]
|
||||
|
||||
async def get_light(self, light_id):
|
||||
light_command = self.gateway.get_device(light_id)
|
||||
light = await self.call_api(light_command)
|
||||
|
||||
return light
|
||||
|
||||
async def set_light_state(self, light_id, next_state):
|
||||
light = await self.get_light(light_id)
|
||||
|
||||
set_state_command = light.light_control.set_state(next_state, index=0)
|
||||
await self.call_api(set_state_command)
|
||||
|
||||
async def get_groups(self):
|
||||
groups_command = self.gateway.get_groups()
|
||||
groups_commands = await self.call_api(groups_command)
|
||||
|
||||
result = await self.call_api(groups_commands)
|
||||
return [
|
||||
{
|
||||
'id': group.id,
|
||||
'name': group.name,
|
||||
'member_ids': group.member_ids,
|
||||
}
|
||||
for group in result
|
||||
]
|
||||
|
||||
async def set_lights_state(self, light_ids, next_state):
|
||||
_ = await asyncio.gather(*[
|
||||
self.set_light_state(light_id, next_state)
|
||||
for light_id in light_ids
|
||||
])
|
||||
|
||||
lights = await self.get_lights()
|
||||
return list(filter(lambda light: light['id'] in light_ids, lights))
|
||||
|
||||
async def worker(self):
|
||||
while True:
|
||||
await asyncio.sleep(60)
|
||||
await self.notify()
|
||||
|
||||
if self.job.closed:
|
||||
break
|
||||
|
||||
async def start(self):
|
||||
if not self.started:
|
||||
psk_id = None
|
||||
psk = None
|
||||
|
||||
if self.state is not None:
|
||||
psk_id = self.state.get('psk_id')
|
||||
psk = self.state.get('psk')
|
||||
|
||||
if not psk_id:
|
||||
psk_id = uuid.uuid4().hex
|
||||
|
||||
LOGGER.debug('TradfriService.start() {psk_id} {has_psk} {characteristics}'.format(
|
||||
psk_id=psk_id,
|
||||
has_psk=(psk is not None),
|
||||
characteristics=self.characteristics,
|
||||
))
|
||||
|
||||
self.api_factory = pytradfri.api.aiocoap_api.APIFactory(
|
||||
host=self.characteristics['host'],
|
||||
psk_id=psk_id,
|
||||
psk=psk,
|
||||
)
|
||||
|
||||
if not psk:
|
||||
psk = await self.api_factory.generate_psk(
|
||||
self.characteristics['key'],
|
||||
)
|
||||
|
||||
self.gateway = pytradfri.Gateway()
|
||||
|
||||
if not self.job:
|
||||
scheduler = aiojobs.aiohttp.get_scheduler_from_app(self.app)
|
||||
self.job = await scheduler.spawn(self.worker())
|
||||
|
||||
self.set_state({
|
||||
'psk_id': psk_id,
|
||||
'psk': psk,
|
||||
})
|
||||
|
||||
self.started = True
|
||||
|
||||
async def stop(self):
|
||||
LOGGER.debug('TradfriService.stop()')
|
||||
if self.gateway:
|
||||
self.gateway = None
|
||||
|
||||
if self.api_factory:
|
||||
self.api_factory = None
|
||||
|
||||
if self.job is not None and not self.job.closed:
|
||||
await self.job.close()
|
||||
1
packages/homehub_tradfri/homehub_tradfri/testing/.gitignore
vendored
Normal file
1
packages/homehub_tradfri/homehub_tradfri/testing/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
state.json
|
||||
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
|
||||
DEBUG = False
|
||||
TESTING = True
|
||||
STATE_PATH = os.path.join(os.path.dirname(__file__), 'state.json')
|
||||
@@ -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)
|
||||
541
packages/homehub_tradfri/homehub_tradfri/tests/test_services.py
Normal file
541
packages/homehub_tradfri/homehub_tradfri/tests/test_services.py
Normal file
@@ -0,0 +1,541 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from unittest import mock
|
||||
import uuid
|
||||
|
||||
import aiojobs
|
||||
import factory
|
||||
import pytradfri
|
||||
import pytradfri.api.aiocoap_api as pytradfri_api
|
||||
|
||||
from homehub_tradfri import services
|
||||
|
||||
|
||||
class LightFactory(factory.StubFactory):
|
||||
state = True
|
||||
dimmer = 128
|
||||
|
||||
|
||||
class LightControlFactory(factory.StubFactory):
|
||||
lights = factory.LazyFunction(lambda: [LightFactory()])
|
||||
set_state = factory.LazyFunction(
|
||||
lambda: mock.Mock(return_value='fake_set_light_state_command'),
|
||||
)
|
||||
|
||||
|
||||
class DeviceFactory(factory.StubFactory):
|
||||
id = factory.LazyFunction(lambda: str(uuid.uuid4()))
|
||||
name = factory.Faker('domain_word')
|
||||
light_control = factory.SubFactory(LightControlFactory)
|
||||
reachable = True
|
||||
has_light_control = True
|
||||
|
||||
|
||||
class GroupFactory(factory.StubFactory):
|
||||
id = factory.LazyFunction(lambda: str(uuid.uuid4()))
|
||||
name = factory.Faker('domain_word')
|
||||
member_ids = factory.LazyFunction(lambda: ['fake_light1', 'fake_light2'])
|
||||
|
||||
|
||||
class Test_TradfriService:
|
||||
def _valid_characteristics(self):
|
||||
return {
|
||||
'host': 'thisisntright.local',
|
||||
'key': 'thisisntright',
|
||||
}
|
||||
|
||||
def _fake_lights(self):
|
||||
return [
|
||||
{
|
||||
'id': 'light1',
|
||||
'name': 'Light 1',
|
||||
'state': True,
|
||||
'reachable': False,
|
||||
'dimmer': 128,
|
||||
},
|
||||
{
|
||||
'id': 'light2',
|
||||
'name': 'Light 2',
|
||||
'state': True,
|
||||
'reachable': False,
|
||||
'dimmer': 128,
|
||||
},
|
||||
{
|
||||
'id': 'light3',
|
||||
'name': 'Light 3',
|
||||
'state': True,
|
||||
'reachable': False,
|
||||
'dimmer': 128,
|
||||
},
|
||||
]
|
||||
|
||||
def _fake_groups(self):
|
||||
return [
|
||||
{
|
||||
'id': 'group1',
|
||||
'name': 'Group 1',
|
||||
'member_ids': ['light1'],
|
||||
},
|
||||
]
|
||||
|
||||
def test_init(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
|
||||
# Then
|
||||
assert service.api_factory is None
|
||||
assert service.gateway is None
|
||||
assert service.job is None
|
||||
assert service.started is False
|
||||
|
||||
def test_state_key(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
|
||||
# When
|
||||
result = service.state_key()
|
||||
|
||||
# Then
|
||||
assert result.endswith('.thisisntright.local.thisisntright')
|
||||
|
||||
async def test_current_data(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
|
||||
with mock.patch.object(service, 'get_groups') as mock_get_groups:
|
||||
with mock.patch.object(service, 'get_lights') as mock_get_lights:
|
||||
fake_groups = self._fake_groups()
|
||||
mock_get_groups.return_value = fake_groups
|
||||
|
||||
fake_lights = self._fake_lights()
|
||||
mock_get_lights.return_value = fake_lights
|
||||
|
||||
# When
|
||||
result = await service.current_data()
|
||||
|
||||
# Then
|
||||
assert result.data == {
|
||||
'groups': fake_groups,
|
||||
'lights': fake_lights,
|
||||
}
|
||||
assert result.exception is None
|
||||
|
||||
async def test_current_data_get_groups_exception(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
|
||||
with mock.patch.object(service, 'get_groups') as mock_get_groups:
|
||||
with mock.patch.object(service, 'get_lights') as mock_get_lights:
|
||||
fake_get_groups_error = RuntimeError('FIAL')
|
||||
mock_get_groups.side_effect = fake_get_groups_error
|
||||
|
||||
fake_lights = self._fake_lights()
|
||||
mock_get_lights.return_value = fake_lights
|
||||
|
||||
# When
|
||||
result = await service.current_data()
|
||||
|
||||
# Then
|
||||
assert result.data is None
|
||||
assert result.exception == fake_get_groups_error
|
||||
|
||||
async def test_current_data_get_lights_exception(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
|
||||
with mock.patch.object(service, 'get_groups') as mock_get_groups:
|
||||
with mock.patch.object(service, 'get_lights') as mock_get_lights:
|
||||
fake_groups = self._fake_groups()
|
||||
mock_get_groups.return_value = fake_groups
|
||||
|
||||
fake_get_lights_error = RuntimeError('FIAL')
|
||||
mock_get_lights.side_effect = fake_get_lights_error
|
||||
|
||||
# When
|
||||
result = await service.current_data()
|
||||
|
||||
# Then
|
||||
assert result.data is None
|
||||
assert result.exception == fake_get_lights_error
|
||||
|
||||
async def test_call_api(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
|
||||
service.api_factory = mock.Mock(
|
||||
spec=pytradfri_api.APIFactory,
|
||||
)
|
||||
service.api_factory.request = mock.AsyncMock(
|
||||
return_value='fake_api_result',
|
||||
)
|
||||
|
||||
fake_commands = ['fake', 'commands']
|
||||
|
||||
# When
|
||||
result = await service.call_api(fake_commands)
|
||||
|
||||
# Then
|
||||
assert result == 'fake_api_result'
|
||||
service.api_factory.request.assert_called_with(fake_commands)
|
||||
|
||||
async def test_get_lights(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
service.gateway = mock.Mock(spec=pytradfri.Gateway)
|
||||
|
||||
fake_get_devices_command = 'fake_get_devices_command'
|
||||
service.gateway.get_devices.return_value = fake_get_devices_command
|
||||
|
||||
with mock.patch.object(service, 'call_api') as mock_call_api:
|
||||
fake_devices = [
|
||||
DeviceFactory(has_light_control=True),
|
||||
DeviceFactory(has_light_control=False),
|
||||
]
|
||||
mock_call_api.return_value = fake_devices
|
||||
|
||||
# When
|
||||
result = await service.get_lights()
|
||||
|
||||
# Then
|
||||
assert len(result) == 1
|
||||
|
||||
light_ids = [light['id'] for light in result]
|
||||
assert light_ids == [fake_devices[0].id]
|
||||
|
||||
light = result[0]
|
||||
assert light['id'] == fake_devices[0].id
|
||||
assert light['name'] == fake_devices[0].name
|
||||
assert light['state'] == fake_devices[0].light_control.lights[0].state
|
||||
assert light['reachable'] == fake_devices[0].reachable
|
||||
assert light['dimmer'] == fake_devices[0].light_control.lights[0].dimmer
|
||||
|
||||
async def test_get_light(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
service.gateway = mock.Mock(spec=pytradfri.Gateway)
|
||||
|
||||
fake_get_device_command = 'fake_get_device_command'
|
||||
service.gateway.get_device.return_value = fake_get_device_command
|
||||
|
||||
with mock.patch.object(service, 'call_api') as mock_call_api:
|
||||
fake_device = DeviceFactory()
|
||||
mock_call_api.return_value = fake_device
|
||||
|
||||
# When
|
||||
result = await service.get_light('some_light')
|
||||
|
||||
# Then
|
||||
assert result == fake_device
|
||||
|
||||
async def test_set_light_state(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
|
||||
with mock.patch.object(service, 'get_light') as mock_get_light:
|
||||
with mock.patch.object(service, 'call_api') as mock_call_api:
|
||||
fake_light = DeviceFactory()
|
||||
mock_get_light.return_value = fake_light
|
||||
|
||||
mock_call_api.return_value = True
|
||||
|
||||
# When
|
||||
await service.set_light_state('some_light', True)
|
||||
|
||||
# Then
|
||||
mock_get_light.assert_called_with('some_light')
|
||||
fake_light.light_control.set_state.assert_called_with(
|
||||
True, index=0,
|
||||
)
|
||||
mock_call_api.assert_called_with(
|
||||
'fake_set_light_state_command',
|
||||
)
|
||||
|
||||
async def test_get_groups(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
service.gateway = mock.Mock(spec=pytradfri.Gateway)
|
||||
|
||||
fake_get_groups_command = 'fake_get_groups_command'
|
||||
service.gateway.get_groups.return_value = fake_get_groups_command
|
||||
|
||||
with mock.patch.object(service, 'call_api') as mock_call_api:
|
||||
fake_groups = [GroupFactory(), GroupFactory()]
|
||||
mock_call_api.return_value = fake_groups
|
||||
|
||||
# When
|
||||
result = await service.get_groups()
|
||||
|
||||
# Then
|
||||
assert len(result) == 2
|
||||
|
||||
group = result[0]
|
||||
assert group['id'] == fake_groups[0].id
|
||||
assert group['name'] == fake_groups[0].name
|
||||
assert group['member_ids'] == fake_groups[0].member_ids
|
||||
|
||||
async def test_set_lights_state(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
|
||||
with mock.patch.object(service, 'set_light_state') as mock_set_light_state:
|
||||
with mock.patch.object(service, 'get_lights') as mock_get_lights:
|
||||
fake_lights = self._fake_lights()
|
||||
mock_get_lights.return_value = fake_lights
|
||||
|
||||
# When
|
||||
result = await service.set_lights_state(
|
||||
['light1', 'light2'], True,
|
||||
)
|
||||
|
||||
# Then
|
||||
assert result == [fake_lights[0], fake_lights[1]]
|
||||
assert mock_set_light_state.call_count == 2
|
||||
mock_set_light_state.assert_any_call('light1', True)
|
||||
mock_set_light_state.assert_any_call('light2', True)
|
||||
assert mock_get_lights.called is True
|
||||
|
||||
async def test_worker(self, homehub_app):
|
||||
# Given
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', self._valid_characteristics(),
|
||||
)
|
||||
service.job = mock.Mock(spec=aiojobs._job.Job)
|
||||
service.job.closed = True
|
||||
service.update_weather = mock.AsyncMock()
|
||||
service.notify = mock.AsyncMock()
|
||||
|
||||
with mock.patch('asyncio.sleep') as mock_asyncio_sleep:
|
||||
# When
|
||||
await service.worker()
|
||||
|
||||
# Then
|
||||
mock_asyncio_sleep.assert_called_with(60)
|
||||
assert service.notify.called is True
|
||||
|
||||
@mock.patch('aiojobs.aiohttp.get_scheduler_from_app')
|
||||
async def test_start(self, mock_get_scheduler, homehub_app):
|
||||
# Given
|
||||
fake_scheduler = mock.Mock(spec=aiojobs._scheduler.Scheduler)
|
||||
mock_get_scheduler.return_value = fake_scheduler
|
||||
|
||||
fake_job = mock.Mock(spec=aiojobs._job.Job)
|
||||
fake_scheduler.spawn.return_value = fake_job
|
||||
|
||||
characteristics = self._valid_characteristics()
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', characteristics,
|
||||
)
|
||||
|
||||
fake_gateway = mock.Mock(spec=pytradfri.Gateway)
|
||||
|
||||
fake_api_factory = mock.Mock(spec=pytradfri_api.APIFactory)
|
||||
fake_api_factory.generate_psk.return_value = 'fake_psk'
|
||||
|
||||
fake_worker = mock.AsyncMock()
|
||||
service.worker = mock.Mock()
|
||||
service.worker.return_value = fake_worker
|
||||
|
||||
with mock.patch('pytradfri.Gateway') as mock_gateway:
|
||||
with mock.patch.object(pytradfri_api, 'APIFactory') as mock_api_factory:
|
||||
with mock.patch.object(service, 'set_state'):
|
||||
mock_gateway.return_value = fake_gateway
|
||||
mock_api_factory.return_value = fake_api_factory
|
||||
|
||||
# When
|
||||
await service.start()
|
||||
|
||||
# Then
|
||||
assert service.api_factory == fake_api_factory
|
||||
pytradfri_api.APIFactory.assert_called_with(
|
||||
host=characteristics['host'],
|
||||
psk_id=mock.ANY,
|
||||
psk=None,
|
||||
)
|
||||
psk_id = pytradfri_api.APIFactory.call_args.kwargs['psk_id']
|
||||
assert isinstance(psk_id, str)
|
||||
|
||||
fake_api_factory.generate_psk.assert_called_with(
|
||||
characteristics['key'],
|
||||
)
|
||||
|
||||
assert service.gateway == fake_gateway
|
||||
assert mock_gateway.called
|
||||
|
||||
assert service.job == fake_job
|
||||
mock_get_scheduler.assert_called_with(homehub_app)
|
||||
fake_scheduler.spawn.assert_called_with(fake_worker)
|
||||
|
||||
service.set_state.assert_called_with({
|
||||
'psk_id': psk_id,
|
||||
'psk': 'fake_psk',
|
||||
})
|
||||
|
||||
assert service.started is True
|
||||
|
||||
@mock.patch('aiojobs.aiohttp.get_scheduler_from_app')
|
||||
async def test_start_with_state(self, mock_get_scheduler, homehub_app):
|
||||
# Given
|
||||
fake_scheduler = mock.Mock(spec=aiojobs._scheduler.Scheduler)
|
||||
mock_get_scheduler.return_value = fake_scheduler
|
||||
|
||||
fake_job = mock.Mock(spec=aiojobs._job.Job)
|
||||
fake_scheduler.spawn.return_value = fake_job
|
||||
|
||||
characteristics = self._valid_characteristics()
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', characteristics,
|
||||
)
|
||||
service.state = {
|
||||
'psk_id': 'state_psk_id',
|
||||
'psk': 'state_psk',
|
||||
}
|
||||
|
||||
fake_gateway = mock.Mock(spec=pytradfri.Gateway)
|
||||
fake_api_factory = mock.Mock(spec=pytradfri_api.APIFactory)
|
||||
|
||||
fake_worker = mock.AsyncMock()
|
||||
service.worker = mock.Mock()
|
||||
service.worker.return_value = fake_worker
|
||||
|
||||
with mock.patch('pytradfri.Gateway') as mock_gateway:
|
||||
with mock.patch.object(pytradfri_api, 'APIFactory') as mock_api_factory:
|
||||
with mock.patch.object(service, 'set_state'):
|
||||
mock_gateway.return_value = fake_gateway
|
||||
mock_api_factory.return_value = fake_api_factory
|
||||
|
||||
# When
|
||||
await service.start()
|
||||
|
||||
# Then
|
||||
assert service.api_factory == fake_api_factory
|
||||
mock_api_factory.assert_called_with(
|
||||
host=characteristics['host'],
|
||||
psk_id='state_psk_id',
|
||||
psk='state_psk',
|
||||
)
|
||||
|
||||
assert not fake_api_factory.generate_psk.called
|
||||
|
||||
service.set_state.assert_called_with({
|
||||
'psk_id': 'state_psk_id',
|
||||
'psk': 'state_psk',
|
||||
})
|
||||
|
||||
@mock.patch('aiojobs.aiohttp.get_scheduler_from_app')
|
||||
async def test_start_already_started(self, mock_get_scheduler, homehub_app):
|
||||
# Given
|
||||
fake_scheduler = mock.Mock(spec=aiojobs._scheduler.Scheduler)
|
||||
mock_get_scheduler.return_value = fake_scheduler
|
||||
|
||||
characteristics = self._valid_characteristics()
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', characteristics,
|
||||
)
|
||||
service.started = True
|
||||
|
||||
fake_job = mock.Mock(spec=aiojobs._job.Job)
|
||||
service.job = fake_job
|
||||
|
||||
fake_gateway = mock.Mock(spec=pytradfri.Gateway)
|
||||
service.gateway = fake_gateway
|
||||
|
||||
fake_api_factory = mock.Mock(spec=pytradfri_api.APIFactory)
|
||||
service.api_factory = fake_api_factory
|
||||
|
||||
with mock.patch('pytradfri.Gateway') as mock_gateway:
|
||||
with mock.patch.object(pytradfri_api, 'APIFactory') as mock_api_factory:
|
||||
with mock.patch.object(service, 'set_state'):
|
||||
# When
|
||||
await service.start()
|
||||
|
||||
# Then
|
||||
assert service.api_factory == fake_api_factory
|
||||
assert not mock_api_factory.called
|
||||
|
||||
assert not fake_api_factory.generate_psk.called
|
||||
|
||||
assert service.gateway == fake_gateway
|
||||
assert not mock_gateway.called
|
||||
|
||||
assert service.job == fake_job
|
||||
assert not mock_get_scheduler.called
|
||||
assert not fake_scheduler.spawn.called
|
||||
|
||||
assert not service.set_state.called
|
||||
|
||||
assert service.started is True
|
||||
|
||||
async def test_stop(self, homehub_app):
|
||||
# Given
|
||||
characteristics = self._valid_characteristics()
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', characteristics,
|
||||
)
|
||||
|
||||
fake_job = mock.Mock(spec=aiojobs._job.Job)
|
||||
fake_job.closed = False
|
||||
service.job = fake_job
|
||||
|
||||
fake_gateway = mock.Mock(spec=pytradfri.Gateway)
|
||||
service.gateway = fake_gateway
|
||||
|
||||
fake_api_factory = mock.Mock(spec=pytradfri_api.APIFactory)
|
||||
service.api_factory = fake_api_factory
|
||||
|
||||
with mock.patch('pytradfri.Gateway'):
|
||||
with mock.patch.object(pytradfri_api, 'APIFactory'):
|
||||
with mock.patch.object(service, 'set_state'):
|
||||
# When
|
||||
await service.stop()
|
||||
|
||||
# Then
|
||||
assert service.api_factory is None
|
||||
assert service.gateway is None
|
||||
assert service.job.close.called
|
||||
|
||||
async def test_stop_already_stopped(self, homehub_app):
|
||||
# Given
|
||||
characteristics = self._valid_characteristics()
|
||||
service = services.TradfriService(
|
||||
homehub_app, 'testing', characteristics,
|
||||
)
|
||||
|
||||
fake_job = mock.Mock(spec=aiojobs._job.Job)
|
||||
fake_job.closed = True
|
||||
service.job = fake_job
|
||||
|
||||
fake_gateway = mock.Mock(spec=pytradfri.Gateway)
|
||||
service.gateway = fake_gateway
|
||||
|
||||
fake_api_factory = mock.Mock(spec=pytradfri_api.APIFactory)
|
||||
service.api_factory = fake_api_factory
|
||||
|
||||
with mock.patch('pytradfri.Gateway'):
|
||||
with mock.patch.object(pytradfri_api, 'APIFactory'):
|
||||
with mock.patch.object(service, 'set_state'):
|
||||
# When
|
||||
await service.stop()
|
||||
|
||||
# Then
|
||||
assert not service.job.close.called
|
||||
70
packages/homehub_tradfri/karma.conf.js
Normal file
70
packages/homehub_tradfri/karma.conf.js
Normal 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',
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
74
packages/homehub_tradfri/package.json
Normal file
74
packages/homehub_tradfri/package.json
Normal file
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"name": "@bthlabs/homehub-tradfri",
|
||||
"version": "1.3.0",
|
||||
"description": "BTHLabs HomeHub - IKEA Tradfri Integration",
|
||||
"main": "lib/index.js",
|
||||
"author": "BTHLabs <contact@bthlabs.pl>",
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"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",
|
||||
"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",
|
||||
"lodash": "4.17.15",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
10
packages/homehub_tradfri/requirements-dev.txt
Normal file
10
packages/homehub_tradfri/requirements-dev.txt
Normal file
@@ -0,0 +1,10 @@
|
||||
-r requirements.txt
|
||||
factory-boy==3.2.0
|
||||
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
|
||||
2
packages/homehub_tradfri/requirements.txt
Normal file
2
packages/homehub_tradfri/requirements.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
homehub_backend>=1.3.0
|
||||
pytradfri[async]==6.4.0
|
||||
10
packages/homehub_tradfri/setup.cfg
Normal file
10
packages/homehub_tradfri/setup.cfg
Normal file
@@ -0,0 +1,10 @@
|
||||
[flake8]
|
||||
exclude = build/,lib/,node_modules/
|
||||
ignore = E402
|
||||
max-line-length = 120
|
||||
|
||||
[tool:pytest]
|
||||
testpaths =
|
||||
homehub_tradfri/tests
|
||||
env =
|
||||
HOMEHUB_SETTINGS_MODULE=homehub_tradfri.testing.settings
|
||||
53
packages/homehub_tradfri/setup.py
Normal file
53
packages/homehub_tradfri/setup.py
Normal 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_tradfri.{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_tradfri/__init__.py', 'rt', encoding='utf8') as f:
|
||||
version = re.search(r"""__version__ = '(.*?)'""", f.read()).group(1)
|
||||
|
||||
packages = ['homehub_tradfri']
|
||||
packages.extend(_process_packages(find_packages(
|
||||
'homehub_tradfri', exclude=[
|
||||
'testing', 'testing.*', 'tests', 'tests.*',
|
||||
],
|
||||
)))
|
||||
|
||||
setup(
|
||||
name='homehub_tradfri',
|
||||
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 - IKEA Tradfri Integration',
|
||||
long_description=readme,
|
||||
classifiers=[
|
||||
'License :: OSI Approved :: Apache Software License',
|
||||
],
|
||||
packages=packages,
|
||||
include_package_data=True,
|
||||
python_requires='>=3.7',
|
||||
install_requires=requirements,
|
||||
)
|
||||
47
packages/homehub_tradfri/src/TradfriService.js
Normal file
47
packages/homehub_tradfri/src/TradfriService.js
Normal file
@@ -0,0 +1,47 @@
|
||||
import {API, BaseService} from '@bthlabs/homehub-core';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
|
||||
import {kServiceTradfri, kWidgetTradfri} from './defs';
|
||||
|
||||
export class TradfriService extends BaseService {
|
||||
static kind = kServiceTradfri;
|
||||
static widget = kWidgetTradfri;
|
||||
static emptyCharacteristics () {
|
||||
return {
|
||||
host: '',
|
||||
key: '',
|
||||
};
|
||||
}
|
||||
async start () {
|
||||
const result = await API.Services.start(
|
||||
this.kind, this.instance, this.characteristics
|
||||
);
|
||||
|
||||
this.notify(result);
|
||||
}
|
||||
async stop () {
|
||||
return API.Services.stop(this.kind, this.instance);
|
||||
}
|
||||
setCharacteristics (newCharacteristics) {
|
||||
const shouldRestart = Object.keys(
|
||||
TradfriService.emptyCharacteristics()
|
||||
).some(
|
||||
(key) => {
|
||||
return !isEqual(this.characteristics[key], newCharacteristics[key]);
|
||||
}
|
||||
);
|
||||
|
||||
super.setCharacteristics(newCharacteristics);
|
||||
|
||||
if (shouldRestart) {
|
||||
this.restart();
|
||||
}
|
||||
}
|
||||
setLightsState = async (lightIds, nextState) => {
|
||||
const result = await API.Services.use(
|
||||
kServiceTradfri, this.instance, 'set_lights_state', [lightIds, nextState]
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
179
packages/homehub_tradfri/src/TradfriWidgetView.js
Normal file
179
packages/homehub_tradfri/src/TradfriWidgetView.js
Normal file
@@ -0,0 +1,179 @@
|
||||
import {FatalError, Widget} from '@bthlabs/homehub-components';
|
||||
import {
|
||||
IconArrowsRotate, IconBasicLightbulb, Icon,
|
||||
} from '@bthlabs/homehub-icons';
|
||||
import ClassName from 'classnames';
|
||||
import React from 'react';
|
||||
import {Form} from 'react-bootstrap';
|
||||
|
||||
import './TradfriWidgetView.scss';
|
||||
|
||||
export const TradfriWidgetSettingsView = (props) => {
|
||||
const onHostInputChange = React.useCallback(
|
||||
(event) => {
|
||||
props.setNextCharacteristics({
|
||||
...props.nextCharacteristics,
|
||||
host: event.target.value,
|
||||
});
|
||||
},
|
||||
[props]
|
||||
);
|
||||
|
||||
const onKeyInputChange = React.useCallback(
|
||||
(event) => {
|
||||
props.setNextCharacteristics({
|
||||
...props.nextCharacteristics,
|
||||
key: event.target.value,
|
||||
});
|
||||
},
|
||||
[props]
|
||||
);
|
||||
|
||||
if (!props.nextCharacteristics) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Form>
|
||||
<Form.Group controlId="input-host">
|
||||
<Form.Label>Host</Form.Label>
|
||||
<Form.Control
|
||||
size="sm"
|
||||
value={props.nextCharacteristics.host}
|
||||
onChange={onHostInputChange}
|
||||
/>
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group controlId="input-key">
|
||||
<Form.Label>Key</Form.Label>
|
||||
<Form.Control
|
||||
size="sm"
|
||||
value={props.nextCharacteristics.key}
|
||||
onChange={onKeyInputChange}
|
||||
/>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export const Group = (props) => {
|
||||
const lights = React.useMemo(
|
||||
() => {
|
||||
return props.lights.filter((light) => {
|
||||
return props.group.member_ids.includes(light.id);
|
||||
});
|
||||
},
|
||||
[props]
|
||||
);
|
||||
|
||||
const isOn = React.useMemo(
|
||||
() => {
|
||||
return lights.every((light) => {
|
||||
return light.state;
|
||||
});
|
||||
},
|
||||
[lights]
|
||||
);
|
||||
|
||||
const onClick = React.useCallback(
|
||||
() => {
|
||||
props.onSetLightsState(
|
||||
lights.map((light) => {
|
||||
return light.id;
|
||||
}),
|
||||
!isOn
|
||||
);
|
||||
},
|
||||
[props, lights, isOn]
|
||||
);
|
||||
|
||||
const groupClassName = ClassName('group', {
|
||||
'group-on': isOn,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={groupClassName} onClick={onClick}>
|
||||
<span _hint="GroupName">{props.group.name}</span>
|
||||
<Icon icon={IconBasicLightbulb} size={24} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const TradfriWidgetView = (props) => {
|
||||
const onGroupSetLightsState = React.useCallback(
|
||||
(lightIds, nextState) => {
|
||||
(async () => {
|
||||
const nextServiceState = {
|
||||
data: {
|
||||
...props.serviceState.data(),
|
||||
lights: props.serviceState.data().lights.map((light) => {
|
||||
if (lightIds.includes(light.id)) {
|
||||
return {
|
||||
...light,
|
||||
state: nextState,
|
||||
};
|
||||
}
|
||||
|
||||
return light;
|
||||
}),
|
||||
},
|
||||
};
|
||||
props.setServiceState(nextServiceState);
|
||||
|
||||
await props.service.setLightsState(lightIds, nextState);
|
||||
})();
|
||||
},
|
||||
[props]
|
||||
);
|
||||
|
||||
if (props.serviceState === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const className = ClassName('TradfriWidgetView', {
|
||||
'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() && props.serviceState.data().groups.map((group) => {
|
||||
return (
|
||||
<Group
|
||||
key={`${group.id}`}
|
||||
group={group}
|
||||
lights={props.serviceState.data().lights}
|
||||
onSetLightsState={onGroupSetLightsState}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{props.serviceState.hasFatalError() &&
|
||||
<FatalError
|
||||
service={props.service}
|
||||
serviceState={props.serviceState}
|
||||
/>
|
||||
}
|
||||
</Widget>
|
||||
);
|
||||
};
|
||||
|
||||
TradfriWidgetView.defaultLayout = {
|
||||
h: 4,
|
||||
w: 6,
|
||||
};
|
||||
TradfriWidgetView.icon = IconBasicLightbulb;
|
||||
TradfriWidgetView.layoutConstraints = {
|
||||
minH: 4,
|
||||
minW: 6,
|
||||
};
|
||||
TradfriWidgetView.settingsView = TradfriWidgetSettingsView;
|
||||
TradfriWidgetView.title = 'Tradfri';
|
||||
57
packages/homehub_tradfri/src/TradfriWidgetView.scss
Normal file
57
packages/homehub_tradfri/src/TradfriWidgetView.scss
Normal file
@@ -0,0 +1,57 @@
|
||||
.TradfriWidgetView {
|
||||
color: white;
|
||||
|
||||
.widget-content {
|
||||
align-content: start;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
height: 100%;
|
||||
margin-left: -8px;
|
||||
overflow-y: scroll;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
&.is-loading {
|
||||
.widget-content {
|
||||
align-items: center;
|
||||
flex-wrap: nowrap;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.group {
|
||||
border: 1px solid white;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
height: 48px;
|
||||
margin-left: 8px;
|
||||
margin-top: 8px;
|
||||
padding: 4px;
|
||||
transition: background 300ms;
|
||||
transition: color 300ms;
|
||||
width: 172px;
|
||||
|
||||
&:first-child {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
&.group-on {
|
||||
background: white;
|
||||
color: black;
|
||||
}
|
||||
|
||||
span {
|
||||
&:first-child {
|
||||
align-self: flex-end;
|
||||
flex: 1;
|
||||
line-height: 1.3;
|
||||
margin-right: 4px;
|
||||
max-height: 38px;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
packages/homehub_tradfri/src/defs.js
Normal file
2
packages/homehub_tradfri/src/defs.js
Normal file
@@ -0,0 +1,2 @@
|
||||
export const kServiceTradfri = 'kServiceTradfri';
|
||||
export const kWidgetTradfri = 'kWidgetTradfri';
|
||||
17
packages/homehub_tradfri/src/index.js
Normal file
17
packages/homehub_tradfri/src/index.js
Normal file
@@ -0,0 +1,17 @@
|
||||
/*!
|
||||
* BTHLabs HomeHub - IKEA Tradfri Integration (https://bthlabs.pl/)
|
||||
* Copyright 2021-present BTHLabs
|
||||
* Apache License Version 2.0
|
||||
*/
|
||||
|
||||
import * as defs from './defs';
|
||||
import {TradfriService} from './TradfriService';
|
||||
import {TradfriWidgetView} from './TradfriWidgetView';
|
||||
|
||||
export const WIDGETS = {
|
||||
[defs.kWidgetTradfri]: TradfriWidgetView,
|
||||
};
|
||||
|
||||
export const SERVICES = {
|
||||
[defs.kServiceTradfri]: TradfriService,
|
||||
};
|
||||
155
packages/homehub_tradfri/tests/TradfriService.spec.js
Normal file
155
packages/homehub_tradfri/tests/TradfriService.spec.js
Normal file
@@ -0,0 +1,155 @@
|
||||
import * as HomeHubCore from '@bthlabs/homehub-core';
|
||||
|
||||
import * as TradfriService from 'src/TradfriService';
|
||||
|
||||
import {TradfriDataFactory} from 'tests/__fixtures__/tradfri';
|
||||
|
||||
describe('src/TradfriService', () => {
|
||||
describe('TradfriService', () => {
|
||||
let fakeCharacteristics = null;
|
||||
let fakeResult = null;
|
||||
|
||||
beforeEach(() => {
|
||||
fakeCharacteristics = {
|
||||
host: 'thisisntright.local',
|
||||
key: 'thisisntright',
|
||||
};
|
||||
fakeResult = TradfriDataFactory();
|
||||
|
||||
spyOn(HomeHubCore.API.Services, 'start').and.returnValue(fakeResult);
|
||||
spyOn(HomeHubCore.API.Services, 'stop').and.returnValue('ok');
|
||||
spyOn(HomeHubCore.API.Services, 'use').and.returnValue(
|
||||
fakeResult.lights
|
||||
);
|
||||
});
|
||||
|
||||
describe('emptyCharacteristics', () => {
|
||||
it('returns empty characteristics', () => {
|
||||
// Given
|
||||
const result = TradfriService.TradfriService.emptyCharacteristics();
|
||||
|
||||
// Then
|
||||
expect(result).toEqual({
|
||||
key: '',
|
||||
host: '',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('start', () => {
|
||||
it('notifies subscribers with the result of start service API call', async () => {
|
||||
// Given
|
||||
const service = new TradfriService.TradfriService({
|
||||
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 TradfriService.TradfriService({
|
||||
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 = {
|
||||
host: 'thisisntrighttoo.local',
|
||||
key: 'thisisntrighttoo',
|
||||
};
|
||||
const service = new TradfriService.TradfriService({
|
||||
instance: 'testing',
|
||||
characteristics: fakeCharacteristics,
|
||||
});
|
||||
spyOn(service, 'restart');
|
||||
|
||||
// When
|
||||
service.setCharacteristics(newCharacteristics);
|
||||
|
||||
// Then
|
||||
expect(service.characteristics).toEqual(newCharacteristics);
|
||||
});
|
||||
|
||||
it('restarts the service if host characteristic changed', () => {
|
||||
// Given
|
||||
const newCharacteristics = {
|
||||
...fakeCharacteristics,
|
||||
host: 'thisisntrighttoo.local',
|
||||
};
|
||||
const service = new TradfriService.TradfriService({
|
||||
instance: 'testing',
|
||||
characteristics: fakeCharacteristics,
|
||||
});
|
||||
spyOn(service, 'restart');
|
||||
|
||||
// When
|
||||
service.setCharacteristics(newCharacteristics);
|
||||
|
||||
// Then
|
||||
expect(service.restart).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restarts the service if key characteristic changed', () => {
|
||||
// Given
|
||||
const newCharacteristics = {
|
||||
...fakeCharacteristics,
|
||||
key: 'thisisntrighttoo',
|
||||
};
|
||||
const service = new TradfriService.TradfriService({
|
||||
instance: 'testing',
|
||||
characteristics: fakeCharacteristics,
|
||||
});
|
||||
spyOn(service, 'restart');
|
||||
|
||||
// When
|
||||
service.setCharacteristics(newCharacteristics);
|
||||
|
||||
// Then
|
||||
expect(service.restart).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setLightsState', () => {
|
||||
it('calls the use service capability API method', async () => {
|
||||
// Given
|
||||
const service = new TradfriService.TradfriService({
|
||||
instance: 'testing',
|
||||
characteristics: fakeCharacteristics,
|
||||
});
|
||||
|
||||
// When
|
||||
const result = await service.setLightsState(['light1'], true);
|
||||
|
||||
// Then
|
||||
expect(result).toEqual(fakeResult.lights);
|
||||
expect(HomeHubCore.API.Services.use).toHaveBeenCalledWith(
|
||||
service.kind, 'testing', 'set_lights_state', [['light1'], true],
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
420
packages/homehub_tradfri/tests/TradfriWidgetView.spec.js
Normal file
420
packages/homehub_tradfri/tests/TradfriWidgetView.spec.js
Normal file
@@ -0,0 +1,420 @@
|
||||
import {FatalError, Widget} from '@bthlabs/homehub-components';
|
||||
import {ServiceState} from '@bthlabs/homehub-core';
|
||||
import {shallow} from 'enzyme';
|
||||
import React from 'react';
|
||||
import {Form} from 'react-bootstrap';
|
||||
|
||||
import {TradfriService} from 'src/TradfriService';
|
||||
import * as TradfriWidgetView from 'src/TradfriWidgetView';
|
||||
|
||||
import {TradfriDataFactory} from 'tests/__fixtures__/tradfri';
|
||||
|
||||
describe('src/widgets/TradfriWidgetView', () => {
|
||||
describe('TradfriWidgetSettingsView', () => {
|
||||
let fakeNextCharacteristics = null;
|
||||
let mockSetNextCharacteristics = null;
|
||||
|
||||
beforeEach(() => {
|
||||
fakeNextCharacteristics = {
|
||||
host: '',
|
||||
key: '',
|
||||
};
|
||||
mockSetNextCharacteristics = jasmine.createSpy();
|
||||
});
|
||||
|
||||
it('calls the setNextCharacteristics callback when host input changes', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetSettingsView
|
||||
nextCharacteristics={fakeNextCharacteristics}
|
||||
setNextCharacteristics={mockSetNextCharacteristics}
|
||||
/>
|
||||
);
|
||||
|
||||
// When
|
||||
component.find(Form.Control).at(0).simulate('change', {
|
||||
target: {value: 'thisisntright.local'},
|
||||
});
|
||||
|
||||
// Then
|
||||
expect(mockSetNextCharacteristics).toHaveBeenCalledWith({
|
||||
...fakeNextCharacteristics,
|
||||
host: 'thisisntright.local',
|
||||
});
|
||||
});
|
||||
|
||||
it('calls the setNextCharacteristics callback when key input changes', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetSettingsView
|
||||
nextCharacteristics={fakeNextCharacteristics}
|
||||
setNextCharacteristics={mockSetNextCharacteristics}
|
||||
/>
|
||||
);
|
||||
|
||||
// When
|
||||
component.find(Form.Control).at(1).simulate('change', {
|
||||
target: {value: 'thisisntright'},
|
||||
});
|
||||
|
||||
// Then
|
||||
expect(mockSetNextCharacteristics).toHaveBeenCalledWith({
|
||||
...fakeNextCharacteristics,
|
||||
key: 'thisisntright',
|
||||
});
|
||||
});
|
||||
|
||||
it('renders empty when nextCharacteristics is empty', () => {
|
||||
// Given
|
||||
fakeNextCharacteristics = null;
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetSettingsView
|
||||
nextCharacteristics={fakeNextCharacteristics}
|
||||
setNextCharacteristics={mockSetNextCharacteristics}
|
||||
/>
|
||||
);
|
||||
|
||||
// Then
|
||||
expect(component.isEmptyRender()).toBe(true);
|
||||
});
|
||||
|
||||
it('configures and renders the host input', () => {
|
||||
// Given
|
||||
fakeNextCharacteristics = {
|
||||
...fakeNextCharacteristics,
|
||||
host: 'thisisntright.local',
|
||||
key: 'thisisntright',
|
||||
};
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetSettingsView
|
||||
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.host);
|
||||
});
|
||||
|
||||
it('configures and renders the key input', () => {
|
||||
// Given
|
||||
fakeNextCharacteristics = {
|
||||
...fakeNextCharacteristics,
|
||||
host: 'thisisntright.local',
|
||||
key: 'thisisntright',
|
||||
};
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetSettingsView
|
||||
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.key);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Group', () => {
|
||||
let fakeData = null;
|
||||
let mockOnSetLightsState = null;
|
||||
|
||||
beforeEach(() => {
|
||||
fakeData = TradfriDataFactory();
|
||||
mockOnSetLightsState = jasmine.createSpy();
|
||||
});
|
||||
|
||||
it('calls the onSetLightsState callback when it is clicked', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.Group
|
||||
group={fakeData.groups[0]}
|
||||
lights={fakeData.lights}
|
||||
onSetLightsState={mockOnSetLightsState}
|
||||
/>
|
||||
);
|
||||
|
||||
// When
|
||||
component.simulate('click');
|
||||
|
||||
// Then
|
||||
expect(mockOnSetLightsState).toHaveBeenCalledWith(
|
||||
['light1', 'light2'], false
|
||||
);
|
||||
});
|
||||
|
||||
it('renders as on when all the lights in the the group are on', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.Group
|
||||
group={fakeData.groups[0]}
|
||||
lights={fakeData.lights}
|
||||
onSetLightsState={mockOnSetLightsState}
|
||||
/>
|
||||
);
|
||||
|
||||
// Then
|
||||
expect(component.hasClass('group-on')).toBe(true);
|
||||
});
|
||||
|
||||
it('does not render as of when some of the lights in the the group are off', () => {
|
||||
// Given
|
||||
fakeData.lights[0].state = false;
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.Group
|
||||
group={fakeData.groups[0]}
|
||||
lights={fakeData.lights}
|
||||
onSetLightsState={mockOnSetLightsState}
|
||||
/>
|
||||
);
|
||||
|
||||
// Then
|
||||
expect(component.hasClass('group-on')).toBe(false);
|
||||
});
|
||||
|
||||
it('renders the group name', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.Group
|
||||
group={fakeData.groups[0]}
|
||||
lights={fakeData.lights}
|
||||
onSetLightsState={mockOnSetLightsState}
|
||||
/>
|
||||
);
|
||||
|
||||
// When
|
||||
const groupName = component.find('span[_hint="GroupName"]').at(0);
|
||||
|
||||
// Then
|
||||
expect(groupName.exists()).toBe(true);
|
||||
expect(groupName.text()).toEqual(fakeData.groups[0].name);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TradfriWidgetView', () => {
|
||||
let fakeAppearance = null;
|
||||
let fakeService = null;
|
||||
let fakeServiceState = null;
|
||||
let fakeData = null;
|
||||
let mockSetServiceState = null;
|
||||
|
||||
beforeEach(() => {
|
||||
fakeAppearance = {color: 'red'};
|
||||
fakeService = new TradfriService({
|
||||
instance: 'testing',
|
||||
layout: {x: 0, y: 0, h: 1, w: 1},
|
||||
});
|
||||
fakeData = TradfriDataFactory();
|
||||
fakeServiceState = new ServiceState({
|
||||
data: fakeData,
|
||||
});
|
||||
mockSetServiceState = jasmine.createSpy();
|
||||
|
||||
spyOn(fakeService, 'setLightsState').and.resolveTo('ok');
|
||||
});
|
||||
|
||||
it('defines the widget attributes', () => {
|
||||
// Then
|
||||
expect(TradfriWidgetView.TradfriWidgetView.defaultLayout).toEqual({
|
||||
h: jasmine.any(Number),
|
||||
w: jasmine.any(Number),
|
||||
});
|
||||
expect(TradfriWidgetView.TradfriWidgetView.icon).toBeDefined();
|
||||
expect(TradfriWidgetView.TradfriWidgetView.layoutConstraints).toEqual({
|
||||
minH: jasmine.any(Number),
|
||||
minW: jasmine.any(Number),
|
||||
});
|
||||
expect(TradfriWidgetView.TradfriWidgetView.settingsView).toEqual(
|
||||
TradfriWidgetView.TradfriWidgetSettingsView
|
||||
);
|
||||
expect(TradfriWidgetView.TradfriWidgetView.title).toEqual('Tradfri');
|
||||
});
|
||||
|
||||
it('handles group lights state change', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// When
|
||||
component.find(TradfriWidgetView.Group).at(0).invoke('onSetLightsState')(
|
||||
['light1'], false
|
||||
);
|
||||
|
||||
// Then
|
||||
expect(fakeService.setLightsState).toHaveBeenCalledWith(
|
||||
['light1'], false
|
||||
);
|
||||
|
||||
const expectedNewState = {data: {...fakeData}};
|
||||
expectedNewState.data.lights[0].state = false;
|
||||
expect(mockSetServiceState).toHaveBeenCalledWith(expectedNewState);
|
||||
});
|
||||
|
||||
it('renders empty when service state is null', () => {
|
||||
// Given
|
||||
fakeServiceState = null;
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// Then
|
||||
expect(component.isEmptyRender()).toBe(true);
|
||||
});
|
||||
|
||||
it('configures and renders the Widget', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// 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(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// 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(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// When
|
||||
const loader = component.find('Icon[_hint="Loader"]').at(0);
|
||||
|
||||
// Then
|
||||
expect(loader.exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not compute and render groups when service state has no data', () => {
|
||||
// Given
|
||||
spyOn(fakeServiceState, 'hasData').and.returnValue(false);
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// When
|
||||
const groups = component.find(TradfriWidgetView.Group);
|
||||
|
||||
// Then
|
||||
expect(groups.length).toEqual(0);
|
||||
});
|
||||
|
||||
it('configures and renders a Group for every group', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// When
|
||||
const groups = component.find(TradfriWidgetView.Group);
|
||||
|
||||
// Then
|
||||
expect(groups.length).toEqual(1);
|
||||
|
||||
const group = groups.at(0);
|
||||
expect(group.prop('group')).toEqual(fakeData.groups[0]);
|
||||
expect(group.prop('lights')).toEqual(fakeData.lights);
|
||||
});
|
||||
|
||||
it('does not render FatalError if service state has no fatal error', () => {
|
||||
// Given
|
||||
const component = shallow(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// 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(
|
||||
<TradfriWidgetView.TradfriWidgetView
|
||||
appearance={fakeAppearance}
|
||||
service={fakeService}
|
||||
serviceState={fakeServiceState}
|
||||
setServiceState={mockSetServiceState}
|
||||
/>
|
||||
);
|
||||
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
6
packages/homehub_tradfri/tests/__entry__.js
Normal file
6
packages/homehub_tradfri/tests/__entry__.js
Normal 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);
|
||||
34
packages/homehub_tradfri/tests/__fixtures__/tradfri.js
Normal file
34
packages/homehub_tradfri/tests/__fixtures__/tradfri.js
Normal file
@@ -0,0 +1,34 @@
|
||||
export const TradfriDataFactory = () => {
|
||||
return {
|
||||
lights: [
|
||||
{
|
||||
'id': 'light1',
|
||||
'name': 'Light 1',
|
||||
'state': true,
|
||||
'reachable': false,
|
||||
'dimmer': 128,
|
||||
},
|
||||
{
|
||||
'id': 'light2',
|
||||
'name': 'Light 2',
|
||||
'state': true,
|
||||
'reachable': false,
|
||||
'dimmer': 128,
|
||||
},
|
||||
{
|
||||
'id': 'light3',
|
||||
'name': 'Light 3',
|
||||
'state': true,
|
||||
'reachable': false,
|
||||
'dimmer': 128,
|
||||
},
|
||||
],
|
||||
groups: [
|
||||
{
|
||||
'id': 'group1',
|
||||
'name': 'Group 1',
|
||||
'member_ids': ['light1', 'light2'],
|
||||
},
|
||||
],
|
||||
};
|
||||
};
|
||||
7
packages/homehub_tradfri/tests/__setup__/enzyme.setup.js
Normal file
7
packages/homehub_tradfri/tests/__setup__/enzyme.setup.js
Normal file
@@ -0,0 +1,7 @@
|
||||
import Enzyme from 'enzyme';
|
||||
import Adapter from 'enzyme-adapter-react-16';
|
||||
|
||||
Enzyme.configure({
|
||||
adapter: new Adapter(),
|
||||
disableLifecycleMethods: true,
|
||||
});
|
||||
110
packages/homehub_tradfri/webpack.config.js
Executable file
110
packages/homehub_tradfri/webpack.config.js
Executable 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_tradfri',
|
||||
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;
|
||||
7455
packages/homehub_tradfri/yarn.lock
Normal file
7455
packages/homehub_tradfri/yarn.lock
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user