Giter Site home page Giter Site logo

node-canopen's Introduction

node-canopen

CANopen is the internationally standardized (EN 50325-4) CAN-based higher-layer protocol for embedded control system. More information on CANopen can be found on the CiA site

This library allows the manipulation of CANopen devices as defined in CiA 301.

Porting Guide (Version 5 -> 6)

When updating from version 5 to version 6 be aware of the following changes:

  1. Modifying the Eds via the protocol modules has been deprecated and the preferred method is to use the new dedicated methods in the Eds class itself. This change was made to allow configuration without needing to create a Device object first. The following table is non-exhaustive and serves only to illustrate the change:
Old method New method
device.emcy.cobId = 0x8A device.eds.setEmcyCobId(0x8A)
device.nmt.producerTime = 500 device.eds.setHeartbeatProducerTime(500)
device.sdo.addServer(0x8B) device.eds.addSdoClientParameter(0x8B)
device.sync.generate = true device.eds.setSyncGenerationEnable(true)
  1. NMT state now matters. Prior to version 6 the NMT state was available, but not used internally. The Device object is now aware of the NMT state and will bring up and shutdown protocol objects as the state changes. If your PDOs are not firing after the update make sure you are calling Nmt#startNode to switch to NmtState.OPERATIONAL. This new behavior should only take effect upon calling Device#start().

  2. Events have been refactored and moved to their respective protocol modules. Old events are still available, but will only fire if the Device#init() method has been called.

  3. The internal Eds array of DataObjects is now keyed from the hex index rather than the decimal index to make debug printing less confusing. A getter with the old indexing is provided so that iterating directly on Eds.dataObjects will still work as expected, however you should switch to using the new iterator methods (Eds.values(), Eds.entries(), Eds.keys()).

  4. SDO client/server parameters will no longer assume you want to add the node ID if you choose 0x580/0x600 for the SDO COB-IDs. As far as I can tell this is not officially in the standard, but was a convienence added to some other libraries.

Documentation

Pre-built documentation for the latest release is available here.

Examples for each protocol are also available in the examples folder.

Device

The Device class represents a CANopen device and provides context for the protocol objects as well as access methods for the manufacturer data fields. It contains the Eds and protocol objects.

OD Entry Description Supported
0x1000 Device type
0x1002 Manufacturer status register ✔️
0x1008 Manufacturer device name ✔️
0x1009 Manufacturer hardware version ✔️
0x100A Manufacturer software version ✔️
0x1010 Store parameters
0x1011 Restore default parameters

Eds

The Eds class represents a CANopen electronic datasheet file and can be used to load and save the eds file format as defined in CiA 306. Device configuration files (DCF) are not currently supported.

Eds provides setters for many of the communication profile objects that are defined in CiA 301. Most of the protocol objects require one or more entries in the Eds before they can function. Typically the user will want to create or set those entries before calling Device.start().

Protocols

Emergency - EMCY

The CANopen emergency protocol is used to indicate internal errors with a CANopen device. Call Emcy.write() to produce an emergency object. If a valid 'Emergency consumer object entry' is present, the Emcy module will emit event:emergency when the matching COB-ID is consumed.

OD Entry Description Supported
0x1001 Error register ✔️
0x1003 Pre-defined error field ✔️
0x1014 COB_ID EMCY ✔️
0x1015 Inhibit time EMCY ✔️
0x1028 Emergency consumer object ✔️
0x1029 Error behavior object

Layer Setting Services - LSS

The CANopen layer setting services protocol allows the CAN-ID and bitrate of an LSS consumer device to be modified. This allows for setting up a network of identical devices without relying on physical dip switches or non-volatile storage to distinguish between them.

OD Entry Description Supported
0x1018 Identity object ✔️

Supported Features:

  • LSS producer ✔️
  • LSS consumer ✔️

Network Management - NMT

The CANopen network management protocol is used to manipulate the state of NMT consumer devices on the network and is responsible for the device heartbeat. Heartbeat generation will begin automatically when 'Producer heartbeat time' is set. If a 'Consumer heartbeat time' entry is present, then the Nmt module will emit event:timeout if the consumer heartbeat is lost.

OD Entry Description Supported
0x100C Guard time
0x100D Life time factor
0x1016 Consumer heartbeat time ✔️
0x1017 Producer heartbeat time ✔️

Supported Features:

  • Remote state changes ✔️
  • Heartbeat
    • Generation ✔️
    • Monitoring ✔️
  • Command processing
    • State changes ✔️
    • Reset node ✔️
    • Reset communications ✔️

Process Data Object - PDO

The CANopen process data object protocol is used for broadcasting data changes with minimal overhead, similar to a more traditional CAN network architecture. A mapped TPDO can be sent with the Pdo.write() method. Event driven TPDOs will be sent automatically when the device is in NmtState.OPERATIONAL. The Pdo module will emit event:pdo when a mapped RPDO is consumed.

OD Entry Description Supported
0x1400 - 0x15FF RPDO communication parameter ✔️
0x1600 - 0x17FF RPDO mapping parameter ✔️
0x1800 - 0x19FF TPDO communication parameter ✔️
0x1A00 - 0x1BFF TPDO mapping parameter ✔️

Service Data Object - SDO

The CANopen service data object protocol provides direct access to a device's object dictionary. Call the SdoClient.upload() or SdoClient.download() methods to initate a transfer.

OD Entry Description Supported
0x1200 - 0x127F SDO server parameter ✔️
0x1280 - 0x12FF SDO client parameter ✔️

Synchronization - SYNC

The CANopen sync protocol is used to synchronize actions between devices on the network. If enabled, Sync message generation will begin automatically when Device.start() is called. Sync will emit event:sync when a Sync object is consumed.

OD Entry Description Supported
0x1005 COB-ID SYNC ✔️
0x1006 Communication cycle period ✔️
0x1007 Sync window length
0x1019 Sync counter overflow value ✔️

Time stamp - TIME

The CANopen time protocol is used to provide a simple network clock. Call Time.write() to produce a time stamp object. Time will emit event:time when a time stamp object is consumed.

OD Entry Description Supported
0x1012 COB-ID TIME ✔️
0x1013 High resolution time stamp

node-canopen's People

Contributors

dawn-minion avatar dependabot[bot] avatar jonathanvanschenck avatar wilkinsw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

node-canopen's Issues

[2.5.3] PDO wrong COB_ID when different from default.

When the COB_ID for PDO is different from the default value, the node address should not be added.

Partial solution (src/protocol/pdo.js):

@@ -221,7 +221,7 @@ class Pdo {
             throw TypeError("CAN extended frames are not supported.")
 
         cobId &= 0x7FF;
-        if((cobId & 0xF) == 0x0)
+        if((cobId & 0x7F) == 0x0)
             cobId |= this.device.id;

Does this run on windows?

I am trying to read a Can Bus USB device that support CanOpen on a windows machine but its failing with

npm ERR! code EBADPLATFORM
npm ERR! notsup Unsupported platform for [email protected]: wanted {"os":"linux","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm ERR! notsup Valid OS: linux
npm ERR! notsup Valid Arch: any
npm ERR! notsup Actual OS: win32
npm ERR! notsup Actual Arch: x64

[v2 Beta] Bug in Pdo.start

In pdo.js:101-102, I think you the entry in the Eds should be used instead of the dataObject stored in the Pdo:

                        let entry = this.device.eds.getEntry(dataObject.index);
                        if(entry.subNumber > 0)
                            entry = entry[dataObject.subIndex];

                        this.events.push([entry, 'update', listener]);
                        entry.on('update', listener);

It confused me at first, but pdo.dataObjects does not contain objects of class DataObject. That's why dataObject.on() does not exist.

[v2 Beta] SDO download fails if previous request timed out

Noticed this this morning, if an SDO download times out (With err: SDO protocol timed out), it seems subsequent requests to the same index+subindex fail immediately with a timeout as well.

Looking at the CAN dump, it does indeed send the expected CAN message on the write starting, but it does not send the SDO abort message once the timeout is reached, and the subsequent times it does not send anything at all.

[2.5.2] SDO Transfer device property is not always initialized

When a client tries to initiate an upload or download of an entry that does not exist, device.receive() throws a TypeError.

Example stack trace for an upload:

TypeError: Cannot read property 'send' of undefined
    at Transfer.send (/appfs/apps/nodejs-server/node_modules/canopen/src/protocol/sdo.js:221:21)
    at Transfer.abort (/appfs/apps/nodejs-server/node_modules/canopen/src/protocol/sdo.js:260:14)
    at Sdo._serverUploadInitiate (/appfs/apps/nodejs-server/node_modules/canopen/src/protocol/sdo.js:796:27)
    at Sdo._onMessage (/appfs/apps/nodejs-server/node_modules/canopen/src/protocol/sdo.js:987:26)
    at emitOne (events.js:121:20)
    at Device.emit (events.js:211:7)
    at Device.receive (/appfs/apps/nodejs-server/node_modules/canopen/src/device.js:104:18)

It looks like this.device of the Transfer objects in the Sdo's this.clients are not initialized anywhere and that's why the send() function throws.
I'm only using the library to implement an SDO server, but it looks like the SDO client implementation does not have this problem: this.device of the Transfer objects in the Sdo's this.transfers is initialized correctly, it seems.

[2.5.3] RPDO mapping array sub-index

Example solution (src/protocol/pdo.js):

@@ -178,7 +178,10 @@ class Pdo {
 
             for(const dataObject of pdo.dataObjects) {
                 const index = dataObject.index;
-                const entry = this.device.dataObjects[index];
+                let entry = this.device.dataObjects[index];
+                if(entry.subNumber > 0) {
+                    entry = entry[dataObject.subIndex];
+                }
                 const size = entry.raw.length;

EDS Boolean getters return NaN

I think their may be a bug in the latest changes for the EDS getters where the data is defined as boolean, as the parseInt function is returning NaN instead of an integer value and hence the "this.device.eds.lssSupported" in the LSS.init function is always false. May be the same issue in other locations.

Could you export DataObject

Could you export DataObject
I found that this class has not been exported, can you export this class in this module?

[2.5.1] Pdo.write: keep track of lastValue in the dataObject instead of the Pdo

Based on the code in Pdo._parsePDO() it looks the intention was to keep track of lastValue per dataObject in pdo.dataObjects, but lines 153-156 store lastValue in the Pdo itself:

            if(pdo.lastValue != newValue) {
                pdo.lastValue = newValue;
                dataUpdated = true;
            }

I think these lines should be replaced by

            if(dataObject.lastValue != newValue) {
                dataObject.lastValue = newValue;
                dataUpdated = true;
            }

I don't use Pdo._onMessage() because we don't have Rx PDO's in our application, but it looks like that function has the same problem.

Allow loading EDS from string/Buffer, and adding data entries at runtime

In our tests we're currently generating an EDS at runtime based on input data, and then verifying our SDO operations work against a mock server based on the EDS generated at runtime. In Device.js, it would be nice if we could just pass the already loaded string or Buffer to this here instead of having to save it to a file.

As well, it would be nice to be able to dynamically add entries to the Device at runtime, as some cases we do not use an EDS. Whilst we can just do this by manually loading it via device.dataObjects, it'd be nice if it was an official API in case the Device.js object changes later.

[2.5.3] RPDO communication parameters

Fields "inhibitTime", "eventTime" and "syncStart" are not mandatory in RPDO.
Example solution (src/protocol/pdo.js):

@@ -232,17 +232,17 @@ class Pdo {
         /* sub-index 3:
          *   bit 0..15      Inhibit time.
          */
-        const inhibitTime = entry[3].value;
+        const inhibitTime = (index >= 0x1800)?entry[3].value:0;
 
         /* sub-index 5:
          *   bit 0..15      Event timer value.
          */
-        const eventTime = entry[5].value;
+        const eventTime = (index >= 0x1800)?entry[5].value:0;
 
         /* sub-index 6:
          *   bit 0..7       SYNC start value.
          */
-        const syncStart = entry[6].value;
+        const syncStart = (index >= 0x1800)?entry[6].value:0;
 
         let pdo = {
             cobId:          cobId,

Typescript support

Hey,
I looked through code and saw that the documentation is already really good. But it could be easier to work with if it had Typescript support. Did you ever think about doing something like this?
For me it is a lot easier to work with, because my IDE tells me what functions are there and the documentation of the code. This could make it easier especially for people who are new to lower the bar for them.
I started using your codebase and was working with the documentation. This is also valid and should be sustained, but TS is easier to work with then JS, because with the compile errors you avoid doing a lot of mistakes.

wrong cobId Tx and Rx in SDO upload

I recently upgrade an old project from canopen 2.8.2 to 6.0.0 and found all SDO uploads failing with timeout.
The reason is that the cobIdTx and cobIdRx are in version 6.0.0 no longer automatically enriched with the server node id.
CAN traffix while SDO timeout in canopen 6.0.0:

(2024-03-31 21:41:42.263225) can0 600 [8] 40 E6 55 02 00 00 00 00
(2024-03-31 21:41:42.294210) can0 600 [8] 80 E6 55 02 00 00 04 05

CAN traffic without SDO timeout in canopen 2.8.2:

(2024-03-31 21:47:04.374661) can0 620 [8] 40 E6 55 02 00 00 00 00
(2024-03-31 21:47:04.375400) can0 5A0 [8] 41 E6 55 02 2A 00 00 00
...

possible workaround in 6.0.0 is to call
device.eds.addSdoClientParameter(0x20, 0x600|0x20 ,0x580|0x20);
to manually set correct effective cobId(Tx/Rx), instead of
device.eds.addSdoClientParameter(0x20, 0x600 ,0x580);

if looks odd to me that you are checking like this if serverId already has been applied to cobId(Tx/Rx):

            if ((cobIdRx & 0xF) == 0x0)
                cobIdRx |= deviceId;

I assume this more should be

            if ((cobIdRx & 0x7F) == 0x0)
                cobIdRx |= deviceId;

as node ids are valid from 1 to 127 and not just from 1 to 15.
Please review if this is a bug or a desired behaviour, but if it is desired you at least need to update the SDO examples to reflect the changed call of addSdoClientParameter.

Apply SDO timeout to each segment

I currently have a 10 second timeout set for SDO transfers, and I noticed that on segmented transfers the timeout is applied for the entire operation, and not per segment like I expected. Sometimes I need to send a ~100KB or so file to a device on my network, which takes 30-40 seconds or so. I would expect the 10 second timeout to count for each segment, not the entire transfer.

Currently the timeout will trigger, despite the SDO transfer still working correctly. Ideally I'd only want the timeout to trigger when the device stops responding to an expected segment.

Include SDO error code in abort reject

It would be very handy to include the original abort code in the SDO rejection error passed to the Promise reject. We have a few custom codes in our device that require it's own handling that aren't included in the list here.

Writes to SDO server

Whenever a client writes SDO data to a server, I would like to act on this new data. I cannot find any provisions in the code to do this. I have implemented a callback in the SDO server myself, but I was wondering if there is a supported way to do this, without continiously checking the object dictionary for changes?

Thanks in advance!

[2.5.1] Pdo.start: wrong "this" binding in the listener functions

When the listener function on pdo.js:104-106 gets executed, it has the "this" scope of the dataObject it was assigned to on line 113: entry.on('update', listener);.
The problem is that you want to call Pdo.write(), so the "this" should be the Pdo and not the dataObject.
Solved by replacling pdo.js:104-106 by an arrow function: const listener = () => this.write(cobId);

I haven't tested the other cases in Pdo.start(), but the other listener functions problably need similar fixes.

Handle multiple block transfers

This is in reference to #36

The current implementation of the SDO block transfer may run into issues when running multiple transfers. This needs to be tested and fixed if needed.

Exception in src/Network.js if receiving an NMT command with a non-zero node ID

We're currently sending NMT commands to specific nodes directly via node-can (So not using the lib, but on the same canopen interface this lib uses), and we're seeing the following exception happen if we send an NMT reset request to a non-zero node ID:

canopen/src/Network.js:88
                this.devices[target].state = state;
                                           ^

TypeError: Cannot set property 'state' of undefined
    at Network._onMessage (canopen/src/Network.js:88:44)

Messages we send are echoed back to us, so are picked up by _onMessage in Network.js. The code there then assumes we have a device registered with the node ID we received. Since we don't, it then throws the type error above.

This also means we can be crashed by receiving any NMT command with a non-zero ID.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.