def setUpClass(cls): cls.network1 = canopen.Network() cls.network1.connect("test", bustype="virtual") cls.remote_node = cls.network1.add_node(2, EDS_PATH) cls.network2 = canopen.Network() cls.network2.connect("test", bustype="virtual") cls.local_node = cls.network2.create_node(2, EDS_PATH)
def __init__(self, use_sep_bus_object=False, adapter='socketcan', channel='can0', bitrate=250000): """ :param boolean use_sep_bus_object: Select wether a seperate bus object should be created and used. :param str adapter: Specify which type of CAN adapter should be used. Options: 'socketcan#, 'pcan' :raises can.CanError: When connection fails. """ # Init variables self.use_sep_bus_object = use_sep_bus_object self.adapter = adapter self.channel = channel self.bitrate = bitrate # Create empty lidst of dict for subscriptions self.rcvd_msgs = [] # Create network self.network = canopen.Network() # Connect network self.Connect()
def _setup_connection(self): """Creates a network interface object establishing an empty connection with all the network attributes already specified.""" if self._connection is None: self._connection = canopen.Network() try: self._connection.connect(bustype=self.__device, channel=self.__channel, bitrate=self.__baudrate) except (PcanError, VCIDeviceNotFoundError) as e: logger.error('Transceiver not found in network. Exception: %s', e) raise_err( lib.IL_EFAIL, 'Error connecting to the transceiver. ' 'Please verify the transceiver ' 'is properly connected.') except OSError as e: logger.error( 'Transceiver drivers not properly installed. Exception: %s', e) if hasattr(e, 'winerror') and e.winerror == 126: e.strerror = 'Driver module not found.' \ ' Drivers might not be properly installed.' raise_err(lib.IL_EFAIL, e) except Exception as e: logger.error('Failed trying to connect. Exception: %s', e) raise_err(lib.IL_EFAIL, 'Failed trying to connect. {}'.format(e)) else: logger.info('Connection already established')
async def motion_control(q): network = canopen.Network() network.connect(channel='can0', bustype='socketcan') # network.connect(channel=0 , bustype='canalystii', bitrate=500000) motor1 = f124(network, 1, 'KINCO-JDFD.EDS') motor2 = f124(network, 2, 'KINCO-JDFD.EDS') motor1.node.sdo['Controlword'].raw = 0x86 motor2.node.sdo['Controlword'].raw = 0x86 # time.sleep(0.5) # motor2.set_motor_control('disable') # motor2.set_motor_control('reset') motor1.set_motor_direct(1) motor1.set_motor_mode('speed') #motor1.set_motor_direct(1) motor2.set_motor_mode('speed') motor1.node.sdo['Profile_acceleration'].raw = 163.84 * 40 motor1.node.sdo['Profile_deceleration'].raw = 163.84 * 40 motor2.node.sdo['Profile_acceleration'].raw = 163.84 * 40 motor2.node.sdo['Profile_deceleration'].raw = 163.84 * 40 motor1.set_motor_speed(0) motor2.set_motor_speed(0) motor1.set_motor_control('enable_speed') motor2.set_motor_control('enable_speed') print('motor init ok') while True: command = await q.get() print('left_motor_speed: {}, right_motor_speed: {}'.format( command[0], command[1])) motor1.set_motor_speed(command[0]) motor2.set_motor_speed(command[1]) await asyncio.sleep(0.005)
def __init__(self): self._active_node = None self._bitrate = None self._bustype = None self._channel = None self._network = canopen.Network() # Create one network per CAN bus. self._od_file = None
def test_sync_producer(self): network = canopen.Network() network.connect(bustype="virtual", receive_own_messages=True) producer = canopen.sync.SyncProducer(network) producer.transmit() msg = network.bus.recv(1) network.disconnect() self.assertEqual(msg.arbitration_id, 0x80) self.assertEqual(msg.dlc, 0)
def __init__(self): self.network = canopen.Network() # #eventually the following lines should take arguments from config can_info = config.get('bus_info').get('CAN') try: self.network.connect(channel=can_info.get('channel'), bustype=can_info.get('bus_type')) self.connected = True nodes = config.get('can_nodes') for node in nodes: nodeData = nodes.get(node) self.network.add_node(nodeData['id'], lib_path + '/utils/eds-files/' + nodeData['eds_file']) ''' # To do this new procedure, the CAN part of the config must look like this can_nodes: motor: id: 1 eds_file: '[nodeId=001]eds_eDrive150.eds' tsi: id: 3 eds_file: pack1: id: 4 eds_file: 'Pack.eds' pack2: id: 5 eds_file: 'Pack.eds' ''' #ensure nodes are connected # self.network.scanner.search() # time.sleep(1) # print("Connected Nodes:") # for node_id in self.network.scanner.nodes: # print("Found node %d!" % node_id) allSensors = config.get('Sensors') self.sdoDict = {} for sensorName in allSensors: sensorDict = allSensors.get(sensorName) if sensorDict['bus_type'] == 'CAN': #DEBUG: print(sensorName) print(sensorDict) # print config.get('Sensors').get(sensorDict) if 'nmt' not in sensorName: self.sdoDict[sensorName] = self.configure_sdo(sensorName,sensorDict) #DEBUG: # print('sdoDict =') # print(sdoDict)] print('Made it here for some reason') except OSError: #can.CanError is an OSError self.connected = False print('CAN Bus not connecting!') return None
def test_time_producer(self): network = canopen.Network() network.connect(bustype="virtual", receive_own_messages=True) producer = canopen.timestamp.TimeProducer(network) producer.transmit(1486236238) msg = network.bus.recv(1) network.disconnect() self.assertEqual(msg.arbitration_id, 0x100) self.assertEqual(msg.dlc, 6) self.assertEqual(msg.data, b"\xb0\xa4\x29\x04\x31\x43")
def setup(): network = canopen.Network() network.connect(channel='/dev/ttyACM0', bustype='slcan', bitrate=250000) network.scanner.search() time.sleep(0.05) for node_id in network.scanner.nodes: nodes_in_network.append(node_id) network.send_message(0x200 + node_id, [0x02, 0x00, 0x01, 0x00]) # set power save mode nodes["node{0}".format(node_id)] = (canopen.RemoteNode(node_id, 'imu-dictionary.eds')) network.add_node(nodes["node{0}".format(node_id)])
def __init__(self, bustype, channel, bitrate, debug=False): self._debug = debug self.__network = canopen.Network() self.__network.connect(bustype=bustype, channel=channel, bitrate=bitrate) if self._debug: print("Opened Channel " + channel) self.__nodes = []
def __init__(self): with open('../config.yaml', 'r') as ymlfile: self.config = yaml.safe_load(ymlfile) self.selected_config = self.config['selected_config'] # local node self.connectToNetwork(canopen.Network()) self.network.create_node(5, '../eds_files/steering_node.eds') while True: sleep(1) self.network.sync.transmit()
def connect_bus(): """quick function to connect to can bus""" network = canopen.Network() node = canopen.RemoteNode(0x7C, EDS_FILE) network.add_node(node) network.connect(bustype="socketcan", channel="vcan0") # network.nmt.state = "OPERATIONAL" return network, node
def _connect(self, channel, node_idx, datasheet): """ return network, node raise HwError() if the device is not connected raise ValueError(): if the device doesn't seem the right one """ # Connect to the CANbus and the CANopen network. network = canopen.Network() bustype = 'socketcan' if channel != 'fake' else 'virtual' try: network.connect(bustype=bustype, channel=channel) network.check() except CanError: raise model.HwError("CAN network %s not found." % (channel, )) except OSError as ex: if ex.errno == 19: # No such device raise model.HwError("CAN network %s not found." % (channel, )) raise # Tell CANopen what we *expect* to find if channel == 'fake': node = FakeRemoteNode(node_idx, datasheet) else: node = canopen.RemoteNode(node_idx, datasheet) # Note: add_node() supports a "upload_eds" flag to read the object dict from # the device. However the current firmware doesn't support that. network.add_node(node) # Check the device is there, and also force the state to be updated try: if channel != "fake": node.nmt.wait_for_heartbeat(timeout=5) except NmtError: raise model.HwError( "Focus tracker not found on channel %s with ID %s" % (channel, node_idx)) logging.debug("Device is in state %s", node.nmt.state) # If the device is stopped, it won't answer any SDO if node.nmt.state not in ("OPERATIONAL", "PRE-OPERATIONAL"): node.nmt.state = "PRE-OPERATIONAL" logging.debug("Turning on the device to state %s", node.nmt.state) # Check that the device has the right Vendor ID and Product code, mostly # in case the node index corresponds to a different device, also on the network. vid = node.sdo["Identity object"]["Vendor-ID"].raw pcode = node.sdo["Identity object"]["Product code"].raw if vid != VENDOR_ID or pcode != PRODUCT_CODE: raise ValueError( "Device %d on channel %s doesn't seem to be a FocusTracker (vendor 0x%04x, product 0x%04x)" % (node_idx, channel, vid, pcode)) return network, node
def setup(): global network global node network = canopen.Network() network.connect(channel='/dev/ttyACM0', bustype='slcan', bitrate=250000) network.send_message(0x201, [0x00, 0x03, 0x01, 0xA0, 0x00]) node = canopen.RemoteNode(1, 'imu-dictionary.eds') network.add_node(node)
def __init__(self): with open('../config.yaml', 'r') as ymlfile: self.config = yaml.safe_load(ymlfile) # local node self.selected_config = self.config['selected_config'] self.connectToNetwork(canopen.Network()) self.network.create_node(5, '../eds_files/Arduino1.eds') while True: sleep(1) self.network[5].sdo[0x2000][1].phys = random.randint(0, 1024) self.network[5].sdo[0x2000][2].phys = random.randint(0, 1024) self.network.sync.transmit()
def create_network_node(self, node_id, od): # Start with creating a network representing a CAN bus network = canopen.Network() try: # Add a node with its corresponding Object Dictionary node = network.add_node(node_id, od) except Exception as e: self.ui.statusbar.showMessage(str(e), 5000) network, node = None, None return network, node
def setup(self): try: os.system('sudo ip link set can0 type can bitrate 1000000') os.system('sudo ifconfig can0 up') os.system('sudo ifconfig can0 txqueuelen 1000') # Start with creating a network representing one CAN bus self.network = canopen.Network() # Connect to the CAN bus self.network.connect(bustype='socketcan', channel='can0') self.network.check() # Add some nodes with corresponding Object Dictionaries self.node1 = canopen.BaseNode402(12, '/home/pi/canopen/examples/brunner_eds.eds') self.node2 = canopen.BaseNode402(15, '/home/pi/canopen/examples/brunner_eds.eds') for node in [self.node1, self.node2]: self.network.add_node(node) # Read a variable using SDO node.sdo[0x1006].raw = 1 node.sdo[0x1014].raw = 163 node.sdo[0x1003][0].raw = 0 # Transmit SYNC every 100 ms self.network.sync.start(0.1) for node in [self.node1, self.node2]: node.load_configuration() node.setup_402_state_machine() node.state = 'SWITCH ON DISABLED' node.op_mode = "PROFILED VELOCITY" # Read PDO configuration from node node.tpdo.read() # Re-map TxPDO1 node.tpdo[1].clear() node.tpdo[1].add_variable('Statusword') node.tpdo[1].add_variable('Position actual value') node.tpdo[1].trans_type = 1 node.tpdo[1].event_timer = 0 node.tpdo[1].enabled = True # Save new PDO configuration to node node.tpdo.save() node.rpdo.read() node.state = 'READY TO SWITCH ON' acceleration = 1600 deceleration = acceleration self.node1.sdo[0x6083].raw = acceleration # target acc self.node2.sdo[0x6083].raw = acceleration self.node1.sdo[0x6084].raw = deceleration # target dec self.node2.sdo[0x6084].raw = deceleration self.is_setup = True except Exception as e: self.is_setup = False
def canopen_test_nmt(user_os): """ canopen testing : set the state of device in NMT tested device : beckhoff remote I/O LC5100 """ print("test nmt!") # Start with creating a network representing one CAN bus net = canopen.Network() # Connect to the CAN bus # Arguments are passed to python-can's can.interface.Bus() constructor # (see https://python-can.readthedocs.io/en/latest/bus.html). # connection is depended on your OS if user_os == "linux": net.connect(bustype='socketcan', channel='can0') print("connect via \'socketcan\' to can0") else: net.connect(bustype='usb2can', channel='69E696BD', bitrate=125000) print("connect via \'usb2can\' to channel 69E696BD, bitrate=125000") # Check network net.check() # Add some nodes with corresponding Object Dictionaries node_lc5100 = canopen.RemoteNode(node_id=1, object_dictionary='LC5100.eds') for obj in node_lc5100.object_dictionary.values(): print('0x%X: %s' % (obj.index, obj.name)) net.add_node(node_lc5100) # Test NMT command by goes through each state of device nmt_cmd = {} nmt_cmd.update({"start" : 0x01}) nmt_cmd.update({"stop" : 0x02}) nmt_cmd.update({"pre_op" : 0x80}) nmt_cmd.update({"reset" : 0x81}) print("NMT command list: ") print(nmt_cmd) while True: try: user_input = input("Enter NMT command from above : ") if user_input in nmt_cmd.keys(): print("sending CMD : {}...".format(user_input)) node_lc5100.nmt.send_command(nmt_cmd.get(user_input)) else: if user_input == 'q': break else: print("command is not in the list.") except Except as e: print(e)
def canopen_test_sdo(user_os): """ canopen testing : read and write the data using SDO tested device : beckhoff remote I/O LC5100 """ print("test SDO") # Start with creating a network representing one CAN bus net = canopen.Network() # Connect to the CAN bus # Arguments are passed to python-can's can.interface.Bus() constructor # (see https://python-can.readthedocs.io/en/latest/bus.html). # connection is depended on your OS if user_os == "linux": net.connect(bustype='socketcan', channel='can0') print("connect via \'socketcan\' to can0") else: net.connect(bustype='usb2can', channel='69E696BD', bitrate=125000) print("connect via \'usb2can\' to channel 69E696BD, bitrate=125000") # Create node device. Node device should be configured as "RemoteNode". # So, Device will be able to be used as "SDO server". node_lc5100 = canopen.RemoteNode(node_id=1, object_dictionary='LC5100.eds') # Add some nodes with corresponding Object Dictionaries net.add_node(node_lc5100) # Set to pre-operational mode node_lc5100.nmt.send_command(0x80) time.sleep(3) # SDO command testing by reading object of device # Index of SDO request are from the datasheet device_type = node_lc5100.sdo['Device Type'] device_name = node_lc5100.sdo['Manufacturer Device Name'] device_harware_ver = node_lc5100.sdo['Manufacturer Hardware Version'] # For variable-type of return object from sdo[] can be extracted by using .raw print("Device type = {}".format(device_type.raw)) print("Device name = {}".format(device_name.raw)) print("Device harware version = {}".format(device_harware_ver.raw)) test_obj_index = 0x1010 sdo_object = node_lc5100.sdo[test_obj_index] print("type(sdo_object) = {}, len()={}".format(sdo_object, len(sdo_object))) # Iterate over arrays or records for value in sdo_object.values(): print("value = {}".format(value.raw)) heartbeat_time_consumer = node_lc5100.sdo[0x1016][1] heartbeat_time_producer = node_lc5100.sdo[0x1017] print("heartbeat time (consumer) : {}".format(heartbeat_time_consumer.raw)) print("heartbeat time (producer) : {}".format(heartbeat_time_producer.raw))
def detect(chan): network = canopen.Network() network.connect(bustype='socketcan', channel=chan, bitrate=500000) try: network.scanner.search() time.sleep(1) #for node_id in network.scanner.nodes: # print("Found node %d" % node_id) return network.scanner.nodes finally: network.disconnect()
def __init__(self, id, eds_file): """ add node to the can :param id: node id :param eds_file: the location of the eds file :return: """ self.network = canopen.Network() self.network.connect(channel='can0', bustype='socketcan') self.network.check() self.network.sync.start(0.01) self.id = id self.eds_file = eds_file self.node = self.network.add_node(self.id, self.eds_file)
def setup(): global network network = canopen.Network() network.connect(bustype='socketcan', channel='can1', bitrate = 250000) network.scanner.search() time.sleep(0.5) for node_id in network.scanner.nodes: nodes_in_network.append(node_id) nodes["node{0}".format(node_id)] = (canopen.RemoteNode(node_id, 'imu-dictionary.eds')) network.add_node(nodes["node{0}".format(node_id)]) network.send_message(0x200 + node_id, [0x02, 0x00, 0x01, 0x00]) time.sleep(0.5) init_flags()
def connect(self): try: self.network = canopen.Network() self.network.connect(bitrate=self.bitrate, channel=self.interface_name, bustype=self.bustype) self.connected = True except OSError: self.connected = False self.logger.error( f"Could not connect on the {self.interface_name} interface." " A reboot will probably solve the problem") raise can.CanError( f"Could not connect on the {self.interface_name} interface." " A reboot will probably solve the problem")
def connect(self): if not self.isReady(): try: self.network = canopen.Network() self.network.connect(bustype='pcan', channel='PCAN_USBBUS1', bitrate=1000000) self.canReady = True except Exception as error: self.errors.append(['CAN', 'Network not connected']) self.canReady = False
def __init__(self): #ROS Node and CAN setup self.network = canopen.Network() can_interface = rospy.get_param('~can_interface') self.network.connect(channel=can_interface, bustype='socketcan') rospy.init_node('mani_controller') position_publisher = rospy.Publisher('mani_position_read', Joints_data) position_subscriber = rospy.Subscriber('mani_position_write', Joints_data, self.can_send) self.lates_to_send = Joints_data() self.network.subscribe(0xA01, self.can_recv) self.network.subscribe(0xA02, self.can_recv) self.rate = rospy.Rate(30) # 10hz
def connect_to_network(): network = canopen.Network() with open('../config.yaml', 'r') as ymlfile: config = yaml.safe_load(ymlfile) try: selected_config = config['selected_config'] bustype = config[selected_config]['bustype'] channel = config[selected_config]['channel'] bitrate = config[selected_config]['bitrate'] network.connect(bustype=bustype, channel=channel, bitrate=bitrate) except OSError: logging.error('CanOpenListener is unable to listen to network,' ' please check if configuration is set properly!' f'(bustype = {bustype}, channel = {channel},' f' bitrate = {bitrate})') network = add_nodes(network, config[selected_config]['nodes']) return config, network
def __init__(self, logger, node_id, can_context=DEFAULT_CAN_CONTEXT, program_number=1): super(CANopenProgramDownloader, self).__init__() self.logger = logger self.node_id = node_id self.can_context = can_context self.program_number = program_number self.network = canopen.Network() self.node = self.network.add_node(self.node_id, self.create_object_dictionary()) self.data_sdo = self.node.sdo[H1F50_PROGRAM_DATA][self.program_number] self.ctrl_sdo = self.node.sdo[H1F51_PROGRAM_CTRL][self.program_number] self.swid_sdo = self.node.sdo[H1F56_PROGRAM_SWID][self.program_number] self.flash_sdo = self.node.sdo[H1F57_FLASH_STATUS][self.program_number]
def setup(): global network network = canopen.Network() network.connect(channel='/dev/ttyACM0', bustype='slcan', bitrate=250000) network.scanner.search() time.sleep(0.5) for node_id in network.scanner.nodes: nodes_in_network.append(node_id) nodes_fieldnames.append("node{0}".format(node_id)) nodes["node{0}".format(node_id)] = (canopen.RemoteNode( node_id, 'imu-dictionary.eds')) network.add_node(nodes["node{0}".format(node_id)]) network.send_message(0x200 + node_id, [0x02, 0x00, 0x01, 0x00]) print("Found node %d" % node_id) time.sleep(0.5)
def start(self, args): self._devel = args.d self._mapping.read() self._display = DisplayApp(args.d, self._mapping) self._network = canopen.Network() self._network.listeners = self._network.listeners + [ BMSListener(self._display) ] self._network.connect(bustype='socketcan', channel=args.dev) self._controller = self._network.add_node(7, 'CANopenSocket.eds') # main EWA thread here self._main_thread.start() # blocks until the UI ends try: self._display.run() except BaseException as e: logging.error(traceback.format_exc())
def __init__(self): #initialise can network self.ser = serial.Serial( 'COM8', 9800, timeout=1) # open serial port for EE controller self.network = canopen.Network() # define network self.network.connect(channel='PCAN_USBBUS1', bustype='pcan', bitrate=1000000) # establish communication self.network.check() #create driver objects for id in self.can_ids: motor = c5e.Driver(self.network, id) motor.enable() self.motors.append(motor) self.network.sync.start(0.1) self._position = (0, 4, 0) #TODO home