예제 #1
0
 def update(self, mode, status='OOOOOO'):
     try:
         self.mode = mode
         self.status = status
         self.last_refresh = datetime.now()
         self.__db_connection = sqlite.connect('alarm.sqlite')
         self.__db_cursor = self.__db_connection.cursor()
         self.__db_cursor.execute(
             "UPDATE areas SET status= :new_status, mode= :new_mode, last_refresh= :new_date WHERE id = :id",
             {
                 "id": self.id,
                 "new_status": self.status,
                 "new_mode": self.mode,
                 "new_date": self.last_refresh
             })
         self.__db_connection.commit()
         print(
             "Area '{0:s}' updated: mode:{1:s} status:{2:s} last_refresh:{3:%Y-%m-%d %H:%M:%S}"
             .format(self.name, self.mode, self.status, self.last_refresh))
         if self.__db_cursor.rowcount == 0:
             raise TypeError(
                 "Area '{0:s}' update: no DB record found".format(
                     self.name))
     except sqlite.Error as e:
         if self.__db_connection:
             self.__db_connection.rollback()
         raise TypeError("Area {0:s}' update SQL error: %s:" %
                         e.args[0].format(self.name))
     finally:
         if self.__db_connection:
             self.__db_connection.close()
예제 #2
0
 def __init__(self, EventStr):
     self.call_str = None
     self.created = None
     if EventStr[0:2] == 'UK':
         if len(EventStr) == 5:
             self.call_str = EventStr
             self.created = datetime.now()
             try:
                 self.__id = int(EventStr[3:5])
             except ValueError:
                 raise TypeError(
                     "Utility key event conversion error - wrong id")
             self.__keyswitch_obj = SLists.getKeySwitch(self.__id)
         else:
             raise TypeError("Utility key event length should be 5 bytes")
     else:
         raise TypeError("Utility key event should start with UK")
     try:
         self.__db_connection = sqlite.connect('db.sqlite')
         self.__db_connection.row_factory = sqlite.Row
         self.__db_cursor = self.__db_connection.cursor()
         self.__db_cursor.execute("SELECT name FROM zones WHERE id = :id",
                                  {"id": self.__id})
         self.__db_row = self.__db_cursor.fetchone()
         if self.__db_row:
             self.name = self.__db_row['name']
     except sqlite.Error as e:
         raise TypeError("Keyswitch load SQL error: %s:" % e.args[0])
     finally:
         if self.__db_connection:
             self.__db_connection.close()
예제 #3
0
 def __init__(self, EventStr):
     self.call_str = None
     self.created = None
     self.desc = None
     self.mode = None
     if EventStr[0:2] == 'RA':
         self.desc = 'Area request'
     elif EventStr[0:2] == 'AD':
         self.desc = 'Area disarm'
         self.mode = 'D'
     elif EventStr[0:2] == 'AA':
         if len(EventStr) >= 6:
             if (EventStr[5:6] != 'F') \
               and (EventStr[5:6] != 'I') \
               and (EventStr[5:6] != 'S') \
               and (EventStr[5:6] != 'A'):
                 raise TypeError("Area arm mode must be F,I,S,A")
             else:
                 self.mode = EventStr[5:6]
     else:
         raise TypeError("Area event should start with RA, AA, AD")
     try:
         self.__area_id = int(EventStr[3:5])
     except ValueError:
         raise TypeError("Area Event conversion error - wrong area")
     if self.__area_id < 1 or self.__area_id > 4:
         raise TypeError("Area Event error: area must be between 1..4")
     self.call_str = EventStr[0:5]
     self.created = datetime.now()
     self.area = SLists.getArea(self.__area_id)
     """
예제 #4
0
 def __init__(self, EventStr):
     self.call_str = None
     self.created = None
     self.desc = None
     try:
         self.__zone_id = int(EventStr[3:5])
     except ValueError:
         raise TypeError(
             "Zone Event conversion error - wrong identificator")
     if self.__zone_id < 1 or self.__zone_id > 48:
         raise TypeError("Zone Event error: area must be between 1..48")
     self.call_str = EventStr[0:5]
     self.created = datetime.now()
     self.zone = SLists.getZone(self.__zone_id)
예제 #5
0
 def __init__(self, id):
     self.id = id
     self.name = None
     self.mqtt_topic = None
     self.mqtt_payload = None
     self.mqtt_direction = None
     self.__serial_queue = comm.SerialOutQueue
     try:
         self.__db_connection = sqlite.connect('db.sqlite')
         self.__db_connection.row_factory = sqlite.Row
         self.__db_cursor = self.__db_connection.cursor()
         self.__db_cursor.execute(
             "SELECT desc, mqtt_topic, payload, direction FROM keyswitches WHERE id = :id",
             {"id": self.id})
         self.__db_row = self.__db_cursor.fetchone()
         if self.__db_row:
             self.name = self.__db_row['desc']
             self.mqtt_topic = self.__db_row['mqtt_topic']
             self.mqtt_payload = self.__db_row['payload']
             self.mqtt_direction = self.__db_row['direction']
     except sqlite.Error as e:
         raise TypeError("Key switch load SQL error: %s:" % e.args[0])
     finally:
         if self.__db_connection:
             self.__db_connection.close()
    def __mul__(self, right):
        if type(right) not in [int, float, Sparse_Matrix]:
            raise TypeError('unsupported operand type(s) for +' + ': \'' +
                            type_as_str(self) + '\' and \'' +
                            type_as_str(right) + '\'')
        if type(self) is Sparse_Matrix and type(right) is Sparse_Matrix:
            if self.cols != right.rows:
                raise AssertionError("Size of two Sparse_Matrix are not equal")
            nm = Sparse_Matrix(self.rows, right.cols)
            for index in range(self.rows):
                for indexs in range(right.cols):
                    num = self.row(index)
                    nums = right.col(indexs)
                    xs = 0
                    xy = None
                    if len(num) > len(nums):
                        xy = num
                    else:
                        xy = nums
                    for x in range(len(xy)):
                        xs += num[x] * nums[x]
                    nm[index, indexs] = xs
            return nm

        if type(right) in [int, float]:
            nm = Sparse_Matrix(self.rows, self.cols)
            for index in range(self.rows):
                for indexs in range(self.cols):
                    fr = self.matrix.get((index, indexs), 0) * right
                    nm[index, indexs] = fr
            return nm
예제 #7
0
 def load_from_db(self):
     try:
         self.__db_connection = sqlite.connect('db.sqlite')
         self.__db_connection.row_factory = sqlite.Row
         self.__db_cursor = self.__db_connection.cursor()
         self.__db_cursor.execute(
             "SELECT name, mode, status, last_refresh, mqtt_topic FROM areas WHERE id = :id",
             {"id": self.id})
         self.__db_row = self.__db_cursor.fetchone()
         if self.__db_row:
             self.name = self.__db_row['name']
             self.mode = self.__db_row['mode']
             self.status = self.__db_row['status']
             self.last_refresh = datetime.strptime(
                 self.__db_row['last_refresh'],
                 '%Y-%m-%d %H:%M:%S.%f')  #2018-10-11 17:30:40.214852
             self.last_change = self.last_refresh
             self.mqtt_topic = self.__db_row['mqtt_topic']
         del self.zones_list[:]
         for self.__db_row in self.__db_cursor.execute(
                 "SELECT id FROM zones WHERE area_id = :id",
             {"id": self.id}):
             self.zones_list.append(self.__db_row['id'])
     except sqlite.Error as e:
         raise TypeError("Area load SQL error: %s:" % e.args[0])
     finally:
         if self.__db_connection:
             self.__db_connection.close()
예제 #8
0
파일: data.py 프로젝트: yazici/cvlab
 def __repr__(self):
     id_ = "0x{:08X}".format(id(self))
     if self._type == Data.NONE: return '<Data [empty] at {}>'.format(id_)
     if self.type() == Data.IMAGE:
         try:
             shape = "?"
             shape = len(self._value)
             shape = self._value.shape
         except Exception:
             pass
         return '<Data [image {}] at {}>'.format(shape, id_)
     if self.type() == Data.NONE:
         return "<Data [empty image] at {}>".format(id_)
     if self.type() == Data.SEQUENCE:
         s = ""
         images_count = 0
         none_count = 0
         for d in self._value:
             if d.type() == Data.SEQUENCE:
                 s += str(d) + ", "
             if d.type() == Data.IMAGE:
                 images_count += 1
             if d.type() == Data.NONE:
                 none_count += 1
         if images_count:
             s += str(images_count) + " images, "
         if none_count:
             s += str(none_count) + " nones, "
         if len(s) > 0:
             s = s.rstrip(', ')
         s = '<Sequence ' + '[' + s + '] at {}>'.format(id_)
         return s
     raise TypeError("Wrong data type - cannot desequence")
예제 #9
0
    def __init__(self,
                 opu_type: str,
                 frametime_us: int,
                 exposure_us: int,
                 sequence_nb_prelim=0,
                 output_roi: Roi = None,
                 verbose=0,
                 name="opu"):

        if opu_type == "type1":
            from lightonopu import opu1_pybind
            self.__opu = opu1_pybind.OPU()
            self._output_shape_max = _output1_shape_max
            # With Model1 we just get the ROI in the middle
            self._output_roi_strategy = OutputRoiStrategy.mid_square
            self._output_roi_increment = 8
        elif opu_type == "type2":
            from lightonopu import opu2_pybind
            self.__opu = opu2_pybind.OPU()
            self._output_shape_max = _output2_shape_max
            # With Model2 we get max width in the middle
            self._output_roi_strategy = OutputRoiStrategy.mid_width
            self._output_roi_increment = 1
        elif opu_type == "type3":
            from lightonopu import opu3_pybind
            self.__opu = opu3_pybind.OPU()
            self._output_shape_max = _output3_shape_max
            # With Model2 we get max width in the middle
            self._output_roi_strategy = OutputRoiStrategy.mid_width
            self._output_roi_increment = 1
        else:
            raise TypeError("Don't know this OPU type: " + opu_type)

        # context for pid file
        self.pidfile = ExitStack()
        self.opu_type = opu_type
        # "off" fields allow to know what to send at resource acquisition
        # force to int if input is e.g. a float
        self._frametime_us_off = int(frametime_us)
        self._exposure_us_off = int(exposure_us)
        self._gain_dB_off = default_gain_dB
        self._output_roi_off = output_roi
        self._reserved_off = 0
        self._sequence_nb_prelim = sequence_nb_prelim
        self.name = name

        self.verbose = verbose
        from lightonml import get_trace_fn, get_debug_fn
        self._trace = get_trace_fn()
        self._debug = get_debug_fn()

        # forward opu interface to class
        self.transform1 = self.__opu.transform1
        self.transform2 = self.__opu.transform2
        self.transform_single = self.__opu.transform_single
        self.transform_online = self.__opu.transform_online
        if hasattr(self.__opu, "transform_online_test"):
            self.transform_online_test = self.__opu.transform_online_test
 def __delitem__(self, index):
     if type(index[0]) is not int:
         raise TypeError('Sparse_Matrix.__delitem__:Argument row' + ': \'' +
                         str(index[0]) + '\' must be int \'')
     if type(index[1]) is not int:
         raise TypeError('Sparse_Matrix.__delitem__:Argument col' + ': \'' +
                         str(index[1]) + '\' must be int \'')
     if index[0] < 0:
         raise TypeError('Sparse_Matrix.__delitem__:Argument row' + ': \'' +
                         str(index[0]) + '\' must be greater than 0 \'')
     if index[1] < 0:
         raise TypeError('Sparse_Matrix.__delitem__:Argument col' + ': \'' +
                         str(index[1]) + '\' must be greater than 0 \'')
     if index[0] > self.rows - 1:
         raise TypeError('Sparse_Matrix.__delitem__:Argument row' + ': \'' +
                         str(index[0]) + '\' must be within index \'')
     if index[1] > self.cols - 1:
         raise TypeError('Sparse_Matrix.__delitem__:Argument col' + ': \'' +
                         str(index[1]) + '\' must be within index \'')
     if len(index) != 2:
         raise TypeError(
             'Sparse_Matrix.__delitem__:Argument must tuple of 2\'')
     if index not in self.matrix.keys():
         return
     self.matrix.pop(index)
예제 #11
0
 def answer(self, EventStr):
     if isinstance(EventStr, str):
         if EventStr[0:2] == 'UK':
             try:
                 self.__id = int(EventStr[3:5])
             except ValueError:
                 raise TypeError(
                     "Utility key event conversion error - wrong id")
             if EventStr[5:8] == '&ok':
                 self.__keyswitch_obj = SLists.getKeySwitch(self.__id)
             elif EventStr[5:10] != '&fail':
                 raise TypeError(
                     "Utility key event answer should end with &ok or &fail"
                 )
         else:
             raise TypeError(
                 "Utility key event answer should start with UK")
     else:
         raise TypeError("Utility key event answer should be string")
예제 #12
0
파일: data.py 프로젝트: yazici/cvlab
 def desequence_all(self):
     with self.lock:
         """Zwraca tablice jednowymiarowa z wszystkimi wartosciami sekwencji"""
         if self._type == Data.NONE: return [None]
         if self._type == Data.IMAGE: return [self._value]
         if self._type == Data.SEQUENCE:
             t = []
             for d in self._value:
                 t += d.desequence_all()
             return t
         raise TypeError("Wrong data type - cannot desequence")
 def __rsub__(self, left):
     if type(left) not in [int, float, Sparse_Matrix]:
         raise TypeError('unsupported operand type(s) for +' + ': \'' +
                         type_as_str(self) + '\' and \'' +
                         type_as_str(left) + '\'')
     if type(left) in [int, float]:
         nm = Sparse_Matrix(self.rows, self.cols)
         for index in range(self.rows):
             for indexs in range(self.cols):
                 fr = self.matrix.get((index, indexs), 0) - left
                 nm[index, indexs] = fr
         return nm
예제 #14
0
 def __init__(self,
              transactions: List[Transaction],
              number: str,
              hash_number: str,
              timestamp: str):
     self.transactions: List[Transaction] = transactions
     self.number = number
     self.hash_number = hash_number
     self.timestamp = timestamp
     for (key, value) in self.__dict__.items():
         if isinstance(value, HexBytes):
             raise TypeError(f"{key} has invalid type: {type(value)}")
예제 #15
0
 def answer(self, EventStr):
     if isinstance(EventStr, str):
         if EventStr[0:2] == 'RZ':
             try:
                 self.__zone_id = int(EventStr[3:5])
             except ValueError:
                 raise TypeError(
                     "Zone conversion error - wrong identificator")
             if self.__zone_id < 1 or self.__zone_id > 48:
                 raise TypeError("Zone must be between 1..48")
             if len(EventStr) == 10:
                 self.__mode = EventStr[5:6]
                 self.__status = EventStr[6:10]
                 self.zone.update(self.__mode, self.__status)
             else:
                 raise TypeError(
                     "Zone event answer length must be 10 bytes")
         else:
             raise TypeError("Zone event answer should start with RZ")
     else:
         raise TypeError("Zone event should be string")
예제 #16
0
    def answer(self, EventStr):
        if isinstance(EventStr, str):
            if (EventStr[0:2] == 'RA') or (EventStr[0:2]
                                           == 'AA') or (EventStr[0:2] == 'AD'):
                try:
                    self.__area_id = int(EventStr[3:5])
                except ValueError:
                    raise TypeError("Area conversion error - wrong area")
                if self.__area_id < 1 or self.__area_id > 4:
                    raise TypeError("Area must be between 1..4")
                if EventStr[0:2] == 'RA':
                    if len(EventStr) == 12:
                        self.__mode = EventStr[5:6]
                        self.__status = EventStr[6:12]
                        self.area.update(self.__mode, self.__status)
                    else:
                        raise TypeError(
                            "Request event answer length must be 12 bytes")
                elif (EventStr[0:2] == 'AA') or (EventStr[0:2] == 'AD'):
                    if EventStr[5:8] == '&ok':
                        self.area.update(self.mode)
                    elif EventStr[5:10] != '&fail':
                        raise TypeError(
                            "Area event answer AA or AD should end with &ok or &fail"
                        )

            else:
                raise TypeError(
                    "Area event answer should start with RA, AA, AD")
        else:
            raise TypeError("Area event should be string")
예제 #17
0
    def update_status(self, status):
        try:
            self._status = status
            self._last_refresh = datetime.now()

            self._db_connection = sqlite.connect('alarm.sqlite')
            self._db_cursor = self._db_connection.cursor()
            self._db_cursor.execute(
                "UPDATE zones SET status= :new_status, last_refresh= :new_date WHERE id = :id",
                {
                    "id": self._id,
                    "status": self._status,
                    "last_refresh": self._last_refresh
                })
            self._db_connection.commit()
            if self._db_cursor.rewcount == 0:
                raise TypeError("Area update: no DB record found")
        except sqlite.Error as e:
            raise TypeError("Area update SQL error: %s:" % e.args[0])
        finally:
            if self._db_connection:
                self._db_connection.close()
예제 #18
0
파일: data.py 프로젝트: yazici/cvlab
 def copy(self):
     with self.lock:
         if self._type == self.NONE:
             return EmptyData()
         if self._type == self.SEQUENCE:
             return Sequence([d.copy() for d in self._value])
         elif self._type == self.IMAGE:
             if self._value is None or (hasattr(self._value, "size")
                                        and not len(self._value)):
                 pass
             return ImageData(self._value)
         else:
             raise TypeError("Wrong Data.type")
예제 #19
0
def json_arrow_encoder(obj):
    """
    Encodes Arrow objects for JSON output.
    This function can be used with
    `json.dumps(..., default=json_arrow_encoder)`, for example.
    If the object is not an Arrow type, a TypeError is raised
    :param obj: Object to encode
    :return: JSON representation of Arrow object as defined by Arrow
    """
    if isinstance(obj, arrow.Arrow):
        return obj.for_json()

    raise TypeError("Object {} is not JSON serializable".format(obj))
예제 #20
0
def jsonify(*args, **kwargs):
    """Serialize data to JSON and wrap it in a :class:`~flask.Response`
    with the :mimetype:`application/json` mimetype.
    Uses :func:`dumps` to serialize the data, but ``args`` and
    ``kwargs`` are treated as data rather than arguments to
    :func:`json.dumps`.
    1.  Single argument: Treated as a single value.
    2.  Multiple arguments: Treated as a list of values.
        ``jsonify(1, 2, 3)`` is the same as ``jsonify([1, 2, 3])``.
    3.  Keyword arguments: Treated as a dict of values.
        ``jsonify(data=data, errors=errors)`` is the same as
        ``jsonify({"data": data, "errors": errors})``.
    4.  Passing both arguments and keyword arguments is not allowed as
        it's not clear what should happen.
    .. code-block:: python
        from flask import jsonify
        @app.route("/users/me")
        def get_current_user():
            return jsonify(
                username=g.user.username,
                email=g.user.email,
                id=g.user.id,
            )
    Will return a JSON response like this:
    .. code-block:: javascript
        {
          "username": "******",
          "email": "admin@localhost",
          "id": 42
        }
    The default output omits indents and spaces after separators. In
    debug mode or if :data:`JSONIFY_PRETTYPRINT_REGULAR` is ``True``,
    the output will be formatted to be easier to read.
    .. versionchanged:: 0.11
        Added support for serializing top-level arrays. This introduces
        a security risk in ancient browsers. See :ref:`security-json`.
    .. versionadded:: 0.2
    """
    if args and kwargs:
        raise TypeError("jsonify() behavior undefined when passed both args and kwargs")
    elif len(args) == 1:  # single args are passed directly to dumps()
        data = args[0]
    else:
        data = args or kwargs

    return current_app.response_class(
        f"{dumps(data)}\n", mimetype=current_app.config["JSONIFY_MIMETYPE"]
    )
 def __pow__(self, right):
     if type(right) is not int:
         raise TypeError('unsupported operand type(s) for +' + ': \'' +
                         type_as_str(self) + '\' and \'' +
                         type_as_str(right) + '\'')
     if right < 1:
         raise AssertionError('number must be greater than 0')
     if self.cols != self.rows:
         raise AssertionError(
             'Sparse_Matrix must be square(rows and columns must be equal)')
     nm = Sparse_Matrix(self.rows, self.cols)
     for idex in range(nm.rows):
         for indexs in range(nm.cols):
             power = int(self.matrix.get((idex, indexs), 0))**int(right)
             nm[idex, indexs] = power
     return nm
예제 #22
0
 def __init__(self, id):
     self.id = id
     self.name = None
     try:
         self.__db_connection = sqlite.connect('alarm.sqlite')
         self.__db_connection.row_factory = sqlite.Row
         self.__db_cursor = self.__db_connection.cursor()
         self.__db_cursor.execute(
             "SELECT desc FROM keyswitches WHERE id = :id", {"id": self.id})
         self.__db_row = self.__db_cursor.fetchone()
         if self.__db_row:
             self.name = self.__db_row['desc']
     except sqlite.Error as e:
         raise TypeError("Key switch load SQL error: %s:" % e.args[0])
     finally:
         if self.__db_connection:
             self.__db_connection.close()
예제 #23
0
 def load_from_db(self):
     try:
         self.__db_connection = sqlite.connect('alarm.sqlite')
         self.__db_connection.row_factory = sqlite.Row
         self.__db_cursor = self.__db_connection.cursor()
         self.__db_cursor.execute(
             "SELECT name, mode, status, last_refresh FROM areas WHERE id = :id",
             {"id": self.id})
         self.__db_row = self.__db_cursor.fetchone()
         if self.__db_row:
             self.name = self.__db_row['name']
             self.mode = self.__db_row['mode']
             self.status = self.__db_row['status']
             self.last_refresh = self.__db_row['last_refresh']
     except sqlite.Error as e:
         raise TypeError("Area load SQL error: %s:" % e.args[0])
     finally:
         if self.__db_connection:
             self.__db_connection.close()
 def __setitem__(self, index, val):
     if type(index[0]) is not int:
         raise TypeError('Sparse_Matrix.__setitem__:Argument row' + ': \'' +
                         str(index[0]) + '\' must be int \'')
     if type(index[1]) is not int:
         raise TypeError('Sparse_Matrix.__setitem__:Argument col' + ': \'' +
                         str(index[1]) + '\' must be int \'')
     if index[0] < 0:
         raise TypeError('Sparse_Matrix.__setitem__:Argument row' + ': \'' +
                         str(index[0]) + '\' must be greater than 0 \'')
     if index[1] < 0:
         raise TypeError('Sparse_Matrix.__setitem__:Argument col' + ': \'' +
                         str(index[1]) + '\' must be greater than 0 \'')
     if index[0] > self.rows - 1:
         raise TypeError('Sparse_Matrix.__setitem__:Argument row' + ': \'' +
                         str(index[0]) + '\' must be within index \'')
     if index[1] > self.cols - 1:
         raise TypeError('Sparse_Matrix.__setitem__:Argument col' + ': \'' +
                         str(index[1]) + '\' must be within index \'')
     if len(index) != 2:
         raise TypeError(
             'Sparse_Matrix.__setitem__:Argument must tuple of 2\'')
     if type(val) not in [int, float]:
         raise TypeError(
             'Sparse_Matrix.__setitem__:Argument value must be an int or float(numeric)'
         )
     if val > 0:
         dict2 = {index: val}
         self.matrix.update(dict2)
     if index not in self.matrix.keys():
         return
     if val == 0 and self.matrix.get(index) != 0:
         self.matrix.pop(index)
     else:
         dict2 = {index: val}
         self.matrix.update(dict2)
예제 #25
0
 def __init__(self, EventStr):
     self.call_str = None
     self.created = None
     self.desc = None
     if EventStr[0:2] == 'RA':
         if len(EventStr) == 5:
             self.desc = 'Area request'
         else:
             raise TypeError("Area request event length must be 5 bytes")
     elif EventStr[0:2] == 'AD':
         if len(EventStr) == 5:
             self.desc = 'Area disarm'
         else:
             raise TypeError("Area disarm event length must be 5 bytes")
     elif EventStr[0:2] == 'AA':
         if (len(EventStr) < 5) or (len(EventStr) > 6):
             raise TypeError("Area arm event length must be 5..6 bytes")
         if len(EventStr) == 6:
             if (EventStr[5:6] != 'F') \
               and (EventStr[5:6] != 'I') \
               and (EventStr[5:6] != 'S') \
               and (EventStr[5:6] != 'A') :
                 raise TypeError("Area arm event must be F,I,S,A")
     else:
         raise TypeError("Area event should start with RA, AA, AD")
     try:
         self.__area = int(EventStr[3:5])
     except ValueError:
         raise TypeError("Area Event conversion error - wrong area")
     if self.__area < 1 or self.__area > 4:
         raise TypeError("Area Event error: area must be between 1..4")
     self.call_str = EventStr
     self.created = datetime.now()
     self.__area_obj = next((x for x in AreaList if x.id == self.__area),
                            None)
     if (EventStr[0:2] == 'AA') and (len(EventStr) == 5):
         self.call_str = self.call_str + 'I'
     if (EventStr[0:2] == 'AA') or (EventStr[0:2] == 'AD'):
         self.call_str = self.call_str + '<passw>'
         self.__mode = self.call_str[5:6]
예제 #26
0
 def load_from_db(self):
     try:
         self.__db_connection = sqlite.connect(
             'db.sqlite',
             detect_types=sqlite.PARSE_DECLTYPES | sqlite.PARSE_COLNAMES)
         self.__db_connection.row_factory = sqlite.Row
         self.__db_cursor = self.__db_connection.cursor()
         self.__db_cursor.execute(
             'SELECT name, mode, status, area_id, last_refresh, mqtt_topic FROM zones WHERE id = :id',
             {"id": self.id})
         self.__db_row = self.__db_cursor.fetchone()
         if self.__db_row:
             self.name = self.__db_row['name']
             self.mode = self.__db_row['mode']
             self.status = self.__db_row['status']
             self.area_id = self.__db_row['area_id']
             self.last_refresh = self.__db_row['last_refresh'],
             self.mqtt_topic = self.__db_row['mqtt_topic']
     except sqlite.Error as e:
         raise TypeError("Zone load SQL error: %s:" % e.args[0])
     finally:
         if self.__db_connection:
             self.__db_connection.close()
 def __add__(self, right):
     if type(right) not in [int, float, Sparse_Matrix]:
         raise TypeError('unsupported operand type(s) for +' + ': \'' +
                         type_as_str(self) + '\' and \'' +
                         type_as_str(right) + '\'')
     if type(self) is Sparse_Matrix and type(right) is Sparse_Matrix:
         if self.size() != right.size():
             raise AssertionError("Size of two Sparse_Matrix are not equal")
         nm = Sparse_Matrix(self.rows, self.cols)
         for index in range(self.rows):
             for indexs in range(self.cols):
                 fr = self.matrix.get(
                     (index, indexs), 0) + right.matrix.get(
                         (index, indexs), 0)
                 nm[index, indexs] = fr
         return nm
     if type(right) in [int, float]:
         nm = Sparse_Matrix(self.rows, self.cols)
         for index in range(self.rows):
             for indexs in range(self.cols):
                 fr = self.matrix.get((index, indexs), 0) + right
                 nm[index, indexs] = fr
         return nm
예제 #28
0
 def update(self, mode, status='OOOOOO'):
     self.last_refresh = datetime.now()
     if self.mode != mode or self.status != status:
         self.last_change = self.last_refresh
     self.mode = mode
     self.status = status
     try:
         self.__db_connection = sqlite.connect('db.sqlite')
         self.__db_cursor = self.__db_connection.cursor()
         self.__db_cursor.execute(
             "UPDATE areas SET status= :new_status, mode= :new_mode, last_refresh= :new_date WHERE id = :id",
             {
                 "id": self.id,
                 "new_status": self.status,
                 "new_mode": self.mode,
                 "new_date": self.last_refresh
             })
         self.__db_connection.commit()
         logger.info(
             "Area '{0:s}' updated: mode:{1:s} status:{2:s} last_refresh:{3:%Y-%m-%d %H:%M:%S}"
             .format(self.name, self.mode, self.status, self.last_refresh))
         if self.__db_cursor.rowcount == 0:
             raise TypeError(
                 "Area '{0:s}' update: no DB record found".format(
                     self.name))
     except sqlite.Error as e:
         if self.__db_connection:
             self.__db_connection.rollback()
         raise TypeError("Area {0:s}' update SQL error: %s:" %
                         e.args[0].format(self.name))
     finally:
         if self.__db_connection:
             self.__db_connection.close()
     # Getting mode string
     if self.mode == 'D':
         l_mode_str = 'Disarmed'
     elif self.mode == 'A':
         l_mode_str = 'Armed'
     elif self.mode == 'F':
         l_mode_str = 'Force armed'
     elif self.mode == 'S':
         l_mode_str = 'Stay armed'
     elif self.mode == 'I':
         l_mode_str = 'Instant armed'
     # Getting status string
     if self.status == 'OOOOOO':
         l_status_list = ['Ready']
     else:
         l_status_list = []
         if self.status[0:1] == 'M':
             l_status_list.append('Zone in memory')
         if self.status[1:2] == 'T':
             l_status_list.append('Trouble')
         if self.status[2:3] == 'N':
             l_status_list.append('Not ready')
         if self.status[3:4] == 'P':
             l_status_list.append('In programming')
         if self.status[4:5] == 'A':
             l_status_list.append('In alarm')
         if self.status[5:6] == 'S':
             l_status_list.append('Strobe')
     self.mqtt_payload = json.dumps(
         dict([
             ("last_refresh_dt",
              self.last_refresh.strftime("%Y-%m-%d %H:%M:%S")),
             ("last_change_dt",
              self.last_change.strftime("%Y-%m-%d %H:%M:%S")),
             ("mode_str", l_mode_str),
             ("status_str", '; '.join(l_status_list)),
             ("mode", self.mode),
             ("status", self.status),
         ]))
     comm.mqtt.publish(self.mqtt_topic, self.mqtt_payload)
예제 #29
0
 def add(self, note):
     if type(note) == Note:
         self.notes.append(note)
     else:
         raise TypeError('Should be a Note object')
예제 #30
0
def printHello(aa):
    if not isinstance(aa, str):
        raise TypeError("bad parameter type")
    print("hello", str)