craftbeerpi4-pione/cbpi/utils/encoder.py

34 lines
985 B
Python
Raw Normal View History

2018-11-18 15:40:10 +01:00
from json import JSONEncoder
2019-01-08 23:31:39 +01:00
from cbpi.database.model import ActorModel, SensorModel
2018-11-18 15:40:10 +01:00
class ComplexEncoder(JSONEncoder):
def default(self, obj):
2019-01-05 20:43:48 +01:00
from cbpi.database.orm_framework import DBModel
2018-12-29 00:27:19 +01:00
2018-11-18 15:40:10 +01:00
try:
2019-01-08 23:31:39 +01:00
if isinstance(obj, ActorModel):
data = dict(**obj.__dict__, state=obj.instance.get_state())
del data["instance"]
return data
elif isinstance(obj, SensorModel):
data = dict(**obj.__dict__, state=obj.instance.get_state(), value=obj.instance.get_value())
del data["instance"]
return data
2018-12-29 00:27:19 +01:00
#elif callable(getattr(obj, "reprJSON")):
# return obj.reprJSON()
2019-01-08 23:31:39 +01:00
elif isinstance(obj, DBModel):
return None
2019-01-02 21:20:44 +01:00
#elif hasattr(obj, "callback"):
# return obj()
2018-11-18 15:40:10 +01:00
else:
2019-01-04 09:29:09 +01:00
raise TypeError()
2019-01-02 21:20:44 +01:00
except TypeError:
2018-11-18 15:40:10 +01:00
pass
return None