Esempio n. 1
0
def broadcast():

    try:
        device_list = list()
        localaddress = list()
        ips = getIPs()
        print "found local ip as ", ips
        for ip in ips:
            str(ip)
            localaddress = ip + "/24"

        # make a device object
        this_device = LocalDeviceObject(
            objectName="BEMOSS",
            objectIdentifier=
            599,  #change if there exists a bacnet device with same identifier
            maxApduLengthAccepted=1024,
            segmentationSupported="segmentedBoth",
            vendorIdentifier=99,
        )

        # Device application
        this_application = Application(this_device, localaddress)

        request = WhoIsRequest()
        request.pduDestination = GlobalBroadcast()

        def time_out():
            time.sleep(5)
            stop()

        thread = threading.Thread(target=time_out)
        thread.start()

        this_application.request(request)
        this_application.found_address = list()
        this_application.found_deviceidentifier = list()
        run()
        #time.sleep(10)
        this_application.release = True
        this_application.update = False
        address, deviceidentifier = this_application.updator()

        todelete = list()
        for i in range(0, len(deviceidentifier)):
            if deviceidentifier[i] == 0:
                todelete.append(i)
        for i in todelete:
            del address[i], deviceidentifier[
                i]  #Deleting identified bacnet router
        Remote_address = list(set(address))  #Removing repeatition
        Identifier = list(set(deviceidentifier))  #Removing repeatition

        print "destination address list is ", Remote_address
        print "object instance of that address", Identifier

        return this_application, Remote_address, Identifier
    except Exception, e:
        _log.exception("an error has occurred: %s", e)
        return None
Esempio n. 2
0
    def request(self):
        socket.setdefaulttimeout(self.timeout)
        responses = list()
        IPs = find_own_ip.getIPs()
        for IP in IPs:
            for _ in range(self.retries):
                sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                     socket.IPPROTO_UDP)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
                sock.bind((IP, 1900))
                try:
                    sock.sendto(self.message, self.group)
                except:
                    print("[Errno 101] Network is unreachable")

                while True:
                    try:
                        raw = sock.recv(1024)
                        response = str(SSDPResponseLocation(raw))
                        if self._debug: print response
                        else: pass

                        if response not in responses:
                            responses.append(response)

                    except socket.timeout:
                        break
Esempio n. 3
0
def main(
):  # USage address, obj_type, obj_inst, prop_id--- 192.168.10.67 8 123 70 value

    arguments = sys.argv
    if (len(arguments) is not 6):
        print "Insufficient arguments please provide exactly 5 arguments with device address as 1st argument , object property as 2nd argument, property instance as 3rd argument and " \
              "property name as 4th argument and value to be written as 5th argument"
        return
    ips = getIPs()
    device_address = ips[0] + "/24"
    # make a device object
    this_device = LocalDeviceObject(
        objectName="BEMOSS-PLUS",
        objectIdentifier=int(599),
        maxApduLengthAccepted=int(1024),
        segmentationSupported="segmentedBoth",
        vendorIdentifier=int(15),
    )

    # make a simple application
    this_application = SynchronousApplication(this_device, device_address)

    _log.debug("starting build")
    address = arguments[1]
    obj_type = int(arguments[2])
    device_id = int(arguments[3])
    prop_id = int(arguments[4])  #convert to PropertyIdentifier
    value = int(arguments[5])
    result = get_iam(this_application, device_id, address)

    target_address = result.pduSource

    _log.debug('pduSource = ' + repr(result.pduSource))
    _log.debug('iAmDeviceIdentifier = ' + str(result.iAmDeviceIdentifier))
    _log.debug('maxAPDULengthAccepted = ' + str(result.maxAPDULengthAccepted))
    _log.debug('segmentationSupported = ' + str(result.segmentationSupported))
    _log.debug('vendorID = ' + str(result.vendorID))

    device_id = result.iAmDeviceIdentifier[1]
    Specific_object, Specific_property = getObjectnProperty(obj_type, prop_id)
    if Specific_object == "" or Specific_property == "":
        print "Incorrect object type or property instance"
        return
    try:

        Result = write_bacnet(this_application, target_address,
                              Specific_object, device_id, Specific_property,
                              value)
        print Result
        return
    except Exception as e:
        print "Error during reading-- ", e
        exit(1)
    return
Esempio n. 4
0
    def startListeningEvents(self, threadingLock, callback):
        def common_start(sa, sb):
            """ returns the longest common substring from the beginning of sa and sb """
            def _iter():
                for a, b in zip(sa, sb):
                    if a == b:
                        yield a
                    else:
                        return

            return ''.join(_iter())

        _address = self.get_variable('address')
        _address = _address.replace('http://', '')
        _address = _address.replace('https://', '')
        ips = getIPs()
        #if no good match, use the last ip
        myaddress = ips[-1]
        maxmatch = ''
        for ip in ips:
            tempmatch = common_start(ip, _address)
            if len(tempmatch) > len(maxmatch):
                myaddress = ip  #If bemoss machine has multiple IP, use that IP most similar to address of WEMO device
                maxmatch = tempmatch

        if self.listeningThread is None:  #if this is firt time, and no thread present
            self.port = random.randint(10000, 60000)
            self.listeningThread = threading.Thread(target=keepListening,
                                                    args=(threadingLock,
                                                          myaddress, self.port,
                                                          callback))
            self.listeningThread.start()
            time.sleep(1)

        message = {
            'CALLBACK': '<http://' + myaddress + ':' + str(self.port) + '>',
            'NT': 'upnp:event',
            'TIMEOUT': 'Second-800',
            'HOST': _address
        }
        self.reqresult = requests.request('SUBSCRIBE',
                                          self.get_variable('address') +
                                          '/upnp/event/basicevent1',
                                          headers=message)
        if self.reqresult.status_code != 200:
            print "Subscription error."
            print str(self.reqresult)
            return

        self.sid = self.reqresult.headers['sid']
        self.myaddress = myaddress
        self._address = _address
        self.callback = callback
Esempio n. 5
0
def discover(type, timeout=2, retries=1):

    group = ("239.255.255.250", 1900)
    if type == 'thermostat':
        message = "TYPE: WM-DISCOVER\r\nVERSION: 1.0\r\n\r\nservices: com.marvell.wm.system*\r\n\r\n"
    else:
        message = "\r\n".join([
            'M-SEARCH * HTTP/1.1', 'HOST: {0}:{1}', 'MAN: "ssdp:discover"',
            'ST: {st}', 'MX: 3', '', ''
        ])
        if type == 'WeMo':
            service = "upnp:rootdevice"
            message = message.format(*group, st=service)
        elif type == 'Philips':
            service = "urn:schemas-upnp-org:device:Basic:1"
            message = message.format(*group, st=service)

    socket.setdefaulttimeout(timeout)
    responses = list()
    IPs = find_own_ip.getIPs()
    for IP in IPs:
        for _ in range(retries):
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                 socket.IPPROTO_UDP)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
            sock.bind((IP, 1900))
            try:
                sock.sendto(message, group)
            except:
                print("[Errno 101] Network is unreachable")

            while True:
                try:
                    raw = sock.recv(1024)
                    response = str(SSDPResponseLocation(raw))
                    if debug: print response
                    else: pass
                    if type == "thermostat":
                        if "/sys" in response and response not in responses:
                            responses.append(response)
                    elif type == "WeMo":
                        if (':49153/setup.xml' in response or
                                ':49154/setup.xml' in response or '/setup.xml'
                                in response) and response not in responses:
                            responses.append(response)
                    elif type == "Philips":
                        if ":80/description.xml" in response and response not in responses:
                            print "response {}".format(response)
                            responses.append(response)
                except socket.timeout:
                    break
Esempio n. 6
0
def discover(type, timeout=2, retries=1):

    group = ("239.255.255.250", 1900)
    if type=='thermostat':
        message="TYPE: WM-DISCOVER\r\nVERSION: 1.0\r\n\r\nservices: com.marvell.wm.system*\r\n\r\n"
    else:
        message = "\r\n".join([
            'M-SEARCH * HTTP/1.1',
            'HOST: {0}:{1}',
            'MAN: "ssdp:discover"',
            'ST: {st}','MX: 3','',''])
        if type=='WeMo':
            service="upnp:rootdevice"
            message=message.format(*group, st=service)
        elif type=='Philips':
            service="urn:schemas-upnp-org:device:Basic:1"
            message=message.format(*group, st=service)

    socket.setdefaulttimeout(timeout)
    responses = list()
    IPs = find_own_ip.getIPs()
    for IP in IPs:
        for _ in range(retries):
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
            sock.bind((IP, 1900))
            try:
                sock.sendto(message, group)
            except:
                print("[Errno 101] Network is unreachable")

            while True:
                try:
                    raw = sock.recv(1024)
                    response = str(SSDPResponseLocation(raw))
                    if debug: print response
                    else: pass
                    if type=="thermostat":
                        if "/sys" in response and response not in responses:
                            responses.append(response)
                    elif type=="WeMo":
                        if (':49153/setup.xml' in response or ':49154/setup.xml' in response or '/setup.xml' in response) and response not in responses:
                            responses.append(response)
                    elif type=="Philips":
                        if ":80/description.xml" in response and response not in responses:
                            print "response {}".format(response)
                            responses.append(response)
                except socket.timeout:
                    break
Esempio n. 7
0
def findIP():
    """
    Reads the listen address from cassandra settings file
    :return:
    """
    try:
        casSettingsFile = open(os.path.expanduser("~")+"/workspace/bemoss_os/cassandra_settings.txt",'r')
        settingsContent = casSettingsFile.read()
        casSettingsFile.close()
        ip_address = re.search('rpc_address: *([0-9\.]*)\n',settingsContent).group(1)
    except IOError as er:
        print "No cassandra_settings file. Using current IP"
        ip_address = getIPs()[-1]

    return ip_address
Esempio n. 8
0
    def __init__(self, *args):

        ips = getIPs()
        device_address = ips[0] + "/24"
        # make a device object
        this_device = LocalDeviceObject(
            objectName="BEMOSS-PLUS",
            objectIdentifier=int(599),
            maxApduLengthAccepted=int(1024),
            segmentationSupported="segmentedBoth",
            vendorIdentifier=int(15),
        )
        # make a simple application
        SynchronousApplication._debug("__init__ %r", args)
        BIPSimpleApplication.__init__(self, *args)
        self.expect_confirmation = True
Esempio n. 9
0
    def startListeningEvents(self,threadingLock,callback):

        def common_start(sa, sb):
            """ returns the longest common substring from the beginning of sa and sb """
            def _iter():
                for a, b in zip(sa, sb):
                    if a == b:
                        yield a
                    else:
                        return

            return ''.join(_iter())

        _address = self.get_variable('address')
        _address = _address.replace('http://', '')
        _address = _address.replace('https://', '')
        ips = getIPs()
        #if no good match, use the last ip
        myaddress = ips[-1]
        maxmatch = ''
        for ip in ips:
            tempmatch = common_start(ip,_address)
            if len(tempmatch)>len(maxmatch):
                myaddress = ip #If bemoss machine has multiple IP, use that IP most similar to address of WEMO device
                maxmatch=tempmatch

        if self.listeningThread is None: #if this is firt time, and no thread present
            self.port = random.randint(10000,60000)
            self.listeningThread = threading.Thread(target=keepListening,args=(threadingLock,myaddress,self.port, callback))
            self.listeningThread.start()
            time.sleep(1)

        message = {
            'CALLBACK': '<http://'+myaddress+':'+str(self.port)+'>',
            'NT': 'upnp:event',
            'TIMEOUT': 'Second-800',
            'HOST': _address}
        self.reqresult = requests.request('SUBSCRIBE',self.get_variable('address')+'/upnp/event/basicevent1',headers=message)
        if self.reqresult.status_code != 200:
            print "Subscription error."
            print str(self.reqresult)
            return

        self.sid = self.reqresult.headers['sid']
        self.myaddress = myaddress
        self._address = _address
        self.callback = callback
Esempio n. 10
0
def findIP():
    """
    Reads the listen address from cassandra settings file
    :return:
    """
    try:
        casSettingsFile = open(
            settings.PROJECT_DIR + "/cassandra_settings.txt", 'r')
        settingsContent = casSettingsFile.read()
        casSettingsFile.close()
        ip_address = re.search('rpc_address: *([0-9\.]*)\n',
                               settingsContent).group(1)
    except IOError as er:
        print "No cassandra_settings file. Using current IP"
        ip_address = getIPs()[-1]

    return ip_address
Esempio n. 11
0
def findIP():
    """
    Reads the listen address from cassandra settings file
    :return:
    """
    try:
        casSettingsFile = open(
            os.path.expanduser("~") +
            "/workspace/bemoss_os/cassandra_settings.txt", 'r')
        settingsContent = casSettingsFile.read()
        casSettingsFile.close()
        ip_address = re.search('rpc_address: *([0-9\.]*)\n',
                               settingsContent).group(1)
    except IOError as er:
        print "No cassandra_settings file. Using current IP"
        ip_address = getIPs()[-1]

    return ip_address
Esempio n. 12
0
    def __init__(self, *args, **kwargs):
        super(BACnetAgent, self).__init__(*args, **kwargs)
        ips = getIPs()
        print "found local ip as ", ips
        device_address = ips[0] + "/24"
        max_apdu_len =  1024
        seg_supported = "segmentedBoth"
        obj_id =  599
        obj_name = "BEMOSS BACnet driver"
        ven_id = 15

        self.async_call = AsyncCall()
        self.setup_device(device_address,
                         max_apdu_len, seg_supported,
                         obj_id, obj_name, ven_id)
        self.subscribe(topic="read_property",callback=self.processRead)
        self.subscribe(topic="write_property",callback=self.processWrite)
        self.subscribe(topic="broadcast", callback=self.broadcast)
        self.subscribe(topic="simple_read",callback=self.processSimpleRead)
        self.run()
Esempio n. 13
0
def bacnet_proxy_agent(config_path, **kwargs):
    config = utils.load_config(config_path)
    vip_identity = config.get("vip_identity", "platform.bacnet_proxy")
    # pop off the uuid based identity
    ips = getIPs()
    print "found local ip as ", ips
    device_address = ips[0] + "/24"
    kwargs.pop('identity', None)
    max_apdu_len = config.get("max_apdu_length", 1024)
    seg_supported = config.get("segmentation_supported", "segmentedBoth")
    obj_id = config.get("object_id", 599)
    obj_name = config.get("object_name", "Volttron BACnet driver")
    ven_id = config.get("vendor_id", 15)

    return BACnetProxyAgent(device_address,
                            max_apdu_len,
                            seg_supported,
                            obj_id,
                            obj_name,
                            ven_id,
                            heartbeat_autostart=True,
                            identity=vip_identity,
                            **kwargs)
Esempio n. 14
0
    def discover(self,username, password, token=None):
        myIps = getIPs()
        device_list = []

        for ip in myIps:
            for i in range(1,256):
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(0.05)  # 0.01 second timeout on commands
                parts = ip.split('.')
                new_ip = '.'.join(parts[:3]+[str(i)])
                port = 10001
                try:
                    sock.connect((new_ip,port))
                except socket.error as er:
                    continue
                sock.settimeout(3)
                login_message = b'WML1D'+username+','+password+'\r'
                sock.sendall(login_message)
                reply = sock.recv(4096).strip()
                is_ok = reply.split(',')[0] == "OK"
                if is_ok:
                    mac_message = b'RMMI1\r'
                    sock.sendall(mac_message)
                    mac = sock.recv(4096)[6:].strip().replace(':','')
                    name_message = b'RMTN1\r'
                    sock.sendall(name_message)
                    name = sock.recv(4096)[6:].strip()
                    model_message = b'REV1\r'
                    sock.sendall(model_message)
                    model = sock.recv(4096)[5:].strip().split(',')[0]
                    device_list.append({'address': new_ip+':'+str(port) , 'mac': mac,
                                    'model': self.API_info()[0]['device_model'], 'vendor': self.API_info()[0]['vendor_name'],
                                    'nickname': name})

            #print device_list
            return device_list
Esempio n. 15
0
def main():
    # parse the command line arguments
    arg_parser = ConfigArgumentParser(description=__doc__)

    arg_parser.add_argument("device_id",
                            type=int,
                            help="Device ID of the target device")

    arg_parser.add_argument(
        "--address",
        help=
        "Address of target device, may be needed to help route initial request to device."
    )

    arg_parser.add_argument("--out-file",
                            type=argparse.FileType('wb'),
                            help="Optional output file for configuration",
                            default=sys.stdout)

    arg_parser.add_argument(
        "--max_range_report",
        nargs='?',
        type=float,
        help=
        'Affects how very large numbers are reported in the "Unit Details" column of the output. '
        'Does not affect driver behavior.',
        default=1.0e+20)

    args = arg_parser.parse_args()

    _log.debug("initialization")
    _log.debug("    - args: %r", args)
    ips = getIPs()
    print "found local ip as ", ips
    device_address = ips[0] + "/24"
    # make a device object
    this_device = LocalDeviceObject(
        objectName="BEMOSS",
        objectIdentifier=int(599),
        maxApduLengthAccepted=int(1024),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

    # make a simple application
    this_application = SynchronousApplication(this_device, device_address)

    _log.debug("starting build")

    result = get_iam(this_application, args.device_id, args.address)

    target_address = result.pduSource

    _log.debug('pduSource = ' + repr(result.pduSource))
    _log.debug('iAmDeviceIdentifier = ' + str(result.iAmDeviceIdentifier))
    _log.debug('maxAPDULengthAccepted = ' + str(result.maxAPDULengthAccepted))
    _log.debug('segmentationSupported = ' + str(result.segmentationSupported))
    _log.debug('vendorID = ' + str(result.vendorID))

    device_id = result.iAmDeviceIdentifier[1]

    try:
        device_name = read_prop(this_application, target_address, "device",
                                device_id, "objectName")
        _log.debug('device_name = ' + str(device_name))
    except TypeError:
        _log.debug('device missing objectName')

    try:
        device_description = read_prop(this_application, target_address,
                                       "device", device_id, "description")
        _log.debug('description = ' + str(device_description))
    except TypeError:
        _log.debug('device missing description')

    config_writer = DictWriter(
        args.out_file, ('Reference Point Name', 'Volttron Point Name', 'Units',
                        'Unit Details', 'BACnet Object Type', 'Property',
                        'Writable', 'Index', 'Write Priority', 'Notes'))

    config_writer.writeheader()

    try:
        objectCount = read_prop(this_application,
                                target_address,
                                "device",
                                device_id,
                                "objectList",
                                index=0)
        list_property = "objectList"
    except TypeError:
        objectCount = read_prop(this_application,
                                target_address,
                                "device",
                                device_id,
                                "structuredObjectList",
                                index=0)
        list_property = "structuredObjectList"

    _log.debug('objectCount = ' + str(objectCount))

    for object_index in xrange(1, objectCount + 1):
        _log.debug('object_device_index = ' + repr(object_index))

        bac_object = read_prop(this_application,
                               target_address,
                               "device",
                               device_id,
                               list_property,
                               index=object_index)

        obj_type, index = bac_object
        print object_index
        print
        print
        process_object(this_application, target_address, obj_type, index,
                       args.max_range_report, config_writer)
Esempio n. 16
0
def init():
    try:
        casSettingsFile = open(
            os.path.expanduser("~") +
            "/workspace/bemoss_os/cassandra_settings.txt", 'r')
    except IOError as er:
        print "creating a new cassandra_settings file"
        cluster_name = raw_input(
            "Enter a unique name for cassandra cluster-name: ")
        if cluster_name == '':
            cluster_name = 'bemosscluster'
            print 'Using default clustername: ' + cluster_name
        db_username = raw_input("Enter database username: "******"Enter database password: "******"Enter password again: ")
            while password2 != db_password:
                password2 = raw_input("Password doesn't match. Input again: ")
                #TODO have some exit condition
        ip_address = getIPs()[-1]
        casSettingsFile = open(
            os.path.expanduser("~") +
            "/workspace/bemoss_os/cassandra_settings.txt", 'w')
        contents = """cluster_name: '%s'
keyspace_name: bemossspace
replication_factor: 2
listen_address: %s
rpc_address: %s
seeds: "%s"
authenticator: PasswordAuthenticator
db_username: %s
db_password: %s
MAX_HEAP_SIZE="400M"
HEAP_NEWSIZE="100M"
    """ % (cluster_name, ip_address, ip_address, ip_address, db_username,
           db_password)
        casSettingsFile.write(contents)
        casSettingsFile.close()
        casSettingsFile = open(
            os.path.expanduser("~") +
            "/workspace/bemoss_os/cassandra_settings.txt", 'r')

    settingsContent = casSettingsFile.read()
    casSettingsFile.close()
    try:
        casYamlFile = open(
            os.path.expanduser("~") +
            "/workspace/cassandra/conf/cassandra.yaml", 'r')
        yamlContent = casYamlFile.read()
        casYamlFile.close()
    except IOError as er:
        print "Not found:" + os.path.expanduser(
            "~") + "/workspace/cassandra/conf/cassandra.yaml"
        raise

    try:
        casEnvFile = open(
            os.path.expanduser("~") +
            "/workspace/cassandra/conf/cassandra-env.sh", 'r')
        envContent = casEnvFile.read()
        casEnvFile.close()
    except IOError as er:
        print "Not found:" + os.path.expanduser(
            "~") + "/workspace/cassandra/conf/cassandra.yaml"
        raise

    cluster_name = re.search('cluster_name:(.*)\n', settingsContent).group(1)
    listen_address = re.search('listen_address:(.*)\n',
                               settingsContent).group(1)
    rpc_address = re.search('rpc_address: *([0-9\.]*)\n',
                            settingsContent).group(1)
    db_username = re.search('db_username: *(.*)\n', settingsContent).group(1)
    db_password = re.search('db_password: *(.*)\n', settingsContent).group(1)
    keyspace = re.search('keyspace_name: *(.*)\n', settingsContent).group(1)
    replication_factor = re.search('replication_factor: *(.*)\n',
                                   settingsContent).group(1)
    myips = getIPs()

    seeds = re.search('seeds:(.*)\n', settingsContent).group(1)
    authenticator = re.search('authenticator:(.*)\n', settingsContent).group(1)
    MAX_HEAP_SIZE = re.search('MAX_HEAP_SIZE=("[a-zA-Z0-9]*")\n',
                              settingsContent).group(1)
    HEAP_NEWSIZE = re.search('HEAP_NEWSIZE=("[a-zA-Z0-9]*")\n',
                             settingsContent).group(1)

    #check if any of the seeds IP is current machine IP. At least one seed needs to be self IP
    bad_seed = True
    for ip in myips:
        if ip in seeds:
            bad_seed = False

    if bad_seed:
        oldseeds = seeds.replace('"', '').strip()
        seeds = '"%s, %s"' % (myips[-1], oldseeds)

    if listen_address.strip() not in myips or rpc_address.strip() not in myips:

        listen_address = myips[-1]
        rpc_address = myips[-1]

    casSettingsFile = open(
        os.path.expanduser("~") +
        "/workspace/bemoss_os/cassandra_settings.txt", 'w')
    contents = """cluster_name: %s
keyspace_name: %s
replication_factor: %s
listen_address: %s
rpc_address: %s
seeds: %s
authenticator: %s
db_username: %s
db_password: %s
MAX_HEAP_SIZE=%s
HEAP_NEWSIZE=%s
""" % (cluster_name.strip(), keyspace.strip(), replication_factor.strip(),
       myips[-1], myips[-1], seeds.strip(), authenticator.strip(),
       db_username.strip(), db_password.strip(), MAX_HEAP_SIZE.strip(),
       HEAP_NEWSIZE.strip())
    casSettingsFile.write(contents)
    casSettingsFile.close()

    yamlContent = re.sub('cluster_name:(.*)\n',
                         'cluster_name: %s\n' % cluster_name, yamlContent)
    yamlContent = re.sub('listen_address:(.*)\n',
                         'listen_address: %s\n' % listen_address, yamlContent)
    yamlContent = re.sub('rpc_address:(.*)\n',
                         'rpc_address: %s\n' % rpc_address, yamlContent)
    yamlContent = re.sub('authenticator:(.*)\n',
                         'authenticator: %s\n' % authenticator, yamlContent)
    yamlContent = re.sub('seeds:(.*)\n', 'seeds: %s\n' % seeds, yamlContent)
    envContent = re.sub('#?MAX_HEAP_SIZE=("[a-zA-Z0-9]*")\n',
                        'MAX_HEAP_SIZE=%s\n' % MAX_HEAP_SIZE, envContent)
    envContent = re.sub('#?HEAP_NEWSIZE=("[a-zA-Z0-9]*")\n',
                        'HEAP_NEWSIZE=%s\n' % HEAP_NEWSIZE, envContent)

    try:
        casYamlFile = open(
            os.path.expanduser("~") +
            "/workspace/cassandra/conf/cassandra.yaml", 'w')
        casYamlFile.write(yamlContent)
        casYamlFile.close()
    except IOError as er:
        print "Error writing:" + os.path.expanduser(
            "~") + "/workspace/cassandra/conf/cassandra.yaml"
        raise

    try:
        casEnvFile = open(
            os.path.expanduser("~") +
            "/workspace/cassandra/conf/cassandra-env.sh", 'w')
        casEnvFile.write(envContent)
        casEnvFile.close()
    except IOError as er:
        print "Error writing:" + os.path.expanduser(
            "~") + "/workspace/cassandra/conf/cassandra.yaml"
        raise
Esempio n. 17
0
Agents_DIR = settings.Agents_DIR
db_database = settings.DATABASES['default']['NAME']
db_host = settings.DATABASES['default']['HOST']
db_port = settings.DATABASES['default']['PORT']
db_user = settings.DATABASES['default']['USER']
db_password = settings.DATABASES['default']['PASSWORD']
db_table_node_device = settings.DATABASES['default']['TABLE_node_device']
db_table_device_info = settings.DATABASES['default']['TABLE_device_info']
db_table_node_info = settings.DATABASES['default']['TABLE_node_info']

multinode_data = db_helper.get_multinode_data()

node_name = multinode_data['this_node']

myips = find_own_ip.getIPs()
_email_subject = node_name+'@'+str(myips[0])
emailService = EmailService()

#email settings
email_fromaddr = settings.NOTIFICATION['email']['fromaddr']
email_recipients = settings.NOTIFICATION['email']['recipients']
email_username = settings.NOTIFICATION['email']['username']
email_password = settings.NOTIFICATION['email']['password']
email_mailServer = settings.NOTIFICATION['email']['mailServer']


smsService = SMSService()
notify_heartbeat = settings.NOTIFICATION['heartbeat']

#Offline variables initialized
Esempio n. 18
0
def init():
    try:
        casSettingsFile = open(os.path.expanduser("~")+"/workspace/bemoss_os/cassandra_settings.txt",'r')
    except IOError as er:
        print "creating a new cassandra_settings file"
        cluster_name = raw_input("Enter a unique name for cassandra cluster-name: ")
        db_username = raw_input("Enter database username: "******"Enter database password: "******"Enter password again: ")
        while password2 != db_password:
            password2 = raw_input("Password doesn't match. Input again: ")
        ip_address = getIPs()[-1]
        casSettingsFile = open(os.path.expanduser("~")+"/workspace/bemoss_os/cassandra_settings.txt",'w')
        contents="""cluster_name: '%s'
keyspace_name: bemossspace
replication_factor: 2
listen_address: %s
rpc_address: %s
seeds: "%s"
authenticator: PasswordAuthenticator
db_username: %s
db_password: %s
MAX_HEAP_SIZE="400M"
HEAP_NEWSIZE="100M"
    """ % (cluster_name,ip_address,ip_address,ip_address,db_username,db_password)
        casSettingsFile.write(contents)
        casSettingsFile.close()
        casSettingsFile = open(os.path.expanduser("~")+"/workspace/bemoss_os/cassandra_settings.txt",'r')

    settingsContent = casSettingsFile.read()
    casSettingsFile.close()
    try:
        casYamlFile = open(os.path.expanduser("~")+"/workspace/cassandra/conf/cassandra.yaml",'r')
        yamlContent = casYamlFile.read()
        casYamlFile.close()
    except IOError as er:
        print "Not found:" + os.path.expanduser("~")+"/workspace/cassandra/conf/cassandra.yaml"
        raise

    try:
        casEnvFile = open(os.path.expanduser("~")+"/workspace/cassandra/conf/cassandra-env.sh",'r')
        envContent = casEnvFile.read()
        casEnvFile.close()
    except IOError as er:
        print "Not found:" + os.path.expanduser("~")+"/workspace/cassandra/conf/cassandra.yaml"
        raise

    cluster_name = re.search('cluster_name:(.*)\n',settingsContent).group(1)
    listen_address = re.search('listen_address:(.*)\n',settingsContent).group(1)
    rpc_address = re.search('rpc_address: *([0-9\.]*)\n',settingsContent).group(1)
    db_username = re.search('db_username: *(.*)\n',settingsContent).group(1)
    db_password = re.search('db_password: *(.*)\n',settingsContent).group(1)
    keyspace = re.search('keyspace_name: *(.*)\n',settingsContent).group(1)
    replication_factor = re.search('replication_factor: *(.*)\n',settingsContent).group(1)
    myips = getIPs()

    seeds = re.search('seeds:(.*)\n',settingsContent).group(1)
    authenticator = re.search('authenticator:(.*)\n',settingsContent).group(1)
    MAX_HEAP_SIZE = re.search('MAX_HEAP_SIZE=("[a-zA-Z0-9]*")\n',settingsContent).group(1)
    HEAP_NEWSIZE = re.search('HEAP_NEWSIZE=("[a-zA-Z0-9]*")\n',settingsContent).group(1)

    #check if any of the seeds IP is current machine IP. At least one seed needs to be self IP
    bad_seed = True
    for ip in myips:
        if ip in seeds:
            bad_seed = False

    if bad_seed:
        oldseeds = seeds.replace('"','').strip()
        seeds = '"%s, %s"'% (myips[-1],oldseeds)

    if listen_address.strip() not in myips or rpc_address.strip() not in myips:

        listen_address = myips[-1]
        rpc_address = myips[-1]



    casSettingsFile = open(os.path.expanduser("~")+"/workspace/bemoss_os/cassandra_settings.txt",'w')
    contents="""cluster_name: %s
keyspace_name: %s
replication_factor: %s
listen_address: %s
rpc_address: %s
seeds: %s
authenticator: %s
db_username: %s
db_password: %s
MAX_HEAP_SIZE=%s
HEAP_NEWSIZE=%s
""" % (cluster_name.strip(),keyspace.strip(),replication_factor.strip(),myips[-1],myips[-1],seeds,authenticator.strip(),db_username.strip(),db_password.strip(),MAX_HEAP_SIZE.strip(),HEAP_NEWSIZE.strip())
    casSettingsFile.write(contents)
    casSettingsFile.close()

    yamlContent = re.sub('cluster_name:(.*)\n','cluster_name: %s\n' % cluster_name,yamlContent)
    yamlContent = re.sub('listen_address:(.*)\n','listen_address: %s\n' % listen_address,yamlContent)
    yamlContent = re.sub('rpc_address:(.*)\n','rpc_address: %s\n' % rpc_address,yamlContent)
    yamlContent = re.sub('authenticator:(.*)\n','authenticator: %s\n' % authenticator,yamlContent)
    yamlContent = re.sub('seeds:(.*)\n','seeds: %s\n' % seeds,yamlContent)
    envContent = re.sub('#?MAX_HEAP_SIZE=("[a-zA-Z0-9]*")\n','MAX_HEAP_SIZE=%s\n' % MAX_HEAP_SIZE,envContent)
    envContent = re.sub('#?HEAP_NEWSIZE=("[a-zA-Z0-9]*")\n','HEAP_NEWSIZE=%s\n'%HEAP_NEWSIZE,envContent)

    try:
        casYamlFile = open(os.path.expanduser("~")+"/workspace/cassandra/conf/cassandra.yaml",'w')
        casYamlFile.write(yamlContent)
        casYamlFile.close()
    except IOError as er:
        print "Error writing:" + os.path.expanduser("~")+"/workspace/cassandra/conf/cassandra.yaml"
        raise

    try:
        casEnvFile = open(os.path.expanduser("~")+"/workspace/cassandra/conf/cassandra-env.sh",'w')
        casEnvFile.write(envContent)
        casEnvFile.close()
    except IOError as er:
        print "Error writing:" + os.path.expanduser("~")+"/workspace/cassandra/conf/cassandra.yaml"
        raise
Esempio n. 19
0
    def runServer(self, dbcon):

        # Main request messages format
        #
        # For discovery ----- {"TYPE": "DISCOVER", "PAYLOAD": {
        #     "MODEL_NAMES": { "On_Off Switch": None,"LightSwitch": None},""BUILDING_ID":12345}, "AUTHORIZATION_CODE": "xxxxxx"}
        #
        # For status change -{"TYPE": "CHANGE_STATUS", "PAYLOAD": {"APR": ["WNC_484389", ],"PND": [],"NBM": []},
        #                                "AUTHORIZATION_CODE": "xxxxxx"}
        #
        # For Authorize------ {"TYPE": "AUTHORIZE", "PAYLOAD": {"AGENT_ID": "Phil_0017881a4676"}, "AUTHORIZATION_CODE": "xxxxxx"}
        #
        # For Control ------- {"TYPE": "CONTROL", "PAYLOAD": {"AGENT_ID": "Sock_221609K0102348","POSTMSG": {"status":"OFF"}},
        #                     "AUTHORIZATION_CODE": "xxxxxx"}
        #
        #
        #
        class handlerClass(WebSocket):

            def __init__(self, agent, *args, **kwargs):
                self.agent = agent
                super(handlerClass, self).__init__(*args, **kwargs)


            def handleMessage(self):
                # where u get data from gateway
                try:
                    print("got this MESSAGE from IOT gateway ", self.data)
                    json_message=json.loads(self.data)   #todo bad data handling everywhere
                    if(json_message["TYPE"])=="DISCOVER":
                        self.agent.bemoss_publish(target="devicediscoveryagent", topic="gateway_discovered_devices", message=json_message["PAYLOAD"], sender=self)
                    elif (json_message["TYPE"]) == "MONITOR":
                        for element in json_message["PAYLOAD"]:
                            try:
                                for agent_id, data in element.items():
                                    self.agent.bemoss_publish(target=agent_id.encode("utf-8") , topic="gateway_monitor_data" , message=data , sender=self)
                            except Exception as e:
                                continue
                    elif (json_message["TYPE"]) == "CONTROL":
                            for agent_id, data in json_message["PAYLOAD"].items():
                                self.agent.bemoss_publish(target=agent_id.encode("utf-8"), topic="gateway_control_response",
                                                  message=data, sender=self)
                    elif (json_message["TYPE"]) == "AUTHORIZE":
                        self.agent.bemoss_publish(target="approvalhelperagent", topic="device_config",
                                                  message=json_message["PAYLOAD"], sender=self)
                    elif (json_message["TYPE"]) == "CHANGE_STATUS":
                        pass#Is this needed ?
                    elif(json_message["TYPE"]) == "FIRST TIME CONNECT":
                        self.gateway_handshake(json_message)
                        self.gateway_configure(json_message)
                    elif (json_message["TYPE"]) == "RECONNECT": #comes here only if cloud BEM went offline and gateway onneted to it
                         #wrote seperately to do some stored data fetching from gateway
                        self.gateway_handshake(json_message)
                    #todo get any stored data? or stored data is received with some specific type
                except Exception as e:
                    print (e)

            def initialise_gateway(self,gateway_id,building_id):

                info = {}
                IP, port = self.address
                info["ip_address"] = IP + ":" + str(port)
                self.agent.dbcon.execute("UPDATE iot_gateway SET gateway_settings=%s,status=%s WHERE gateway=%s",
                                         (json.dumps(info), "APR", str(gateway_id)))
                self.agent.dbcon.commit()
                self.agent.subscribe('gateway_discover' + '_' + str(building_id),self.gateway_discover)
                self.agent.subscribe('gateway_device_status_update' + '_' + str(gateway_id), self.gateway_device_status_update)
                self.agent.subscribe('gateway_device_control' + '_' + str(gateway_id), self.gateway_device_control)
                self.agent.subscribe('gateway_device_authorize' + '_' + str(gateway_id), self.gateway_device_authorize)

            def check_entry(self,gateway_details,building_id):
                time_requested = gateway_details[2]
                current_time = datetime.datetime.now()
                gateway_id=gateway_details[0]
                diff = current_time - time_requested.replace(tzinfo=None)
                time = divmod(diff.days * 86400 + diff.seconds, 60)
                if time[0] <6000 or (time[0] == 1 and time[1] == 0):
                    self.initialise_gateway(gateway_id, building_id)
                else:
                    print "deleting this entry"
                    self.agent.dbcon.execute('delete from iot_gateway where gateway=%s',
                                             (str(gateway_id),))  # deleting the entry since connection is not valid
                    self.agent.dbcon.commit()
                    self.close()

            def gateway_handshake(self,json_message):
                gateway_id = json_message["UNIQUE_ID"]
                gateway_details = self.agent.get_gateway_config(self.agent.dbcon, gateway_id)
                if gateway_details is not None:
                    building_id = gateway_details[5]
                    status = gateway_details[6]
                    if status == "PND":
                        self.check_entry(gateway_details, building_id)
                    else:
                        self.initialise_gateway(gateway_id, building_id)
                else:
                    print("No entry of connected gateway on db, so simply closing connection")
                    self.close()


            def handleConnected(self):
                print(self.address, 'connected')
                # self.senddata() #i can do handshake here

            def gateway_configure(self,json_message):

                details=dict()
                gateway_id = json_message["UNIQUE_ID"]
                gateway_details = self.agent.get_gateway_config(self.agent.dbcon, gateway_id)
                details["NAME"]=gateway_details[1]
                details["SETTINGS"]=gateway_details[3]
                details["ACCOUNT_ID"]=gateway_details[4]
                details["BUILDING_ID"]=gateway_details[5]

                try:

                    ADU=dict()
                    ADU["TYPE"]="CONFIGURE"
                    ADU["PAYLOAD"] = details
                    ADU["AUTHORIZATION_CODE"] = settings.GATEWAY_AUTHORIZATION_CODE
                    print("sending to gateway")
                    self.sendMessage(json.dumps(ADU))

                except Exception as e:
                    print("somethin went wrong")

            def gateway_discover(self, dbcon, sender, topic, message):


                try:

                    ADU=dict()
                    ADU["TYPE"]="DISCOVER"
                    ADU["PAYLOAD"] = message

                    ADU["AUTHORIZATION_CODE"] = settings.GATEWAY_AUTHORIZATION_CODE
                    print("sending to gateway")
                    self.sendMessage(json.dumps(ADU))

                except Exception as e:
                    print("somethin went wrong")

            def gateway_device_authorize(self, dbcon, sender, topic, message):

                try:

                    PDU = dict()
                    PDU["AGENT_ID"] = message
                    ADU = dict()
                    ADU["TYPE"] = "AUTHORIZE"
                    ADU["PAYLOAD"] = PDU
                    ADU["AUTHORIZATION_CODE"] = settings.GATEWAY_AUTHORIZATION_CODE
                    print("sending to gateway")
                    self.sendMessage(json.dumps(ADU))

                except Exception as e:
                    print("somethin went wrong")

            def gateway_device_status_update(self, dbcon, sender, topic, message):

                try:
                    APRlist = list()
                    PNDlist = list()
                    NBMlist = list()
                    status_change=dict()
                    ADU = dict()
                    ADU["TYPE"] = "CHANGE_STATUS"
                    for agent_id, status in message:
                        if status==APPROVAL_STATUS.APR:
                            APRlist.append(agent_id)
                        elif status==APPROVAL_STATUS.PND:
                            PNDlist.append(agent_id)
                        else:
                            NBMlist.append(agent_id)
                    status_change["APR"] = APRlist
                    status_change["PND"] = PNDlist
                    status_change["NBM"] = NBMlist
                    ADU["PAYLOAD"] = status_change
                    ADU["AUTHORIZATION_CODE"] = settings.GATEWAY_AUTHORIZATION_CODE
                    print("sending to gateway")
                    self.sendMessage(json.dumps(ADU))

                except Exception as e:
                    print("somethin went wrong")

            def gateway_device_control(self, dbcon, sender, topic, message):

                try:

                    PDU = dict()
                    PDU["AGENT_ID"] = message['AGENT_ID']
                    PDU["POSTMSG"]=message['POSTMSG']
                    ADU = dict()
                    ADU["TYPE"] = "CONTROL"
                    ADU["PAYLOAD"] = PDU     #{"AGENT_ID": "Sock_221609K0102348","POSTMSG": {"status":"OFF"}}
                    ADU["AUTHORIZATION_CODE"] = settings.GATEWAY_AUTHORIZATION_CODE
                    print("sending to gateway")
                    self.sendMessage(json.dumps(ADU))

                except Exception as e:
                    print("somethin went wrong")

            def handleClose(self):
                print(self.address, 'closed')

        ips = getIPs()
        print "found local ips- ", ips
        device_address = ips[0]
        self.server = SimpleSSLWebSocketServer(device_address, 8889, handlerClass, certfile=settings.GATEWAY_KEYS_FOLDER+"/server.crt",
                                               keyfile=settings.GATEWAY_KEYS_FOLDER+"/server.key")

        print("server startedd")
        self.server.serveforever(self)
Esempio n. 20
0
from volttron.platform.agent import utils
from volttron.platform.vip.agent import Agent, Core, PubSub, compat
from bemoss_lib.utils import db_helper
from bemoss_lib.utils.BEMOSSAgent import BEMOSSAgent
import random
from bemoss_lib.utils import db_helper
#initiliazation
utils.setup_logging()
_log = logging.getLogger(__name__)
Agents_DIR = settings.Agents_DIR
clock_time = 20  #frequency of polling nodes
Agents_Launch_DIR = settings.Agents_Launch_DIR
building_name = settings.PLATFORM['node']['building_name']
db_database = settings.DATABASES['default']['NAME']

my_ip_address = find_own_ip.getIPs()[
    -1]  #use the last IP in the list for host ip

debug_agent = settings.DEBUG
host_name = settings.PLATFORM['node']['name']
db_host = settings.DATABASES['default']['HOST']
db_port = settings.DATABASES['default']['PORT']
db_user = settings.DATABASES['default']['USER']
db_password = settings.DATABASES['default']['PASSWORD']
db_table_node_info = settings.DATABASES['default']['TABLE_node_info']
db_table_node_device = settings.DATABASES['default']['TABLE_node_device']
db_table_device_info = settings.DATABASES['default']['TABLE_device_info']
db_table_device_data = settings.DATABASES['default']['TABLE_device']
db_table_active_alert = settings.DATABASES['default']['TABLE_active_alert']
db_table_device_type = settings.DATABASES['default']['TABLE_device_type']
db_table_bemoss_notify = settings.DATABASES['default']['TABLE_bemoss_notify']
db_table_alerts_notificationchanneladdress = settings.DATABASES['default'][