キーエンス KV5000 KV-LE21Vとラズベリーパイ
イーサネット上位通信
COM
 
resp

#KV5000上位リンク   PYTHON
import socket
 
class MySocket:
    def __init__(self, sock=None):
        print('init')
        if sock is None:
            self.sock = socket.socket(
                            socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock
    def connect(self, host, port):
       print('connect')
       try:
           self.sock.connect((host, port))
           return 0
       except socket.error:
           print('ソケットエラーです')
           return -1
    def mysend(self, msg):
        print('mysend')
        self.sock.send(msg.encode('utf-8'))
        
    def myreceive(self):
        print('myreceive')
        data=[]
        data=(self.sock.recv(1024))
        
#        print(data)
        return data
#-----------------------------------------------------
def main():
 
    host='192.168.1.4'
    port=8501
    myapp = MySocket()
    ret=myapp.connect(host,port)
#1ワードの読み出し 16ビット符号有り
    if ret==0:
        cmd='RDS '
        myapp.mysend(cmd+'DM00000.S 4'+'\r')
        ret=[]
        count=4
        ret=myapp.myreceive().decode('utf-8')
#        print(ret)
        datanum=[]
        anser=ret[0:2]
      
        if anser!='E1':
            for i in range(0,count):
                start=7*i
                end=7*i+6
                data=(int(ret[start:end],10))
                if data>=32767:
                    data=data-65536
                datanum.append(data)
                print(str(datanum[i]))
            
#1ワードの読み出し 16ビット符号無し
#    myapp.connect(host,port)
    cmd='RDS '
    myapp.mysend(cmd+'DM0000.U 4'+'\r')
    count=4
    ret=[]
    ret=myapp.myreceive().decode('utf-8')
#    print(ret)    
    datanum=[]
    anser=ret[0:2]
 
    if anser!='E1':
        for i in range(0,count):
            start=6*i
            end=6*i+5
            data=(int(ret[start:end],10))
            datanum.append(data)
            print(str(datanum[i]))
#1ワードの読み出し 32ビット符号無し
#    myapp.connect(host,port)
    cmd='RDS '
    myapp.mysend(cmd+'D0000.D 2'+'\r\n')
    count=2
    ret=[]
    ret=myapp.myreceive().decode('utf-8')
    
    datanum=[]
    anser=ret[0:2]
  
    if anser!='E1':
        for i in range(0,count):
            start=11*i
            end=11*i+10
            
            data=(int(ret[start:end],10))
            
            datanum.append(data)
            print(data)
if __name__ == '__main__':
  main()

戻る