class ModbusClientRS: def __init__(self): self.client = ModbusClient() def writeRegister(self, address, value): if self.client.is_open(): return self.client.write_single_register(address, value) return None def readRegister(self, address, value): if self.client.is_open(): self.client.read_holding_registers(address, value) def connect(self, host, port): # self.client.debug(True) self.client.host(SERVER_HOST) self.client.port(SERVER_PORT) if not self.client.is_open(): if not self.client.open(): print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT)) def is_open(self): return self.client.is_open() def disconnect(self): return self.client.close()
def test(): c = ModbusClient() # uncomment this line to see debug message # c.debug(True) # define modbus server host, port c.host(SERVER_HOST) c.port(SERVER_PORT) while True: # open or reconnect TCP to server if not c.is_open(): if not c.open(): print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT)) # if open() is ok, read register (modbus function 0x03) if c.is_open(): print c.write_single_register(504, intToUint16(-216)) # sleep 2s before next polling time.sleep(2)
def modbus_com(SERVER_HOST, SERVER_PORT, function_code, start_register, amount_of_registers): c = ModbusClient() c.host(SERVER_HOST) c.port(SERVER_PORT) cnt = 0 while True: # open or reconnect TCP to server if not c.is_open(): if not c.open(): print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT)) # if open() is ok, read register (modbus function 0x03) if c.is_open(): if function_code == "3": # Read the amount_of_registers from start_register regs = c.read_holding_registers(int(start_register), int(amount_of_registers)) # if success display registers if regs: print("reg address" + str(start_register) + "to" + str( int(start_register) + int(amount_of_registers) - 1) + ":" + str(regs)) elif function_code == "16": #Future support pass cnt += 1 if cnt >= 2: print("クライアント通信終了") c.close() break # sleep 1s before next polling time.sleep(1)
def __init__(self, address, port): c = ModbusClient() c.host(address) c.port(port) c.unit_id(1) c.open() data = c.read_holding_registers(130, 12) self.data=data c.close() if data: self.LowT1Start = format(data[0], 'x') self.LowT1Stop = format(data[1], 'x') self.LowT2Start = format(data[2], 'x') self.LowT2Stop = format(data[3], 'x') self.NormT1Start = format(data[4], 'x') self.NormT1Stop = format(data[5], 'x') self.NormT2Start = format(data[6], 'x') self.NormT2Stop = format(data[7], 'x') self.PeakT1Start = format(data[8], 'x') self.PeakT1Stop = format(data[9], 'x') self.PeakT2Start = format(data[10], 'x') self.PeakT2Stop = format(data[11], 'x') else: print("Read Volt And Amper ERROR")
def connect(host, port): """Connects to the defined HOST AND PORT. returns the client""" c = ModbusClient() c.host(host) c.port(port) if not c.is_open(): if not c.open(): raise Exception() return c
def make_summary(): SERVER_HOST = "192.168.43.239" SERVER_PORT = 502 SERVER_UNIT_ID = 2 c = ModbusClient() c.host(SERVER_HOST) c.port(SERVER_PORT) c.unit_id(SERVER_UNIT_ID) if not c.is_open(): if not c.open(): print("cannot connect ....") if c.is_open(): # read 54 registers at address 0, store result in regs list regs = c.read_input_registers(0,54) # if success change register value to float if regs: abc = [utils.decode_ieee(f) for f in utils.word_list_to_long(regs)] data = { "Power KWH" : "%0.3f"%abc[0], "Power KVAH" : "%0.3f"%abc[1], "Power KVArP" : "%0.3f"%abc[2], "Power KVArN" : "%0.3f"%abc[3], "Line Voltages V RY" : "%0.3f"%abc[4], "Line Voltages V YB" : "%0.3f"%abc[5], "Line Voltages V BR" : "%0.3f"%abc[6], "Line Current IR" : "%0.3f"%abc[7], "Line Current IY" : "%0.3f"%abc[8], "Line Current IB" : "%0.3f"%abc[9], "Active Power Consumed" : "%0.3f"%abc[10], "Reactive Power Consumed" : "%0.3f"%abc[11], "Apparent Power Consumed" : "%0.3f"%abc[12], "Phase Voltages VRN" : "%0.3f"%abc[13], "Phase Voltages VYN" : "%0.3f"%abc[14], "Phase Voltages VBN" : "%0.3f"%abc[15], "Power Factor" : "%0.3f"%abc[16], "Frequency" : "%0.3f"%abc[17], "Real Power on R" : "%0.3f"%abc[18], "Real Power on Y" : "%0.3f"%abc[19], "Real Power on B" : "%0.3f"%abc[20], "Reactive Power on R" : "%0.3f"%abc[21], "Reactive Power on Y" : "%0.3f"%abc[22], "Reactive Power on B" : "%0.3f"%abc[23], "Apparent Power on R" : "%0.3f"%abc[24], "Apparent Power on Y" : "%0.3f"%abc[25], "Apparent Power on B" : "%0.3f"%abc[26] } mydate = datetime.datetime.now() date=datetime.datetime.strftime(mydate,'%Y/%m/%d--%H:%M:%S') abc.insert(27,date) myfile = open('data.csv','a') with myfile: writer = csv.writer(myfile, delimiter=',', quoting=csv.QUOTE_ALL) writer.writerow(abc) return data
def Read(self): self.Reset() self.Error = True try: # Initializing connection to Eaton power meter via TCP c = ModbusClient() c.host(ip) c.port(port) c.open() #All time-stamp values timeMark = datetime.datetime.now() self.Error = False self.ErrorType = '' self.year = timeMark.year self.month = timeMark.month self.day = timeMark.day self.hour = timeMark.hour self.minute = timeMark.minute self.second = timeMark.second #All meter values self.Vab = convert(c, vabaddr) self.Vbc = convert(c, vbcaddr) self.Vca = convert(c, vcaaddr) self.Van = convert(c, vanaddr) self.Vbn = convert(c, vbnaddr) self.Vcn = convert(c, vcnaddr) self.phVab = convert(c, phvabaddr) self.phVbc = convert(c, phvbcaddr) self.phVca = convert(c, phvcaaddr) self.Ia = convert(c, iaaddr) self.Ib = convert(c, ibaddr) self.Ic = convert(c, icaddr) self.In = convert(c, inaddr) self.phIa = convert(c, phiaaddr) self.phIb = convert(c, phibaddr) self.phIc = convert(c, phicaddr) self.WphA = convert(c, wphaaddr) self.WphB = convert(c, wphbaddr) self.WphC = convert(c, wphcaddr) self.VARphA = convert(c, varaaddr) self.VARphB = convert(c, varbaddr) self.VARphC = convert(c, varcaddr) self.VanTHD = convert(c, vanaddr) self.VbnTHD = convert(c, vbnaddr) self.VcnTHD = convert(c, vcnaddr) self.IaTHD = convert(c, iathdaddr) self.IbTHD = convert(c, ibthdaddr) self.IcTHD = convert(c, icthdaddr) c.close() except: try: c.close() except: pass self.Error = True self.ErrorType = 'Connection Error'
def save_data(self, name_x): SERVER_HOST = name_x SERVER_PORT = 502 c = ModbusClient() c.host(SERVER_HOST) c.port(SERVER_PORT) if not c.is_open(): if not c.open(): toast("failed") if c.is_open(): toast("connected")
class ModbusClass: def __init__(self): # Make an instance of modbus object self._client = ModbusClient() #Connect to the LOGO def _connectToLogo(self, ip_address, port_num): try: self._client.host(ip_address) self._client.port(port_num) self._client.open() print('Connected') except AttributeError: print('Failed to connect to Logo') # Generic Function for reading from any LOGO def _readData(self, _list=[], *args): _data = [] for regNumber in _list: dataValue = self._client.read_holding_registers( regNumber) # Reading voltage on AI3 dataValue = dataValue[0] dataValue = int(dataValue) _data.append(dataValue) else: return _data # Perform two's compliment on any given number just incase the number is negative def twosCompliment(self, _list, *args): _result_list = [] for number in _list: # All values are expected to be below 8 Bits. If More than 8 Bits, number is negative if number > 256: number = number - 65536 _result_list.append(number) else: number = number _result_list.append(number) else: return _result_list # Convert the electrical signals into meaningful data def signalConditioning(self, _gain, _offset, _signals=[], *args): _result_list = [] for _signal in _signals: _conditioned_signal = (_signal * _gain + _offset) _conditioned_signal = round(_conditioned_signal, 2) _result_list.append(_conditioned_signal) else: return _result_list
def defineModbus(serverHost, serverPort): przerywnik(inspect.getframeinfo( inspect.currentframe())[2]) # nazwa funkcji # defiine atribut of modbus client c = ModbusClient() # uncomment this line to see debug message # c.debug(True) # define modbus server host, port c.host(serverHost) c.port(serverPort) print('Define modbus server at {}::{}'.format(serverHost, serverPort)) return c
def state_off(self, name_x): SERVER_HOST = name_x SERVER_PORT = 502 c = ModbusClient() c.host(SERVER_HOST) c.port(SERVER_PORT) c.open() is_ok = c.write_single_coil(32768, False) if is_ok: self.first_read_label_text = str('kapali') self.image_source = "sf0.png" else: self.first_read_label_text = str('failed')
def connect_nexus_machine(self): c = ModbusClient() c.host("192.168.0.147") c.port(502) c.open() input_register = c.read_coils(0, 16) while True: if input_register: self.lineEditIP.setText(str(input_register)) else: print("read error") time.sleep(5)
def readValueIP(address, port, addr, reg): c = ModbusIPClient() c.host(address) c.port(int(port)) value = -1 if not c.is_open(): if not c.open(): print("Unable to connect to "+address+":"+str(port)) if c.is_open(): try: value = c.read_holding_registers(int(addr), int(reg)) except Exception as e: raise e finally: c.close() return value[0]
def state_on(self, name_x): SERVER_HOST = name_x SERVER_PORT = 502 c = ModbusClient() c.host(SERVER_HOST) c.port(SERVER_PORT) c.open() is_ok = c.write_single_coil(32768, True) bits = c.read_holding_registers(32768) if bits: self.first_read_label_text = str('Acik') self.image_source = "sf_yesil.png" else: self.first_read_label_text = str('cannotread')
def tcp_function_escrita(Porta, Endereco, BaudRate, Registrador, Valor): TCPIP_MODBUS = ModbusClient() TCPIP_MODBUS.host(Endereco) TCPIP_MODBUS.port(Porta) if not TCPIP_MODBUS.is_open(): if not TCPIP_MODBUS.open(): print('Cannot connect to the Modbus TCP/IP Server/Slave') if TCPIP_MODBUS.is_open(): TCPIP_DATA = TCPIP_MODBUS.write_single_register(Registrador, Valor) if TCPIP_DATA: print('TCP/IP successfully Write') else: print('Write Errors in TCP/IP Server/Slave')
def importFromGrid(setPoint, SOCDischarge, SOCCharge): log.write('%02d, %02d, %02d, ' % (setPoint, SOCDischarge, SOCCharge)) #log.write(str(setPoint)+', '+str(SOCDischarge)+', '+str(SOCCharge)+', ') hub4 = ModbusClient() hub4.host(farmIP) hub4.port(hub4Port) hub4.unit_id(hub4Id) inverter = ModbusClient() inverter.host(farmIP) inverter.port(invPort) inverter.unit_id(invId) success = False if inverter.open(): r = inverter.read_input_registers(30, 1) soc = r[0] / 10.0 # convert to a percentage log.write('%.1f, inverter, ' % (soc)) print 'SOC=', (soc) else: log.write('failed to open inverter coms') #sort the chargeing if hub4.open(): success = True if soc < SOCCharge: #allow chargeing at max power set point log.write('charging, ') success = success & hub4.write_single_register(2700, setPoint) else: #battery sufficiently charged set charging power to 0 log.write('not charging, ') success = success & hub4.write_single_register(2700, 0) if soc > SOCDischarge: #allow battery to discharge log.write('discharging, ') success = success & hub4.write_single_register(2702, 100) else: #disallow discharge log.write('not discharging, ') success = success & hub4.write_single_register(2702, 0) hub4.close() log.write('hub4, ') else: log.write('hub4 failed to open hub4 comms') return success
def tcp_function(Porta, Endereco, BaudRate, Registrador, Linhas): TCPIP_MODBUS = ModbusClient() TCPIP_MODBUS.host(Endereco) TCPIP_MODBUS.port(Porta) if not TCPIP_MODBUS.is_open(): if not TCPIP_MODBUS.open(): print('Cannot connect to the Modbus TCP/IP Server/Slave') if TCPIP_MODBUS.is_open(): TCPIP_DATA = TCPIP_MODBUS.read_input_registers(Registrador, Linhas) if TCPIP_DATA: print('TCP/IP successfully read') else: print('Read Errors in TCP/IP Server/Slave') return TCPIP_DATA
def getModbusData(host, port, start_register, end_register): # Returns a list containing the data from each Modbus register between #...and including the start and end register # Depending on the format of any particular value you want, its data may be distributed #...over multiple registers and will require further formatting to be human-readable. # This function only returns the data directly taken from the device's Modbus registers. # Setting up the client #---------------------------------------------------- client = ModbusClient() # Creates a Modbus client opject client.host(host) # Assigns the specified host (IP) address to the client client.port(port) # Assigns the specified port to the client start_register -= 2 # The Modbus registers listed in the Shark100 User's manual end_register -= 2 #...are all offset by 2 from their actual values, #...so we account for that here. num_of_registers = end_register - start_register + 1 # Since the registers are taken as integers, we can take the range between the start and end #...registers and add 1 to get the total number of registers to query. #---------------------------------------------------- # Reading the device's Modbus registers #---------------------------------------------------- client.open() # Opens the connection response = client.read_holding_registers(start_register, num_of_registers) # This function returns a list of values, one for each of the Modbus registers specified. # It works even if some of the registers queried have data stored in different formats, #...so be careful not to automatically treat all data the same. client.close() # Closes the connection #---------------------------------------------------- return response
class Pebl: def __init__(self, ip, system, port=502): self.c = ModbusClient(host=ip, port=502, auto_open=True) self.c.host(ip) self.c.port(port) self.c.open() self.system = system print("opened") def run(self): return_values = [] data_points = csv_json_alarms(self.system) for data_point in data_points: print(data_point) if data_point['type'] == 'COIL': value = self.c.read_coils(int(data_point['address'])) print(value) name = data_point['alarm'] return_values.append({'name': name, 'value': value}) f = open('data.json', 'w') f.write(json.dumps(return_values)) f.close() def run_manual(self): return_values = [] data_points = csv_json_alarms(self.system) for data_point in data_points: print(data_point) if data_point['type'] == 'COIL': value = self.c.read_coils(int(data_point['address'])) name = data_point['alarm'] if data_point['trigger'] == 'NC': if not value[0]: return_values.append({'name': name, 'value': 'OK'}) else: return_values.append({'name': name, 'value': 'ALARM'}) elif data_point['trigger'] == 'NO': if value[0]: return_values.append({'name': name, 'value': 'ALARM'}) else: return_values.append({'name': name, 'value': 'OK'}) return return_values
class ModbusTCPReader: def __init__(self, host, port): self.mbtcp = ModbusClient() self.host = host self.port = port def mbtcp_read(self): if not self.mbtcp.host(self.host): print("Error de Host") if not self.mbtcp.port(self.port): print("Error de Puerto") return self.mbtcp def mbtcp_close(self, arg): arg.close()
from pyModbusTCP.client import ModbusClient import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) _client = ModbusClient() minimum = "global" maximum = "global" avarage = "global" logger.info("connecting") # Connect to LOGO try: _client.host("146.141.117.20") _client.port(503) _client.open() logger.info("connected") except ValueError: logger.info("Failed To Connect")
logging.info("Publishing " + fulltopic) mqc.publish(fulltopic, reMap(self.value), qos=0, retain=False) except Exception as exc: logging.error("Error reading " + self.topic + ": %s", exc) try: mqc = mqtt.Client() mqc.connect(args.mqtt_host, args.mqtt_port, 10) mqc.loop_start() c = ModbusClient() # define modbus server host, port c.host(args.modbus_host) c.port(args.modbus_port) while True: # open or reconnect TCP to server if not c.is_open(): if not c.open(): logging.error("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT)) data = [] for key, value in inputRegisters.items(): if c.is_open(): row = c.read_input_registers(int(value)) row.insert(0, key) data.append(row)
class ClientGUI: def __init__(self): self.lock = RLock() self.calibgui = None self.client = ModbusClient() self.register_values_widgets = {} self.counter = 1 self.find_thread = None self.obj_data = None self.stop_signal = False self.__build_ui() def run_ui(self): self.root.mainloop() def __build_ui(self): # ui hierarchy: # #root # connectframe # connectlabel # connectbutton # snapshotbutton # calibbuton # mainframe # registerframe # reglabel # registergridframe # ... # outputframe # outputlabel # outputtext root = Tk() self.root = root root.wm_title("RemoteSurf Modbus Client") root.protocol("WM_DELETE_WINDOW", self.__delete_window) self.font = tkFont.Font(root = root, family = "Helvetica", size = 12) connectframe = Frame(root) connectbutton = Button(connectframe, text = "Connect", command = self.__connectbutton_click) connectlabel = Label(connectframe, text = "Not connected.") calibbutton = Button(connectframe, text = "Calibrate", command = self.__calibbutton_click) homebutton = Button(connectframe, text = "Home", command = self.__homebutton_click) findbutton = Button(connectframe, text = "Find", command = self.__findbutton_click) mainframe = Frame(root) registerframe = Frame(mainframe) reglabel = Label(registerframe, text = "Set registers") registergridframe = Frame(registerframe) # outputframe = Frame(mainframe) # outputlabel = Label(outputframe, text = "Output") # vscrollbar = Scrollbar(outputframe) # hscrollbar = Scrollbar(outputframe) # outputtext = ThreadSafeConsole(outputframe, root, vscrollbar, font = self.font, wrap = NONE) connectframe.pack(side = TOP, fill = X) connectlabel.pack(side = BOTTOM, anchor = W) homebutton.pack(side = RIGHT) findbutton.pack(side = RIGHT) calibbutton.pack(side = RIGHT) connectbutton.pack(side = RIGHT) mainframe.pack(side = BOTTOM, fill = BOTH, expand = YES) registerframe.pack(side = TOP, expand = YES, anchor = W) # outputframe.pack(side = BOTTOM, fill = BOTH, expand = YES) reglabel.pack(side = TOP, anchor = CENTER) registergridframe.pack(side = BOTTOM, anchor = W) # registerframe.config(bg = "cyan") # mainframe.config(bg = "pink") # registergridframe.config(bg = "red") registergridframe.columnconfigure(0, weight = 1) registergridframe.columnconfigure(1, weight = 1) registergridframe.columnconfigure(2, weight = 1) registergridframe.columnconfigure(3, weight = 1) self.x_pad = 10 registergrid_widgets = [] titles = ["Address", "Label", "Value", ""] col = 0 for title in titles: title_label = Label(registergridframe, text = title) title_label.grid(row = 0, column = col, padx = self.x_pad) registergrid_widgets.append(title_label) col += 1 registers_data = [(500, "x"), (501, "y"), (502, "z"), (503, "A"), (504, "B"), (505, "C"), ] for i in range(len(registers_data)): reg_data = registers_data[i] row = i + 1 self.__add_register(registergridframe, reg_data, row, registergrid_widgets) # hscrollbar.config(orient = HORIZONTAL, command = outputtext.xview) # hscrollbar.pack(side = BOTTOM, fill = X) # outputtext.config(state = DISABLED, yscrollcommand = vscrollbar.set, xscrollcommand = hscrollbar.set) #must change to NORMAL before writing text programmatically # outputtext.pack(side = LEFT, fill = BOTH, expand = YES, padx = x_padding, pady = y_padding) # vscrollbar.config(command = outputtext.yview) # vscrollbar.pack(side = RIGHT, fill = Y) self.connectframe = connectframe self.connectlabel = connectlabel self.connectbutton = connectbutton self.mainframe = mainframe self.registerframe = registerframe self.reglabel = reglabel self.registergridframe = registergridframe self.calibbutton = calibbutton # self.outputframe = outputframe # self.outputlabel = outputlabel # self.vscrollbar = vscrollbar # self.hscrollbar = hscrollbar # self.outputtext = outputtext root.update() w, h = root.winfo_width(), root.winfo_height() root.minsize(w, h) x, y = MAINFRAME_POS root.geometry('%dx%d+%d+%d' % (w, h, x, y)) def __homebutton_click(self): values = { 500: 300, 501: 0, 502: 500, 503: 180, 504: 0, 505: 180, } self.set_values(values, go_to_value = False) def __add_register(self, master, data, row, widget_list): regaddresslabel = Label(master, text=str(data[0])) regaddresslabel.grid(row=row, column=0) reglabellabel = Label(master, text=data[1]) reglabellabel.grid(row=row, column=1) regvalueentry = AccessibleEntry(master, justify = RIGHT) regvalueentry.set("0") regvalueentry.grid(row=row, column=2, padx=self.x_pad) regsetbtn = Button(master, text="Set", command = self.__setbutton_click) regsetbtn.grid(row=row, column=3) widget_list.append(regaddresslabel) widget_list.append(reglabellabel) widget_list.append(regvalueentry) widget_list.append(regsetbtn) self.register_values_widgets[data[0]] = (0, regvalueentry) def __calibbutton_click(self): if not self.calibgui: self.calibgui = CalibGUI(self) def __findbutton_click(self): if self.find_thread is None: self.find_thread = Thread(target=self.__find_object) self.find_thread.start() def __find_object(self): import DataCache as DC from glob import glob from os.path import join import numpy as np from SFMSolver import SFMSolver, find_ext_params import Utils print "FINDING" np.set_printoptions(precision=3, suppress=True) files_dir = "out/2017_3_8__14_51_22/" files = glob(join(files_dir, "*.jpg")) masks = [] for f in files: m = f.replace(".jpg", "_mask.png") masks.append(m) sfm = SFMSolver(files, masks) if self.obj_data is None: imgs, kpts, points, data = sfm.calc_data_from_files_triang_simple() self.obj_data = imgs, kpts, points, data else: imgs, kpts, points, data = self.obj_data arr_calib = DC.getData("out/%s/arrangement_calib.p" % ARRANGEMENT_CALIB_DIR) ttc = arr_calib["ttc"] tor = arr_calib["tor"] if "cam_mtx" in arr_calib: print "camMtx, distcoeffs load" Utils.camMtx = arr_calib["cam_mtx"] Utils.dist_coeffs = arr_calib["dist_coeffs"] if self.stop_signal: self.stop_signal = False return for point in FIND_POINTS: values = { 500: point[0], 501: point[1], 502: point[2], 503: point[3], 504: point[4], 505: point[5], } print "set_values call" self.set_values(values, True) print "set_values return" time.sleep(0.5) CamGrabber.capture_if_no_chessboard = True CamGrabber.capture = True time.sleep(0.5) if self.stop_signal: self.stop_signal = False return find_dir = logger.outputdir files = glob("%s/*.jpg" % find_dir) print files # files_dir = "out/2017_4_5__15_57_20/" # files = glob(join(files_dir, "*.jpg")) files.sort() files = files[-len(FIND_POINTS):] results = [] for f in files: res = find_ext_params(f, imgs, kpts, points, data, tor, ttc) results.append(res) if self.stop_signal: self.stop_signal = False return for i in range(len(results)): print i, results[i] write_log((i, results[i])) result = max(results, key=lambda x: x[2]) write_log(result) values = { 500: int(result[0][0] * 10), 501: int(result[0][1] * 10), 502: int(result[0][2] * 10) + 200, 503: int(result[1][2]), 504: int(result[1][1]), 505: int(result[1][0]), } print "num inl: ", result[2] pprint(values) self.set_values(values, go_to_value=False) self.find_thread = None def __connectbutton_click(self): if self.client.is_open(): self.client.close() else: self.client.host(SERVER_HOST) self.client.port(SERVER_PORT) if self.client.open(): write_log("Connection established") self.refresh_values() self.read_robot_pos() else: write_log("ERROR: Connecting failed") self.__update_gui() def read_robot_pos(self): write_log("Reading robot position:") posdict = {} for i in range(1000, 1006): if self.client.is_open(): with self.lock: real_val_uint = self.client.read_input_registers(i)[0] real_val_holding_uint = self.client.read_holding_registers(i)[0] assert real_val_uint == real_val_holding_uint real_val_int = uintToInt16(real_val_uint) posdict[i] = real_val_int write_log("%d, %d" % (i, real_val_int)) else: write_log("ERROR: Read could not be completed, client not connected.") self.__update_gui() break write_log("Read done.") return posdict def refresh_values(self): for address in self.register_values_widgets: if self.client.is_open(): value, widget = self.register_values_widgets[address] with self.lock: real_val_uint = self.client.read_input_registers(address)[0] real_val_holding_uint = self.client.read_holding_registers(address)[0] assert real_val_uint == real_val_holding_uint real_val_int = uintToInt16(real_val_uint) widget.set(str(real_val_int)) self.register_values_widgets[address] = (real_val_int, widget) else: write_log("ERROR: Read could not be completed, client not connected.") self.__update_gui() break write_log("Refresh done.") return self.register_values_widgets def __update_gui(self): if self.client.is_open(): self.connectlabel.config(text = "Connected to: %s:%d" % (SERVER_HOST, SERVER_PORT)) self.connectbutton.config(text = "Disconnect") else: self.connectbutton.config(text = "Connect") self.connectlabel.config(text = "Not connected.") self.root.update() def __print_memory(self): self.refresh_values() write_log("Memory dump:") write_log("------------") for address in self.register_values_widgets: val, widget = self.register_values_widgets[address] write_log("%d, %d" % (address, val)) write_log("------------") def __setbutton_click(self, wait = False): if not self.client.is_open(): write_log("ERROR: Not connected to client") return # writing message counter retval = self.__write_register(COUNTER_REGISTER_OUT, self.counter) if not retval: self.__update_gui() return # writing registers for address in self.register_values_widgets: value, widget = self.register_values_widgets[address] widgetvalue_int = None try: widgetvalue_int = int(widget.get()) except ValueError: write_log("ERROR: Wrong input format in value entry for address: %d" % address) continue if value == widgetvalue_int: continue retval = self.__write_register(address, widgetvalue_int) if retval: self.register_values_widgets[address] = (widgetvalue_int, widget) else: self.__update_gui() self.refresh_values() # message counter wait if wait: global break_wait while not break_wait: with self.lock: counter = self.client.read_input_registers(COUNTER_REGISTER_IN)[0] if counter == self.counter: break time.sleep(0.1) break_wait = False # counter increment self.counter = (self.counter + 1) % 20 if PRINT_ALL_MEMORY_ON_WRITE: self.__print_memory() self.read_robot_pos() def __write_register(self, address, value): if not (-32768 <= value <= 32767): write_log("ERROR: -32768 <= value <= 32767 is false for address: %d" % address) return False widgetvalue_uint = intToUint16(value) if self.client.is_open(): with self.lock: retval = self.client.write_single_register(address, widgetvalue_uint) if retval: write_log("Register written. Address: %d, value: %d" % (address, value)) return True else: write_log("ERROR: Write failed. Address: %d, value: %d" % (address, value)) else: write_log("ERROR: client not connected.") return False def set_values(self, values, wait = True, go_to_value = True): """ :param values: dictionary of { address : value} both int :return: """ for address in values: if address not in self.register_values_widgets: continue val, widget = self.register_values_widgets[address] widget.set(str(values[address])) if go_to_value: self.__setbutton_click(wait) def __delete_window(self): CamGrabber.exit = True self.stop_signal = True self.client.close() self.root.quit()
def test_port(self): # test valid/invalid cases for port() c = ModbusClient() self.assertEqual(c.port(), 502, 'default modbus/TCP port is 502') self.assertEqual(c.port(-1), None) self.assertEqual(c.port(42), 42)
class Device(): def __init__(self, host, port, timeout, byteorder=BE): # big_endian : Byte order of the device memory structure # True >> big endian # False >> little endian if byteorder == BE: self.big_endian=True else: self.big_endian=False self.dev = ModbusClient() self.dev.host(host) self.dev.port(port) self.dev.timeout(timeout) self.dev.open() #self.dev.debug = True #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ READ METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #Method to read binary variable def read_bits(self, VarNameList, AddressList, functioncode=2): # Arguments: # VarNameList : list of variable name # AddressList : list of variable register address in decimal (relative address) # functioncode : functioncode for modbus reading operation # 1 >> for Discrete Output (Coils) # 2 >> for Discrete Input # Return : dictionary of variable name and its value self.values = [] if functioncode == 1: for address in AddressList: self.values.extend(self.dev.read_coils(address[0], len(address))) elif functioncode == 2: for address in AddressList: self.values.extend(self.dev.read_discrete_inputs(address[0], len(address))) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to read INT16 or UINT16 variable def read_INT16(self, VarNameList, AddressList, MultiplierList, signed=False, roundto=3, functioncode=3): # Arguments: # VarNameList : list of variable name # AddressList : list of variable register address in decimal (relative address) # MultiplierList : list of multiplier # roundto : number of digits after decimal point # any positive integer number >> to limit the number of digits after decimal point # None >> to disable # signed : True >> for signed values # False >> for unsigned values # functioncode : functioncode for modbus reading operation # 3 >> for Holding Register # 4 >> for Input Register # Return : dictionary of variable name and its value self.values = [] if functioncode == 3: for address in AddressList: self.values.extend(self.dev.read_holding_registers(address[0],len(address))) elif functioncode == 4: for address in AddressList: self.values.extend(self.dev.read_input_registers(address[0],len(address))) if signed: self.values = UINT16toINT16(self.values) for i in range(0, len(self.values)): self.values[i] = round(self.values[i]*MultiplierList[i],roundto) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to read INT32 or UINT32 variable def read_INT32(self, VarNameList, AddressList, MultiplierList, signed=False, roundto=3, functioncode=3): # Arguments: # VarNameList : list of variable name # AddressList : list of variable register address in decimal (relative address) # MultiplierList : list of multiplier # roundto : number of digits after decimal point # any positive integer number >> to limit the number of digits after decimal point # None >> to disable # signed : True >> for signed values # False >> for unsigned values # functioncode : functioncode for modbus reading operation # 3 >> for Holding Register # 4 >> for Input Register # Return : dictionary of variable name and its value self.values = [] if functioncode == 3: for address in AddressList: self.values.extend(self.dev.read_holding_registers(address[0],len(address))) elif functioncode == 4: for address in AddressList: self.values.extend(self.dev.read_input_registers(address[0],len(address))) self.values = UINT16toINT32(self.values, self.big_endian, signed) for i in range(0, len(self.values)): self.values[i] = round(self.values[i]*MultiplierList[i], roundto) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to read INT64 or UINT64 variable def read_INT64(self, VarNameList, AddressList, MultiplierList, signed=False, roundto=3, functioncode=3): # Arguments: # VarNameList : list of variable name # AddressList : list of variable register address in decimal (relative address) # MultiplierList : list of multiplier # roundto : number of digits after decimal point # any positive integer number >> to limit the number of digits after decimal point # None >> to disable # signed : True >> for signed values # False >> for unsigned values # functioncode : functioncode for modbus reading operation # 3 >> for Holding Register # 4 >> for Input Register # Return : dictionary of variable name and its value self.values = [] if functioncode == 3: for address in AddressList: self.values.extend(self.dev.read_holding_registers(address[0],len(address))) elif functioncode == 4: for address in AddressList: self.values.extend(self.dev.read_input_registers(address[0],len(address))) self.values = UINT16toINT64(self.values, self.big_endian, signed) for i in range(0, len(self.values)): self.values[i] = round(self.values[i]*MultiplierList[i], roundto) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to read FLOAT16 variable def read_FLOAT16(self, VarNameList, AddressList, MultiplierList, roundto=3, functioncode=3): # Arguments: # VarNameList : list of variable name # AddressList : list of variable register address in decimal (relative address) # MultiplierList : list of multiplier # roundto : number of digits after decimal point # any positive integer number >> to limit the number of digits after decimal point # None >> to disable # functioncode : functioncode for modbus reading operation # 3 >> for Holding Register # 4 >> for Input Register # Return : dictionary of variable name and its value self.values = [] if functioncode == 3: for address in AddressList: self.values.extend(self.dev.read_holding_registers(address[0],len(address))) elif functioncode == 4: for address in AddressList: self.values.extend(self.dev.read_input_registers(address[0],len(address))) self.values = UINT16toFLOAT16(self.values) for i in range(0, len(self.values)): self.values[i] = round(self.values[i]*MultiplierList[i], roundto) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to read FLOAT32 variable def read_FLOAT32(self, VarNameList, AddressList, MultiplierList, roundto=3, functioncode=3): # Arguments: # VarNameList : list of variable name # AddressList : list of variable register address in decimal (relative address) # MultiplierList : list of multiplier # roundto : number of digits after decimal point # any positive integer number >> to limit the number of digits after decimal point # None >> to disable # functioncode : functioncode for modbus reading operation # 3 >> for Holding Register # 4 >> for Input Register # Return : dictionary of variable name and its value self.values = [] if functioncode == 3: for address in AddressList: self.values.extend(self.dev.read_holding_registers(address[0],len(address))) elif functioncode == 4: for address in AddressList: self.values.extend(self.dev.read_input_registers(address[0],len(address))) self.values = UINT16toFLOAT32(self.values, self.big_endian) for i in range(0, len(self.values)): self.values[i] = round(self.values[i]*MultiplierList[i], roundto) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to read FLOAT64 variable def read_FLOAT64(self, VarNameList, AddressList, MultiplierList, roundto=3, functioncode=3): # Arguments: # VarNameList : list of variable name # AddressList : list of variable register address in decimal (relative address) # MultiplierList : list of multiplier # roundto : number of digits after decimal point # any positive integer number >> to limit the number of digits after decimal point # None >> to disable # functioncode : functioncode for modbus reading operation # 3 >> for Holding Register # 4 >> for Input Register # Return : dictionary of variable name and its value self.values = [] if functioncode == 3: for address in AddressList: self.values.extend(self.dev.read_holding_registers(address[0],len(address))) elif functioncode == 4: for address in AddressList: self.values.extend(self.dev.read_input_registers(address[0],len(address))) self.values = UINT16toFLOAT64(self.values, self.big_endian) for i in range(0, len(self.values)): self.values[i] = round(self.values[i]*MultiplierList[i], roundto) self.Result = dict(zip(VarNameList, self.values)) return self.Result #Method to read STRING variable def read_STRING(self, VarNameList, AddressList, functioncode=3): # Arguments: # VarNameList : list of variable name # AddressList : list of variable register address in decimal (relative address) # functioncode : functioncode for modbus reading operation # 3 >> for Holding Register # 4 >> for Input Register # Return : dictionary of variable name and its value self.values = [] if functioncode == 3: for address in AddressList: _uint16Val = self.dev.read_holding_registers(address[0],len(address)) self.values.append(UINT16toSTRING(_uint16Val, self.big_endian)) elif functioncode == 4: for address in AddressList: _uint16Val = self.dev.read_input_registers(address[0],len(address)) self.values.append(UINT16toSTRING(_uint16Val, self.big_endian)) self.Result = dict(zip(VarNameList, self.values)) return self.Result #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ WRITE METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# # Method to write binary value on discrete output register (Coil) def write_bit(self, registerAddress, value): # Arguments: # registerAddress : register address in decimal (relative address) # value : 0 or 1 self.dev.write_single_coil(registerAddress, value) # Method to write numeric value on holding register def write_num(self, registerAddress, value, valueType): # Arguments: # registerAddress : register START address in decimal (relative address) # value : numerical value # valueType : UINT16, UINT32, UINT64, INT16, INT32, INT64, FLOAT16, # FLOAT32, FLOAT64, STRING startAddress = registerAddress val = None if valueType == UINT16: val = [value] elif valueType == INT16: val = INT16toUINT16([value]) elif valueType == UINT32: val = INT32toUINT16(value, self.big_endian, signed=False) elif valueType == INT32: val = INT32toUINT16(value, self.big_endian, signed=True) elif valueType == UINT64: val = INT64toUINT16(value, self.big_endian, signed=False) elif valueType == INT64: val = INT64toUINT16(value, self.big_endian, signed=True) elif valueType == FLOAT16: val = FLOAT16toUINT16([value]) elif valueType == FLOAT32: val = FLOAT32toUINT16(value, self.big_endian) elif valueType == FLOAT64: val = FLOAT64toUINT16(value, self.big_endian) elif valueType == STRING: val = STRINGtoUINT16(value, self.big_endian) # write multiple registers self.dev.write_multiple_registers(startAddress, val) def close(self): self.dev.close()
def test_port(self): # test valid/invalid cases for port() c = ModbusClient() self.assertEqual(c.port(), 502, "default modbus/TCP port is 502") self.assertEqual(c.port(-1), None) self.assertEqual(c.port(42), 42)
from pyModbusTCP.client import ModbusClient from pyModbusTCP import utils import time client_host = "192.168.250.2" client_port = 502 c = ModbusClient() c.host(client_host) c.port(client_port) if not c.is_open(): if not c.open(): print("unable to connect to " + client_host + ":" + str(client_port)) def int32_to_int8(n): mask = (1 << 16) - 1 return [(n >> k) & mask for k in range(0, 32, 16)] var_int = utils.encode_ieee(7.5) print(var_int) sonuc=int32_to_int8(var_int) print(sonuc) if c.is_open(): # read 10 registers at address 0, store result in regs list print(var_int) c.write_single_register(0,5)
class AcuvimIITCPMODBUS: def __init__(self, server_host, port, unit_id): self.c = ModbusClient() self.c.host(server_host) self.c.port(port) self.c.unit_id(unit_id) self.map = self.__import_map() def __import_map(self): with open('map.json') as json_file: return json.load(json_file) def __read_16_bit(self, address): if not self.c.is_open(): self.c.open() return self.c.read_holding_registers(address, 1)[0] def __read_32_bit(self, address, number=1): if not self.c.is_open(): self.c.open() reg_l = self.c.read_holding_registers(address, number * 2) if reg_l: return [ utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l) ][0] else: return None def __what_is_the_access_property(self, dict): if dict['Access Property'] == 'R': return 0 if dict['Access Property'] == 'W': return 2 else: return 1 def __get_registry(self, dict): if dict['Data Type'] == 'Word': return (self.__read_16_bit(dict["Address(D)"])) elif dict['Data Type'] == 'Float': return (self.__read_32_bit(dict["Address(D)"])) elif dict['Data Type'] == 'Dword': return (self.__read_32_bit(dict["Address(D)"])) elif dict['Data Type'] == 'int': return (self.__read_16_bit(dict["Address(D)"])) elif dict['Data Type'] == 'Bit': return (self.__read_16_bit(dict["Address(D)"])) def get_clock(self): if not self.c.is_open(): self.c.open() read_datetime = self.c.read_holding_registers(4159, 7) return datetime.datetime(read_datetime[1], read_datetime[2], read_datetime[3], read_datetime[4], read_datetime[5], read_datetime[6]) def read_value(self, parameter=None, address=None): if parameter is not None: temp_dict = list( filter(lambda d: d['Parameter'] == parameter, self.map)) if not len(temp_dict) == 0 and self.__what_is_the_access_property( temp_dict[0]) <= 1: return (self.__get_registry(temp_dict[0])) elif address is not None: temp_dict = list( filter(lambda d: d['Address(D)'] == address, self.map)) if not len(temp_dict) == 0 and self.__what_is_the_access_property( temp_dict) <= 1: return (self.__get_registry(temp_dict[0])) else: return None
def send_data(): SERVER_HOST = "169.254.0.12" SERVER_PORT = 502 #this has to be 502 for tcp/ip modbus SERVER_UNIT_ID = 100 #slave id is 100 for schneider powerlogic ion 7650 #default value for ionmeter #subnet mask= 255.240.0.0 #gateway= 0.0.0.0 #Required Registers to be read :- #Va= 40166 2 registers ie. c.read_input_registers(40166,2) #power kw a = 40198 2 registers #kVAR a= 40208 2 registers #kVA a= 40218 2 registers #frequency = 40159 1 register #Ia= 40150 1 register #this function reads the float value for address and number of bits (not required) #def read_float( address, number=1): # reg_l = c.read_holding_registers(address, number ) #can change to read_input_registers just to check # if reg_l: # return [utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)] # else: # return None c = ModbusClient() c.host(SERVER_HOST) c.port(SERVER_PORT) c.unit_id(SERVER_UNIT_ID) #default slave id for schneider is 100 if not c.is_open(): if not c.open(): print("cannot connect ....") if c.is_open(): #read_holding_registers has an offset of 4000 to begin with while True: voltage_a = c.read_holding_registers( 166, 1) #list output for integer take voltage_a[0] voltage_a = voltage_a[0] #print voltage_a #current_a=c.read_holding_registers(150,1) k = state_val.count(1) current_a = random.uniform( state_val.count(1) * cur_val, state_val.count(1) * cur_val + 0.05) if k != 0 else 0 #current_a=current_a[0] #print current_a real_power_a = c.read_holding_registers(208, 1) #real_power_a=real_power_a[0] #print real_power_a reactive_power_a = c.read_holding_registers(218, 1) #reactive_power_a=reactive_power_a[0] #print reactive_power_a apparent_power_a = c.read_holding_registers(218, 1) #apparent_power_a=apparent_power_a[0] #print apparent_power_a freq = c.read_holding_registers(159, 1) freq = freq[0] / 10 #move this part to decision in case of load scheduling #set_priority() #print_priority() #print freq np.array(voltage_a, dtype=float) np.array(current_a, dtype=float) np.array(real_power_a, dtype=float) np.array(reactive_power_a, dtype=float) np.array(apparent_power_a, dtype=float) np.array(freq, dtype=float) data = { "voltage_reading": '%.2f' % voltage_a, "current_reading": '%.2f' % current_a, "frequency_reading": '%.2f' % freq, "load_0_status": "ON" if state_val[0] == 1 else "OFF", "load_1_status": "ON" if state_val[1] == 1 else "OFF", "load_2_status": "ON" if state_val[2] == 1 else "OFF", "load_3_status": "ON" if state_val[3] == 1 else "OFF", "bpi_0": '%.2f' % bpi[0], "bpi_1": '%.2f' % bpi[1], "bpi_2": '%.2f' % bpi[2], "bpi_3": '%.2f' % bpi[3], "sv0": state_val[0], "sv1": state_val[1], "sv2": state_val[2], "sv3": state_val[3] } print(data) decision(data) return data
class HeatPump(): def __init__(self, ipOrHostName, portNumber, unitId, code): self.code = code self.registers = HeatPumpRegisters() self.mbClient = ModbusClient() self.mbClient.host(ipOrHostName) self.mbClient.port(portNumber) self.mbClient.unit_id(unitId) self.mbClient.open() self.outsideTemperature = HeatPumpConstants.NAN_VALUE self.currentRoomTemperature = HeatPumpConstants.NAN_VALUE self.currentExhaustFanSpeed = HeatPumpConstants.NAN_VALUE self.currentSupplyFanSpeed = HeatPumpConstants.NAN_VALUE self.airingLevelDay = HeatPumpConstants.NAN_VALUE self.airingLevelNight = HeatPumpConstants.NAN_VALUE self.powerConsumptionHeatingDay = HeatPumpConstants.NAN_VALUE self.powerConsumptionWarmWaterDay = HeatPumpConstants.NAN_VALUE return def setAiringLevelDay(self, airingLevel, code): return self._setAiringLevel(self.registers.AIRING_LEVEL_DAY.Address, airingLevel, code) def setAiringLevelNight(self, airingLevel, code): return self._setAiringLevel(self.registers.AIRING_LEVEL_NIGHT.Address, airingLevel, code) def _setAiringLevel(self, registerAddress, airingLevel, code): if int(code) != self.code: return (False, "Invalid security code") if not self.mbClient.is_open() and not self.mbClient.open(): return (False, "Unable to connect to {}:{}".format(self.mbClient.host(), self.mbClient.port())) if type(airingLevel) == str: try: airingLevel = int(airingLevel) except: raise TypeError("Could not convert {} to type 'int'".format(airingLevel)) retVal = self.mbClient.write_single_register(registerAddress, airingLevel) if not retVal: return (False, "Failed to set airing level") else: return (True, "Setting airing level successful") def readCurrentValues(self): if not self.mbClient.is_open() and not self.mbClient.open(): print ("Unable to connect to {}:{}".format(self.mbClient.host(), self.mbClient.port())) return False regVal_outsideTemperature = self.mbClient.read_input_registers(self.registers.OUTSIDE_TEMPERATURE.Address, self.registers.OUTSIDE_TEMPERATURE.SequenceSize) regVal_currentRoomTemperature = self.mbClient.read_input_registers(self.registers.CURRENT_ROOM_TEMPERATURE.Address, self.registers.CURRENT_ROOM_TEMPERATURE.SequenceSize) regVal_currentExhaustFanSpeed = self.mbClient.read_input_registers(self.registers.CURRENT_EXHAUST_FAN_SPEED.Address, self.registers.CURRENT_EXHAUST_FAN_SPEED.SequenceSize) regVal_currentSupplyFanSpeed = self.mbClient.read_input_registers(self.registers.CURRENT_SUPPLY_FAN_SPEED.Address, self.registers.CURRENT_SUPPLY_FAN_SPEED.SequenceSize) regVal_airingLevelDay = self.mbClient.read_holding_registers(self.registers.AIRING_LEVEL_DAY.Address, self.registers.AIRING_LEVEL_DAY.SequenceSize) regVal_airingLevelNight = self.mbClient.read_holding_registers(self.registers.AIRING_LEVEL_NIGHT.Address, self.registers.AIRING_LEVEL_NIGHT.SequenceSize) regVal_powerConsumptionHeatingDay = self.mbClient.read_input_registers(self.registers.POWER_CONSUMPTION_HEATING_DAY.Address, self.registers.POWER_CONSUMPTION_HEATING_DAY.SequenceSize) regVal_powerConsumptionWarmWaterDay = self.mbClient.read_input_registers(self.registers.POWER_CONSUMPTION_WARMWATER_DAY.Address, self.registers.POWER_CONSUMPTION_WARMWATER_DAY.SequenceSize) outsideTemperature = self.registers.shiftValue(regVal_outsideTemperature, self.registers.OUTSIDE_TEMPERATURE.SequenceSize) # outsideTemperature can be less than zero self.outsideTemperature = self.registers.convertSignedValue(outsideTemperature, HeatPumpConstants.MBREG_BITWIDTH) * 0.1 self.currentRoomTemperature = self.registers.shiftValue(regVal_currentRoomTemperature, self.registers.CURRENT_ROOM_TEMPERATURE.SequenceSize) * 0.1 self.currentExhaustFanSpeed = self.registers.shiftValue(regVal_currentExhaustFanSpeed, self.registers.CURRENT_EXHAUST_FAN_SPEED.SequenceSize) self.currentSupplyFanSpeed = self.registers.shiftValue(regVal_currentSupplyFanSpeed, self.registers.CURRENT_SUPPLY_FAN_SPEED.SequenceSize) self.airingLevelDay = self.registers.shiftValue(regVal_airingLevelDay, self.registers.AIRING_LEVEL_DAY.SequenceSize) self.airingLevelNight = self.registers.shiftValue(regVal_airingLevelNight, self.registers.AIRING_LEVEL_NIGHT.SequenceSize) self.powerConsumptionHeatingDay = self.registers.shiftValue(regVal_powerConsumptionHeatingDay, self.registers.POWER_CONSUMPTION_HEATING_DAY.SequenceSize) self.powerConsumptionWarmWaterDay = self.registers.shiftValue(regVal_powerConsumptionWarmWaterDay, self.registers.POWER_CONSUMPTION_WARMWATER_DAY.SequenceSize) return True
class modBusWriteRead(): def __init__(self,client_host): self.client_host = client_host self.client_port = 502 self.err_list = [] self.connect() #buradan bağlantı yapılacak; def connect(self): self.modbus_c = ModbusClient() self.modbus_c.host(self.client_host) self.modbus_c.port(self.client_port) if not self.modbus_c.is_open(): if not self.modbus_c.open(): text="unable to connect to " + self.client_host + ":" + str(self.client_port) print(text) def write_data_reg(self,address,list): if self.modbus_c.open(): if len(list)>120: sent_list = self.hazirla_dizi_to_write(list) i = 0 hedef_reg_taban = address for list_to_sent in sent_list: hedef_reg = hedef_reg_taban + (i * 120) a = self.modbus_c.write_multiple_registers(hedef_reg, list_to_sent) if a == None or a == False: self.err_list.append(False) i += 1 else: a = self.modbus_c.write_multiple_registers(address, list) if a == None or a == False: self.err_list.append(False) if len(self.err_list) > 0: self.err_list = [] pass # dikkat # print("data göndermede hata oluştu, tekrar deneyin !") def hazirla_dizi_to_write(self,d_list): # eğer gönderilecek değer 120 den büyük ise aşağıdaki fonksiyon 120 lik diziler döndürüyor r_list = [] g_list = [] i = 0 for index in range(len(d_list)): g_list.append(d_list[index]) i += 1 if i > 119: i = 0 r_list.append(g_list) g_list = [] if (len(d_list) - 1) == index and i < 119: r_list.append(g_list) return r_list def read_data_reg(self,address,reg_count,read_float=False ): # burada 16 lık ya da float olarak okunabiliyor if self.modbus_c.is_open(): if read_float == False: plc_list_int = self.modbus_c.read_holding_registers(address, reg_count) return plc_list_int elif read_float == True: plc_list_f_16=self.modbus_c.read_holding_registers(address,reg_count) if plc_list_f_16 is not None: plc_list_float=self.long_to_float(plc_list_f_16) return plc_list_float def long_to_float(self,list_16): list_float=[] list_16.reverse() list_long=utils.word_list_to_long(list_16) for any_long in list_long: list_float.append(utils.decode_ieee(any_long)) list_float.reverse() return list_float
def get_points(conn, devices): for device in devices: try: cur = conn.cursor() #Get IP Address and port from database cur.execute("SELECT ip, port FROM device WHERE devID = ?", (device, )) request = cur.fetchone() ip = request[0] port = request[1] client = ModbusClient() client.host(ip) client.port(port) client_connected = True if (client.is_open() == False): if (client.open() == False): print("Unable to connect to " + ip + ":" + str(port)) client_connected = False if (client_connected == True): cur.execute( "SELECT name, address, type, pointID, mult_factor FROM device_points WHERE devID = ? AND deleted = 0", (device, )) rows = cur.fetchall() for row in rows: if (row[2] == "dig_in"): req = client.read_discrete_inputs(int(row[1]), 1) datetime_str = datetime.now().strftime( "%Y-%m-%d %H:%M:%S.%f") point_ID = row[3] value = req[0] * row[4] print(datetime_str + " | " + str(point_ID) + " | " + str(value)) cur.execute("INSERT INTO point_data VALUES (?, ?, ?)", (datetime_str, point_ID, value)) #print("Value for point " + row[0] + ": " + str(req) + datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) if (row[2] == "dig_out"): req = client.read_coils(int(row[1]), 1) datetime_str = datetime.now().strftime( "%Y-%m-%d %H:%M:%S.%f") point_ID = row[3] value = req[0] * row[4] error_code = 0 print(datetime_str + " | " + str(point_ID) + " | " + str(value)) cur.execute("INSERT INTO point_data VALUES (?, ?, ?)", (datetime_str, point_ID, value)) #print("Value for point " + row[0] + ": " + str(req) + datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) if (row[2] == "an_in"): req = client.read_input_registers(int(row[1]), 1) datetime_str = datetime.now().strftime( "%Y-%m-%d %H:%M:%S.%f") point_ID = row[3] value = req[0] * row[4] error_code = 0 print(datetime_str + " | " + str(point_ID) + " | " + str(value)) cur.execute("INSERT INTO point_data VALUES (?, ?, ?)", (datetime_str, point_ID, value)) #print("Value for point " + row[0] + ": " + str(req) + datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) if (row[2] == "an_out"): req = client.read_holding_registers(int(row[1]), 1) datetime_str = datetime.now().strftime( "%Y-%m-%d %H:%M:%S.%f") point_ID = row[3] value = req[0] * row[4] error_code = 0 print(datetime_str + " | " + str(point_ID) + " | " + str(value)) cur.execute("INSERT INTO point_data VALUES (?, ?, ?)", (datetime_str, point_ID, value)) #print("Value for point " + row[0] + ": " + str(req) + datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) print("\n") conn.commit() cur.close() client.close() except Error as e: print(e) conn.close() database = "./database/SCADADB.db" conn = create_connection(database)
# write 4 bits to True, wait 2s, write False, restart... from pyModbusTCP.client import ModbusClient import time SERVER_HOST = "localhost" SERVER_PORT = 502 c = ModbusClient() # uncomment this line to see debug message #c.debug(True) # define modbus server host, port c.host(SERVER_HOST) c.port(SERVER_PORT) toggle = True while True: # open or reconnect TCP to server if not c.is_open(): if not c.open(): print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT)) # if open() is ok, write coils (modbus function 0x01) if c.is_open(): # write 4 bits in modbus address 0 to 3 print("") print("write bits") print("----------")
temp = 0 for i in range(1, 9): for j in range(1, 8): temp = temp + 1 dict_coord[temp] = [41 * i, 33 * -j] while_flag = 0 cap = cv.VideoCapture(1) counter = 0 while (True): #Trigger the camera to take a picture #c = ModbusClient(host="192.1.1.2", port=502, auto_open=True) c = ModbusClient() c.host("192.1.1.2") c.port(502) d = ModbusClient() d.host("192.1.1.2") d.port(502) # managing TCP sessions with call to c.open()/c.close() c.open() if (counter >= 56): counter = 0 else: counter += 1 while (while_flag != 1): _, frame = cap.read() cv.imwrite(os.path.join(camera_path, 'image.jpg'), frame) time.sleep(1) # cap.release()
def send_data(): SERVER_HOST = "169.254.0.12" SERVER_PORT = 502 #this has to be 502 for tcp/ip modbus SERVER_UNIT_ID = 100 #slave id is 100 for schneider powerlogic ion 7650 #default value for ionmeter #subnet mask= 255.240.0.0 #gateway= 0.0.0.0 #Required Registers to be read :- #Va= 40166 2 registers ie. c.read_input_registers(40166,2) #power kw a = 40198 2 registers #kVAR a= 40208 2 registers #kVA a= 40218 2 registers #frequency = 40159 1 register #Ia= 40150 1 register #this function reads the float value for address and number of bits (not required) #def read_float( address, number=1): # reg_l = c.read_holding_registers(address, number ) #can change to read_input_registers just to check # if reg_l: # return [utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)] # else: # return None c = ModbusClient() c.host(SERVER_HOST) c.port(SERVER_PORT) c.unit_id(SERVER_UNIT_ID) #default slave id for schneider is 100 if not c.is_open(): if not c.open(): print("cannot connect ....") if c.is_open(): #read_holding_registers has an offset of 4000 to begin with while True: voltage_a=c.read_holding_registers(166,1)#list output for integer take voltage_a[0] #voltage_a=voltage_a[0] #print voltage_a current_a=c.read_holding_registers(150,1) #current_a=current_a[0] #print current_a real_power_a=c.read_holding_registers(208,1) #real_power_a=real_power_a[0] #print real_power_a reactive_power_a=c.read_holding_registers(218,1) #reactive_power_a=reactive_power_a[0] #print reactive_power_a apparent_power_a=c.read_holding_registers(218,1) #apparent_power_a=apparent_power_a[0] #print apparent_power_a freq=c.read_holding_registers(159,1) freq=freq[0]/10 #print freq np.array(voltage_a,dtype=float) np.array(current_a,dtype=float) np.array(real_power_a,dtype=float) np.array(reactive_power_a,dtype=float) np.array(apparent_power_a,dtype=float) np.array(freq,dtype=float) data = { "voltage_reading" : voltage_a, "current_reading" : current_a, "real_power_rating" : real_power_a, "reactive_power_rating" : reactive_power_a, "apparent_power_rating" : apparent_power_a, "frequency_reading" : freq } print (data) return data
from pyModbusTCP.client import ModbusClient import time # TCP auto connect on first modbus request c = ModbusClient() c.host("192.168.0.112") c.port(502) c.open() _15minutes = 10 * 60 print("EE") # c.write_single_coil(0,0) # relay0 # c.write_single_coil(1,0) # relay1 # c.write_single_coil(2,0) # relay2 #off all """ print("0") c.write_single_coil(1,1) # relay1 c.write_single_coil(2,1) # relay2 time.sleep(60) """ # # 001 # print("1") # c.write_single_coil(0,0) # relay0 # c.write_single_coil(1,0) # relay1 # c.write_single_coil(2,1) # relay2 # time.sleep(_15minutes) # # 010
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)))
#c.debug(True) # Register Addresses addr = [10, 11, 12, 13, 14, 15] # Unused Register Addresses toggle = [1, 2, 3, 4, 5, 6] # Register Values for writing ... hosts = [SERVER_HOST1, SERVER_HOST2] while True: # print("Enter Port Number ( 0 : MASTER-1 ---- 1 : MASTER2 )") HOST = int( input("Enter Port Number (MASTER-1 : 1 ***** MASTER-2 : 2 ) : ")) if (HOST == 1): print("MASTER - 1 ( IP : {0} ) is choosen.".format(SERVER_HOST1)) SERVER_HOST = SERVER_HOST1 c.host(SERVER_HOST) c.port(SERVER_PORT) if not c.is_open(): if not c.open(): print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT)) # if open() is ok, write coils (modbus function 0x01) if c.is_open(): # write 4 bits in modbus address 0 to 3 addr = 10 toggle = 22 is_ok = c.write_single_register(addr, toggle) if is_ok: print("Writint register to " + str(addr) + " : " + str(toggle)) else: print("Unable to write " + str(addr) + " : " + str(toggle))
if __name__ == "__main__": host = input("\nPlease enter IP address [127.0.0.1]: ") port = input("Please enter port [502]: ") if not host: host = "172.16.143.146" if not port: port = 502 c = ModbusClient(timeout=5) c.host(host) c.port(port) for attempt in range(3): print("\nTrying to connect to " + host + ":" + str(port) + "... Attempt " + str(attempt+1)) if c.open(): print("\nSuccessful Connection") failedconnection = False time.sleep(0.5) choice = "" while choice != "q": choice = input("\nPress \n[r] to Read \n[w] to Write \n[q] to Quit: ") if choice == "r": print("\nChose Read") read_regs() elif choice == "w": print("\nChose Write")