mathiask88 / node-snap7

node.js wrapper for snap7
MIT License
166 stars 59 forks source link

How to write a single bit in a struct? #53

Closed Jay031 closed 5 years ago

Jay031 commented 5 years ago

Hi guys, I'm breaking my neck over this problem. I have a struct at DB number 2 at start number 80. The struct contains 8 booleans. I can read them easily and convert them to an array, but how can I write and update only one of them?

For example if I want to write 80.7 (the 8th item of the struct) I want to start at 80.7 but ofcourse that's not supported: s7client.WriteArea(s7client.S7AreaDB, 2, 80.7, 1, s7client.S7WLBit, new Buffer([0x01]), function (err) { if (err) return console.log(' >> WriteArea failed. Code #' + err + ' - ' + s7client.ErrorText(err)); });

I searched in some old issues and other languages but didn't find the solution I was looking for. Can anyon help me out with this one?

Jay031 commented 5 years ago

I'm now trying it with an offset in buffer.writeInt with he start on DB2.80 Placing a bit "1" in the buffer with offset 7 to get to DB2 80.7, but I can't get it to work..

const buffer = new Buffer(8); buffer.writeIntBE(1, 7);

  s7client.WriteArea(s7client.S7AreaDB, 2, 80, 1, s7client.S7WLBit, buffer, function (err) {
    if (err)
      return console.log(' >> WriteArea failed. Code #' + err + ' - ' + s7client.ErrorText(err));
  });
Johanneslueke commented 5 years ago

Did you try to write everything back? from start to end but with the change applied? I did that. not very efficient but i am going sure everything is written.

Jay031 commented 5 years ago

I figured it out after lots of trial and error! My solution:

s7client.WriteArea(s7client.S7AreaDB, 2, (start * 8 + offset), 1, s7client.S7WLBit, buffer, function (err) {
    if (err)
      return console.log(' >> WriteArea failed. Code #' + err + ' - ' + s7client.ErrorText(err));
  });

So, beacuse its a S7WLBit, I need to put the start on the bit-value not on "80.7" But on 80*8 + 7 = 647 When I put start on 647 I can set a Buffer like this to put the value on true:

const buffer = new Buffer(1);
  buffer.writeIntBE(1);

Use writeIntBE(0) to put it on false. Hope this helps anyone!

mathiask88 commented 5 years ago

https://github.com/mathiask88/node-snap7/issues/3