1#
2# Copyright (C) 2018 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import multiprocessing
18
19from host_controller import common
20
21
22class SharedDict(object):
23    """Class for the state of devices connected to the host.
24
25    shared between the main process and the process pool.
26
27    Attributes:
28        _manager: SyncManager. an instance of a manager for shared objects and
29                  values between processes.
30        _dict: multiprocessing.SyncManager.dict. A dictionary
31               shared among processes.
32    """
33
34    def __init__(self, manager=None):
35        if manager is not None:
36            self._manager = manager
37        else:
38            self._manager = multiprocessing.Manager()
39        self._dict = self._manager.dict()
40
41    def __getitem__(self, key):
42        """getitem for self._dict.
43
44        Args:
45            key: string, serial number of a device.
46
47        Returns:
48            integer value defined in _DEVICE_STATUS_DICT.
49        """
50        if key not in self._dict:
51            self._dict[key] = common._DEVICE_STATUS_DICT["unknown"]
52        return self._dict[key]
53
54    def __setitem__(self, key, value):
55        """setitem for self._dict.
56
57        if the value is not a defined one, device status is set to "unknown".
58
59        Args:
60            key: string, serial number of a device.
61            value: integer, status value defined in _DEVICE_STATUS_DICT.
62        """
63        if value not in range(len(common._DEVICE_STATUS_DICT)):
64            self._dict[key] = common._DEVICE_STATUS_DICT["unknown"]
65        else:
66            self._dict[key] = value