Skip to content

Commit cb33c86

Browse files
committed
Add JSON characteristic
1 parent de7cacf commit cb33c86

File tree

1 file changed

+53
-0
lines changed
  • adafruit_ble/characteristics

1 file changed

+53
-0
lines changed

adafruit_ble/characteristics/json.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
`json`
3+
====================================================
4+
5+
This module provides Json characteristic.
6+
7+
"""
8+
9+
import json
10+
from . import Attribute
11+
from . import Characteristic
12+
13+
__version__ = "0.0.0-auto.0"
14+
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_BLE.git"
15+
16+
17+
class JsonCharacteristic(Characteristic):
18+
"""Json string characteristic."""
19+
20+
def __init__(
21+
self,
22+
*,
23+
uuid=None,
24+
properties=Characteristic.READ,
25+
read_perm=Attribute.OPEN,
26+
write_perm=Attribute.OPEN,
27+
initial_value=None,
28+
):
29+
super().__init__(
30+
uuid=uuid,
31+
properties=properties,
32+
read_perm=read_perm,
33+
write_perm=write_perm,
34+
max_length=512,
35+
fixed_length=False,
36+
initial_value=self.pack(initial_value),
37+
)
38+
39+
@staticmethod
40+
def pack(value):
41+
return json.dumps(value).encode("utf-8")
42+
43+
@staticmethod
44+
def unpack(value):
45+
return json.loads(str(value, "utf-8"))
46+
47+
def __get__(self, obj, cls=None):
48+
if obj is None:
49+
return self
50+
return self.unpack(super().__get__(obj, cls))
51+
52+
def __set__(self, obj, value):
53+
super().__set__(obj, self.pack(value))

0 commit comments

Comments
 (0)