Exemplo n.º 1
0
                        dest='height',
                        type=int,
                        default=600,
                        help='Height of the frames in the video stream.')
    parser.add_argument(
        '-strout',
        '--stream-output',
        dest="stream_out",
        help='The URL to send the livestreamed object detection to.')
    args = parser.parse_args()
    height = 600
    width = 800
    ip = '127.0.0.1'
    port = '502'
    connection = ModbusClient(host=ip, port=port, auto_open=True)
    connection.debug(True)
    input_q = Queue(1)  # fps is better if queue is higher but then more lags
    output_q = Queue()
    for i in range(1):
        t = Thread(target=worker, args=(input_q, output_q))
        t.daemon = True
        t.start()

    if (args.stream_in):
        print('Reading from IP')
        video_capture = IPVideoStream(src=args.stream_in).start()
    else:
        print('Reading from webcam.')
        video_capture = WebcamVideoStream(src=args.video_source,
                                          width=args.width,
                                          height=args.height).start()
Exemplo n.º 2
0
 filtered_classes = [
     'person',
     'car',
 ]
 height = 720
 width = 1280
 size = str(width) + 'x' + str(height)
 quality = "50"
 fps = "30.0"
 stream_ip = (
     "http://10.10.10.10/control/faststream.jpg?stream=full&preview&previewsize="
     + size + "&quality=" + quality + "&fps=" + fps + "&camera=left")
 modbus_ip = '192.168.127.254'
 modbus_port = '502'
 connection = ModbusClient(host=modbus_ip, port=modbus_port, auto_open=True)
 connection.debug(False)
 alarm_lock = Lock()
 input_q = Queue(1)
 output_q = Queue()
 t = Thread(target=worker, args=(input_q, output_q))
 t.daemon = True
 t.start()
 text = ''
 alarm = [False, False]
 video_capture = IPVideoStream(src=stream_ip).start()
 fps = FPS().start()
 thread_list = []
 while True:
     try:
         frame = cv2.imdecode(video_capture.read(), 1)
         input_q.put(frame)
Exemplo n.º 3
0
 def test_debug(self):
     # test valid/invalid cases for debug()
     c = ModbusClient()
     self.assertEqual(c.debug(), False, "debug default is off")
     self.assertEqual(c.debug(False), False)
     self.assertEqual(c.debug(True), True)
Exemplo n.º 4
0
 def test_debug(self):
     # test valid/invalid cases for debug()
     c = ModbusClient()
     self.assertEqual(c.debug(), False, 'debug default is off')
     self.assertEqual(c.debug(False), False)
     self.assertEqual(c.debug(True), True)
Exemplo n.º 5
0
class AmpSwitch(object):
    def __init__(self, host, port=502, switches=(), debug=False):
        """ """

        self.host = host
        self.port = port
        self.debug = debug
        self.switches = switches

        self.dev = None

        self.connect()

    def __str__(self):
        return "AmpSwitch(host=%s, port=%s, dev=%s>" % (self.host,
                                                        self.port,
                                                        self.dev)
    def setDebug(self, state):
        self.debug = state
        self.connect()
        
    def close(self):
        if self.dev is not None:
            self.dev.close()
            self.dev = None

    def connect(self):
        """ (re-) establish a connection to the device. """

        if self.dev is None:
            self.dev = ModbusClient()
            self.dev.debug(self.debug)
            self.dev.host(self.host)
            self.dev.port(self.port)

        if self.dev.is_open():
            return True

        ret = self.dev.open()
        if not ret:
            raise RuntimeError("failed to connect to %s:%s" % (self.host,
                                                               self.port))

        return True

    def readCoils(self):
        """ Return the state of all our switches. """

        self.connect()

        regs = self.dev.read_coils(0, 16)
        return regs

    def setCoils(self, on=(), off=()):
        """Turn on and off a given set of switches. 

        Argunents
        ---------

        on, off : list-like, or a single integer.

        Notes:
        ------

        The off set is executed first. . There is a command to change
        all switchees at once, but I have not made it work yet.

        """
        self.connect()

        if isinstance(on, int):
            on = on,
        if isinstance(off, int):
            off = off,

        regs0 = self.readCoils()
        regs1 = regs0[:]
        for c in off:
            ret = self.dev.write_single_coil(c, False)
            regs1[c] = False
        for c in on:
            ret = self.dev.write_single_coil(c, True)
            regs1[c] = True
        
        # ret = self.dev.write_multiple_registers(0, regs1)
        ret = self.readCoils()
        return ret

    def chooseCoil(self, n):
        return self.setCoils(on=n, off=list(range(16)))
Exemplo n.º 6
0
BUFFER_SIZE = 1024

TCP_IP = 'localhost'
GP_PORT = 4520
MODBUS_HOST = '192.168.0.251'
MODBUS_PORT = 502

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, GP_PORT))
s.listen(5)

(gp, address) = s.accept()

c = ModbusClient(host=MODBUS_HOST, port=MODBUS_PORT, auto_open=True)
c.debug(False)

while 1:
    if not c.is_open():
        if not c.open():
            print "Unable to connect to %s" % (MODBUS_HOST)
    data = gp.recv(BUFFER_SIZE)
    (command, dest, args) = parse_data(data)
    reply_data = modbus_request(command, dest, args)
    if (reply_data == "q"):
        print "Got command to quit"
        gp.close()
        print "Closed"
        (gp, address) = s.accept()
        print "Connected again"
    else:
Exemplo n.º 7
0
from pyModbusTCP.client import ModbusClient
from pyModbusTCP.constants import MODBUS_RTU
from config.modbus import *
from time import sleep
    
### MODBUS INITIALIZATION
c = ModbusClient()
c.mode(MODBUS_RTU) # enable MODBUS_RTU mode
c.timeout(1)
c.debug(True)
c.auto_open(True)
c.auto_close(True)

reg_value={'dum':None} # DUMMY FOR RECORDING REGISTRY LISTS
### END MODBUS INITIALIZATION

### INTERNAL FUNCTIONS
def loc_id(loc):
    device=loc.split('.')
    modmap,conn_id = MODBUS_MAP[device[2]],CONNECTIONS[device[0]][device[1]]
    return modmap,conn_id # [slave_id,reg_values],[IP_addr,port,slave_id_modifier]

def reg_add(modmap,color):
    reg=[0x0,0x0,0x0]
    for cl in COLOR_LIST[color]:
        mapcol=modmap[1][cl] # [0xXXXX,0xXXXX,0xXXXX]
        for i in range(0,3):
            reg[i]+=mapcol[i]
    return reg

def open_comm(): # MODBUS AUTO-RECONNECT
Exemplo n.º 8
0
class Modbus():

    def __init__(self, smarthome, gateway_ip, gateway_port=502, gateway_id=1, update_cycle=60):
        logger.info("Modbus: init plugin")
        self._sh = smarthome
        self._gateway_id = int(gateway_id)
        self._update_cycle = int(update_cycle)
        self._keylist = {}
        #self._client = ModbusTcpClient(gateway_ip,port=gateway_port)
        self._client = ModbusClient(host=gateway_ip, port=gateway_port, auto_open=True, auto_close=True)
        self._client.unit_id(2)
        self._client.debug(True)
        if not self._client.is_open():
            if not self._client.open():
                logger.error("Modbus: connection to gateway can not be established")
            else:
                logger.info("Modbus: connection to gateway established")
                self._client.close()

    def run(self):
        self.alive = True
        self._sh.scheduler.add('MODBUS', self._update_values, prio=5, cycle=self._update_cycle)

    def stop(self):
        self.alive = False
        self._sh.scheduler.remove('MODBUS')

    def parse_item(self, item):
        if 'modbus_gateway_id' in item.conf:
            gateid = int(item.conf['modbus_gateway_id'])
        else:
            gateid = 1
        if gateid != self._gateway_id:
            #logger.debug("Modbus: parse item error (gateway_id is not configured as plugin): {0}".format(item))
            return None

        if 'modbus_cmd' not in item.conf:
            #logger.debug("Modbus: parse item error (modbus_cmd missing): {0}".format(item))
            return None

        if 'modbus_scaling' not in item.conf:
            #logger.debug("Modbus: parse item error (modbus_scaling missing): {0}".format(item))
            return None

        if 'modbus_register' in item.conf:
            logger.debug("Modbus: parse item: {0}".format(item))
            register = item.conf['modbus_register']
            if not register in self._keylist:
                self._keylist[register] = {'items': [item], 'logics': []}
            else:
                self._keylist[register]['items'].append(item) 
        return None
       #    return self.update_item
       #else:
       #    return None


    def parse_logic(self, logic):
        pass

    def _update_values(self):
        for register in self._keylist:
            for item in self._keylist[register]['items']:
                if int(item.conf['modbus_cmd']) == 4:
                    reg_list = self._client.read_input_registers(int(item.conf['modbus_register'])-30001, 1)
                    logger.info("Modbus: Plain value: {}".format(str(reg_list[0])))
                    if reg_list is None:
                        return None
                    if len(reg_list) > 0:
                        phys_value = reg_list[0] / (int(item.conf['modbus_scaling']))# * pow(10, int(item.conf['modbus_decimal']))
                        logger.info("Modbus: Physical value: {0}".format(phys_value))
                        item(phys_value, 'MODBUS', ' {0}'.format(phys_value))
                elif int(item.conf['modbus_cmd']) == 6:
                    sendvalue = int(item()*int(item.conf['modbus_scaling']))
                    reg_list = self._client.write_single_register(int(item.conf['modbus_register'])-40001, sendvalue)
                    if not reg_list:
                        logger.info("Modbus: Error writing register")


    def update_item(self, item, caller=None, source=None, dest=None):
        if caller != 'MODBUS':
            logger.info("update item: {0}".format(item.id()))
            if int(item.conf['modbus_cmd']) == 4:
                reg_list = self._client.read_input_registers(int(item.conf['modbus_register'])-30001, 1)
                logger.info("Modbus: Plain value: {}".format(str(reg_list[0])))
                if reg_list is None:
                    return None
                if len(reg_list) > 0:
                    phys_value = reg_list[0] / (int(item.conf['modbus_scaling']))# * pow(10, int(item.conf['modbus_decimal']))
                    logger.info("Modbus: Physical value: {0}".format(phys_value))
                    item(phys_value, 'MODBUS', ' {0}'.format(phys_value))
Exemplo n.º 9
0
class AmpSwitch(object):
    def __init__(self, host, port=502, switches=(), debug=False):
        """ """

        self.host = host
        self.port = port
        self.debug = debug
        self.switches = switches

        self.dev = None

        self.connect()

    def __str__(self):
        return "AmpSwitch(host=%s, port=%s, dev=%s>" % (self.host, self.port,
                                                        self.dev)

    def setDebug(self, state):
        self.debug = state
        self.connect()

    def close(self):
        if self.dev is not None:
            self.dev.close()
            self.dev = None

    def connect(self):
        """ (re-) establish a connection to the device. """

        if self.dev is None:
            self.dev = ModbusClient()
            self.dev.debug(self.debug)
            self.dev.host(self.host)
            self.dev.port(self.port)

        if self.dev.is_open():
            return True

        ret = self.dev.open()
        if not ret:
            raise RuntimeError("failed to connect to %s:%s" %
                               (self.host, self.port))

        return True

    def readCoils(self):
        """ Return the state of all our switches. """

        self.connect()

        regs = self.dev.read_coils(0, 16)
        return regs

    def setCoils(self, on=(), off=()):
        """Turn on and off a given set of switches. 

        Argunents
        ---------

        on, off : list-like, or a single integer.

        Notes:
        ------

        The off set is executed first. . There is a command to change
        all switchees at once, but I have not made it work yet.

        """
        self.connect()

        if isinstance(on, int):
            on = on,
        if isinstance(off, int):
            off = off,

        regs0 = self.readCoils()
        regs1 = regs0[:]
        for c in off:
            ret = self.dev.write_single_coil(c, False)
            regs1[c] = False
        for c in on:
            ret = self.dev.write_single_coil(c, True)
            regs1[c] = True

        # ret = self.dev.write_multiple_registers(0, regs1)
        ret = self.readCoils()
        return ret

    def chooseCoil(self, n):
        return self.setCoils(on=n, off=list(range(16)))