Northland
Posts: 8
Joined: Fri May 06, 2016 6:07 am

How to use this code

Tue May 31, 2016 6:05 am

I have a solar inverter and some nice person shared his code:

Code: Select all

import urllib2
import serial, time

import sqlite3
import json
import urllib
import datetime
import calendar
import os

os_env = os.environ

APP_DIR = os.path.abspath(os.path.dirname(__file__))  # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))

#Commands with CRC cheats
QPGS = '\x51\x50\x47\x53\x30\x3f\xda\x0d'
QPIGS = '\x51\x50\x49\x47\x53\xB7\xA9\x0d' #valid?
QMCHGCR ='\x51\x4D\x43\x48\x47\x43\x52\xD8\x55\x0D' #?
QMUCHGCR='\x51\x4D\x55\x43\x48\x47\x43\x52\x26\x34\x0D' #?
QPIWS = '\x51\x50\x49\x57\x53\xB4\xDA\x0D' #valid?
POP02 = '\x50\x4F\x50\x30\x32\xE2\x0B\x0D' # set to SBU
POP00 = '\x50\x4F\x50\x30\x30\xC2\x48\x0D' #Set to UTILITY

#initialization and open the port
#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call

ser = serial.Serial()
#ser.port = "/dev/ttyUSB1"
ser.port = "com7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 2400
ser.bytesize = serial.EIGHTBITS     #number of bits per bytes
ser.parity = serial.PARITY_NONE     #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE  #number of stop bits
#ser.timeout = None                 #block read
ser.timeout = 1                     #non-block read
#ser.timeout = 2                    #timeout block read
ser.xonxoff = False                 #disable software flow control
ser.rtscts = False                  #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False                  #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2                #timeout for write


try: 
    ser.open()

except Exception, e:
    print "error open serial port: " + str(e)
    exit()
		
		
def floorTime(dt=None, roundTo=60):
    """
    Floor a datetime object to any time laps in seconds
    dt : datetime.datetime object, default now.
    """
    import datetime

    if dt is None:
        dt = datetime.datetime.now()

    dt_min = datetime.datetime(datetime.MINYEAR, 1, 1)
    dt_min = dt_min.replace(tzinfo=dt.tzinfo)

    seconds = (dt - dt_min).seconds
    rounding = seconds // roundTo * roundTo
    return dt + datetime.timedelta(0, rounding - seconds, -dt.microsecond)
  

  
def get_data():
    #get inverter data from axpert inverter
    dc_1_u = 0
    dc_1_i = 0
    ac_1_u = 0
    ac_1_p = 0
    dc_2_u = 0
    dc_2_i = 0
    ac_2_u = 0
    ac_2_p = 0
    dc_3_u = 0
    dc_3_i = 0
    ac_3_u = 0
    ac_3_p = 0
    current_power = 0
    daily_energy = 0
    total_energy = 0

	
    if ser.isOpen():
        try:
            ser.flushInput()            #flush input buffer, discarding all its contents
            ser.flushOutput()           #flush output buffer, aborting current output and discard all that is in buffer
            ser.write(QPGS)
            time.sleep(0.1)             #give the serial port sometime to receive the data
            response = ser.readline()
            nums = response.split(' ', 99)
            print nums[0], nums[1],nums[2],nums[3],nums[4],nums[5],nums[6],nums[7],nums[8],nums[9],nums[10],nums[11],nums[12],nums[13],nums[14],nums[15],nums[16],nums[17],nums[18],nums[19],nums[20],nums[21],nums[22],nums[23],nums[24],nums[25], nums[26]
            The_parallel_num = nums[0]
            Serial_number = nums[1] 
            Work_mode = nums[2] 
            Fault_code = nums[3] 
            Grid_voltage = nums[4]
            Grid_frequency = nums[5]
            AC_output_voltage = nums[6]
            AC_output_frequency = nums[7]
            AC_output_apparent_power = nums[8]
            AC_output_active_power = nums[9]
            Load_percentage = nums[10]
            Battery_voltage = nums[11]
            Battery_charging_current = nums[12]
            Battery_capacity = nums[13] 
            PV_Input_Voltage = nums[14]
            Total_charging_current = nums[15]
            Total_AC_output_apparent_power = nums[16] 
            Total_output_active_power = nums[17]
            Total_AC_output_percentage = nums[18]
            Inverter_Status = nums[19]
            Output_mode = nums[20]
            Charger_source_priority = nums[21]
            Charger_source_priority = nums[22]
            Max_charger_range = nums[23]
            Max_AC_charger_current = nums[24]
            PV_input_current_for_battery = nums[25]
            Battery_discharge_current = nums[26]
            print "--------------"
		
        except Exception, e1:
            print "error communicating...: " + str(e1)
            ser.close()
    else:
        ser.close()
        print "cannot open serial port "
	
    return[1] #just return
 

 
def main():
    while True:
        time.sleep(1)
        data = get_data()
    
        
if __name__ == '__main__':
    main()

I just bought a Pi and connected the inverter via usb. But not sure how I should use this code.
I see in the code some ports must be specified, but I dont know how to find them.

When I click run a shell window opens and says
.....File "/home/pi/serial.py", line 5, in <module>
ser = serial.Serial(
AttributeError: 'module' object has no attribute 'Serial'
>>>

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: How to use this code

Tue May 31, 2016 8:19 am

Well, I can't help you on the main question about how to use your script as I have no idea what a solar inverter is or does (although I'm sure Google can help me out there).

However, I can fix your immediate error: rename your file to something other than serial.py (and delete any serial.pyc file in your /home/pi folder. When you say "import serial" you're actually importing your own serial script rather than the python serial module which is why the line "ser = serial.Serial()" fails.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

R-A
Posts: 50
Joined: Sun Sep 11, 2016 4:59 pm
Location: Johannesburg, South Africa
Contact: Website

Re: How to use this code

Sun Sep 11, 2016 5:03 pm

Where did you get this code?
How are you connected to the serial device?
I'm using a Raspberry Pi 3 Model B with 7" LCD Touch screen and Mini USB Wireless Keyboard

R-A
Posts: 50
Joined: Sun Sep 11, 2016 4:59 pm
Location: Johannesburg, South Africa
Contact: Website

Re: How to use this code

Sun Sep 11, 2016 6:10 pm

Are you sure that is python code? where did you get it from?
I'm using a Raspberry Pi 3 Model B with 7" LCD Touch screen and Mini USB Wireless Keyboard

User avatar
kusti8
Posts: 3439
Joined: Sat Dec 21, 2013 5:29 pm
Location: USA

Re: How to use this code

Sun Sep 11, 2016 7:27 pm

R-A wrote:Are you sure that is python code? where did you get it from?
This is obviously Python and elParaguayo is right. It's because the OP script is named script.py and it's trying to import another script or itself.
There are 10 types of people: those who understand binary and those who don't.

Return to “Python”