Example #1
0
class siemens():
    def conPLC(IP):
        siemens = SiemensS7Net(SiemensPLCS.S300, IP)
        if siemens.ConnectServer().IsSuccess == True:
            PLC = siemens
        elif siemens.ConnectServer().IsSuccess == False:
            PLC = "connect failed"
        return PLC

    # 以下是读取PLC数据的函数
    def printReadResult(result):
        if result.IsSuccess:
            print(result.Content)
        else:
            print("failed   " + result.Message)

    # 以下是写PLC的程序
    def printWriteResult(result):
        if result.IsSuccess:
            print("success")
        else:
            print("falied  " + result.Message)

    if __name__ == "__main__":
        siemens = SiemensS7Net(SiemensPLCS.S300, "192.168.1.21")
        if siemens.ConnectServer().IsSuccess == False:
            print("与PLC连接失败。")
        else:
            # bool read write test
            # siemens.WriteBool("M80.6", True)
            printReadResult(siemens.ReadBool("Q4.6"))
Example #2
0
 def conPLC(IP):
     siemens = SiemensS7Net(SiemensPLCS.S300, IP)
     if siemens.ConnectServer().IsSuccess == True:
         PLC = siemens
     elif siemens.ConnectServer().IsSuccess == False:
         PLC = "connect failed"
     return PLC
Example #3
0
 def plc_reset(self, dic_plc_reset={}):
     print("进入plc_reset")
     print('dic_plc_reset:', dic_plc_reset)
     plc_reset_count = len(dic_plc_reset)
     if plc_reset_count > 0:  # 若存在需要清零的PLC
         for key, value in dic_plc_reset.items():
             siemens = SiemensS7Net(SiemensPLCS.S200Smart, value)  # 创建PLC实例
             print("要清零的PLC的IP:", value)
             if siemens.ConnectServer().IsSuccess:  # 若连接成功
                 while not siemens.ReadBool(
                         "M0.0").Content:  # 给M0.0赋值为True,直到成功
                     siemens.WriteBool("M0.0", True)  # 通知PLC清零
                     sleep(2)
                 while siemens.ReadBool(
                         "M0.0").Content:  # 如果置零信号成功发送,给M0.0赋值为False,直到成功
                     output = siemens.ReadInt16("DB1.10").Content
                     if output < 10:  # 如果发送清零信号后,PLC数据清零(这里数据小于10就认为清零成功)
                         print("清零成功")
                         siemens.WriteBool("M0.0", False)
                         sleep(2)
                     else:
                         print("%sPLC数据未清零,当前数值%s" % (value, output))
                         logging.info("%sPLC数据未清零,当前数值%s" % (value, output))
                         sleep(5)
                 siemens.ConnectClose()  # 关闭PLC连接
             else:  # 建立PLC长连接失败,发送邮件至相关人员
                 self.plc_connect_failed(value)
     else:
         pass
Example #4
0
 def connect_test(self):
     self.Ui_MainWindow.label_status.setStyleSheet(
         "background-color: rgb(255, 255, 127);")
     self.Ui_MainWindow.label_status.setText('正在连接PLC...')
     QApplication.processEvents()
     # 创建PLC实例
     self._thread.siemens = SiemensS7Net(SiemensPLCS.S200Smart, self.IP)
     if self._thread.siemens.ConnectServer().IsSuccess:  # 连接成功
         self.Ui_MainWindow.label_status.setText('PLC连接成功!')
         self._thread.connect_to_plc = True
     else:  # 若连接失败
         self._thread.connect_to_plc = False
         self.Ui_MainWindow.label_status.setStyleSheet(
             "background-color: rgb(255, 0, 0);")
         self.Ui_MainWindow.label_status.setText('PLC连接失败!')
     QApplication.processEvents()
Example #5
0
    def __init__(self):
        super(MyThread, self).__init__()
        self.working = True  # 工作状态标志量
        self.pause = False  # 刻字之后暂停

        self.conf = Config()
        self.IP = self.conf.read_config('PLC', 'IP')
        # 零件放到位,刻字延迟时间
        self.delay = int(self.conf.read_config('laser', 'delay'))

        # 创建PLC实例
        self.siemens = SiemensS7Net(SiemensPLCS.S200Smart, self.IP)
        if self.siemens.ConnectServer().IsSuccess:  # 连接成功
            self.connect_to_plc = True
        else:
            self.connect_to_plc = False
Example #6
0
    def data_collection(self, dic_id_ip={}):
        print("进入data_collection")
        print('dic_id_ip=%s' % dic_id_ip)
        values = []  # 存储连接失败的PLC的ip
        dic_to_database = {
        }  # 存储需要采集的项目的数据,准备放入数据库。格式--key:value = andon_mps.id:plc的数据
        for key, value in dic_id_ip.items():
            siemens = SiemensS7Net(SiemensPLCS.S200Smart, value)
            # 建立PLC长连接
            if siemens.ConnectServer(
            ).IsSuccess:  # 连接成功,读取PLC的当前计数VW10, 并存入dic_to_database
                # sql = "SELECT mps_info_id FROM andon_history WHERE mps_info_id=%s limit 1" % key  # 查询该key(mps_info_id)之前是否有记录
                # rows = self.select_query(sql)
                dic_to_database[key] = siemens.ReadInt16("DB1.10").Content
                siemens.ConnectClose()  # 关闭PLC连接
            else:  # 若连接失败,则发送邮件至相关人员
                values.append(value)

        if len(values) > 0:
            self.plc_connect_failed(values)
        return dic_to_database
        print('dic_to_database:', dic_to_database)
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
'''
警告:以下代码只能在测试PLC中运行,禁止使用生产现场的PLC来测试,否则,后果自负
Warning: The following code can only be run in the Test plc, prohibit the use of the production site PLC to test, otherwise, the consequences
'''
from HslCommunication import SiemensS7Net
from HslCommunication import SiemensPLCS
from HslCommunication import SoftBasic

def printReadResult(result):
    if result.IsSuccess:
    	print(result.Content)
    else:
    	print("failed   "+result.Message)
def printWriteResult(result):
    if result.IsSuccess:
        print("success")
    else:
        print("falied  " + result.Message)

if __name__ == "__main__":
    siemens = SiemensS7Net(SiemensPLCS.S1200, "192.168.8.12")
    if siemens.ConnectServer().IsSuccess == False:
        print("connect falied")
    else:
        # bool read write test
        read = siemens.ReadBool("M100.0")
        printReadResult(read)
Example #8
0
###################################################
from HslCommunication import SiemensS7Net
from HslCommunication import SiemensPLCS
import time

siemens = SiemensS7Net(SiemensPLCS.S200Smart, "192.168.2.1")

if siemens.ConnectServer().IsSuccess == True:
    print('')
    print('连接成功 !')
    print('')
    #print ('请按启动')
else:
    print('')
    print('连接失败 !')
    print('')
    exit()
###################################################

a = 0

while 1:
    a = 0
    #红色
    siemens.WriteBool("Q0.2", True)
    time.sleep(0.1)
    siemens.WriteBool("Q0.2", False)
    time.sleep(0.1)
    siemens.WriteBool("Q0.5", True)
    time.sleep(0.1)
    siemens.WriteBool("Q0.5", False)
Example #9
0
    def testAll(self):
        # 下面是单元测试
        plc = SiemensS7Net(SiemensPLCS.S1200, "192.168.8.12")
        if plc.ConnectServer().IsSuccess == False:
            print("无法连接PLC,将跳过单元测试。等待网络正常时,再进行测试")
            return

        # 开始单元测试,从bool类型开始测试
        address = "M200.3"
        self.assertTrue(plc.WriteBool(address, True).IsSuccess)
        self.assertTrue(plc.ReadBool(address).Content == True)

        address = "M300"
        # short类型
        self.assertTrue(plc.WriteInt16(address, 12345).IsSuccess)
        self.assertTrue(plc.ReadInt16(address).Content == 12345)
        shortTmp = [123, 423, -124, 5313, 2361]
        self.assertTrue(plc.WriteInt16(address, shortTmp).IsSuccess)
        readShort = plc.ReadInt16(address, len(shortTmp)).Content
        for i in range(len(readShort)):
            self.assertTrue(readShort[i] == shortTmp[i])

        # ushort类型
        self.assertTrue(plc.WriteUInt16(address, 51234).IsSuccess)
        self.assertTrue(plc.ReadUInt16(address).Content == 51234)
        ushortTmp = [5, 231, 12354, 5313, 12352]
        self.assertTrue(plc.WriteUInt16(address, ushortTmp).IsSuccess)
        readUShort = plc.ReadUInt16(address, len(ushortTmp)).Content
        for i in range(len(readUShort)):
            self.assertTrue(readUShort[i] == ushortTmp[i])

        # int类型
        self.assertTrue(plc.WriteInt32(address, 12342323).IsSuccess)
        self.assertTrue(plc.ReadInt32(address).Content == 12342323)
        intTmp = [123812512, 123534, 976124, -1286742]
        self.assertTrue(plc.WriteInt32(address, intTmp).IsSuccess)
        readint = plc.ReadInt32(address, len(intTmp)).Content
        for i in range(len(intTmp)):
            self.assertTrue(readint[i] == intTmp[i])

        # uint类型
        self.assertTrue(plc.WriteUInt32(address, 416123237).IsSuccess)
        self.assertTrue(plc.ReadUInt32(address).Content == 416123237)
        uintTmp = [81623123, 91712749, 91273123, 123, 21242, 5324]
        self.assertTrue(plc.WriteUInt32(address, uintTmp).IsSuccess)
        readuint = plc.ReadUInt32(address, len(uintTmp)).Content
        for i in range(len(uintTmp)):
            self.assertTrue(readuint[i] == uintTmp[i])

        # float类型
        self.assertTrue(plc.WriteFloat(address, 123.45).IsSuccess)
        self.assertTrue(round(plc.ReadFloat(address).Content, 2) == 123.45)
        floatTmp = [123, 5343, 1.45, 563.3, 586.2]
        self.assertTrue(plc.WriteFloat(address, floatTmp).IsSuccess)
        readFloat = plc.ReadFloat(address, len(floatTmp)).Content
        for i in range(len(floatTmp)):
            self.assertTrue(floatTmp[i] == round(readFloat[i], 2))

        # double类型
        self.assertTrue(plc.WriteDouble(address, 1234.5434).IsSuccess)
        self.assertTrue(plc.ReadDouble(address).Content == 1234.5434)
        doubleTmp = [1.4213, 1223, 452.5342, 231.3443]
        self.assertTrue(plc.WriteDouble(address, doubleTmp).IsSuccess)
        readDouble = plc.ReadDouble(address, len(doubleTmp)).Content
        for i in range(len(doubleTmp)):
            self.assertTrue(readDouble[i] == doubleTmp[i])

        # long类型
        self.assertTrue(plc.WriteInt64(address, 123617231235123).IsSuccess)
        self.assertTrue(plc.ReadInt64(address).Content == 123617231235123)
        longTmp = [12312313123, 1234, 412323812368, 1237182361238123]
        self.assertTrue(plc.WriteInt64(address, longTmp).IsSuccess)
        readLong = plc.ReadInt64(address, len(longTmp)).Content
        for i in range(len(longTmp)):
            self.assertTrue(readLong[i] == longTmp[i])

        # ulong类型
        self.assertTrue(plc.WriteUInt64(address, 1283823681236123).IsSuccess)
        self.assertTrue(plc.ReadUInt64(address).Content == 1283823681236123)
        ulongTmp = [21316, 1231239127323, 1238612361283123]
        self.assertTrue(plc.WriteUInt64(address, ulongTmp).IsSuccess)
        readULong = plc.ReadUInt64(address, len(ulongTmp)).Content
        for i in range(len(ulongTmp)):
            self.assertTrue(readULong[i] == ulongTmp[i])

        # string类型
        self.assertTrue(plc.WriteString(address, "123123").IsSuccess)
        self.assertTrue(plc.ReadString(address, 6).Content == "123123")

        # byte类型
        byteTmp = bytearray([0x4F, 0x12, 0x72, 0xA7, 0x54, 0xB8])
        self.assertTrue(plc.Write(address, byteTmp).IsSuccess)
        self.assertTrue(
            SoftBasic.IsTwoBytesAllEquel(
                plc.Read(address, 6).Content, byteTmp))
Example #10
0
def read_PLC(dev):
    global dict
    plc = dict[dev]["inf"]["plc"]
    ip = dict[dev]["inf"]["ip"]
    port = dict[dev]["inf"]["port"]
    p = 0
    if plc == "300":
        p = SiemensPLCS.S300
    if plc == "400":
        p = SiemensPLCS.S400
    if plc == "1200":
        p = SiemensPLCS.S1200
    if plc == "1500":
        p = SiemensPLCS.S1500
    if plc.lower() == "200smart":
        p = SiemensPLCS.S200Smart

    siemens = SiemensS7Net(p, ip)
    siemens.port = int(port)

    if siemens.ConnectServer().IsSuccess == True:
        read = {}
        for db, AB in dict[dev]["block"].items():
            # print(db)
            # print(AB)
            if (db == "M") or (db == "I"):
                read[db] = (siemens.Read(db + str(AB["A"]),
                                         int(AB["B"] - AB["A"] + 1)))
                # print(db)
            else:
                read[db] = (siemens.Read(db + "." + str(AB["A"]),
                                         int(AB["B"] - AB["A"] + 1)))
            # print(db)
        s = 0
        for i, k in read.items():
            if k.IsSuccess != True:
                s = 1
        if s == 0:
            for name, k in dict[dev]["content"].items():
                # print(name)
                # print(k)
                typ = k["typ"]
                ard = k["ard"]
                block = k["block"]
                # print(typ)
                # print(block)
                na = re.findall(
                    r"\d+",
                    ard,
                )  # 搜索DB22.33.7中的22、33组成数组["22","33","7"]
                if "M" in ard:
                    s = int(na[0]) - int(dict[dev]["block"]["M"]["A"])
                if "DB" in ard:
                    s = int(na[1]) - int(dict[dev]["block"][block]["A"])
                if typ == "REAL":
                    # print(s)
                    dict[dev]["content"][name][
                        "value"] = siemens.byteTransform.TransSingle(
                            read[block].Content, s)
                if typ == "INT":
                    # print(s)
                    dict[dev]["content"][name][
                        "value"] = siemens.byteTransform.TransInt16(
                            read[block].Content, s)
                if typ == "DINT":
                    # print(s)
                    dict[dev]["content"][name][
                        "value"] = siemens.byteTransform.TransInt32(
                            read[block].Content, s)
                if typ == "BOOL":
                    # pass
                    if "M" in ard:
                        s1 = int(na[0]) - int(dict[dev]["block"]["M"]["A"])
                        s2 = int(na[1])
                        # print(s1, s2)
                        dict[dev]["content"][name]["value"] = \
                            siemens.byteTransform.TransBoolArray(read[block].Content, s1, 1)[s2]
                    if "I" in ard:
                        s1 = int(na[0]) - int(dict[dev]["block"]["I"]["A"])
                        s2 = int(na[1])
                        # print(s1, s2)
                        dict[dev]["content"][name]["value"] = \
                            siemens.byteTransform.TransBoolArray(read[block].Content, s1, 1)[s2]
                    if "DB" in ard:
                        s1 = int(na[1]) - int(dict[dev]["block"][block]["A"])
                        s2 = int(na[2])
                        # print(s1, s2)
                        dict[dev]["content"][name]["value"] = \
                            siemens.byteTransform.TransBoolArray(read[block].Content, s1, 1)[s2]
                dict[dev]["content"][name]["qua"] = 1
            dict[dev]["inf"]["t"] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                  time.localtime())
            dict[dev]["inf"]["Read_qua"] = 1
            dict[dev]["inf"]["Rec_qua"] = 1
        else:
            for name, k in dict[dev]["content"].items():
                dict[dev]["content"][name]["value"] = "null"
                dict[dev]["content"][name]["qua"] = 0
    else:
        for name, k in dict[dev]["content"].items():
            dict[dev]["content"][name]["value"] = "null"
            dict[dev]["content"][name]["qua"] = 0
        dict[dev]["inf"]["Read_qua"] = 0
        dict[dev]["inf"]["Rec_qua"] = 0
Example #11
0
import pymysql
import time
import threading
from HslCommunication import SiemensS7Net
from HslCommunication import SiemensPLCS
import os

siemens = SiemensS7Net(SiemensPLCS.S1500, "10.0.0.49")
print(siemens.ConnectServer().IsSuccess)
Example #12
0
def printReadResult(result, addr):
    if result.IsSuccess:
        print("success[" + addr + "]   " + str(result.Content))
    else:
        print("failed[" + addr + "]   " + result.Message)


def printWriteResult(result, addr):
    if result.IsSuccess:
        print("success[" + addr + "]")
    else:
        print("falied[" + addr + "]  " + result.Message)


if __name__ == "__main__":
    siemens = SiemensS7Net(SiemensPLCS.S1200, "127.0.0.1")
    if siemens.ConnectServer().IsSuccess == False:
        print("connect falied")
    else:
        # bool read write test
        siemens.WriteBool("M80.6", True)
        printReadResult(siemens.ReadBool("M80.6"), "M80.6")

        # byte read write test
        siemens.WriteByte("M100", 58)
        printReadResult(siemens.ReadByte("M100"), "M100")

        # int16 read write test
        siemens.WriteInt16("M102", 12358)
        printReadResult(siemens.ReadInt16("M102"), "M102")
Example #13
0
def printReadResult(result, addr):
    if result.IsSuccess:
        print("success[" + addr + "]   " + str(result.Content))
    else:
        print("failed[" + addr + "]   " + result.Message)


def printWriteResult(result, addr):
    if result.IsSuccess:
        print("success[" + addr + "]")
    else:
        print("falied[" + addr + "]  " + result.Message)


if __name__ == "__main__":
    siemens = SiemensS7Net(SiemensPLCS.S1200, "192.168.9.56")
    if siemens.ConnectServer().IsSuccess == False:
        print("connect falied")
    else:
        # bool read write test
        siemens.WriteBool("M580.6", True)
        printReadResult(siemens.ReadBool("M580.6"), "M580.6")

        # byte read write test
        siemens.WriteByte("M900", 58)
        printReadResult(siemens.ReadByte("M500"), "M500")

        # int16 read write test
        siemens.WriteInt16("M500", 12358)
        printReadResult(siemens.ReadInt16("M500"), "M500")
        """