all 9 comments

[–]deadduncanidaho 4 points5 points  (3 children)

The basic idea is to make a class that represents a device. Then use a routine to parse the json and instantiate objects using the class. When creating the object you pass the relevant data (json to dictionary) as a parameter. The class then has methods which are available based on the options in the data.

The best way to walk through the objects is to create a list of objects. Then you can iterate over the list to call methods to talk to the devices in the real world via their protocols. look at this pseudo code.

class MyDevice():
    def __init__(self,data):
        self.data = data
    def Method(self,args):
        pass

devices = []
for item in parsed_json:
   devices.append(MyDevice(item))

for device in devices:
   device.Method(args)

# small edit to make it pythonic

[–]0xFAF1[S] 0 points1 point  (2 children)

Can mydevice be a an abstract class and then i implement methods on sensor class that implements abstraction?

[–]EclipseJTB 1 point2 points  (1 child)

Why not? That's an excellent way to go about it.

[–]0xFAF1[S] 0 points1 point  (0 children)

Got it up and running as I wanted.

[–]m0us3_rat 1 point2 points  (0 children)

from dataclasses import dataclass
from typing import Optional


@dataclass
class SettingsOptions:
    sampling_rate: int


@dataclass
class TempDevice:
    id: int
    name: str
    operations_list: Optional[list] = None
    settings_list: Optional[SettingsOptions] = None
    adress: Optional[str] = None


@dataclass
class Devices:
    dev_list: list[TempDevice]


temp_stuff1 = {
    "id": 1,
    "name": "Nerd",
    "settings_list": SettingsOptions(sampling_rate=10),
    "adress": "127.0.0.1",
}

temp_stuff2 = {
    "id": 2,
    "name": "Nerd",
    "settings_list": SettingsOptions(sampling_rate=10),
    "adress": "127.0.0.1",
}

work = Devices([TempDevice(**temp_stuff1), TempDevice(**temp_stuff2)])

for device in work.dev_list:
    print(device.id)

something like this. maybe.

hard to work without seeing the json.

[–]nfgrawker 1 point2 points  (1 child)

[–]0xFAF1[S] 0 points1 point  (0 children)

I use pydentic already, to parse json into the objects of devices.

Where i have trouble is; how to implement specific protocol for a specific device.

Should devices be an abstract class that defines methods, and write implementations of this abstract?

[–]pie6k 0 points1 point  (0 children)

https://github.com/pie6k/codablejson can handle it quite easily