Esempio n. 1
0
 def __init__(self):
     mini.BAUDRATE = 115200
     try:
         self.primary_instrument = mini.Instrument("/dev/ttyUSB0", 1, mode='rtu')
     except:
         self.primary_instrument = mini.Instrument("/dev/ttyUSB1", 1, mode='rtu')
     self.primary_instrument.write_register(4, value=20, functioncode=6)
Esempio n. 2
0
    def __init__(self, threadID, name, config, modbusRs2mqttPublisher,
                 mqttSubscriber2modbusRs, modbusRs2modbusTcp,
                 modbusTcp2modbusRs):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.config = config
        self.log = logging.getLogger("modbusRs")
        self.modbusRs2mqttPublisher = modbusRs2mqttPublisher
        self.mqttSubscriber2modbusRs = mqttSubscriber2modbusRs
        self.modbusRs2modbusTcp = modbusRs2modbusTcp
        self.modbusTcp2modbusRs = modbusTcp2modbusRs
        self.tick = 0.01
        self.interval = 3
        self.exitFlag = False
        self.s = {
            "serial1": minimalmodbus.Instrument(self.config["serial1"]["port"],
                                                1),
            "serial2": minimalmodbus.Instrument(self.config["serial2"]["port"],
                                                1)
        }

        self.s["serial1"].serial.baudrate = self.config["serial1"]["speed"]
        self.s["serial1"].serial.bytesize = self.config["serial1"]["bytesize"]
        self.s["serial1"].serial.stopbits = self.config["serial1"]["stopbits"]
        self.s["serial1"].serial.timeout = self.config["serial1"]["timeout"]
        self.s["serial1"].mode = minimalmodbus.MODE_RTU

        self.s["serial2"].serial.baudrate = self.config["serial2"]["speed"]
        self.s["serial2"].serial.bytesize = self.config["serial2"]["bytesize"]
        self.s["serial2"].serial.stopbits = self.config["serial2"]["stopbits"]
        self.s["serial2"].serial.timeout = self.config["serial2"]["timeout"]
        self.s["serial2"].mode = minimalmodbus.MODE_RTU
    def connect_to_nodes(self):
        self.gripper_node = minimalmodbus.Instrument(self.port,
                                                     int(self.gripper_node_id))
        self.mining_node = minimalmodbus.Instrument(self.port,
                                                    int(self.mining_node_id))

        self.__setup_minimalmodbus_for_485()
Esempio n. 4
0
def get_modbus_device():
    try:
        instrument = minimalmodbus.Instrument(serial_if0, 1)
        instrument.debug = True
        return serial_if0
    except:
        print("Not found. Searching for RS485 on {}".format(serial_if1))
        instrument = minimalmodbus.Instrument(serial_if1, 1)
        instrument.debug = True
        return serial_if1
Esempio n. 5
0
def connectVFD():
    global instr
    try:
        instr = minimalmodbus.Instrument('/dev/ttyUSB0', 1)
        instr.debug = True  #TODO:comment this out after testing is done
        instr.serial.parity = serial.PARITY_EVEN
    except IOError:
        try:
            instr = minimalmodbus.Instrument('/dev/ttyUSB1', 1)
            instr.debug = True
            instr.serial.parity = serial.PARITY_EVEN
        except IOError:
            print("Failed to connect to VFD")
Esempio n. 6
0
    def __init__(self, message_queue):
        threading.Thread.__init__(self)
        self.instrument = minimalmodbus.Instrument('/dev/ttyUSB-IR2', 1)
        self.instrument.serial.baudrate = 9600
        self.sending = True

        self.message_queue = message_queue
Esempio n. 7
0
def connect_uart(modbus_set,baudrate=9600,timeout=1):
    # RS485连接重试功能和连接超时功能的UART连接
    conn_status = True
    max_retries_count = 10  # 设置最大重试次数
    conn_retries_count = 0  # 初始重试次数
    conn_timeout = 3  # 连接超时时间为3秒
    i = 0
    inst = []
    while conn_status and conn_retries_count <= max_retries_count:
        try:
            print("连接RS485设备中..",modbus_set)
            
            
            for key,value in modbus_set.items():
                inst.append(minimalmodbus.Instrument(key,int(value)))
                print("inst is :",inst[i])
                inst[i].serial.baudrate = baudrate

                inst[i].serial.timeout = timeout
                
                # lt_impep[value]=(inst[i].read_float(4126,3,2,byteorder=0))*120
                # print(lt_impep)
                i = i+1
            print("已连接设备为: ",inst)
            conn_status = False  # 如果RS485连接成功则conn_status为设置为False则退出循环,返回inst列表连接对象
            return inst
            
        except:
            conn_retries_count += 1
            print(conn_retries_count)
            print('connect uart is error!!')
            time.sleep(conn_timeout) # test result!
        continue
Esempio n. 8
0
    def startModbus(self):
        try:
            self.modbusInstrument = minimalmodbus.Instrument(
                self.port_config.portname,
                self.slaveAddress)  # defaults as RTU mode
        except serial.SerialException as se_err:
            self.logger.error("Serial.SerialException - %s" % str(se_err))
            logger.error("Unable to startModbus: %s, %s, %s, %s, %s, %s" %
                         (self.serialPortConfig.portname,
                          str(self.serialPortConfig.baudrate),
                          str(self.serialPortConfig.bytesize),
                          self.serialPortConfig.parity,
                          str(self.serialPortConfig.stopbits),
                          str(self.serialPortConfig.serialTimeout)))
        else:
            self.portOpen = True
            self.logger.info(
                "Opened startModbus: %s, %s, %s, %s, %s, %s" %
                (self.port_config.portname, str(
                    self.port_config.baudrate), str(self.port_config.bytesize),
                 self.port_config.parity, str(self.port_config.stopbits),
                 str(self.port_config.serialTimeout)))
            self.modbusInstrument.debug = True
        '''
        Only port setting that is expected to be different from the default MODBUS settings is baudrate and timeout
        '''
        self.modbusInstrument.serial.baudrate = self.port_config.baudrate
        self.modbusInstrument.serial.timeout = self.port_config.serialTimeout

        self.logger.info("StartModbus: %s, %s, %s" %
                         (self.port_config.portname, str(self.slaveAddress),
                          str(self.port_config.baudrate)))
Esempio n. 9
0
def get_instruments(device_ids):
    definative_com = None
    instances = {}

    for i in device_ids:
        comrange = range(1, 11)
        if definative_com is not None:
            comrange = [definative_com]

        for com in comrange:
            dev = None
            try:
                dev = minimalmodbus.Instrument(f"COM{com}", i)
                dev.read_registers(512, 8)
                instances[i] = dev
                definative_com = i
            except (serial.serialutil.SerialException,
                    minimalmodbus.NoResponseError,
                    minimalmodbus.InvalidResponseError):
                del dev
                pass

    not_found = set(device_ids).difference(instances)
    if not_found:
        raise ConnectionError(
            f"Could not connect to Devices: {list(not_found)}")

    return instances
    def __init__(self):
        rospy.init_node(NODE_NAME)

        self.port = rospy.get_param("~port", DEFAULT_PORT)
        self.baud = rospy.get_param("~baud", DEFAULT_BAUD)

        self.drive_command_publisher_topic = rospy.get_param(
            "~drive_command_topic", DEFAULT_DRIVE_COMMAND_TOPIC)
        self.iris_status_publisher_topic = rospy.get_param(
            "~iris_status_topic", DEFAULT_IRIS_STATUS_TOPIC)

        self.wait_time = 1.0 / rospy.get_param("~hertz", DEFAULT_HERTZ)

        self.iris = minimalmodbus.Instrument(self.port, MODBUS_ID)
        self.__setup_minimalmodbus_for_485()

        self.drive_command_publisher = rospy.Publisher(
            self.drive_command_publisher_topic,
            DriveCommandMessage,
            queue_size=1)
        self.iris_status_publisher = rospy.Publisher(
            self.iris_status_publisher_topic, IrisStatusMessage, queue_size=1)

        self.registers = []

        self.iris_connected = False

        self.iris_last_seen_time = time()

        self.run()
Esempio n. 11
0
 def __init__(self, port, datasocket, crit_logger=None, db_logger=None, codename='', output=False, logger=LOGGER):
     super().__init__()
     self.logger = logger
     self.logger.info('Initializing connection')
     self.comm = minimalmodbus.Instrument(port, 1)
     self.comm.serial.baudrate = 9600
     self.comm.serial.parity = serial.PARITY_EVEN
     self.comm.serial.timeout = 0.5
     error = 0
     while error < 10:
         try:
             self.temperature = self.comm.read_register(4096, 1, signed=True)
             break
         except OSError:
             error = error + 1
     if error > 9:
         exit('Error in communication with TC reader')
     self.logger.info('Connection to Omega established')
     #if self.temperature < -1000:
     #    self.temperature = None
     #threading.Thread.__init__(self)
     self.quit = False
     self.datasocket = datasocket
     self.crlogger = crit_logger
     self.db_logger = db_logger
     self.codename = codename
     self.logger.info('TcReader ready')
     self.output = output
Esempio n. 12
0
    def startModbus(self):
        try:
            self.modbusInstrument = minimalmodbus.Instrument(
                self.port_config.portname,
                self.slaveAddress)  # defaults as RTU mode
            self.portOpen = True
            print("SerialModbusComm - open startModbus: " +
                  self.port_config.portname + ", " +
                  str(self.port_config.baudrate) + ", " +
                  str(self.port_config.bytesize) + ", " +
                  self.port_config.parity + ", " +
                  str(self.port_config.stopbits) + ", " +
                  str(self.port_config.serialTimeout))
            #self.modbusInstrument.debug = True
        except serial.SerialException:
            print("SerialModbusComm - unable to startModbus: " +
                  self.port_config.portname + ", " +
                  str(self.port_config.baudrate) + ", " +
                  str(self.port_config.bytesize) + ", " +
                  self.port_config.parity + ", " +
                  str(self.port_config.stopbits) + ", " +
                  str(self.port_config.serialTimeout))
            self.modbusInstrument.serial.close()
            sys.exit(-1)
        '''
        Only port setting that is expected to be different from the default MODBUS settings is baudrate and timeout
        '''
        self.modbusInstrument.serial.baudrate = self.port_config.baudrate
        self.modbusInstrument.serial.timeout = self.port_config.serialTimeout

        print("SerialModbusComm - startModbus: " + self.port_config.portname +
              ", " + str(self.slaveAddress) + ", " +
              str(self.port_config.baudrate))
Esempio n. 13
0
 def __init__(self, id, port, circumference, reducer):
     """
     初始化函数
     :param id: 电机从地址id
     :param port: 电机控制端口号
     :param circumference:轮子每一圈的周长
     :param reducer:电机减速器减速比
     """
     '''
     # 系统状态寄存器地址0x465d: 说明
     '''
     self._addr_data = {
         # 固定速度             编码器线数               电机圈数值            系统状态寄存器:
         'fix_speed': 0x4420, 'rec_line_num': 0x42ea, 'position': 0x42ff, 'sys_status': 0x465d,
         'enable': 0x4657
     }
     self._last_position = 0.0
     self._max_speed = 3000
     self._rec_line_num = 2500
     self._distance_one_circle = 1.0 * circumference / reducer
     self._enable_status = False
     self._last_motor_pos = 0
     self._rec_line_num = 1000
     self._motor = minimalmodbus.Instrument(port, id, debug=False    )
     self._motor.serial.baudrate = 9600
Esempio n. 14
0
def flowmeterdata_read():

    Port = '/dev/ttyUSB0'
    FlowId = 1
    Bdrate = 9600
    Parity = serial.PARITY_NONE
    Stopbit = 1
    Timeout = 0.5
    instrument1 = minimalmodbus.Instrument(Port, FlowId)
    instrument1.serial.baudrate = Bdrate
    instrument1.serial.bytesize = 8
    instrument1.serial.parity = Parity
    instrument1.serial.stopbits = Stopbit
    instrument1.serial.timeout = Timeout
    instrument1.mode = minimalmodbus.MODE_RTU
    instrument1.clear_buffers_before_each_transaction = True
    instrument1.close_port_after_each_call = True
    instrument1.debug = True
    print(instrument1)

    try:
        flowrate = instrument1.read_float(0, functioncode=3, number_of_registers=2, byteorder=0)
        print("flowrate is: ",flowrate)
        volumecons = instrument1.read_float(2, functioncode=3, number_of_registers=2, byteorder=0)
        print("volume consumption is: ", volumecons)
        
    except IOError:
        print("Failed to read from instrument")
        time.sleep(1)
        flowmeterdata_read()
        
    return [flowrate, volumecons]
Esempio n. 15
0
 def __init__(self, dev_id, port):
     """
     初始化函数
     :param id: 电机从地址id
     :param port: 电机控制端口号
     """
     '''
     # 系统状态寄存器地址0x465d: 说明
     '''
     self._addr_data = {
         '485_en':0x00,          # 485使能
         'fix_speed': 0x02,      # 写电机速度 
         'cur_speed': 0x10,      # 当前电机速度
         'enable': 0x01,         # 电机使能
         'err':0x0e,             # 系统错误代码
         'I':0x0f,               # 电机IQ电流值0.1A
         'U':0x11,               # 电机电压值
         'zero': 0x19,           # 自动找原点寄存器地址
         'pos_l': 0x16,          # 绝对位置低16位, 只读
         'pos_h': 0x17,          # 绝对位置高16位,只读
         'pu':0x000c,            # 相对位置寄存器低16位,只写,32位
         'dir':0x09,             # 极性
         'acc': 0x03,            # acc r/min/s
     }
     self._max_speed = 3000
     self._enable_status = False
     self._id = dev_id
     self._motor = minimalmodbus.Instrument(port, self._id, debug=False)
     self._motor.serial.baudrate = 19200
     self.ini_motor()
Esempio n. 16
0
def main():
    node = Node('watlow')
    pub_temp = node.Publisher('watlow/temp')
    pub_power = node.Publisher('watlow/power')
    pub_setpoint = node.Publisher('watlow/setpoint')
    sub_set_setpoint = node.Subscriber('watlow/set_setpoint')
    kill_flag = node.kill_flag()
    node.register_node()
    msg = Message()

    minimalmodbus.close_port_after_each_call = True
    instrument = minimalmodbus.Instrument('COM4', 1)  # port name, slave address (in decimal)
    instrument.serial.baudrate = 9600   # Baud
    instrument.serial.bytesize = 8
    instrument.serial.parity = serial.PARITY_NONE
    instrument.serial.stopbits = 1
    instrument.serial.timeout = 0.5   # seconds
    instrument.mode = minimalmodbus.MODE_RTU   # rtu or ascii mode

    print('running')
    while not kill_flag:
        recv = sub_set_setpoint.read()
        if recv is not None and len(recv) >= 1:
            instrument.write_float(2640, Message(recv[-1]).data)
        temp = instrument.read_float(402)
        power = instrument.read_float(2384)
        set_point = instrument.read_float(2652)
        millis = time.time()

        msg.data = np.array((millis, temp))
        pub_temp.publish(msg)
        msg.data = np.array((millis, power))
        pub_power.publish(msg)
        msg.data = np.array((millis, set_point))
        pub_setpoint.publish(msg)
Esempio n. 17
0
def run():
        sensorList = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
        if not os.path.isdir('/sys/class/gpio/gpio146'):
                with open('/sys/class/gpio/export', 'w') as io_bus:
                        io_bus.write('146')

        with open('/sys/class/gpio/gpio146/direction', 'w') as activate_bus:
                activate_bus.write('out')

        while(1):
                for id in sensorList:
                        try:
                                print("input: ", id)
                                instrument = minimalmodbus.Instrument('/dev/ttymxc2', id)
                                instrument.serial.baudrate = 9600
                                instrument.serial.timeout = 0.25
       	                        Consumed = (instrument.read_float(4358))
       	                        PowerUsing = (instrument.read_float(4134))
                                now = datetime.datetime.now()
                                payload = {"power_consumed": Consumed/1000,"power_using": PowerUsing/1000,"reading_time":now,"socket_id":"http://192.168.0.50:8000/sockets/"+str(id)+"/"}
                                print(payload)
                                print(getToken.postData("socket_reading/socket_readings", payload))

                        except (ValueError,OSError):
                                print("Erroring")
                time.sleep(5)
Esempio n. 18
0
 def openCloseComport(self):
     if not self.connected:
         try:
             self.servo = minimalmodbus.Instrument(
                 self.cbSelectComport.currentText(), 1)
             self.servo.serial.baudrate = 57600  # Baud
             self.servo.serial.bytesize = 8
             self.servo.serial.parity = serial.PARITY_NONE
             self.servo.serial.stopbits = 1
             self.servo.serial.timeout = 0.5  # seconds
         except:
             self.statusBar().showMessage("Failed to open port", 2000)
             return
         try:
             self.servo.read_register(0x80)
             self.statusBar().showMessage("Port opened successfully", 2000)
             self.pbOpenCloseComport.setText('Close Comport')
             self.connected = True
         except:
             self.servo.serial.close()
             self.statusBar().showMessage("Device does not respond", 2000)
             return
     else:
         if (self.pbStartStopMonitor.text() == 'Stop Monitor'):
             self.startStopMonitor()
         try:
             self.servo.serial.close()
             self.statusBar().showMessage("Port closed", 2000)
         except:
             pass
         self.pbOpenCloseComport.setText('Open Comport')
         self.connected = False
Esempio n. 19
0
 def __init__(self, id, port):
     """
     初始化函数
     :param id: 电机从地址id
     :param port: 电机控制端口号
     """
     '''
     # 系统状态寄存器地址0x465d: 说明
     '''
     self._addr_data = {
         'fix_speed': 0x0056,    # 电机速度
         '485_enable': 0x00b6,   # 485使能,1有效,2无效
         'cur_speed': 0x005f,    # 当前电机速度
         'enable': 0x0066,       # 电机使能,0停止,1正转,2反转,3刹车, 4刹车解除
         'id':0x0006,            # modbus id
         'mode':0x0049,          # 0力矩模式,1速度模式
         'speed':0x0056,         # 实际速度
         'u':0x0071,             # 电压
         'i':0x00c6,             # 电流
         'err_code': 0x0072,     # 错误代码
     }
     self._max_speed = 2500
     self._id = 1
     self._motor = minimalmodbus.Instrument(port, self._id, debug=False)
     self._motor.serial.baudrate = 9600
     self.ini_motor()
Esempio n. 20
0
 def __init__(self, id, port):
     """
     初始化函数
     :param id: 电机从地址id
     :param port: 电机控制端口号
     """
     '''
     # 系统状态寄存器地址0x465d: 说明
     '''
     self._addr_data = {
         # 固定速度             编码器线数               电机圈数值            系统状态寄存器:
         'fix_speed': 0x4420,  # 写电机速度 
         'cur_speed': 0x42d1,  # 当前电机速度
         'rec_line_num': 0x42ea,  # 编码器线数
         'position': 0x42ff,  # 电机圈数值
         'sys_status': 0x465d,  # 系统状态寄存器,bit17参数保存
         'enable': 0x4657,  # 电机使能
         'id': 0x466c,  # 电机通信地址
         'mode': 0x465a,  # 控制模式选择,1力, 2速度, 3位置
         'err': 0x466e,  # 系统错误代码
         'I': 0x42cc,  # 电机IQ电流值0.1A
         'U': 0x426b,  # 电机电压值
         'nominal_speed': 0x42e8,  # 电机额定速度0.1r/min
     }
     self._max_speed = 3000
     self._enable_status = False
     self._id = id
     self._motor = minimalmodbus.Instrument(port, id, debug=False)
     self._motor.serial.baudrate = 9600
     self.ini_motor()
Esempio n. 21
0
	def __init__(self, port1, addr, baud_rate, byte_size ):
		self.instrument = minimalmodbus.Instrument(port1, addr) # port name, slave address (in decimal)
		#self.instrument.serial.port          # this is the serial port name
		self.instrument.serial.baudrate = baud_rate   # Baud rate 9600 as listed in doc
		self.instrument.serial.bytesize = byte_size
		self.instrument.serial.timeout = 0.5     # This had to be increased from the default setting else it did not work !
		self.instrument.mode = minimalmodbus.MODE_RTU  #RTU mode
Esempio n. 22
0
    def connect(self, slave_desc):
        if slave_desc['com_type'] == 'serial':
            self.com_type = 'serial'
            self.instrument = minimalmodbus.Instrument(slave_desc['port'],
                                                       slave_desc['stationid'],
                                                       slave_desc['mode'])
            if slave_desc['parity'] == 'None':
                self.instrument.serial.parity = serial.PARITY_NONE
            elif slave_desc['parity'] == 'Even':
                self.instrument.serial.parity = serial.PARITY_EVEN
            elif slave_desc['parity'] == 'Odd':
                self.instrument.serial.parity = serial.PARITY_ODD

            self.instrument.serial.baudrate = slave_desc['baudrate']
            self.instrument.serial.bytesize = slave_desc['databits']
            self.instrument.serial.stopbits = slave_desc['stopbits']
            self.instrument.serial.timeout = slave_desc['timeout']
            self.instrument.mode = slave_desc['mode']
            self.function = {}
            self.function['PV'] = slave_desc['PV']
            self.function['SV'] = slave_desc['SV']
            self.facility_name = (slave_desc['facility_name'][0:1],
                                  slave_desc['facility_name'][1:2])
            self.facility_id = (slave_desc['facility_id'][0:1],
                                slave_desc['facility_id'][1:2])
    def run(self):
        minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True

        instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 10)
        instrument.serial.baudrate = 9600
        instrument.serial.bytesize = 8
        instrument.serial.parity = minimalmodbus.serial.PARITY_NONE
        instrument.serial.stopbits = 1
        instrument.serial.timeout = 1
        instrument.debug = False
        instrument.mode = minimalmodbus.MODE_RTU

        diematicReader = DiematicReader(instrument)

        schedule.every(15).seconds.do(self.publish)

        while not self.cancelRequested:
            try:
                self.diematic = diematicReader.read()
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                pass
        
        print("Worker finished")
Esempio n. 24
0
def wLRead(slp,intcpt): 
    # Port name, slave address (in decimal)
    # instrument_wL = minimalmodbus.Instrument(comName, wL_slaveAddr) 
    instrument_wL = minimalmodbus.Instrument(devName, wL_slaveAddr)
    try:
        samplingList = []
        medianVal = 0
        countNum  = 0
        sampleNum = 10
        while (countNum <= sampleNum): 
            # Register address / Number of registers / Function code
            ReadingValue = instrument_wL.read_registers(0,2,4)
            power = len(str(ReadingValue[0]))
            ArrangeValue = ReadingValue[1] + ReadingValue[0]/(10**power)
            samplingList.append(ArrangeValue)
            countNum += 1
            print(countNum)
            time.sleep(1) # Wait for 1 second
            
        medianVal = median(samplingList)
        wLVal     = round(slp * medianVal + intcpt, 3)
        
        idn = instrument_wL.read_register(1, 0, 3)
        print('-----Liquid level sensor-----')
        print('id = '+str(idn))
        print('water level = ' + str(wLVal) + ' m')                
             
    except IOError:
        wLVal = 0
        print("Failed to read from instrument")
        print('------------------------')
        
    return wLVal
Esempio n. 25
0
 def __init__(self, inst_id=1, com_port='COM4', baudrate=115200):
     '''
     Class to connect to SolarMEMS ISSDX sun sensor
     
     Inputs:
         inst_id: (int) instrument id (default=1)
         com_port: serial com port for USB to 485-converter
         baudrate: (int) default baudrate = 19200, fastest baudrate = 115200
     '''
     self.inst_id = inst_id
     self.com_port = com_port
     self.baudrate = baudrate
     self.scale = 1.0
     self.sun_in_fov = True
     self.no_sunlight = False
     self.ang_x_raw = 0.0
     self.ang_y_raw = 0.0
     try:
         self.ss = minimalmodbus.Instrument(self.com_port, self.inst_id)
         self.ss.serial.baudrate = self.baudrate
         self.fov = self.ss.read_register(2)
         if self.fov == 60:
             self.scale = 10.0  #coarse ss is mounted 180 degrees off fine sun sensors
         print('Connected to sun sensor', self.inst_id, 'FOV = +/-',
               self.fov, 'degrees')
     except:
         print('Hey sun sensor', self.inst_id, 'why wont you talk to me?')
Esempio n. 26
0
 def __init__(self, port, baudrate, id):
     self.instrument = minimalmodbus.Instrument(port, id, 'rtu')
     self.instrument.serial.baudrate = baudrate
     self.instrument.serial.bytesize = 8
     self.instrument.serial.parity = serial.PARITY_NONE
     self.instrument.serial.stopbits = 2
     self.instrument.serial.timeout = 1
Esempio n. 27
0
 def connect(self, port, portlock):
     self.portlock = portlock
     if not self.connected:
         self.port = port
         self.comm = mm.Instrument(self.port, self.address)
         self.comm.serial.timeout = 0.3
         self.connected = True
Esempio n. 28
0
 def __init__(self, port, slave_address):
     self.controller = minimalmodbus.Instrument(port,
                                                slave_address,
                                                mode=minimalmodbus.MODE_RTU)
     #Try a command to see if the instrument works
     self.controller.read_register(temperature_setpoint_register,
                                   numberOfDecimals=1)
Esempio n. 29
0
 def __init__(self, port, slave_adress, baudrate_value, parity, bytesize,
              stopbits, timeout_value):
     minimalmodbus.BAUDRATE = baudrate_value
     minimalmodbus.PARITY = parity
     minimalmodbus.BYTESIZE = bytesize
     minimalmodbus.STOPBITS = stopbits
     minimalmodbus.TIMEOUT = timeout_value
     try:
         self.instrument = minimalmodbus.Instrument(port,
                                                    slave_adress,
                                                    mode='rtu')
     except:
         print("No connection to " + str(port) + " or permission denied")
     else:
         self.instrument.mode = minimalmodbus.MODE_RTU  # set rtu mode
         self.instrument.serial.timeout = timeout_value
         self.instrument.serial.baudrate = baudrate_value
     thc_driver.sensors_count += 1
     self.index = thc_driver.sensors_count
     if debug:
         print("    ---------------------------")
         print("    |      SENSOR " + str(thc_driver.sensors_count) +
               "   INFO    |")
         print("    ---------------------------")
         print("  ", "Port: ".ljust(20), str(port).ljust(40))
         print("  ", "Slave adress: ".ljust(20),
               str(slave_adress).ljust(40))
         print("  ", "Boudrate: ".ljust(20), str(baudrate_value).ljust(40))
         print("  ", "Parity: ".ljust(20), str(parity).ljust(40))
         print("  ", "Bytesize: ".ljust(20), str(bytesize).ljust(40))
         print("  ", "Stopbits: ".ljust(20), str(stopbits).ljust(40))
         print("  ", "Timeout: ".ljust(20), str(timeout_value).ljust(40))
         print("")
Esempio n. 30
0
def find_slave_id():
    slave_ids = []
    for slave_id in range(1, 33):
        for i in range(3000, 3003):
            try:
                instrument = mb.Instrument('/dev/ttyUSB0', slave_id)

                # instrument.serial.port          # this is the serial port name
                instrument.serial.baudrate = 9600  # Baud
                instrument.serial.bytesize = 8

                instrument.serial.stopbits = 1
                instrument.serial.timeout = 1  # seconds

                instrument.address = slave_id  # this is the slave address
                instrument.mode = mb.MODE_RTU  # rtu or ascii mode
                # instrument.debug = True
                # print(i, end=" ")

                value = instrument.read_register(i, 0, 4)
                print(value)
                if slave_id not in slave_ids:
                    slave_ids.append(slave_id)
                time.sleep(0.5)
            except:
                print("can't read {} rig".format(i))

    print('done')
    print(slave_ids)
    return (slave_ids)