[Tutor] how to transform the data as below?

Yeh Z ton.nakano at outlook.com
Thu Mar 17 10:11:06 EDT 2016


   Thanks for your help,

   It's my bad, I should put them to a list, not a array?
   such as:
   YY, 100, 140, 200, 110, 160?

   Firstly, I'm confused about how to convert them to string and integers?
   the raw bytes? Is it different to the bytes packing by "pack"? I want to
   read them by a human way.

   Besides, the MUC is made by my friend, we want to make an installation,
   which can send data via UDP from a sensor. Maybe, we can change some
   things in MUC? I don't know MUC totally. :( I just trying to learn Python.

   Thanks

   Yeh

   -------- Original Message --------
   Subject: Re: [Tutor] how to transform the data as below?
   From: Peter Otten <__peter__ at web.de>
   To: tutor at python.org
   CC:

     Yeh wrote:

     > Hi,
     >
     > I got messages from a MCU by using codes below:
     >
     > import socket
     > import time
     >
     > port = 8888
     > s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
     > s.bind(("",port))
     > print('waiting on port:', port)
     > while True:
     > data, addr = s.recvfrom(1024)
     > print("DATA:", data, addr)
     > time.sleep(100)
     >
     > The messages should be a head "YY" and 5 integers, (each integer is
     > transferred by 2 bytes.) but I got data below. So, how to transform
     the
     > data? and how to arrange the data to a array?
     >
     > DATA:
     > b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t\x01x\x01...
     > ('192.168.1.101', 35000)

     What you read are the raw bytes. The array module offers one way to
     convert
     bytes to integers. Unfortunately the separator byte sequence b"YY" (or
     b"XY"
     followed by b"YZ") is also that for the integer 22873:

     >>> array.array("H", b"YY")
     array('H', [22873])

     Therefore you cannot be 100% sure when you start the bytes-to-int
     conversion
     at the first occurence of b"YY". Here's an example that uses a simple
     heuristics (which may fail!) to cope with the problem

     import array, re

     def find_start(data):
         for m in re.compile(b"YY").finditer(data):
             if all(
                     data[i:i+2] == b"YY"
                     for i in range(m.start(), len(data), 12)):
                
                 return m.start()
         raise ValueError

     data = b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t...

     if __name__ == "__main__":
         start = find_start(data)
         for i in range(start, len(data)-11, 12):
             chunk = data[i:i+12]
             print(chunk, "-->", list(array.array("H", chunk[2:])))

     _______________________________________________
     Tutor maillist  -  Tutor at python.org
     To unsubscribe or change subscription options:
     [1]https://mail.python.org/mailman/listinfo/tutor

References

   Visible links
   1. https://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list