Skip to content

Instantly share code, notes, and snippets.

@EmileBons
Last active June 22, 2021 15:41
Show Gist options
  • Save EmileBons/fdbb6f6122d18dac261ca4cca3f945b5 to your computer and use it in GitHub Desktop.
Save EmileBons/fdbb6f6122d18dac261ca4cca3f945b5 to your computer and use it in GitHub Desktop.
Snap7-based example of retrieving the date and time from a DTL-field, DATE-field, or TOD-field (time of day). Tested on a Siemens 1214C PLC.
import datetime
import snap7
from snap7.util import *
class DtlExample:
def __init__(self, ip, db):
self.plc = snap7.client.Client()
self.ip = ip
self.db = db
def connect(self):
self.plc.connect(self.ip, 0, 0)
def db_read(self, offset, length):
return self.plc.db_read(self.db, offset, length)
def disconnect(self):
self.plc.disconnect()
def get_date(self, offset):
date = datetime.datetime(1990, 1, 1)
return date + datetime.timedelta(get_int(self.db_read(offset, 2)[0:2], 0))
def get_dtl(self, offset):
dtl = self.db_read(offset, 12)
return datetime.datetime(get_int(dtl, 0), ord(dtl[2:3]), ord(dtl[3:4]), ord(dtl[5:6]), ord(dtl[6:7]),
ord(dtl[7:8]), get_dword(dtl, 8)/1000)
def get_time_of_day(self, offset):
now = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
return now + datetime.timedelta(milliseconds=self.get_dword(offset))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment