Skip to content
Snippets Groups Projects
Commit de2ee74d authored by Paulus Kruger's avatar Paulus Kruger
Browse files

I2C flock added

parent b86c3346
No related branches found
No related tags found
No related merge requests found
Pipeline #90565 passed
#!/bin/bash #!/bin/bash
hwtr -p 4843 -c APSCTTR hwtr -p 4843 -c APSCTTR --lockfile=/tmp/pypcc_i2c.lock
#!/bin/bash #!/bin/bash
hwtr -p 4842 -c APSPUTR hwtr -p 4842 -c APSPUTR --lockfile=/tmp/pypcc_i2c.lock
#!/bin/bash #!/bin/bash
hwtr -p 4841 -c UNB2TR hwtr -p 4841 -c UNB2TR --lockfile=/tmp/pypcc_i2c.lock
...@@ -148,7 +148,11 @@ def I2Cserver(Qin,Qout,name,lock=None): ...@@ -148,7 +148,11 @@ def I2Cserver(Qin,Qout,name,lock=None):
# self.statevar.set_value("busy"); # self.statevar.set_value("busy");
#print("SetVar",item)#,self.conf.variables[item.id]) #print("SetVar",item)#,self.conf.variables[item.id])
if not(lock is None): if not(lock is None):
try:
lock.acquire() lock.acquire()
except:
logging.error("I2C lock timeout!!")
#continue;
# print('lock'); # print('lock');
try: try:
if (item.type==InstType.varSet): if (item.type==InstType.varSet):
...@@ -162,7 +166,10 @@ def I2Cserver(Qin,Qout,name,lock=None): ...@@ -162,7 +166,10 @@ def I2Cserver(Qin,Qout,name,lock=None):
else: print("OPCUA call not implemented!"); else: print("OPCUA call not implemented!");
finally: finally:
if not(lock is None): if not(lock is None):
try:
lock.release() lock.release()
except:
logging.error("I2C lock release error")
# print('unlock'); # print('unlock');
# print("TODO: Set ready") # print("TODO: Set ready")
logging.info("End i2c process "+name) logging.info("End i2c process "+name)
......
...@@ -5,6 +5,7 @@ import signal ...@@ -5,6 +5,7 @@ import signal
import sys import sys
import threading import threading
import time import time
from pypcc.simpleflock import simpleflock
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("-s", "--simulator", help="Do not connect to I2c, but simulate behaviour.", action="store_true") parser.add_argument("-s", "--simulator", help="Do not connect to I2c, but simulate behaviour.", action="store_true")
...@@ -12,6 +13,7 @@ parser.add_argument("-t", "--test", help="Do not start OPC-UA server.", action=" ...@@ -12,6 +13,7 @@ parser.add_argument("-t", "--test", help="Do not start OPC-UA server.", action="
parser.add_argument("-p", "--port", help="Port number to listen on [%(default)s].", type=int, default=4842) parser.add_argument("-p", "--port", help="Port number to listen on [%(default)s].", type=int, default=4842)
parser.add_argument("-l", "--loglevel", help="Log level [%(default)s].", type=str, choices=["DEBUG","INFO","WARNING","ERROR"], default="WARNING") parser.add_argument("-l", "--loglevel", help="Log level [%(default)s].", type=str, choices=["DEBUG","INFO","WARNING","ERROR"], default="WARNING")
parser.add_argument("--loghost", help="Logstash host to which to forward logs [%(default)s]",type=str, default='') parser.add_argument("--loghost", help="Logstash host to which to forward logs [%(default)s]",type=str, default='')
parser.add_argument("--lockfile", help="Lock while using I2C [%(default)s]",type=str, default='')
parser.add_argument("-c", "--config", help="YAML config files, comma seperated [%(default)s]",type=str, default='RCU') parser.add_argument("-c", "--config", help="YAML config files, comma seperated [%(default)s]",type=str, default='RCU')
args = parser.parse_args() args = parser.parse_args()
...@@ -50,7 +52,9 @@ if not(args.simulator): ...@@ -50,7 +52,9 @@ if not(args.simulator):
import multiprocessing as mp import multiprocessing as mp
# lock=mp.Lock() # lock=mp.Lock()
#else: #else:
lock=None; #lock=None;
lock = None if args.lockfile=='' else simpleflock(args.lockfile,10)
#I2Cports=['UNB2','RCU','CLK'] #I2Cports=['UNB2','RCU','CLK']
#I2Cports=['RCU'] #I2Cports=['RCU']
I2Cports=[x for x in args.config.split(',')] I2Cports=[x for x in args.config.split(',')]
......
from __future__ import print_function
import time
import os
import fcntl
import errno
class simpleflock:
"""Provides the simplest possible interface to flock-based file locking. Intended for use with the `with` syntax. It will create/truncate/delete the lock file as necessary."""
def __init__(self, path, timeout = None):
self._path = path
self._timeout = timeout
# self._fd = None
self._fd = os.open(self._path, os.O_CREAT)
def __del__(self):
os.close(self._fd)
self._fd = None
def acquire(self):
return self.__enter__()
def release(self):
return self.__exit__()
def __enter__(self):
start_lock_search = time.time()
while True:
try:
fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
# Lock acquired!
return
except (OSError, IOError) as ex:
if ex.errno != errno.EAGAIN: # Resource temporarily unavailable
raise
elif self._timeout is not None and time.time() > (start_lock_search + self._timeout):
# Exceeded the user-specified timeout.
raise
# TODO It would be nice to avoid an arbitrary sleep here, but spinning
# without a delay is also undesirable.
time.sleep(0.1)
def __exit__(self, *args):
fcntl.flock(self._fd, fcntl.LOCK_UN)
# Try to remove the lock file, but don't try too hard because it is
# unnecessary. This is mostly to help the user see whether a lock
# exists by examining the filesystem.
# try:
# os.unlink(self._path)
# except:
# pass
if __name__ == "__main__":
print("Acquiring lock...")
with SimpleFlock("locktest", 2):
print("Lock acquired.")
time.sleep(3)
print("Lock released.")
\ No newline at end of file
from test_common import *
from time import sleep
connect("opc.tcp://localhost:4899/")
names=get_all_variables()
for name in names:
att=get_value(name)
print(name,'=',att)
disconnect();
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment