Exemplo n.º 1
0
    def connect(self):
        ret = False

        if self._option['conn']['method'] == 'rtu':
            self._conn = ModbusSerialClient(
                method='rtu',
                port=self._option['conn']['port'],
                timeout=self._timeout,
                baudrate=self._option['conn']['baudrate'])
            ret = self._conn.connect()
            msg = "failed to connect with rtu"
            code = NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION
        elif self._option['conn']['method'] == 'tcpc':
            self._conn = ModbusTcpClient(self._option['conn']['host'],
                                         port=self._option['conn']['port'],
                                         timeout=self._timeout)
            ret = self._conn.connect()
            msg = "failed to connect with tcp"
            code = NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION
        else:
            msg = "It's a wrong connection method. " + str(
                self._option['conn']['method'])

        if ret == False:
            self._logger.warn(msg)
            noti = Notice(
                None, NotiCode.RTU_FAILED_CONNECTION)  # detection is canceled
        else:
            noti = Notice(None,
                          NotiCode.RTU_CONNECTED)  # detection is canceled

        self.writecb(noti)
        super(KSX3267Mate, self).connect()
        return ret
Exemplo n.º 2
0
 def sendnoticeforactuatorstatus(self, ndinfo):
     blk = Notice(ndinfo["id"], NotiCode.ACTUATOR_STATUS, ndinfo["id"],
                  ndinfo["nd"])
     self.writecb(blk)
     for devid, info in ndinfo["act"].iteritems():
         blk = Notice(ndinfo["id"], NotiCode.ACTUATOR_STATUS, devid, info)
         self.writecb(blk)
Exemplo n.º 3
0
 def canceldetection(self, params):
     time.sleep(self._timeout)
     noti = Notice(None, NotiCode.DETECT_CANCELED)  # detection is canceled
     noti.setkeyvalue("opid", self._detection["opid"])
     self.setdetection(False)
     self.writecb(noti)
     return ResCode.OK
Exemplo n.º 4
0
    def connectone(self, opt):
        ret = False
        conn = None

        if opt['method'] == 'rtu':
            conn = ModbusSerialClient(method='rtu',
                                      port=opt['port'],
                                      timeout=self._timeout,
                                      baudrate=opt['baudrate'])
            ret = conn.connect()
            msg = "failed to connect with rtu"
            code = NotiCode.RTU_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION
        elif opt['method'] == 'tcpc':
            conn = ModbusTcpClient(opt['host'],
                                   port=opt['port'],
                                   timeout=self._timeout)
            ret = conn.connect()
            msg = "failed to connect with tcp"
            code = NotiCode.TCP_CONNECTED if ret else NotiCode.RTU_FAILED_CONNECTION
        elif opt['method'] == 'tcpcs':
            self._logger.info("It would wait for a while to connect a client.")
            ret = self.listen(opt)
            msg = "failed to connect with tcp"
            code = NotiCode.TCP_WAITING if ret else NotiCode.RTU_FAILED_CONNECTION
            conn = None
        else:
            msg = "It's a wrong connection method. " + str(opt['method'])

        if ret == False:
            self._logger.warn(msg)
            noti = Notice(
                None, NotiCode.RTU_FAILED_CONNECTION)  # detection is canceled
        else:
            noti = Notice(None,
                          NotiCode.RTU_CONNECTED)  # detection is canceled

        self.writecb(noti)
        return conn
Exemplo n.º 5
0
    def detect(self):
        detected = {}
        for port, conn in self._conn.iteritems():
            if self._isdetecting == False or self.isexecuting() == False:
                self._logger.info("Total detection is canceled.")
                break
            info = self.detectone(port, conn)
            detected[port] = info

        self._logger.info("finished to detect devices : " + str(detected))
        noti = Notice(None, NotiCode.DETECT_FINISHED)  # Detection Started
        if noti:
            noti.setkeyvalue("opid", self._detection["opid"])
            for port, info in detected.iteritems():
                noti.setcontent(port, info)
            self.writecb(noti)
        self.setdetection(False)
Exemplo n.º 6
0
    def readmsg(self):
        #try:
        if self._option["conn"]["binary"]:
            buf = self._conn.read(cdtp.CDTP_MSGLEN)
            self._logger.info("buf: " + buf)
        else:
            binbuf = self._conn.read(cdtp.CDTP_BINMSGLEN * 2)
            self._logger.info("buf: " + binbuf)
            buf = binascii.unhexlify(binbuf)

        parsed = self._cdtp.parse(buf)
        if parsed:
            print "parsed", parsed
            if parsed['type'] == 'Notification':
                snid = parsed["values"]["SNID"]
                if snid in self._lastlog:
                    return self.wrapblk(parsed["values"])
                else:
                    self._logger.info("Message from a not registered device." + str(snid))
                    self._logger.info("Start to reconfigure.")
                    req = self._cdtp.reconfigure(snid, self._option['gatewaykey'], None, 60)
                    self.send(snid, req)
                    return None
            elif parsed['type'] == 'Request':
                if parsed["values"]["gatewaykey"] != self._option['gatewaykey']:
                    self._logger.info("Received from unknown gateway. Skip this request." + str(parsed["values"]["gatewaykey"]))
                    return None
                res = self._cdtp.response(parsed, cdtp.CDTP_OK)
                snid = parsed["values"]["SNID"]
                self._lastlog[snid] = datetime.datetime.now()
                self.send(snid, res)
                
                blk = Notice(self._devinfo.findid(snid, DevType.NODE), NotiCode.NODE_CONNECTED)
                return [blk]
            else:
                print "weired mblock.", parsed
        else:
            print "wrong mblock.", buf
        return None
Exemplo n.º 7
0
    def detect(self):
        detected = {}
        for unit in range(self._detection["saddr"], self._detection["eaddr"]):
            if self._isdetecting == False or self.isexecuting() == False:
                break

            noti = Notice(None, NotiCode.DETECT_NODE_STARTED,
                          devid=unit)  # Detection Started
            if noti:
                noti.setkeyvalue("opid", self._detection["opid"])
                self.writecb(noti)

            noti = None
            info = None
            while True:
                res = self.readregister(self._startregister, 6, unit)
                if res.isError():
                    break

                if len(res.registers) != 6:
                    self._logger.info(
                        "retry to get data since size of data is not matched. 6 "
                        + str(len(res.registers)))
                    continue
                break

            if res.isError():
                noti = Notice(None, NotiCode.DETECT_NO_NODE,
                              devid=unit)  # Detection Started
                self._logger.info("Fail to get information from a node : " +
                                  str(unit) + " " + str(res))

            elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE,
                                      NodeType.INTNODE):  # device type
                if res.registers[3] == ProtoVer.KS_X_3267_2018:
                    info = self.detect_node(unit, res.registers)
                    self._logger.info("Found a node : " + str(unit) + " " +
                                      str(info))
                else:
                    noti = Notice(None,
                                  NotiCode.DETECT_UNKNOWN_PROTOCOL_VER,
                                  devid=unit)  # unknown protocol version
            elif res.registers[1] == NodeType.NUTNODE:
                if res.registers[3] == ProtoVer.TTA_1:
                    info = self.detect_nutri(unit, res.registers)
                    self._logger.info("Found a nutrient system : " +
                                      str(unit) + " " + str(info))
                else:
                    noti = Notice(None,
                                  NotiCode.DETECT_UNKNOWN_PROTOCOL_VER,
                                  devid=unit)  # unknown protocol version
            else:
                noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE,
                              devid=unit)  # unknown device

            if noti is None:
                if info is None:
                    noti = Notice(None,
                                  NotiCode.DETECT_WRONG_DEVICE,
                                  devid=unit)  # fail to find a node
                else:
                    noti = Notice(None,
                                  NotiCode.DETECT_NODE_DETECTED,
                                  devid=self._option["conn"]["port"][8:],
                                  content={unit: info})  # found a node
                    detected[unit] = info

            noti.setkeyvalue("opid", self._detection["opid"])
            print "noti", noti.stringify()
            self.writecb(noti)
            time.sleep(0.1)

        self._logger.info("finished to detect devices : " + str(detected))
        noti = Notice(None, NotiCode.DETECT_FINISHED)  # Detection Started
        if noti:
            noti.setkeyvalue("opid", self._detection["opid"])
            noti.setcontent(self._option["conn"]["port"][8:], detected)
            #for lid, info in detected.iteritems():
            #                noti.setcontent(lid, info)
            self.writecb(noti)
        self.setdetection(False)
Exemplo n.º 8
0
    def detectone(self, port, conn):
        detected = {}
        if self._detection["port"] is not None and port not in self._detection[
                "port"]:
            return detected

        #for unit in range(self._detection["saddr"], self._detection["eaddr"]):
        #mrchoi87
        for unit in range(self._detection["saddr"], 12):
            #for unit in range(10, 12):
            if self._isdetecting == False or self.isexecuting() == False:
                self._logger.info("A port " + str(port) +
                                  " detection is canceled.")
                break

            tempid = port + "-" + str(unit)
            noti = Notice(None, NotiCode.DETECT_NODE_STARTED,
                          devid=tempid)  # Detection Started
            if noti:
                noti.setkeyvalue("opid", self._detection["opid"])
                self.writecb(noti)

            noti = None
            info = None
            res = None
            for _ in range(3):
                res = self.readregister(conn, KSX3267MateV2._DEVINFOREG, 6,
                                        unit)
                if res is None or res.isError():
                    continue

                if len(res.registers) != 6:
                    self._logger.info(
                        "retry to get data since size of data is not matched. 6 "
                        + str(len(res.registers)))
                    continue
                break

            if res is None or res.isError():
                noti = Notice(None, NotiCode.DETECT_NO_NODE,
                              devid=tempid)  # Detection Started
                self._logger.info("Fail to get information from a node : " +
                                  str(unit) + " " + str(res))

            elif res.registers[1] in (NodeType.SENNODE, NodeType.ACTNODE,
                                      NodeType.INTNODE):  # device type
                if res.registers[3] == ProtoVer.KS_X_3267_2018 or res.registers[
                        3] == ProtoVer.KS_X_3267_2018_v1:
                    info = self.detect_node(conn, unit, res.registers)
                    #self._logger.info ("Found a node : " + str(unit) + " " + str(info))
                else:
                    noti = Notice(None,
                                  NotiCode.DETECT_UNKNOWN_PROTOCOL_VER,
                                  devid=tempid)  # unknown protocol version
            elif res.registers[1] == NodeType.NUTNODE:
                if res.registers[3] == ProtoVer.TTA_1:
                    info = self.detect_node(conn, unit, res.registers)
                    #self._logger.info ("Found a nutrient system : " + str(unit) + " " + str(info))
                else:
                    noti = Notice(None,
                                  NotiCode.DETECT_UNKNOWN_PROTOCOL_VER,
                                  devid=tempid)  # unknown protocol version
            else:
                noti = Notice(unit, NotiCode.DETECT_UNKNOWN_NODE,
                              devid=tempid)  # unknown device

            if noti is None:
                if info is None:
                    noti = Notice(None,
                                  NotiCode.DETECT_WRONG_DEVICE,
                                  devid=tempid)  # fail to find a node
                else:
                    noti = Notice(None,
                                  NotiCode.DETECT_NODE_DETECTED,
                                  devid=port,
                                  content={unit: info})  # found a node
                    detected[unit] = info

            noti.setkeyvalue("opid", self._detection["opid"])
            print "noti", noti.stringify()
            self.writecb(noti)
            time.sleep(0.1)

        return detected
Exemplo n.º 9
0
 def sendnoticeforactuatorstatus(self, ndinfo):
     blk = Notice(ndinfo["id"], NotiCode.ACTUATOR_STATUS, ndinfo["id"],
                  ndinfo["nd"])
     for devid, info in list(ndinfo["act"].items()):
         blk.setcontent(devid, info)
     self.writecb(blk)