def discover(self,address,model,token=None):
     retry=5
     device_list = list()
     try:
         device_list = list()
         ip=address                #"38.68.237.248"
         _socket = None
         while retry>0:
             #print retry
             try:
                 _socket = socket.create_connection((ip, 502), _Timeout)
                 break
             except socket.error:
                 if _socket:
                     _socket.close()
                 _socket = None
                 retry=retry-1
         if _socket is not None:
             _socket.close()
             client = connection(ip, port=502)
             client.connect()
             possible_slave_ids = [1]
             for slave_id in possible_slave_ids:
                 result3 = client.read_holding_registers(40003, 1, unit=slave_id)
                 if result3 is not None:
                     device_list.append({'address': ip + ':' + str(slave_id), 'mac': "23342",
                                      'model':model, 'vendor': "Fronius"})
                 print device_list
         return device_list
     except Exception as e:
         print e
         return device_list
Esempio n. 2
0
    def discover(self):
        retry=2

        try:
            device_list = list()
            ip="78.188.64.34"
            _socket = None
            while retry>0:
                try:
                    _socket = socket.create_connection((ip, 502), _Timeout)
                    break
                except socket.error:
                    if _socket:
                        _socket.close()
                    _socket = None
                    retry=retry-1
            if _socket is not None:
                _socket.close()
                slave_id = 1
                client = connection(ip, port=502)
                client.connect()
                result = client.read_device_info(slave_id, object_id=0x01)
                if result is None:
                    result = client.read_device_info(slave_id, object_id=0x00)
                deviceInfo=result.information
                mac = deviceInfo[1]
                model=deviceInfo[4]
                vendor=deviceInfo[0]
                device_list.append({'address': ip + ':' + str(slave_id), 'mac': mac,
                                    'model':model, 'vendor': vendor})
                print device_list
                return device_list
        except Exception as e:
            print e
            return device_list
    def getData(self,name):
        try:
            device_data = list()
            try:
                client = connection(self.address, port=502)
                return_data=dict()
                client.connect()
                config_path = os.path.dirname(os.path.abspath(__file__))
                config_path = config_path + "/Modbusdata/"+ name+".csv"
                with open(os.path.join(config_path), 'rU') as infile:
                    reader = csv.DictReader(infile)
                    data = {}
                    for row in reader:
                        for header, value in row.items():
                            try:
                                data[header].append(value)
                            except KeyError:
                                data[header] = [value]
                device_count = data["Type"]
                device_map = self.duplicates_indices(device_count)
                for device, values in device_map.iteritems():
                    if device=="acvalues":
                        ac_data=self.collectdata(client,data,values,40071,40)
                       # if(ac_data["power_ac"]>3*ac_data["voltage_ac"]*ac_data["current_ac"]):
                            #constant=float(ac_data["power_ac"])/ac_data["appar_power"]
                            #ac_data["power_dc"] = round(ac_data["power_dc"]/10, 2)
                            #ac_data["appar_power"]=round(ac_data["voltage_ac"]*ac_data["current_ac"],2)
                           # ac_data["power_ac"] = round(ac_data["voltage_ac"] * ac_data["current_ac"]*constant,2)
                        device_data.append(ac_data)
                    if device == "dcvalues":
                        dc_data = self.collectdata(client, data, values, 40272, 9)
                        device_data.append(dc_data)
                    if device == "configvalues":
                        config_data = self.collectdata(client, data, values, 40232, 18)
                        device_data.append(config_data)
            except Exception as e:
                print e

            getweatherdata=self.getweatherdata()
            device_data.append(getweatherdata)
            for d in device_data:
                for k, v in d.iteritems():
                    return_data[k]=v
           # return_data["voltage_dc"]=round(float(return_data["power_dc"])/return_data["current_dc"],2)
            if return_data["power_dc"]!=0 and return_data['Power_incident']!=0:
                return_data["efficiency_inverter"]=round(100*float(return_data["power_ac"])/return_data["power_dc"],2)
                return_data['efficiency_solar'] = float('%.2f' % ((return_data['power_dc'] / return_data['Power_incident']) * 100))
                return_data['efficiency_total'] = float('%.2f' % ((return_data['efficiency_solar'] * return_data['efficiency_inverter']) / 100))
                if (return_data["appar_power"] > 2 * return_data["power_ac"]):
                    return_data["appar_power"]=round(float(return_data["appar_power"])/10,2)
            print return_data
            return return_data
        except Exception as e:
            print e
            client.close()
            return None
Esempio n. 4
0
    def setDeviceData(self, postmsg):
        try:
            client = connection(self.address,port=502)
            client.connect()
            if BEMOSS_ONTOLOGY.POWER_LIMIT.NAME in postmsg.keys():
                result2 = client.write_register(40236, 1, unit=self.slave_id)
                result1=client.write_register(40232,postmsg.get('power_limit')*100,unit=self.slave_id)

            if BEMOSS_ONTOLOGY.PFLIMIT.NAME in postmsg.keys():
                result3=client.write_register(40237,postmsg.get('pf_limit')*10,unit=self.slave_id)
                result4=client.write_register(40241, 1, unit=self.slave_id)
            if BEMOSS_ONTOLOGY.REACTIVE_POWER_LIMIT.NAME in postmsg.keys():
                client.write_register(40243,int((postmsg.get('set_reac'))*100),unit=self.slave_id)
                client.write_register(40249, 1, unit=self.slave_id)
            client.close()
            return True
        except Exception as e:
            raise
Esempio n. 5
0
    def getDataFromDevice(self):

        devicedata = dict()
        try:

            client = connection(self.address, port=502)
            client.connect()
            result = client.read_input_registers(0, 18, unit=self.slave_id)
            if hasattr(result, 'registers'):
                if int(result.registers[0]) == 32767:
                    devicedata["temperature"] = None
                else:
                    devicedata["temperature"] = round(
                        float(
                            self.cel2far(
                                float(int(result.registers[0])) / 100.0)), 0)
                devicedata['heat_setpoint'] = round(
                    float(self.cel2far(
                        float(int(result.registers[1])) / 100.0)), 1)
                devicedata['cool_setpoint'] = round(
                    float(self.cel2far(
                        float(int(result.registers[2])) / 100.0)), 1)
                if int(result.registers[7]) == 32767:
                    devicedata['supply_temperature'] = None
                else:
                    devicedata['supply_temperature'] = round(
                        float(
                            self.cel2far(
                                float(int(result.registers[7])) / 100.0)), 1)
                result = client.read_holding_registers(159,
                                                       2,
                                                       unit=self.slave_id)
                if (int(result.registers[0]) == 1):
                    devicedata['override'] = 'ON'
                else:
                    devicedata['override'] = 'OFF'
                devicedata['flap_position'] = int(result.registers[1])
                client.close()
            return devicedata
        except Exception as er:
            print "classAPI_vav: ERROR: Reading Modbus registers at getDeviceStatus:"
            print er
            return devicedata
Esempio n. 6
0
 def setDeviceData(self, postmsg):
     try:
         client = connection(self.address, port=502)
         client.connect()
         if BEMOSS_ONTOLOGY.HEAT_SETPOINT.NAME in postmsg.keys():
             result = client.write_register(
                 6,
                 int(
                     self.far2cel(
                         float(postmsg.get('heat_setpoint')) * 100.0)),
                 unit=self.slave_id)
         if BEMOSS_ONTOLOGY.COOL_SETPOINT.NAME in postmsg.keys():
             result2 = client.write_register(
                 6,
                 int(
                     self.far2cel(
                         float(postmsg.get('cool_setpoint')) * 100.0)),
                 unit=self.slave_id)
         if BEMOSS_ONTOLOGY.OVERRIDE.NAME in postmsg.keys():
             if postmsg.get('override') == 'ON' or postmsg.get(
                     'override') == True:
                 client.write_register(159, 1, unit=self.slave_id)
             elif postmsg.get('override') == 'OFF' or postmsg.get(
                     'override') == False:
                 client.write_register(159, 0, unit=self.slave_id)
         if BEMOSS_ONTOLOGY.FLAP.NAME in postmsg.keys():
             client.write_register(160,
                                   int(postmsg.get('flap_position')),
                                   unit=self.slave_id)
         client.close()
         return True
     except:
         try:
             client.close()
             return False
         except:
             print(
                 'Modbus TCP client was not built successfully at the beginning'
             )
             return False
Esempio n. 7
0
 def setDeviceData(
     self, postmsg
 ):  #cool_setpoint>=(heat_setpoint+deadband) where deadband is 1.8 F
     try:
         client = connection(self.address, port=502)
         client.connect()
         if BEMOSS_ONTOLOGY.HEAT_SETPOINT.NAME in postmsg.keys():
             result = client.write_register(
                 200,
                 int(
                     round(
                         self.far2cel(float(postmsg.get('heat_setpoint'))),
                         2) * 100),
                 unit=self.slave_id)
         if BEMOSS_ONTOLOGY.COOL_SETPOINT.NAME in postmsg.keys():
             result2 = client.write_register(
                 201,
                 int(
                     round(
                         self.far2cel(float(postmsg.get('cool_setpoint'))),
                         2) * 100),
                 unit=self.slave_id)
         if BEMOSS_ONTOLOGY.OVERRIDE.NAME in postmsg.keys():
             if postmsg.get('override') == 'ON' or postmsg.get(
                     'override') == True:
                 client.write_register(159, 1, unit=self.slave_id)
             elif postmsg.get('override') == 'OFF' or postmsg.get(
                     'override') == False:
                 client.write_register(159, 0, unit=self.slave_id)
         if BEMOSS_ONTOLOGY.FLAP.NAME in postmsg.keys():
             client.write_register(160,
                                   int(postmsg.get('flap_position')),
                                   unit=self.slave_id)
         client.close()
         return True
     except Exception as e:
         raise
Esempio n. 8
0
    def getDataFromDevice(self):

            try:
                Current=list()
                Voltage=list()
                client = connection(self.address, port=502)
                client.connect()
                device_data=dict()
                ratios=client.read_holding_registers(74, 5, unit=self.slave_id)
                CT=ratios.registers[0]
                if CT==0:
                    CT=5
                PT=0.1*ratios.registers[1]
                if PT==0:
                    PT=1
                Pf=ratios.registers[3]
                Powerfactor=0.001*self.getSignedNumber(Pf)
                config_path = os.path.dirname(os.path.abspath(__file__))
                config_path = config_path + "/Modbusdata/powermeter.csv"
                with open(os.path.join(config_path), 'rU') as infile:
                    reader = csv.DictReader(infile)
                    data = {}
                    for row in reader:
                        for header, value in row.items():
                            try:
                                data[header].append(value)
                            except KeyError:
                                data[header] = [value]
                Address= data["Address"]
                Address = map(int, Address)
                Currentlist=data["Current"]
                Description=data["Description"]
                Multiplier=data["Multiplier"]
                Dimension = data["Dimension"]
                Multiplier = map(float, Multiplier)
                Voltagelist=data["Potential"]
                for item in Currentlist:
                    if item=="CT":
                        item=CT
                    Current.append(item)
                    Current = map(int, Current)
                for element in Voltagelist:
                    if element=="PT":
                        element=PT
                    Voltage.append(element)
                    Voltage = map(int, Voltage)
                info=zip(Address,Current,Description,Multiplier,Voltage,Dimension)
                result = client.read_holding_registers(0, 31, unit=self.slave_id)
                for key in self.ontology().keys():
                    #for parameter in info:
                        for add,curr,descip,multi,vol,dimen in info:
                            if key==descip:
                                value=result.registers[add]
                                if dimen=="Signed Int":
                                    value=self.getSignedNumber(value)
                                device_data[descip]=float(curr*vol*multi*(int(value)))
                                break
                device_data["powerfactor"] = Powerfactor
                client.close()
                print device_data
                return device_data

            except Exception as er:
                print "classAPI_ModPowerMeter: ERROR: Reading Modbus registers at getDeviceStatus:"
                print er
                raise
Esempio n. 9
0
 def setDeviceData(
     self, postmsg
 ):  #cool_setpoint>=(heat_setpoint+deadband) where deadband is 1.8 F
     client = None
     try:
         client = connection(self.address, port=502)
         client.connect()
         if BEMOSS_ONTOLOGY.HEAT_SETPOINT.NAME in postmsg.keys():
             client.write_register(111, 1, unit=self.slave_id)
             client.write_register(
                 187,
                 int(
                     self.far2cel(float(postmsg.get('heat_setpoint'))) *
                     100.0),
                 unit=self.slave_id)
         if BEMOSS_ONTOLOGY.COOL_SETPOINT.NAME in postmsg.keys():
             client.write_register(
                 188,
                 int(
                     self.far2cel(float(postmsg.get('cool_setpoint'))) *
                     100.0),
                 unit=self.slave_id)
         if BEMOSS_ONTOLOGY.OUTSIDE_DAMPER.NAME in postmsg.keys():
             client.write_register(111, 1, unit=self.slave_id)
             client.write_register(
                 274,
                 int(postmsg.get('outside_damper_position')),
                 unit=self.slave_id)
         if BEMOSS_ONTOLOGY.DAMPER.NAME in postmsg.keys():
             client.write_register(
                 275,
                 int(postmsg.get('bypass_damper_position')),
                 unit=self.slave_id)
         if BEMOSS_ONTOLOGY.FAN_STATE.NAME in postmsg.keys():
             if postmsg.get('fan_state') == 'ON' or postmsg.get(
                     'fan_state') == True:
                 client.write_register(130, 2, unit=self.slave_id)
             elif postmsg.get('fan_state') == 'OFF' or postmsg.get(
                     'fan_state') == False:
                 client.write_register(130, 1, unit=self.slave_id)
         if BEMOSS_ONTOLOGY.COOLING_STATUS.NAME in postmsg.keys():
             client.write_register(111, 1, unit=self.slave_id)
             if postmsg.get('cooling_status') == 'ON':
                 client.write_registers(124, [100, 1, 1, 1],
                                        unit=self.slave_id)
             elif postmsg.get('cooling_status') == 'OFF':
                 client.write_registers(124, [0, 1, 1, 1],
                                        unit=self.slave_id)
         if BEMOSS_ONTOLOGY.COOLING.NAME in postmsg.keys():
             if postmsg.get('cooling_mode') == 'None':
                 client.write_register(10, 0, unit=self.slave_id)
             elif postmsg.get('cooling_mode') == 'STG1':
                 client.write_register(10, 1, unit=self.slave_id)
             elif postmsg.get('cooling_mode') == 'STG2':
                 client.write_register(10, 2, unit=self.slave_id)
             elif postmsg.get('cooling_mode') == 'STG3':
                 client.write_register(10, 3, unit=self.slave_id)
             elif postmsg.get('cooling_mode') == 'STG4':
                 client.write_register(10, 4, unit=self.slave_id)
         if BEMOSS_ONTOLOGY.HEATING.NAME in postmsg.keys():
             client.write_register(129,
                                   int(postmsg.get('heating')),
                                   unit=self.slave_id)
         client.close()
         return True
     except:
         raise
Esempio n. 10
0
    def getDataFromDevice(self):

        try:
            devicedata = dict()
            client = connection(self.address, port=502)
            client.connect()
            result = client.read_input_registers(0, 26, unit=self.slave_id)
            if hasattr(result, 'registers'):
                if int(result.registers[18]) == 32767:
                    devicedata['temperature'] = None
                else:
                    devicedata['temperature'] = round((self.cel2far(
                        float(int(result.registers[18])) / 100.0)), 0)
                devicedata['heat_setpoint'] = round(
                    (self.cel2far(float(int(result.registers[19])) / 100.0)),
                    0)
                devicedata['cool_setpoint'] = round(
                    (self.cel2far(float(int(result.registers[20])) / 100.0)),
                    0)
                if int(result.registers[0]) == 32767:
                    devicedata['supply_temperature'] = None
                else:
                    devicedata['supply_temperature'] = round(
                        float(
                            self.cel2far(
                                float(int(result.registers[0])) / 100.0)), 1)
                if int(result.registers[1]) == 32767:
                    devicedata['return_temperature'] = None
                else:
                    devicedata['return_temperature'] = round(
                        float(
                            self.cel2far(
                                float(int(result.registers[1])) / 100.0)), 1)
                if int(result.registers[2]) == 32767:
                    devicedata['outside_temperature'] = None
                else:
                    devicedata['outside_temperature'] = round(
                        float(
                            self.cel2far(
                                float(int(result.registers[2])) / 100.0)), 1)
                devicedata['pressure'] = float(int(
                    result.registers[22])) / 100.0
                devicedata['outside_damper_position'] = int(
                    result.registers[17])
                devicedata['bypass_damper_position'] = int(
                    result.registers[25])
                cool1 = int(result.registers[4])
                cool2 = int(result.registers[12])
                cool3 = int(result.registers[13])
                cool4 = int(result.registers[14])
                if (int(result.registers[15]) == 1):
                    devicedata['fan_state'] = 'ON'
                else:
                    devicedata['fan_state'] = 'OFF'
                result = client.read_holding_registers(129,
                                                       1,
                                                       unit=self.slave_id)
                if int(result.registers[0]) > 100:
                    devicedata['heating'] = 0
                else:
                    devicedata['heating'] = int(result.registers[0])
                result = client.read_holding_registers(10,
                                                       1,
                                                       unit=self.slave_id)
                if int(result.registers[0]) == 0:
                    devicedata['cooling_mode'] = 'None'
                    devicedata['cooling_status'] = 'OFF'
                elif int(result.registers[0]) == 1:
                    devicedata['cooling_mode'] = 'STG1'
                    if cool1 == 0:
                        devicedata['cooling_status'] = 'OFF'
                    else:
                        devicedata['cooling_status'] = 'ON'
                elif int(result.registers[0]) == 2:
                    devicedata['cooling_mode'] = 'STG2'
                    if cool2 == 0:
                        devicedata['cooling_status'] = 'OFF'
                    else:
                        devicedata['cooling_status'] = 'ON'
                elif int(result.registers[0]) == 3:
                    devicedata['cooling_mode'] = 'STG3'
                    if cool3 == 0:
                        devicedata['cooling_status'] = 'OFF'
                    else:
                        devicedata['cooling_status'] = 'ON'
                elif int(result.registers[0]) == 4:
                    devicedata['cooling_mode'] = 'STG4'
                    if cool4 == 0:
                        devicedata['cooling_status'] = 'OFF'
                    else:
                        devicedata['cooling_status'] = 'ON'

                client.close()
            return devicedata
        except Exception as er:
            print "classAPI_rtu: ERROR: Reading Modbus registers at getDeviceStatus:"
            print er
            raise
Esempio n. 11
0
    def getDeviceStatusJson(self, _response1, _response2):
        # Use the json module to load the string data into a dictionary
        device_data = dict()

        conv_dict = {'UDC': 'Vdc', 'IDC': 'Idc', 'UAC': 'Vac', 'IAC': 'Iac', 'PAC': 'Pac',
                     '2': 'Irradiance_array', '1': 'Temp_ambient', '0': 'Temp_module',
                     '4': 'Wind_velocity', 'TOTAL_ENERGY': 'Energy_total', 'DAY_ENERGY': 'Energy_day'}

        _response1.update(_response2)
        for parameter in _response1.keys():
            if parameter in conv_dict.keys():
                device_data[conv_dict[parameter]] = float(_response1[parameter]['Value'])

        for var in ['Vdc','Vac','Iac','Idc','Irradiance_array']:
            if var not in device_data:
                device_data[var] = 0



        device_data['Energy_total'] = float('%.2f' % (device_data['Energy_total'] / 1000000.0))
        # emission factors used: 7.03 × 10-4 metric tons CO2 / kWh
        # https://www.epa.gov/energy/ghg-equivalencies-calculator-calculations-and-references
        device_data['CO2_saved'] = float('%.2f' % (device_data['Energy_total'] * 0.703 * 2204.62))
        device_data['Energy_day'] = float('%.2f' % (device_data['Energy_day'] / 1000.0))
        device_data['Power_incident'] = float('%.2f' % (device_data['Irradiance_array'] * self.get_variable('Area_array')))

        device_data['Pdc'] = float('%.2f' % (device_data['Vdc'] * device_data['Idc']))
        if device_data['Power_incident'] <= 0.1:
            device_data['Efficiency_solar'] = 0.0
            device_data['Efficiency_inverter'] = 0.0
            device_data['Efficiency_total'] = 0.0
        else:
            device_data['Efficiency_solar'] = float('%.2f' % ((device_data['Pdc'] / device_data['Power_incident']) * 100))
            if device_data['Pdc'] <= 0.1:
                device_data['Efficiency_inverter'] = 0.0
            else:
                device_data['Efficiency_inverter'] = float('%.2f' % ((device_data['Pac'] / device_data['Pdc']) * 100))
                device_data['Efficiency_total'] = float('%.2f' % ((device_data['Efficiency_solar'] * device_data['Efficiency_inverter']) / 100))
        client = connection(self.address, port=502)
        name = "inverter"
        return_data = dict()
        client.connect()
        if not hasattr(self,"data"):
            config_path = os.path.dirname(os.path.abspath(__file__))
            config_path = config_path + "/Modbusdata/" + name + ".csv"
            with open(os.path.join(config_path), 'rU') as infile:
                reader = csv.DictReader(infile)
                data = {}
                for row in reader:
                    for header, value in row.items():
                        try:
                            data[header].append(value)
                        except KeyError:
                            data[header] = [value]
            self.data=data
        device_count = self.data["Type"]
        device_map = self.duplicates_indices(device_count)
        for device, values in device_map.iteritems():

            if device == "configvalues":
                config_data = self.collectdata(client, values, 40232, 18)
                for k, v in config_data.iteritems():
                    device_data[k]=v

        #print device_data
        return device_data