def indication(self, pdu): if _debug: MiddleMan._debug('indication %r (connected %r)', pdu, self.connected) # no data means EOF, stop if not pdu.pduData: if _debug: MiddleMan._debug(' - flushing') # get the actor and tell it to flush and close director.get_actor(server_addr).flush() stop() return # empty lines are ignored if pdu.pduData == '\n': return # turn it into something to pickle try: data = eval(pdu.pduData[:-1]) if _debug: MiddleMan._debug(' - data: %r', data) except Exception, err: if _debug: MiddleMan._debug("eval exception: %r", err) return
def main(): global this_device global this_application # parse the command line arguments args = ConfigArgumentParser(description=__doc__).parse_args() if _debug: _log.debug("initialization") if _debug: _log.debug(" - args: %r", args) # make a device object this_device = LocalDeviceObject( objectName=args.ini.objectname, objectIdentifier=int(args.ini.objectidentifier), maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted), segmentationSupported=args.ini.segmentationsupported, vendorIdentifier=int(args.ini.vendoridentifier), ) # make a simple application this_application = WhoIsIAmApplication(this_device, args.ini.address) this_application.i_am() _log.debug("running") run() stop() _log.debug("fini")
def next_request(self): if _debug: ReadPointListApplication._debug("next_request") # check to see if we're done if not self.point_queue: if _debug: ReadPointListApplication._debug(" - done") stop() return # get the next request addr, obj_type, obj_inst, prop_id = self.point_queue.popleft() # build a request request = ReadPropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, ) request.pduDestination = Address(addr) if _debug: ReadPointListApplication._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) # set a callback for the response iocb.add_callback(self.complete_request) if _debug: ReadPointListApplication._debug(" - iocb: %r", iocb) # send the request this_application.request_io(iocb)
def prop_vendor_ack(self, iocb): # do something for success if iocb.ioResponse: apdu = iocb.ioResponse # decode results from bacnet_settings's read property self.response_bacset = net.dcode(apdu) # get actual proxy IP from Device actual_IP = self.response_bacset[1] # Check public IP public_IP = self.get_public_ip() print public_IP # check if IPs are real IPV4 # If both IPs are different, do a write property to the correct object if self.validate_ip(actual_IP) and self.validate_ip(public_IP): if actual_IP != public_IP: self.proxyIP = public_IP deferred(self.write_bac_set) print actual_IP, public_IP else: print "IPs are the same" stop() else: print "IPs are not valid" stop() #deferred(self.write_bac_set) # do something for error/reject/abort if iocb.ioError: sys.stdout.write(str(iocb.ioError) + '\n')
def next_request(self): if _debug: ReadPropertyApplication._debug("next_request") global device_address, object_identifier, property_list # check to see if we're done if not property_list: if _debug: ReadPropertyApplication._debug(" - done") stop() return # get the next request self.property_identifier = property_list.popleft() if _debug: ReadPropertyApplication._debug(" - property_identifier: %r", self.property_identifier) # build a request request = ReadPropertyRequest( destination=device_address, objectIdentifier=object_identifier, propertyIdentifier=self.property_identifier, ) if _debug: ReadPropertyApplication._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) # set a callback for the response iocb.add_callback(self.complete_request) if _debug: ReadPropertyApplication._debug(" - iocb: %r", iocb) # send the request this_application.request_io(iocb)
def indication(self, pdu): if _debug: MiddleMan._debug('indication %r', pdu) # empty downstream packets mean EOF if not pdu.pduData: stop() return # decode the line and trim off the eol line = str(pdu.pduData.decode('utf-8'))[:-1] if _debug: MiddleMan._debug(' - line: %r', line) line_parts = line.split(' ', 1) if _debug: MiddleMan._debug(' - line_parts: %r', line_parts) if len(line_parts) != 2: sys.stderr.write("err: invalid line: %r\n" % (line, )) return addr, msg = line_parts # check the address dest = Address(addr) if _debug: MiddleMan._debug(' - dest: %r', dest) # send it along try: self.request(PDU(msg.encode('utf_8'), destination=dest)) except Exception as err: sys.stderr.write("err: %r\n" % (err, )) return
def callback(self, iocb): try: global result, count, tag_keys import datetime dt = datetime.datetime.now() count += 1 #print iocb.ioResponse,iocb.ioError if iocb.ioResponse: apdu = iocb.ioResponse key = str(apdu.pduSource) + "#" + str( apdu.objectIdentifier[0]) + "#" + str( apdu.objectIdentifier[1]) + "#" + apdu.apdu_contents( )["propertyIdentifier"] tag = tag_keys.pop(key) timestamp = dt.strftime("%Y-%m-%d %H:%M:%S") datatype = get_datatype( apdu.objectIdentifier[0], apdu.apdu_contents()["propertyIdentifier"]) if not datatype: raise TypeError("unknown datatype") value = apdu.propertyValue.cast_out(datatype) result.append({ "timestamp": timestamp, "value": str(value), "item": tag["tag"], "quality": "Good" }) if count == len(tag_list): stop() except Exception as e: print e, "==================================" raise e
def __write_value(self, config_obj_id: str, _value: float) -> None: try: # get config obj obj = self.__get_object(config_obj_id) obj_id = obj.get('object_id') obj_id = ObjectIdentifier(obj_id).value # make a bacpypes obj id addr = self.__get_device() prop_id = self.__get_prop() # write <addr> <objid> <prop> <value> value = float(_value) self.logger.debug(f"write: {config_obj_id} {_value} for port \'{obj.get('name')}\' {str(obj_id)} {prop_id} {value}") request = WritePropertyRequest( objectIdentifier=obj_id, propertyIdentifier=prop_id ) request.pduDestination = Address(addr) # the value to write datatype = get_datatype(obj_id[0], prop_id) value = datatype(value) request.propertyValue = Any() try: request.propertyValue.cast_in(value) except Exception as err: self.logger.critical(f"write: {err}") iocb = IOCB(request) self.app.request_io(iocb) self.logger.debug("write: waiting for response...") loopCount = 0 while loopCount < 20 and not iocb.ioResponse: loopCount += 1 run_once() asyncore.loop(timeout=0.2, count=1) time.sleep(0.2) self.logger.debug(f"write: loopy {loopCount}") stop() # do something for success if iocb.ioResponse: self.logger.debug(f"write: iocb response success!") apdu = iocb.ioResponse # should be an ack if not isinstance(iocb.ioResponse, SimpleAckPDU): self.logger.error(f"write: Not an ACK") return self.logger.debug(f"write: received ACK") # do something for error/reject/abort if iocb.ioError: self.logger.error(f"write: ioError {str(iocb.ioError)}") except Exception as err: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, file=sys.stdout) self.logger.critical(f"write: {err}")
def indication(self, apdu): #We only care about indications if we sent out a who is request. if not isinstance(self._request, WhoIsRequest): _log.debug( "Ignoring indication as we don't have an outstanding WhoIs") return #We only care about IAmRequest if not isinstance(apdu, IAmRequest): _log.debug("Ignoring indication as apdu is not IAm") return #Ignore IAmRequests that don't have the device id we care about. if self.expected_device_id is not None: device_type, device_instance = apdu.iAmDeviceIdentifier if device_type != 'device': raise DecodingError("invalid object type") if device_instance != self.expected_device_id: _log.debug("Ignoring IAm. Expected ID: {} Received: {}".format( self.expected_device_id, device_instance)) return self.apdu = apdu stop()
def next_request(self): # check to see if we're done if not self.point_queue: stop() return # get the next request point_id, addr, obj_type, obj_inst, prop_id, idx = self.point_queue.popleft() # build a request request = ReadPropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, propertyArrayIndex=idx ) request.pduDestination = Address(addr) # make an IOCB iocb = IOCB(request) # set a callback for the response iocb.add_callback(self.complete_request) # send the request self.request_io(iocb)
def completed(self, had_error=None): if had_error: print("had error: %r" % (had_error, )) else: for objid, objname in zip(self.object_list, self.object_names): print("%s: %s" % (objid, objname)) stop()
def completed(self, had_error=None): if had_error: print("had error: %r" % (had_error, )) else: query_output.set_result( json.dumps(self.property_result_dict, indent=4)) stop()
def run(self): if _debug: ReadPointListThread._debug("run") global this_application # loop through the points for addr, obj_type, obj_inst, prop_id in self.point_queue: # build a request request = ReadPropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, ) request.pduDestination = Address(addr) if _debug: ReadPointListThread._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) if _debug: ReadPointListThread._debug(" - iocb: %r", iocb) # give it to the application this_application.request_io(iocb) # wait for the response iocb.wait() if iocb.ioResponse: apdu = iocb.ioResponse # find the datatype datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier) if _debug: ReadPointListThread._debug(" - datatype: %r", datatype) if not datatype: raise TypeError("unknown datatype") # special case for array parts, others are managed by cast_out if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None): if apdu.propertyArrayIndex == 0: value = apdu.propertyValue.cast_out(Unsigned) else: value = apdu.propertyValue.cast_out(datatype.subtype) else: value = apdu.propertyValue.cast_out(datatype) if _debug: ReadPointListThread._debug(" - value: %r", value) # save the value self.response_values.append(value) if iocb.ioError: if _debug: ReadPointListThread._debug(" - error: %r", iocb.ioError) self.response_values.append(iocb.ioError) # done stop()
def indication(self, pdu): if _debug: MiddleMan._debug("indication %r", pdu) global server_address # no data means EOF, stop if not pdu.pduData: stop() return # pass it along self.request(PDU(pdu.pduData, destination=server_address))
def tearDown(self): # Stop the HHTP Server # stop servce_forever loop and wait until it stops server.shutdown() # Clean up the server - Release socket server.server_close() # Stop the BACnet client # Close the port manually if needed stop() this_application.mux.directPort.handle_close()
def disconnect(self): """ Stop the BACnet stack. Free the IP socket. """ print('Stopping BACnet stack') # Freeing socket try: self.this_application.mux.directPort.handle_close() except: self.this_application.mux.broadcastPort.handle_close() stop() # Stop Core self.t.join() logger.info('BACnet stopped')
def indication(self, add_actor=None, del_actor=None, actor_error=None, error=None): if add_actor: if _debug: MiddleManASE._debug("indication add_actor=%r", add_actor) if del_actor: if _debug: MiddleManASE._debug("indication del_actor=%r", del_actor) if actor_error: if _debug: MiddleManASE._debug("indication actor_error=%r error=%r", actor_error, error) # if there are no clients, quit if not self.elementService.clients: if _debug: MiddleManASE._debug(" - quitting") stop()
def run(self): if _debug: ThreadSupervisor._debug("run") # start them up for read_thread in self.thread_list: read_thread.start() if _debug: ThreadSupervisor._debug(" - all started") # wait for them to finish for read_thread in self.thread_list: read_thread.join() if _debug: ThreadSupervisor._debug(" - all finished") # stop the core stop()
def indication(self, pdu): if _debug: MiddleMan._debug('indication %r', pdu) # empty downstream packets mean EOF if not pdu.pduData: stop() return # decode the line and trim off the eol line = pdu.pduData.decode('utf-8')[:-1] if _debug: MiddleMan._debug(' - line: %r', line) line_parts = line.split(' ', 1) if _debug: MiddleMan._debug(' - line_parts: %r', line_parts) if len(line_parts) != 2: sys.stderr.write("err: invalid line: %r\n" % (line, )) return addr, msg = line_parts # check the address if addr == "*": if not local_broadcast_tuple: sys.stderr.write("err: no local broadcast\n") return dest = local_broadcast_tuple elif ':' in addr: addr, port = addr.split(':') if addr == "*": if not local_broadcast_tuple: sys.stderr.write("err: no local broadcast\n") return dest = (local_broadcast_tuple[0], int(port)) else: dest = (addr, int(port)) else: dest = (addr, local_unicast_tuple[1]) if _debug: MiddleMan._debug(' - dest: %r', dest) # send it along try: self.request(PDU(msg.encode('utf_8'), destination=dest)) except Exception as err: sys.stderr.write("err: %r\n" % (err, )) return
def indication(self, *args, **kwargs): if _debug: ConnectionASE._debug('ConnectionASE.indication %r %r', args, kwargs) if 'addPeer' in kwargs: if _debug: ConnectionASE._debug(" - add peer %s", kwargs['addPeer']) if 'delPeer' in kwargs: if _debug: ConnectionASE._debug(" - delete peer %s", kwargs['delPeer']) if _debug: ConnectionASE._debug(' - director.clients: %r', director.clients) if not director.clients: stop()
def indication(self, addPeer=None, delPeer=None): """ This function is called by the TCPDirector when the client connects to or disconnects from a server. It is called with addPeer or delPeer keyword parameters, but not both. """ if _debug: MiddleManASE._debug('indication addPeer=%r delPeer=%r', addPeer, delPeer) if addPeer: if _debug: MiddleManASE._debug(" - add peer %s", addPeer) if delPeer: if _debug: MiddleManASE._debug(" - delete peer %s", delPeer) # if there are no clients, quit if not self.elementService.clients: if _debug: MiddleManASE._debug(" - quitting") stop()
def indication(self, pdu): if _debug: MiddleMan._debug('indication %r', pdu) if not pdu.pduData: stop() return # decode the line and trim off the eol line = pdu.pduData.decode('utf_8')[:-1] if _debug: MiddleMan._debug(' - line: %r', line) line_parts = line.split(' ', 1) if _debug: MiddleMan._debug(' - line_parts: %r', line_parts) if len(line_parts) != 2: sys.stderr.write("err: invalid line: %r\n" % (line,)) return addr, msg = line_parts try: address = Address(str(addr)) if _debug: MiddleMan._debug(' - address: %r', address) except Exception as err: sys.stderr.write("err: invalid address %r: %r\n" % (addr, err)) return # check for a broadcast message if address.addrType == Address.localBroadcastAddr: dest = local_broadcast_tuple if _debug: MiddleMan._debug(" - requesting local broadcast: %r", dest) elif address.addrType == Address.localStationAddr: dest = address.addrTuple if _debug: MiddleMan._debug(" - requesting local station: %r", dest) else: sys.stderr.write("err: invalid destination address type\n") return # send it along try: self.request(PDU(msg.encode('utf_8'), destination=dest)) except Exception as err: sys.stderr.write("err: %r\n" % (err,)) return
def ping(self) -> None: try: # build a request request = WhoIsRequest() # ping all devices on network request.pduDestination = GlobalBroadcast() # make an IOCB (input output callback) iocb = IOCB(request) self.app.request_io(iocb) self.logger.debug("ping: waiting for responses...") loopCount = 0 while loopCount < 20 and not iocb.ioResponse: loopCount += 1 run_once() asyncore.loop(timeout=0.2, count=1) time.sleep(0.2) self.logger.debug(f"ping: loopy {loopCount}") stop() # handle responses if iocb.ioResponse: self.logger.debug(f"ping: iocb response success!") apdu = iocb.ioResponse if not isinstance(apdu, IAmRequest): self.logger.error(f"ping: Not an IAmRequest") return device_type, device_instance = apdu.iAmDeviceIdentifier if device_type != 'device': raise DecodingError("ping: invalid object type") self.logger.info(f"ping: pduSource={repr(apdu.pduSource)}") self.logger.info(f"ping: deviceId={str(apdu.iAmDeviceIdentifier)}") # do something for error/reject/abort if iocb.ioError: self.logger.error(f"ping: {str(iocb.ioError)}") except Exception as err: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, file=sys.stdout) self.logger.critical(f"ping: {err}")
def indication(self, pdu): if _debug: MiddleMan._debug('indication %r', pdu) # empty downstream packets mean EOF if not pdu.pduData: stop() return # decode the line and trim off the eol line = pdu.pduData.decode('utf-8')[:-1] if _debug: MiddleMan._debug(' - line: %r', line) line_parts = line.split(' ', 1) if _debug: MiddleMan._debug(' - line_parts: %r', line_parts) if len(line_parts) != 2: sys.stderr.write("err: invalid line: %r\n" % (line,)) return addr, msg = line_parts # check the address if addr == "*": dest = local_broadcast_tuple elif ':' in addr: addr, port = addr.split(':') if addr == "*": dest = (local_broadcast_tuple[0], int(port)) else: dest = (addr, int(port)) else: dest = (addr, local_unicast_tuple[1]) if _debug: MiddleMan._debug(' - dest: %r', dest) # send it along try: self.request(PDU(msg.encode('utf_8'), destination=dest)) except Exception as err: sys.stderr.write("err: %r\n" % (err,)) return
def next_request(self): if _debug: ReadPointListApplication._debug("next_request") # check to see if we're done if not self.point_queue: if _debug: ReadPointListApplication._debug(" - done") stop() return # get the next request addr, obj_type, obj_inst, prop_id = self.point_queue.popleft() # build a request self._request = ReadPropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id) self._request.pduDestination = Address(addr) if _debug: ReadPointListApplication._debug(" - request: %r", self._request) # forward it along BIPSimpleApplication.request(self, self._request)
def next_request(self): if _debug: ReadPointListApplication._debug("next_request") # check to see if we're done if not self.point_queue: if _debug: ReadPointListApplication._debug(" - done") stop() return # get the next request addr, obj_type, obj_inst, prop_id = self.point_queue.popleft() # build a request self._request = ReadPropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, ) self._request.pduDestination = Address(addr) if _debug: ReadPointListApplication._debug(" - request: %r", self._request) # forward it along BIPSimpleApplication.request(self, self._request)
def handle_request(self, iocb): if iocb.shutdown: stop() return apdu = iocb.ioRequest if isinstance(apdu, ConfirmedRequestSequence): # if iocb.request_self: # self._handle_self_request(iocb) # return # assign an invoke identifier apdu.apduInvokeID = self.get_next_invoke_id(apdu.pduDestination) # build a key to reference the IOCB when the response comes back invoke_key = (apdu.pduDestination, apdu.apduInvokeID) # keep track of the request self.iocb[invoke_key] = iocb try: self.request(apdu) except StandardError as e: iocb.set_exception(e)
def next_request(self): if _debug: ReadPointListApplication._debug("next_request") # check to see if we're done if not self.point_queue: if _debug: ReadPointListApplication._debug(" - done") stop() return # get the next request point_info = self.point_queue.popleft() if _debug: ReadPointListApplication._debug(" - point_info: %r", point_info) # build a request request = ReadPropertyRequest( destination=Address(point_info["address"]), objectIdentifier=ObjectIdentifier(point_info["objectIdentifier"]).value, propertyIdentifier=point_info.get("propertyIdentifier", "presentValue"), ) if _debug: ReadPointListApplication._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) iocb.point_info = point_info # set a callback for the response iocb.add_callback(self.complete_request) if _debug: ReadPointListApplication._debug(" - iocb: %r", iocb) # send the request this_application.request_io(iocb)
def indication(self, apdu): #We only care about indications if we sent out a who is request. if not isinstance(self._request, WhoIsRequest): _log.debug("Ignoring indication as we don't have an outstanding WhoIs") return #We only care about IAmRequest if not isinstance(apdu, IAmRequest): _log.debug("Ignoring indication as apdu is not IAm") return #Ignore IAmRequests that don't have the device id we care about. if self.expected_device_id is not None: device_type, device_instance = apdu.iAmDeviceIdentifier if device_type != 'device': raise DecodingError("invalid object type") if device_instance != self.expected_device_id: _log.debug("Ignoring IAm. Expected ID: {} Received: {}".format(self.expected_device_id, device_instance)) return self.apdu = apdu stop()
def indication(self, add_actor=None, del_actor=None, actor_error=None, error=None): if add_actor: if _debug: MiddleManASE._debug("indication add_actor=%r", add_actor) if del_actor: if _debug: MiddleManASE._debug("indication del_actor=%r", del_actor) # if there are no clients, quit if not self.elementService.clients: if _debug: MiddleManASE._debug(" - no clients, stopping") stop() if actor_error: if _debug: MiddleManASE._debug("indication actor_error=%r error=%r", actor_error, error) # tell the director to close self.elementService.disconnect(actor_error.peer)
def simple_ack(self, iocb): if iocb.ioResponse: # should be an ack if not isinstance(iocb.ioResponse, SimpleAckPDU): #if _debug: WriteSomethingConsoleCmd._debug(" - not an ack") #return stop() sys.stdout.write("ack\n") stop() # do something for error/reject/abort if iocb.ioError: sys.stdout.write(str(iocb.ioError) + '\n') stop()
def close(self): self.__stopped = True self.__connected = False stop()
def doStop(): stop() applicationThread.join()
def stop(self): stop()
# wait for request wait = 0 while this_application._Application__response_value == None and wait <= maximumWait: wait = wait + 0.01 time.sleep(0.01) returnVal = this_application._Application__response_value except Exception, e: returnVal = None print "An error has happened (CPLRW 126): " + str(e) + "\n" finally: # print "the total wait time was: " + str(wait) + " seconds" # join thread (jordan) stop() applicationThread.join() return returnVal def write(device, portObject, value): request_addr = device.getRequestAddress() obj_type = portObject.getType() obj_inst = portObject.getPortNum() prop_id = portObject.getProp() index = portObject.getIndex() priority = portObject.getPriority() try: # verify datatype
def confirmation(self, apdu): self.apdu = apdu stop()
def doStop(appIndex): global applications application = applications[appIndex] #print application #deferred(stop, application) stop()
def indication(self, apdu): if not self.expect_confirmation: self.apdu = apdu stop()
def indication(self, apdu): self.apdu = apdu stop()
def time_out(): time.sleep(args.timeout) stop()