예제 #1
0
def display_msg_on_sensors_display(MSG_Text):
    # send the MSG to all sensors, store all in sensor_data[k]
    for k, v in core.SPOT_SENSOR.items():
        # (k)ey = IP-Address
        # (v)alue = Port
        log(str(k) + " sending msg to sensor's display : " + MSG_Text, "debug")
        check_sensor(k, v)
        time.sleep(1)
        display_msg(k, v, MSG_Text)
예제 #2
0
파일: spot.py 프로젝트: red-ip/spot
def display_msg_on_sensors_display(MSG_Text):
    # send the MSG to all sensors, store all in sensor_data[k]
    for k, v in core.SPOT_SENSOR.items():
        # (k)ey = IP-Address
        # (v)alue = Port
        log(str(k) + " sending msg to sensor's display : " + MSG_Text, "debug")
        check_sensor(k, v)
        time.sleep(1)
        display_msg(k, v, MSG_Text)
        '''
예제 #3
0
def display_rgbled_on_sensors(rgb_code):
    # send the RGB LED to all sensors, store all in sensor_data[k]
    for k, v in core.SPOT_SENSOR.items():
        # (k)ey = IP-Address
        # (v)alue = Port
        log(
            str(k) + " sending rgb LED to sensor's LED : " + str(rgb_code),
            "debug")
        check_sensor(k, v)
        time.sleep(1)
        display_rgbled(k, v, rgb_code)
예제 #4
0
def main():
    nearby_devices_counter = 0  # how many devices are in the coverage of Spot / in the Homezone
    devices_to_check_counter = 0  # how many devices to check
    nearby_devices_counter_last_run = 0

    log("Starting to collect parameters", "info")
    log("checking if ip interface is ready", "debug")
    # wait till we have an ip
    while get_local_ip("8.8.8.8") is None:
        time.sleep(1)
    log(
        "IP interface is ready to go! local IP : " +
        str(get_local_ip("8.8.8.8")), "debug")

    if core.AUTO_DISCOVERY:
        log("Running Auto Discovery for Sensors ", "debug")
        discovery_sensors()
    log("Getting Devices for check from CCU2", "debug")
    # we will work with devices_to_check all the time and save the response from the sensors here
    devices_to_check = discovery_devices()
    devices_to_check_counter = devices_to_check.__len__()
    log("All parameters collected. System OK -> STARTING WORK", "info")

    try:
        request_discovery = False  # from time to time I'll rediscover sensors and the "device to check list"
        counter = 0  # loop counter
        while True:
            counter += 1  # count every loop
            sensor_data = {}
            pre_lookup = True  # to speed up detection
            if request_discovery:  # in some cases we will need to rediscover sensors and devices
                request_discovery = False
                log("Rediscovering Sensor and devices. Loop : " + str(counter),
                    "debug")
                devices_to_check = {}
                devices_to_check = copy.deepcopy(discovery_devices())
                devices_to_check_counter = devices_to_check.__len__()

                # to see if we got a new sensor
                tmp_sensor_before = {}
                tmp_sensor_before = copy.deepcopy(core.SPOT_SENSOR)
                discovery_sensors()
                tmp_sensor_after = {}
                tmp_sensor_after = copy.deepcopy(core.SPOT_SENSOR)

                for sensor in tmp_sensor_after:  # send to log if a new sensor was found
                    if sensor not in tmp_sensor_before.keys():
                        try:
                            hostnamesensor = get_sensor_name(
                                sensor, sensor_port)
                        except UnboundLocalError:
                            hostnamesensor = "-Err-"
                            log(
                                "main 235 local variable 'sensor_port' referenced before assignment",
                                "error")
                        log(
                            "Sensor :" + str(sensor) + " (" +
                            str(hostnamesensor) + ") is online", "info")

                    # send the device list to all sensors, store all in sensor_data[k]

            threads = []
            thread_counter = 0

            for k, v in core.SPOT_SENSOR.items():
                # (k)ey = IP-Address of the Sensor
                # (v)alue = Port of the Sensor

                log(
                    "checking if : " + str(k) +
                    " . ready to receive the device list", "debug")
                if check_sensor(k, v):  # ping the sensor
                    log(str(k) + ". Sensor is waiting for Data..", "debug")
                    cp_device = {}
                    cp_device = copy.deepcopy(
                        devices_to_check)  # deepcopy to avoiding references
                    if (counter % 2) == 0:  # just check VIP every second time
                        for mac_of_device, value_of_device in cp_device.items(
                        ):
                            if cp_device[mac_of_device]['device'].lower(
                            ) == "novip":
                                del cp_device[mac_of_device]

                    thread_counter += 1
                    thread = myThread(thread_counter, k, v, cp_device)
                    thread.start()
                    threads.append(thread)
                    log(str(k) + " sending data to Sensor", "debug")

                    if not core.SENSOR_AVAILABLE:
                        # zu beginn, eine Liste mit den gefundenenen Sensoren erstellen und ausgeben
                        for sensor_ip, sensor_port in core.SPOT_SENSOR.items():
                            hostnamesensor = get_sensor_name(
                                sensor_ip, sensor_port)
                            log(
                                "Sensor :" + str(sensor_ip) + " (" +
                                str(hostnamesensor) + ") is online", "info")

                        core.SENSOR_AVAILABLE = True
                else:
                    log(
                        "Sensor ping failed to : " + str(k) +
                        " . Moving on to the next sensor", "debug")
                    log("Sensor : " + str(k) + " . Disconnected", "info")
                    request_discovery = True

            # Wait for all threads to complete
            for t in threads:
                t.join()
                sensor_data[str(t.ip_address)] = t.get_list()

            log(
                "Beginning to calculate the presence information from the Sensors",
                "debug")
            presence_of_devices = {}
            presence_of_devices = accumulate_sensor_data(
                sensor_data, devices_to_check)

            # create a time stamp
            time_now = time.time()
            time_stamp = datetime.datetime.fromtimestamp(time_now).strftime(
                '%Y-%m-%d-%H:%M:%S')
            if len(presence_of_devices) == 0:
                if core.SENSOR_AVAILABLE:
                    log("All Sensor are offline!", "error")
                    core.SENSOR_AVAILABLE = False
                log("All Sensors Down. loop counter " + str(counter), "debug")
                request_discovery = True
            else:
                # checking if device presence has changed
                for k, v in devices_to_check.items():  # k = mac-address
                    try:
                        if devices_to_check[k]['presence'].lower(
                        ) == 'true' and presence_of_devices[k] > 0:
                            # was visible   ist visible     do nothing
                            devices_to_check[k]['first_not_seen'] = None
                            devices_to_check[k]['times_not_seen'] = 0

                            seen_by = ""
                            for items in devices_to_check[k]['seen_by']:
                                if devices_to_check[k]['seen_by'][items]:
                                    seen_by = seen_by + str(items) + " "

                            log(
                                str(k) + " is still present. Loop : " +
                                str(counter) + " Seen by : " + seen_by,
                                "debug")

                        elif devices_to_check[k]['presence'].lower() == 'true' and presence_of_devices[k] == 0 and \
                            devices_to_check[k]['times_not_seen'] < core.MAX_TIME_NOT_SEEN:
                            # was visible   ist not visible < MAX   count not seen + 1, set first time not seen
                            devices_to_check[k]['times_not_seen'] += 1
                            if devices_to_check[k]['first_not_seen'] is None:
                                devices_to_check[k][
                                    'first_not_seen'] = time_stamp
                                log(
                                    str(k) +
                                    " is first time no seen. Loop : " +
                                    str(counter), "debug")

                        elif devices_to_check[k]['presence'].lower() == 'true' and presence_of_devices[k] == 0 and \
                                        devices_to_check[k]['times_not_seen'] >= core.MAX_TIME_NOT_SEEN:
                            # was visible   ist not visible = MAX!   update ccu2, was visible = False
                            # send update to ccu2
                            send_ok = send_device_status_to_ccu(
                                devices_to_check[k]['ise_id'], 'false')
                            log("OUT - " + str(devices_to_check[k]['name']) + " since " + \
                                str(devices_to_check[k]['first_not_seen']) + ".", "info")
                            log(str(k) + " - " + str(devices_to_check[k]['name']) + \
                                " is last seen at " + \
                                str(devices_to_check[k]['first_not_seen']) + ". going to update the CCU2", "debug")

                            if send_ok:  # successful
                                log(
                                    str(k) +
                                    " changes successfully updated to CCU2",
                                    "debug")
                            else:
                                log(
                                    str(k) +
                                    " problem trying to update changes to CCU2",
                                    "debug")
                            devices_to_check[k][
                                'presence'] = 'False'  # update the dict
                            display_msg_on_sensors_display(
                                "O:" + str(devices_to_check[k]['name']))
                            time.sleep(1)
                            # passing to a DB ->

                        elif devices_to_check[k]['presence'].lower(
                        ) == 'false' and presence_of_devices[k] > 0:
                            # was not visible   ist visible        update ccu2, was visible = True, reset counter and stamp
                            # send update to ccu2
                            send_ok = send_device_status_to_ccu(
                                devices_to_check[k]['ise_id'], 'true')
                            seen_by = ""
                            for items in devices_to_check[k]['seen_by']:
                                if devices_to_check[k]['seen_by'][items]:
                                    seen_by = seen_by + str(items) + " "

                            log(" IN - " + str(devices_to_check[k]['name']) + " since " + str(time_stamp) + ". Seen by : " + \
                                seen_by, "info")

                            log(str(k) + " - " + str(devices_to_check[k]['name']) + \
                                " is here now. Update is sent to CCU2", "debug")
                            if send_ok:  # successful
                                log(
                                    str(k) +
                                    " changes successfully updated to CCU2",
                                    "debug")
                            else:
                                log(
                                    str(k) +
                                    " problem trying to update changes to CCU2",
                                    "debug")
                            devices_to_check[k][
                                'times_not_seen'] = 0  # reset not seen counter to 0
                            devices_to_check[k][
                                'first_not_seen'] = None  # reset first time stamp
                            devices_to_check[k][
                                'presence'] = 'True'  # update the dict
                            display_msg_on_sensors_display(
                                "I:" + str(devices_to_check[k]['name']))
                            display_rgbled_on_sensors('001')
                            time.sleep(1)
                            # passing to a DB ->
                        else:
                            log(str(k) + " remains unavailable", "debug")

                    except KeyError:
                        log(
                            str(k) + " skipping this loop because its no VIP ",
                            "debug")

                # if activated, send a alive signal to ccu2. To activate it, u need to create a
                # system variable ('last_update_') on the ccu2
                #if core.CCU_LAST_UPDATE is not None:
                #    send_ok = send_device_status_to_ccu('last_update_', '"' + time_stamp + '"')

            # calculate how many devices are around, for this run
            nearby_devices_counter = 0
            for dev, int_presence in presence_of_devices.items(
            ):  # dev = int (0 / 1)
                nearby_devices_counter += int(int_presence)

            log(
                str(nearby_devices_counter) + " of " +
                str(devices_to_check_counter) + " are in the coverage of Spot",
                "debug")
            #if nearby_devices_counter_last_run != nearby_devices_counter:
            #    nearby_devices_counter_last_run = nearby_devices_counter
            if nearby_devices_counter == 0:
                log("no more devices around", "debug")
                # no one there. Start process
                core.SLEEP_TIMER = core.SLEEP_TIMER_OUT
                display_msg_on_sensors_display("ALL OUT")
                display_rgbled_on_sensors('100')

            else:
                # someone is there. Start process
                log(str(nearby_devices_counter) + " devices around", "debug")
                core.SLEEP_TIMER = core.SLEEP_TIMER_IN
                display_rgbled_on_sensors('010')

            if counter > 15:  # Rediscover after every 15 loops
                counter = 0
                request_discovery = True
            log("going sleep for " + str(core.SLEEP_TIMER) + " s", "debug")
            time.sleep(core.SLEEP_TIMER)

    except KeyboardInterrupt:
        log("Got signal to STOP", "info")
        display_rgbled_on_sensors('000')
        display_msg_on_sensors_display("ALL OUT")
        if core.PROG_DAEMONIZE:
            startstop(pidfile=core.PDI_FILE,
                      startmsg='stopping daemon',
                      action='stop')
        else:
            print("KeyboardInterrupt received, stopping work ")
        os._exit(0)
예제 #5
0
파일: spot.py 프로젝트: red-ip/spot
def main():
    log("Starting to collect parameters", "info")
    log("checking if ip interface is ready", "debug")
    # wait till we have an ip
    while get_local_ip("8.8.8.8") is None:
        time.sleep(1)
    log("IP interface is ready to go! local IP : " + str(get_local_ip("8.8.8.8")), "debug")

    if core.AUTO_DISCOVERY:
        log("Running Auto Discovery for Sensors ", "debug")
        discovery_sensors()
    log("Getting Devices for check from CCU2", "debug")
    # we will work with devices_to_check all the time and save the response from the sensors here
    devices_to_check = discovery_devices()

    log("All parameters collected. System OK -> STARTING WORK", "info")

    try:
        request_discovery = False               # time to time I'll rediscover sensors and the "device to check list"
        counter = 0                             # loop counter
        while True:
            counter += 1                        # count every loop
            sensor_data = {}
            if request_discovery:               # in some cases we will need to rediscover sensors and devices
                request_discovery = False
                log("Rediscovering Sensor and devices. Loop : " + str(counter), "debug")
                devices_to_check = {}
                devices_to_check = copy.deepcopy(discovery_devices())
                discovery_sensors()

            # send the device list to all sensors, store all in sensor_data[k]
            for k, v in core.SPOT_SENSOR.items():
                # (k)ey = IP-Address
                # (v)alue = Port
                if check_sensor(k, v):  # ping the sensor
                    cp_device = {}
                    cp_device = copy.deepcopy(devices_to_check)                     # avoiding references by deepcopy
                    sensor_data[k] = check_device_dict_via_sensor(k, v, cp_device)  # collect dates from all sensors
                else:
                    log("Sensor ping failed to : " + str(k) + " . Moving on to the next sensor", "debug")
                    request_discovery = True
            presence_of_devices = {}
            presence_of_devices = accumulate_sensor_data(sensor_data)

            # create a time stamp
            time_now = time.time()
            time_stamp = datetime.datetime.fromtimestamp(time_now).strftime('%Y-%m-%d-%H:%M:%S')
            if len(presence_of_devices) == 0:
                log("All Sensors Down. loop counter " + str(counter), "debug")
                request_discovery = True
            else:
                # checking if device presence has changed
                for k, v in devices_to_check.items():   # k = mac-address
                    if devices_to_check[k]['presence'].lower() == 'true' and presence_of_devices[k] > 0:
                        # was visible   ist visible     do nothing
                        log(str(k) + " is still present. Loop : " + str(counter), "debug")

                    elif devices_to_check[k]['presence'].lower() == 'true' and presence_of_devices[k] == 0 and \
                        devices_to_check[k]['times_not_seen'] < core.MAX_TIME_NOT_SEEN:
                        # was visible   ist not visible < MAX   count not seen + 1, set first time not seen
                        devices_to_check[k]['times_not_seen'] += 1
                        if devices_to_check[k]['first_not_seen'] is None:
                            devices_to_check[k]['first_not_seen'] = time_stamp

                    elif devices_to_check[k]['presence'].lower() == 'true' and presence_of_devices[k] == 0 and \
                                    devices_to_check[k]['times_not_seen'] >= core.MAX_TIME_NOT_SEEN:
                        # was visible   ist not visible = MAX!   update ccu2, was visible = False
                        # send update to ccu2
                        send_ok = send_device_status_to_ccu(devices_to_check[k]['ise_id'], 'false')
                        log(str(k) + " - " + str(devices_to_check[k]['name']) + \
                            " is last seen at " + \
                            str(devices_to_check[k]['first_not_seen']) + ". going to update the CCU2", "info")

                        if send_ok:      # successful
                            log(str(k) + " changes successfully updated to CCU2", "debug")
                        else:
                            log(str(k) + " problem trying to update changes to CCU2", "debug")
                        devices_to_check[k]['presence'] = 'False'                       # update the dict
                        display_msg_on_sensors_display(str(devices_to_check[k]['name']) + " left")
                        time.sleep(1)
                        # passing to a DB ->

                    elif devices_to_check[k]['presence'].lower() == 'false' and presence_of_devices[k] > 0:
                        # was not visible   ist visible        update ccu2, was visible = True, reset counter and stamp
                        # send update to ccu2
                        send_ok = send_device_status_to_ccu(devices_to_check[k]['ise_id'], 'true')
                        log(str(k) + " - " + str(devices_to_check[k]['name']) + \
                            " is here now. Update is sent to CCU2", "info")
                        if send_ok:      # successful
                            log(str(k) + " changes successfully updated to CCU2", "debug")
                        else:
                            log(str(k) + " problem trying to update changes to CCU2", "debug")
                        devices_to_check[k]['times_not_seen'] = 0                       # reset not seen counter to 0
                        devices_to_check[k]['first_not_seen'] = None                    # reset first time stamp
                        devices_to_check[k]['presence'] = 'True'                        # update the dict
                        display_msg_on_sensors_display("Hallo " + str(devices_to_check[k]['name']))
                        time.sleep(1)
                        # passing to a DB ->
                    else:
                        log(str(k) + " remains unavailable", "debug")

                # if activated, send a alive signal to ccu2. To activate it, u need to create a
                # system variable ('last_update_') on the ccu2
                #if core.CCU_LAST_UPDATE is not None:
                #    send_ok = send_device_status_to_ccu('last_update_', '"' + time_stamp + '"')

            if counter > 15:           # Rediscover after every x loops
                counter = 0
                request_discovery = True

            time.sleep(core.SLEEP_TIMER)

    except KeyboardInterrupt:
        log("Got signal to STOP", "info")
        if core.PROG_DAEMONIZE:
            startstop(pidfile=core.PDI_FILE, startmsg='stopping daemon', action='stop')
        else:
            print("KeyboardInterrupt received, stopping work ")
        os._exit(0)