Esempio n. 1
0
File: spot.py Progetto: red-ip/spot
def discovery_devices(wait_till_found=True):
    # get the devices from the ccu2
    try:
        while get_local_ip("8.8.8.8") is None:      # check if we have a ip
            time.sleep(1)

        devices_to_check = get_device_to_check()
        if wait_till_found:
            while devices_to_check is None:
                time.sleep(2)
                devices_to_check = get_device_to_check()
        return devices_to_check

    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)
Esempio n. 2
0
File: spot.py Progetto: red-ip/spot
def discovery_sensors(wait_till_found=True):
    # look up for the sensors
    # sensors are stored at core.SPOT_SENSOR
    try:
        while get_local_ip("8.8.8.8") is None:      # check if we have a ip
            time.sleep(1)

        if wait_till_found:
            updclientstart()
            while len(core.SPOT_SENSOR) == 0:
                updclientstart()
                time.sleep(1)
        else:
            updclientstart()
    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)
Esempio n. 3
0
def discovery_devices(wait_till_found=True):
    # get the devices from the ccu2
    try:
        while get_local_ip("8.8.8.8") is None:  # check if we have a ip
            time.sleep(1)

        devices_to_check = get_device_to_check()
        if wait_till_found:
            while devices_to_check is None:
                time.sleep(2)
                devices_to_check = get_device_to_check()
        return devices_to_check

    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)
Esempio n. 4
0
def discovery_sensors(wait_till_found=True):
    # look up for the sensors
    # sensors are stored at core.SPOT_SENSOR
    try:
        while get_local_ip("8.8.8.8") is None:  # check if we have a ip
            time.sleep(1)

        if wait_till_found:
            updclientstart()
            while len(core.SPOT_SENSOR) == 0:
                updclientstart()
                time.sleep(1)
        else:
            updclientstart()
    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)
Esempio n. 5
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)
Esempio n. 6
0
        core.DEBUG_LOG = None

    # Teste Funktion!
    if options.test:
        print "------------------- Test of a function -------------------"
        core.DEBUG_LOG = True
        log("Test of a function, auto debug True", "debug")
        start_local_sensor('d')
        p.error("Function test End")

    if options.stop:
        log("Got the option to stop the Daemon ", "debug")
        if options.no_local_sensor is None:
            stop_local_sensor()
        startstop(pidfile=core.PDI_FILE,
                  startmsg='stopping daemon',
                  action='stop')

    elif options.restart:
        log("Got the option to restart the Daemon ", "debug")
        if options.no_local_sensor is None:
            stop_local_sensor()
            start_local_sensor("-d")
        startstop(pidfile=core.PDI_FILE,
                  startmsg='restarting daemon',
                  action='restart')

    elif options.status:
        log("Got the option to return the Daemon status", "debug")
        if options.no_local_sensor is None:
            start_local_sensor("-i")
Esempio n. 7
0
def main():
    if core.PIFACECAD_SUPPORT:
        import core.piface_display as lcd_display

        lcd_display.init_support_switches()  # Optional
        lcd_display.display_banner()
        print("PIFACECAD_SUPPORT is Active")

    log("checking if ip interface is ready", "debug")
    # wait till we have an ip
    while get_local_ip("8.8.8.8") == None:
        time.sleep(1)
    log("IP-Interface ready!", "debug")

    # start to listing port 55555 for clients
    updserverstart()

    # Bind the socket to the address given on the command line
    sock = getsock()
    sock.listen(1)

    while True:
        time.sleep(1)
        try:
            log("Waiting for connection", "debug")
            sock.settimeout(600)
            connection, client_address = sock.accept()
            sock.settimeout(60)
        except (KeyboardInterrupt, socket.error, 'Bad file descriptor') as e:
            if str(e) == 'KeyboardInterrupt':
                if core.PROG_DAEMONIZE:
                    log(str(e) + " !! STOPPING !!", "info")
                    startstop(pidfile=core.PDI_FILE_SENSOR, startmsg='stopping daemon', action='stop')
                else:
                    print("KeyboardInterrupt received, stopping work ")
                sock.close()
                os._exit(0)
            else:
                if core.PROG_DAEMONIZE:
                    log(str(e) + " !! Restarting after Socket Error !!", "error")
                else:
                    print("Got a error : %s - restarting socket ") % str(e)
                sock.close()
                sock = getsock()
                sock.listen(1)
        try:
            log("Client is connected, IP : " + str(client_address), "debug")
            while True:

                line = read_tcp(connection)

                # test
                valid_command(line)

                if line == "checkdevice":
                    log("command received and accepted : " + str(line), "debug")
                    log("responding with True", "debug")
                    writeline(connection, "True")

                    log("waiting for command parameters", "debug")

                    parameters = readlines_to_dict(connection)
                    log("parameters: " + str(parameters), "debug")
                    # checking if parameter is a mac address, if not delete this item
                    for k, v in parameters.items():
                        if is_mac(k) == False:
                            log("parameters: " + str(k) + " is not a mac address and will be removed", "debug")
                            del parameters[k]    # remove entry with key 'Name'

                    # check if something left
                    number_of_items_in_dic = len(parameters)
                    if number_of_items_in_dic > 0:
                        log("The number of valid parameters (MAC-Address) is: " + str(number_of_items_in_dic), "debug")
                        # we have some mac-addresses to work with
                        # sent a ok to the client
                        writeline(connection, "True")
                        time.sleep(1)
                        # check if the mac can be seen and sent the result back to the client
                        log("Transmitting the results back to the client (Spot collector)", "debug")
                        writeline_dict(connection, check_device_dict(parameters))
                        log("Transition is done", "debug")

                    else:
                        # we didn't find any mac address
                        writeline(connection, "Fals")
                        break       # stopping the processing

                elif line == "displaytext":
                    log("Received text to Display, responding with True", "debug")
                    writeline(connection, "True")
                    line = read_tcp(connection)
                    if core.PIFACECAD_SUPPORT:
                        log("Displaying Text : " + str(line), "debug")
                        lcd_display.display_msg(str(line))
                        writeline(connection, "True")
                    else:
                        log("PIFACECAD_SUPPORT is not Enabled", "debug")
                        writeline(connection, "Fals")

                elif line == "ping":
                    log("Received ping, responding with True", "debug")
                    writeline(connection, "True")

                else:
                    if line != "":
                        log("Unknown command received: discarded : " + str(line), "debug")
                        log("Responding with Fals", "debug")

                    writeline(connection, "Fals")
                    break

        except (KeyboardInterrupt, socket.error, 'Bad file descriptor', UnboundLocalError) as e:
            if str(e) == 'KeyboardInterrupt':
                if core.PROG_DAEMONIZE:
                    startstop(pidfile=core.PDI_FILE_SENSOR, startmsg='stopping daemon', action='stop')
                else:
                    print("KeyboardInterrupt received, stopping work ")
                sock.close()
                os._exit(0)
            else:
                if core.PROG_DAEMONIZE:
                    log("got a error : " + str(e), "error")
                else:
                    print("got a error : %s - restarting socket ") % str(e)
                sock.close()
                sock = getsock()
                sock.listen(1)
Esempio n. 8
0
    if options.pidfile:
        print "------------------- Set PIDfile to " + options.pidfile + " -------------------"
        log("Set PIDfile to " + options.pidfile, "info")
        core.PDI_FILE_SENSOR = str(options.pidfile)

    # Set LOG
    if options.log:
        print "------------------- Log DEBUG manual set to True -------------------"
        core.DEBUG_LOG = True
        log("DEBUG LOG manual set to True", "debug")
    else:
        core.DEBUG_LOG = None

    if options.stop:
        log("Got the option to stop the Daemon ", "debug")
        startstop(pidfile=core.PDI_FILE_SENSOR, startmsg='stopping daemon', action='stop')
    elif options.restart:
        log("Got the option to restart the Daemon ", "debug")
        startstop(pidfile=core.PDI_FILE_SENSOR, startmsg='restarting daemon', action='restart')
    elif options.status:
        log("Got the option to return the Daemon status", "debug")
        startstop(stdout='.', stderr=None, stdin='.',
                  pidfile=core.PDI_FILE_SENSOR, startmsg='status of daemon', action='status')
    elif options.daemonize:
        print "------------------- Preparing to run in daemon mode -------------------"
        log("Preparing to run in daemon mode", "info")
        startstop(pidfile=core.PDI_FILE_SENSOR, action='start')
    else:
        print("Starting in Terminal")

    main()
Esempio n. 9
0
def main():
    if core.PIFACECAD_SUPPORT:
        import core.piface_display as lcd_display

        lcd_display.init_support_switches()  # Optional
        lcd_display.display_banner()
        print("PIFACECAD_SUPPORT is Active")

    if core.RGBLED_SUPPORT:
        import core.rgbled as rgb_led
        rgb_led.set_color('011')
        print("RGBLED_SUPPORT is Active")

    log("checking if ip interface is ready", "debug")
    # wait till we have an ip
    while get_local_ip("8.8.8.8") == None:
        time.sleep(1)
    myip = get_local_ip('8.8.8.8')
    log("IP-Interface ready! - " + str(myip), "debug")

    # start to listing port 55555 for clients
    updserverstart()
    log("Local Hostname is : " + hostname, "info")

    # Bind the socket to the address given on the command line
    sock = getsock()
    sock.listen(1)

    while True:
        time.sleep(1)
        # check if we did lost the IP
        if str(myip) != str(get_local_ip('8.8.8.8')):
            log(
                "ip interface changed - closing socket and tying to get a new IP",
                "info")
            sock.close()
            while get_local_ip("8.8.8.8") == None:
                time.sleep(1)

            myip = get_local_ip('8.8.8.8')
            log("IP-Interface ready! - " + str(myip), "info")
            sock = getsock()
            sock.listen(1)

        try:
            log("Waiting for connection", "debug")
            sock.settimeout(600)
            connection, client_address = sock.accept()
            sock.settimeout(60)
        except (KeyboardInterrupt, socket.error, 'Bad file descriptor') as e:
            if str(e) == 'KeyboardInterrupt':
                if core.PROG_DAEMONIZE:
                    log(str(e) + " !! STOPPING !!", "info")
                    startstop(pidfile=core.PDI_FILE_SENSOR,
                              startmsg='stopping daemon',
                              action='stop')
                else:
                    print("KeyboardInterrupt received, stopping work ")
                sock.close()
                os._exit(0)
            else:
                if core.PROG_DAEMONIZE:
                    log(
                        str(e) + " !! Restarting after Socket Error !!",
                        "error")
                else:
                    print("Got a error : %s - restarting socket ") % str(e)
                sock.close()
                sock = getsock()
                sock.listen(1)
        try:
            log("Client is connected, IP : " + str(client_address), "debug")
            while True:

                line = read_tcp(connection)

                # test
                if valid_command(line) == False:
                    writeline(connection, "Fals")
                    log("Unknown command received: discarded : " + str(line),
                        "debug")
                    log("Responding with Fals", "debug")
                    break

                if line == "checkdevice":
                    log("command received and accepted : " + str(line),
                        "debug")
                    log("responding with True", "debug")
                    writeline(connection, "True")

                    log("waiting for command parameters", "debug")

                    parameters = readlines_to_dict(connection)
                    log("parameters: " + str(parameters), "debug")
                    # checking if parameter is a mac address, if not delete this item
                    for k, v in parameters.items():
                        if is_mac(k) == False:
                            log(
                                "parameters: " + str(k) +
                                " is not a mac address and will be removed",
                                "debug")
                            del parameters[k]  # remove entry with key 'Name'

                    # check if something left
                    number_of_items_in_dic = len(parameters)
                    if number_of_items_in_dic > 0:
                        log(
                            "The number of valid parameters (MAC-Address) is: "
                            + str(number_of_items_in_dic), "debug")
                        # we have some mac-addresses to work with
                        # sent a ok to the client
                        writeline(connection, "True")
                        time.sleep(1)
                        # check if the mac can be seen and sent the result back to the client
                        log(
                            "Transmitting the results back to the client (Spot collector)",
                            "debug")
                        writeline_dict(connection,
                                       check_device_dict(parameters))
                        log("Transition is done", "debug")

                    else:
                        # we didn't find any mac address
                        writeline(connection, "Fals")
                        break  # stopping the processing

                elif line == "displaytext":
                    log("Received text to Display, responding with True",
                        "debug")
                    writeline(connection, "True")
                    line = read_tcp(connection)
                    if core.PIFACECAD_SUPPORT:
                        if str(line) == "ALL OUT":
                            log("Display backlight OFF ", "debug")
                            lcd_display.display_off()
                        else:
                            log("Displaying Text : " + str(line), "debug")
                            lcd_display.display_msg(str(line))
                        writeline(connection, "True")
                    else:
                        log("PIFACECAD_SUPPORT is not Enabled", "debug")
                        writeline(connection, "Fals")

                elif line == "ping":
                    log("Received ping, responding with True", "debug")
                    writeline(connection, "True")

                elif line == "gethostname":
                    log("Get Hostname received, responding with hostname",
                        "debug")
                    writeline(connection, hostname)

                elif line == "rgbled":
                    log("Received RGB Code to Display, responding with True",
                        "debug")
                    writeline(connection, "True")
                    line = read_tcp(connection)
                    if core.RGBLED_SUPPORT:
                        log("Displaying RGB LED : " + str(line), "debug")
                        rgb_led.set_color(line)

                        writeline(connection, "True")
                    else:
                        log("RGBLED_SUPPORT is not Enabled", "debug")
                        writeline(connection, "Fals")
                else:
                    if line != "":
                        log(
                            "Unknown command received: discarded : " +
                            str(line), "debug")
                        log("Responding with Fals", "debug")

                    writeline(connection, "Fals")
                    break

        except (KeyboardInterrupt, socket.error, 'Bad file descriptor',
                UnboundLocalError) as e:
            if str(e) == 'KeyboardInterrupt':
                if core.PROG_DAEMONIZE:
                    startstop(pidfile=core.PDI_FILE_SENSOR,
                              startmsg='stopping daemon',
                              action='stop')
                else:
                    print("KeyboardInterrupt received, stopping work ")
                sock.close()
                os._exit(0)
            else:
                if core.PROG_DAEMONIZE:
                    log("got a error : " + str(e), "error")
                else:
                    print("got a error : %s - restarting socket ") % str(e)

                sock.close()
                sock = getsock()
                sock.listen(1)
            if core.RGBLED_SUPPORT:
                rgb_led.set_color('000')
Esempio n. 10
0
File: spot.py Progetto: 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)