craftbeerpi4-pione/cbpi/utils/encoder.py

42 lines
1.1 KiB
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):
2019-01-17 22:11:55 +01:00
data = dict(**obj.__dict__)
data["state"] = obj.instance.get_state()
2019-01-08 23:31:39 +01:00
del data["instance"]
2019-01-17 22:11:55 +01:00
2019-01-08 23:31:39 +01:00
return data
elif isinstance(obj, SensorModel):
2019-01-17 22:11:55 +01:00
data = dict(**obj.__dict__)
data["value"] = value=obj.instance.get_value()
2019-01-28 22:21:31 +01:00
data["unit"] = value = obj.instance.get_unit()
2019-01-17 22:11:55 +01:00
data["state"] = obj.instance.get_state()
2019-01-08 23:31:39 +01:00
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):
2019-01-14 07:33:59 +01:00
return obj.__dict__
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-17 22:11:55 +01:00
except Exception as e:
2019-01-28 22:21:31 +01:00
print(e)
2018-11-18 15:40:10 +01:00
pass
return None