Skip to content

Commit

Permalink
debug
Browse files Browse the repository at this point in the history
  • Loading branch information
hidaris committed Nov 24, 2022
1 parent 6be592c commit a503212
Show file tree
Hide file tree
Showing 10 changed files with 27 additions and 64 deletions.
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "thingtalk"
version = "0.9.0"
version = "0.8.2"
description = "Web of Things framework, high performance, easy to learn, fast to code, ready for production"
authors = ["hidaris <[email protected]>"]
readme = "README.md"
Expand Down Expand Up @@ -41,6 +41,7 @@ cached-property = { version = "^1.5", python = "~3.7"}
[tool.poetry.dev-dependencies]
pytest = "^7.2"
pytest-asyncio = "^0.20.0"
httpx = "^0.23.0"

[tool.poetry.extras]
docs = ["mkdocs-material"]
5 changes: 0 additions & 5 deletions tests/test_thing_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,6 @@ def http_request(method, path, data=None):
"Accept": "application/json",
}

proxies = {
"http": None,
"https": None,
}

if _DEBUG:
if data is None:
print("Request: {} {}".format(method, url))
Expand Down
2 changes: 1 addition & 1 deletion thingtalk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
from .app import app
from .models.containers import SingleThing, MultipleThings
from .models.thing import Thing
from .domains.iot import Device
# from .domains.iot import Device
from .models.value import Value
18 changes: 2 additions & 16 deletions thingtalk/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@
from loguru import logger
from zeroconf import Zeroconf, ServiceInfo

from .routers.mqtt import mqtt
from .utils import get_ip
from .models.thing import Server
from .models.containers import MultipleThings
from .routers import things, properties, actions, events, websockets
from .toolkits import mb


app = FastAPI(
title="ThingTalk",
version="0.7.12",
version="0.9.0",
description="Web of Things framework, high performance, easy to learn, fast to code, ready for production",
)
server = Server()
Expand Down Expand Up @@ -51,19 +50,6 @@ async def stop_mdns():
zeroconf.close()


# @app.on_event("startup")
# async def startup():
# await mqtt.set_app(app)
# await mqtt.connect()
# await app.state.things.add_thing(server)


# @app.on_event("shutdown")
# async def shutdown():
# await mqtt.disconnect()
# mb.remove_all_listeners()


restapi = APIRouter()

restapi.include_router(things.router, tags=["thing"])
Expand Down
7 changes: 2 additions & 5 deletions thingtalk/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,8 @@ async def get_thing(request: Request, thing_id: str):
thing_id -- ID of the thing to get, in string form
Returns the thing, or None if not found.
"""
if request.app.state.mode in ["gateway", "multiple"]:
things = request.app.state.things
thing = things.get_thing(thing_id)
else:
thing = request.app.state.thing.get_thing()
things = request.app.state.things
thing = things.get_thing(thing_id)
if thing is None:
raise HTTPException(status_code=404)
return thing
Expand Down
7 changes: 3 additions & 4 deletions thingtalk/domains/iot.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from loguru import logger

from ..models.thing import Thing
from ..toolkits.event_bus import mb


class Device(Thing):
Expand All @@ -12,16 +11,16 @@ def __init__(self, *args, **kwargs):
async def subscribe_broadcast(self):
if "Light" in self._type:
topic = "broadcast/light"
mb.on(topic, self.dispatch)
self.on(topic, self.dispatch)
self.subscribe_topics.append(topic)
logger.info("subscribe light broadcast")
elif "OnOffSwitch" in self._type:
topic = "broadcast/switch"
mb.on(topic, self.dispatch)
self.on(topic, self.dispatch)
self.subscribe_topics.append(topic)
logger.info("subscribe switch broadcast")
elif "Cover" in self._type:
topic = "broadcast/cover"
mb.on(topic, self.dispatch)
self.on(topic, self.dispatch)
self.subscribe_topics.append(topic)
logger.info("subscribe cover broadcast")
4 changes: 3 additions & 1 deletion thingtalk/models/containers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Optional
from loguru import logger

from .event import ThingPairedEvent, ThingRemovedEvent

from ..toolkits.event_bus import mb

if TYPE_CHECKING:
from .thing import Thing
Expand Down Expand Up @@ -75,6 +76,7 @@ async def discover(self, thing: Thing):
async def add_thing(self, thing: Thing):
logger.debug("add_thing")
self.things.update({thing.id: thing})
await thing.init_subscripe()
await thing.subscribe_broadcast()

# await self.server.add_event(ThingPairedEvent({
Expand Down
7 changes: 6 additions & 1 deletion thingtalk/models/thing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from jsonschema.exceptions import ValidationError

from loguru import logger
from pyee import AsyncIOEventEmitter
from pyee.asyncio import AsyncIOEventEmitter

from .event import (
Event,
Expand Down Expand Up @@ -67,6 +67,11 @@ def __init__(self, id_, title, type_=[], description_=""):
self._ui_href = ""
self.subscribe_topics = [f"things/{self._id}"]

# self.on("setProperty", self.handle_set_property)
# self.on("syncProperty", self.handle_sync_property)
# self.on("requestAction", self.handle_request_action)

async def init_subscripe(self):
self.on("setProperty", self.handle_set_property)
self.on("syncProperty", self.handle_sync_property)
self.on("requestAction", self.handle_request_action)
Expand Down
2 changes: 1 addition & 1 deletion thingtalk/models/value.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""An observable, settable value interface."""

from pyee import AsyncIOEventEmitter as EventEmitter
from pyee.asyncio import AsyncIOEventEmitter as EventEmitter


class Value(EventEmitter):
Expand Down
36 changes: 7 additions & 29 deletions thingtalk/routers/things.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,10 @@ async def get_things(request: Request) -> ORJSONResponse:
:param request -- the request
:return ORJSONResponse
"""
if request.app.state.mode == "gateway":
things = request.app.state.things
things = request.app.state.things

descriptions = []
for idx, thing in tuple(things.get_things()):
description = thing.as_thing_description()

description["links"].append(
{
"rel": "alternate",
"href": f"{get_ws_href(request)}{thing.href}",
}
)
description["base"] = f"{get_http_href(request)}{thing.href}"

description["securityDefinitions"] = {
"nosec_sc": {
"scheme": "nosec",
},
}
description["security"] = "nosec_sc"

bak = copy.deepcopy(description)
descriptions.append(bak)

return ORJSONResponse(descriptions)
else:
thing = request.app.state.thing.get_thing()
descriptions = []
for idx, thing in tuple(things.get_things()):
description = thing.as_thing_description()

description["links"].append(
Expand All @@ -65,12 +41,14 @@ async def get_things(request: Request) -> ORJSONResponse:
}
description["security"] = "nosec_sc"

return ORJSONResponse(description)
bak = copy.deepcopy(description)
descriptions.append(bak)

return ORJSONResponse(descriptions)

@router.get("/things/{thing_id}")
async def get_thing_by_id(
request: Request, thing: Thing = Depends(get_thing)
request: Request, thing: Thing = Depends(get_thing)
) -> ORJSONResponse:
"""
Handle a GET request, including websocket requests.
Expand Down

0 comments on commit a503212

Please sign in to comment.