help in python program

Good evening. I’m new in the forum and i am studying python for XBee. I see a page from Digi program but could not understand him. Could somebody explain each line? Thank you.

def parseIS(data):
if len(data) % 2 == 0:
sets, datamask, analogmask = struct.unpack(“!BHB”, data[:4])
data = data[4:]

    sets, mask = struct.unpack("!BH", data[:3])
    data = data[3:]
    datamask = mask % 512 # Move the first 9 bits into a seperate mask
    analogmask  = mask >> 9 #Move the last 7 bits into a seperate mask
retdir = {}

if datamask:
    datavals = struct.unpack("!H", data[:2])[0]
    data = data[2:]
    currentDI = 0
    while datamask:
        if datamask & 1:
            retdir["DIO%d" % currentDI] = datavals & 1
        datamask >>= 1
        datavals >>= 1
        currentDI += 1

currentAI = 0

while analogmask:
    if analogmask & 1:
        aval = struct.unpack("!H", data[:2])[0]
        data = data[2:]

        retdir["AI%d" % currentAI] = aval
    analogmask >>= 1
    currentAI += 1
return retdir
1 Like

Yoru request is a bit unreasonable (explain each line? You don’t understand what ‘currentDI = 0’ does?)

Python is intrepretive, so just run the interactive interpreter, import struct, set data = ‘\x01\x00\x02\x00\x00\x02’, then manually enter various lines, then print the result to see what happens. It might tank an hour, but you’ll develop a very good understanding.

The data I showed you to set means you only have 1 DIO value (DIO1) and it is true.

There are easier programs to learn from. This particular program is using a lot of ‘bitwise’ operations, meaning it’s doing shifts and masks to get the information it needs to process.

It also uses the struct library to pack the response in a specific order of bytes, as well as string manipulation and gathering sub strings by using the string[:] style functions.

If you’re needing a program which does the same thing as this, then your best bet is to go to the various Python resource pages and learn about strings, as well as bitwise operations in Python.

If you’re needing just any program to get the feel of Python, I woudl start by going to our web page, and looking at some of the basic “query for temperature” type scripts to get the feel of Python.

Hope that helps answer your question!

You may download a commented version of the code from the link below. Goodluck.

** I am a private developer and do not work for Digi. Please do not repost this document in another location.