Skip to content

Instantly share code, notes, and snippets.

@bademux
Last active March 10, 2019 19:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bademux/680de2ebef660708d449657a716f0be5 to your computer and use it in GitHub Desktop.
Save bademux/680de2ebef660708d449657a716f0be5 to your computer and use it in GitHub Desktop.
import telnetlib
import time
def read_header(tn):
tn.read_until("\n", 1)
def twos_complement(input_value):
return (~input_value +1) & 0xFF
def mbascii_request(payload):
record = bytearray.fromhex(payload)
record.append(twos_complement(sum(record)))
return ":%s\r\n" % ''.join("%02X" % b for b in record)
def mbascii_response(payload):
return bytearray.fromhex(payload[2:-4])
def mbascii_dorequest(tn, mb_request):
print "TX:%s" % mb_request
tn.write(mbascii_request(mb_request))
status, obj, response = tn.expect([r"\r\n"], 5)
if status == -1:
print "failed to get response"
return False
print "RX:%s" % mbascii_response(response)
return True
tn = telnetlib.Telnet('localhost', 10000)
#tn.set_debuglevel(1)
read_header(tn)
mbascii_dorequest(tn, '01050002FF00') #set 3rd coit ON
mbascii_dorequest(tn, '010100000008') #read first 8 coils
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment