예제 #1
0
def connect(con):
    global register_mode, m2m_mid
    p.rint("--> connecting to illuminum server ...", "l")
    p.set_last_action("connecting")

    context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    c_socket = OpenSSL.SSL.Connection(context, s)
    try:
        c_socket.connect((con.server_ip, con.server_port))
    except:
        p.rint("Could not connect to server", "l")
        p.rint("retrying in 3 sec", "l")
        time.sleep(3)
        return -1

    p.rint("<-- connected to server. ", "l")
    if (register_mode == 0):
        p.rint("--> Starting log-in process", "l")
    else:
        p.rint("--> Begin register process...", "l")
    p.set_last_action("connecting done")

    #### prelogin
    msg = {}
    msg["mid"] = m2m_mid
    msg["cmd"] = "prelogin"
    con.msg_q.append(msg)
    #int("sending prelogin request")

    return c_socket
예제 #2
0
def connect(con):
	global register_mode, m2m_mid
	p.rint("--> connecting to illuminum server ...","l")
	p.set_last_action("connecting")

	context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	c_socket = OpenSSL.SSL.Connection(context, s)
	try:
		c_socket.connect((con.server_ip, con.server_port))
	except:
		p.rint("Could not connect to server","l")
		p.rint("retrying in 3 sec","l")
		time.sleep(3)
		return -1

	p.rint("<-- connected to server. ","l")
	if(register_mode==0):
		p.rint("--> Starting log-in process","l")
	else:
		p.rint("--> Begin register process...","l")
	p.set_last_action("connecting done")

	#### prelogin
	msg = {}
	msg["mid"] = m2m_mid
	msg["cmd"] = "prelogin"
	con.msg_q.append(msg)
	#int("sending prelogin request")

	return c_socket
예제 #3
0
def upload_picture(_con, res):
    global m2m_mid
    #	rint(str(time.time())+" --> this is upload_file")
    #	if(STEP_DEBUG):
    #		p.rint("Step 5. this is upload_file with "+str(len(_con.msg_q))+" msg in q")
    if (len(_con.msg_q) > 0):
        p.rint("skip picture, q full", "d")
        return 1

    p.set_last_action("loading img")
    #if full frame read other file
    try:
        if res != "VGA":
            img = open("/dev/shm/mjpeg/cam_full.jpg", 'rb')
        else:
            img = open("/dev/shm/mjpeg/cam_prev.jpg", 'rb')
    except:
        img = open("ic_camera_black_48dp.png", 'rb')

    i = 0
    while True:
        # should realy read it in once, 10MB buffer
        strng = img.read(_con.max_msg_size - 100)
        if not strng:
            #rint("could not read")
            break

        msg = {}
        msg["cmd"] = "wf"
        msg["fn"] = m2m_mid + "_" + str(
            int(time.time() * 100) % 10000) + '.jpg'
        msg["data"] = base64.b64encode(strng).decode('utf-8')
        msg["sof"] = 0
        if (i == 0):
            msg["sof"] = 1
        msg["eof"] = 0
        msg["msg_id"] = i
        msg["ack"] = 1  #-1
        #msg["ts"]=td
        if (len(strng) != (_con.max_msg_size - 100)):
            msg["eof"] = 1
        #rint('sending('+str(i)+') of '+path+'...')

        msg["td"] = ((time.time(), "send"), (time.time(), "send"))
        _con.msg_q.append(msg)
        #if(STEP_DEBUG):
        #	rint("[A "+time.strftime("%H:%M:%S")+"] Step 6  upload appended message")
        i = i + 1

    p.set_last_action("loading img done")

    #rint(str(time.time())+' all messages for '+path+' are in buffer.. i guess')
    img.close()
    cam.last_picture_taken_ts = time.time()
    return 0
예제 #4
0
def upload_picture(_con, res):
	global m2m_mid
#	rint(str(time.time())+" --> this is upload_file")
#	if(STEP_DEBUG):
#		p.rint("Step 5. this is upload_file with "+str(len(_con.msg_q))+" msg in q")
	if(len(_con.msg_q) > 0):
		p.rint("skip picture, q full","d")
		return 1

	p.set_last_action("loading img")
	#if full frame read other file
	try:
		if res!="VGA":
			img = open("/dev/shm/mjpeg/cam_full.jpg", 'rb')
		else:
			img = open("/dev/shm/mjpeg/cam_prev.jpg", 'rb')
	except:
		img=open("ic_camera_black_48dp.png", 'rb')

	i = 0
	while True:
		# should realy read it in once, 10MB buffer
		strng = img.read(_con.max_msg_size-100)
		if not strng:
			#rint("could not read")
			break

		msg = {}
		msg["cmd"] = "wf"
		msg["fn"] = m2m_mid+"_"+str(int(time.time()*100) % 10000)+'.jpg'
		msg["data"] = base64.b64encode(strng).decode('utf-8')
		msg["sof"] = 0
		if(i == 0):
			msg["sof"] = 1
		msg["eof"] = 0
		msg["msg_id"] = i
		msg["ack"] = 1 #-1
		#msg["ts"]=td
		if(len(strng) != (_con.max_msg_size-100)):
			msg["eof"] = 1
		#rint('sending('+str(i)+') of '+path+'...')

		msg["td"] = ((time.time(), "send"), (time.time(), "send"))
		_con.msg_q.append(msg)
		#if(STEP_DEBUG):
		#	rint("[A "+time.strftime("%H:%M:%S")+"] Step 6  upload appended message")
		i = i+1

	p.set_last_action("loading img done")

	#rint(str(time.time())+' all messages for '+path+' are in buffer.. i guess')
	img.close()
	cam.last_picture_taken_ts = time.time()
	return 0
예제 #5
0
def upload_picture():
#	if(STEP_DEBUG):
	if(len(msg_q_ws) > 0):
		p.rint("skip picture, q full","d")
		return 1

	p.set_last_action("loading img")
	#if full frame read other file
	try:
		img = open("/dev/shm/mjpeg/cam_full.jpg", 'rb')
	except:
		img=open("ic_camera_black_48dp.png", 'rb')

	i = 0
	while True:
		# should realy read it in once, 10MB buffer
		strng = img.read(10000000)
		if not strng:
			#rint("could not read")
			break

		msg = {}
		msg["cmd"] = "wf"
		msg["fn"] = str(int(time.time()*100) % 10000)+'.jpg'
		msg["data"] = base64.b64encode(strng).decode('utf-8')
		msg["sof"] = 0
		if(i == 0):
			msg["sof"] = 1
		msg["eof"] = 0
		msg["msg_id"] = i
		msg["ack"] = 1 #-1
		#msg["ts"]=td
		if(len(strng) != (10000000)):
			msg["eof"] = 1
		#rint('sending('+str(i)+') of '+path+'...')

		msg["td"] = ((time.time(), "send"), (time.time(), "send"))
		for cli in server_ws.clients:
			msg_q_ws.append((msg,cli))
		#if(STEP_DEBUG):
		#	rint("[A "+time.strftime("%H:%M:%S")+"] Step 6  upload appended message")
		i = i+1

	p.set_last_action("loading img done")

	#rint(str(time.time())+' all messages for '+path+' are in buffer.. i guess')
	img.close()
	return 0
예제 #6
0
def parse_incoming_msg(con):
    global register_mode, m2m_pw, m2m_mid
    p.set_last_action("start recv")
    try:
        data = con.sock.recv(con.max_msg_size)
        if (len(data) == 0):
            p.rint("disconnect", "l")
            client_socket = ""
            p.set_last_action("disconnected")

            return -1

        p.rint("received " + str(len(data)) + " byte", "v")
        p.set_last_action("decoding")
        data_dec = data.decode("UTF-8")
        #rint("Data received:"+str(data))
    except:
        p.rint('client_socket.recv detected error', "d")
        return -1

    p.set_last_action("start parse")

    data_dec = con.recv_buffer + data_dec
    data_array = data_dec.split(
        '}'
    )  # might have multiple JSON messages in the buffer or just "{blab}_"

    for a in range(0, len(data_array) - 1):
        data_array[a] += '}'  # add } again, as it got lost during "split"

        try:
            enc = json.loads(data_array[a])
        except:
            p.rint("json decode failed on:" + data_array[a], "l")
            p.set_last_action("decoding bad")

            return -2  # bad message, reconnect

        if (type(enc) is dict):
            con.last_transfer = time.time()
            #rint("json decoded msg")
            #rint(enc)
            # ack ok packets are always send alone, they carry the cmd to acknowledge, but the reason will be a separate msg
            if (enc.get("ack_ok", 0) == 1):
                #rint("this is an ack ok package "+str(len(con.unacknowledged_msg)))
                if (len(con.unacknowledged_msg) > 0):
                    for ele in con.unacknowledged_msg:
                        if (ele[0] == enc.get("cmd",
                                              0)):  # find the right entry
                            con.unacknowledged_msg.remove(ele)
                            if (time.time() - d.last_pic_taken_ts < 15):
                                if (d.estimated_fps == 0):
                                    d.estimated_fps = 1 / (time.time() -
                                                           d.last_pic_taken_ts)
                                else:
                                    d.estimated_fps = 0.90 * d.estimated_fps + 0.10 / (
                                        time.time() - d.last_pic_taken_ts)
                            break
                    #rint("comm wait dec at "+str(time.time())+" --> "+str(len(con.unacknowledged_msg)))
                # recalc timestamp
                if (len(con.unacknowledged_msg) == 0):
                    con.ack_request_ts = 0  # clear ts
                else:
                    con.ack_request_ts = con.unacknowledged_msg[0][
                        1]  # move to latest ts

            ############## M2M CMD ############# prelogin
            elif (enc.get("cmd") == "prelogin" and register_mode == 0):
                p.rint("<-- encryption challange received", "l")
                #### send login
                #rint("received challange "+enc.get("challange"))
                h = hashlib.md5()

                # hash the login with the challange
                h.update(str(m2m_pw + enc.get("challange")).encode("UTF-8"))
                #rint("total to code="+str(pw+enc.get("challange")))
                pw_c = h.hexdigest()
                #rint("result="+pw_c)
                path = os.path.join(
                    os.path.dirname(os.path.realpath(__file__)), "..", "..",
                    ".git")
                v_sec = SEC_VERSION
                #check if there is a user pi
                try:
                    pwd.getpwnam('pi')
                    v_hash = str(
                        subprocess.Popen(
                            [
                                "sudo", "-u", "pi", "git", "--git-dir", path,
                                "log", "--pretty=format:%h", "-n", "1"
                            ],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE).communicate()[0].decode())
                except:
                    v_hash = str(
                        subprocess.Popen(
                            [
                                "sudo", "git", "--git-dir", path, "log",
                                "--pretty=format:%h", "-n", "1"
                            ],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE).communicate()[0].decode())
                p.rint("<-> hash " + str(v_hash), "l")

                msg = {}
                msg["mid"] = m2m_mid
                msg["client_pw"] = pw_c
                msg["cmd"] = "login"
                msg["state"] = trigger.r.s.state
                msg["detection"] = trigger.r.s.detection
                msg["ts"] = time.strftime("%d.%m.%Y || %H:%M:%S")
                msg["ack"] = 1
                msg["v_sec"] = v_sec
                msg["v_hash"] = v_hash
                con.msg_q.append(msg)

            ############## M2M CMD ############# prelogin
            elif (enc.get("cmd") == "prelogin" and register_mode == 1):
                # try to get cam name from raspimjpeg config file
                alias = "SecretCam"
                if (os.path.isfile(
                        os.path.join(
                            os.path.dirname(os.path.realpath(__file__)),
                            "../gpucam/annotation.config"))):
                    file = open(
                        os.path.join(
                            os.path.dirname(os.path.realpath(__file__)),
                            "../gpucam/annotation.config"), "r")
                    file_c = file.readlines()
                    for line in file_c:
                        if (line.find("annotation") == 0
                                and line.find("%04d.%02d.%02d_%02d:%02d:%02d")
                                > 0):
                            alias = line[
                                len("annotation") +
                                1:line.find("%04d.%02d.%02d_%02d:%02d:%02d") -
                                1]
                            break

                ws_login = input("Please enter your username: "******"Hi " + ws_login +
                              ", please enter your userpassword: "******"UTF-8"))
                ws_pw_enc = h.hexdigest()

                h = hashlib.md5()
                h.update(str(ws_pw_enc + enc.get("challange")).encode("UTF-8"))
                ws_pw_ch_enc = h.hexdigest()

                msg = {}
                msg["mid"] = m2m_mid
                msg["login"] = ws_login
                msg["password"] = ws_pw_ch_enc
                msg["m2m_pw"] = m2m_pw
                msg["cmd"] = "register"
                msg["alias"] = alias
                con.msg_q.append(msg)

                #rint(msg)

            ############## M2M CMD ############# login
            elif (enc.get("cmd") == "login"):
                if (enc.get("ok") == 1):
                    con.logged_in = 1

                    r = enc.get("mRed", 0)
                    g = enc.get("mGreen", 0)
                    b = enc.get("mBlue", 0)

                    light.runner.l.d_r = r
                    light.runner.l.d_g = g
                    light.runner.l.d_b = b

                    p.rint("<-- received log-in OK", "l")
                    p.rint(
                        "<-- setting detection to " +
                        str(enc.get("detection")), "l")
                    trigger.set_detection(int(enc.get("detection")))
                else:
                    con.logged_in = 0
                    p.rint("<-- ERROR log-in failed", "l")

            ############## M2M CMD ############# heartbeat
            elif (enc.get("cmd") == "m2m_hb"):
                con.hb_out = 0
                p.rint("<-- connection checked OK", "l")

            ############## M2M CMD ############# set detection
            elif (enc.get("cmd") == "set_detection"):
                p.rint(
                    "<-- received request to change detection state to " +
                    str(enc.get("state")), "l")
                trigger.set_detection(enc.get("state"))

            ############## M2M CMD ############# write file
            elif (enc.get("cmd") == "wf"):
                ignore = 1

            ############## M2M CMD ############# set color
            elif (enc.get("cmd") == "set_color"):
                # avoid light output message, like to many many commands
                r = enc.get("r", 0)
                g = enc.get("g", 0)
                b = enc.get("b", 0)
                light.set_color(r, g, b)
                light.add_q_entry(time.time(), r, g, b,
                                  500)  # 4 sec to dimm to warm orange - now

            ############## M2M CMD ############# set camera intervall
            elif (enc.get("cmd") == "set_interval"):
                if (enc.get("interval", 0) == 0):
                    cam.webview_active = 0
                    gpio.set(gpio.PIN_CAM, 0)
                    p.rint("<-- switching webcam off", "l")
                else:
                    cam.webview_active = 1
                    gpio.set(gpio.PIN_CAM, 1)
                    p.rint("<-- switching webcam on", "l")
                cam.interval = (enc.get("interval", 0))
                cam.quality = (enc.get("qual", "HD"))
                if (enc.get("alarm_while_streaming", "no_alarm") == "alarm"):
                    cam.alarm_while_streaming = 1
                else:
                    cam.alarm_while_streaming = 0
######### SPY MODE #########
                if (enc.get("interval", 0) > 0):
                    (r, g, b) = light.runner.get_color()
                    light.set_old_color(
                        r, g, b,
                        time.time() + light.get_delay_off()
                    )  # set the color to which we return as soon as the webfeed is closed
                    light.add_q_entry(
                        time.time(), 0, 255, 0,
                        1000)  # 4 sec to dimm to off - in 10 min from now
                else:
                    light.add_q_entry(
                        time.time(), -1, -1, -1,
                        1000)  # 4 sec to dimm to off - in 10 min from now
######### SPY MODE #########

############## M2M CMD ############# register
            elif (enc.get("cmd") == "register"):
                if (enc.get("ok", 0) == 1):
                    p.rint("<-- successful registered, sending sign in", "l")
                    register_mode = 0
                else:
                    p.rint(
                        "<-- registration was not successful, status: " +
                        str(enc.get("ok")) + ". Starting over", "l")

                msg = {}
                msg["mid"] = m2m_mid
                msg["cmd"] = "prelogin"
                con.msg_q.append(msg)

            ############## M2M CMD ############# update parameter
            elif (enc.get("cmd") == "update_parameter"):
                p.rint("<-- Received Parameter update from server", "l")
                if (enc.get("alarm_while_streaming", "no_alarm") == "alarm"):
                    cam.alarm_while_streaming = 1
                else:
                    cam.alarm_while_streaming = 0
                cam.interval = (enc.get("interval", 0))
                cam.quality = (enc.get("qual", "HD"))

                # save old parameter
                old_with_cam = config.with_cam
                old_with_lights = config.with_lights
                old_with_ext = config.with_ext
                old_with_pir = config.with_pir

                # save new parameter
                config.with_pir = int(enc.get("with_pir", "0"))
                config.with_lights = int(enc.get("with_lights", "0"))
                config.with_ext = int(enc.get("with_ext", "0"))
                config.with_cam = int(enc.get("with_cam", "0"))

                # re-starting the light and trigger with new parameter, if different
                if (config.with_lights != old_with_lights):
                    p.rint("=== (re)start light, as configuration has changed",
                           "l")
                    light.restart(config)
                    time.sleep(1)

                if (config.with_pir != old_with_pir):
                    p.rint(
                        "=== (re)start trigger, as configuration has changed",
                        "l")
                    trigger.restart(config, gpio)

            ############## M2M CMD #############  get the git version
            elif (enc.get("cmd") == "get_version"):
                path = os.path.join(
                    os.path.dirname(os.path.realpath(__file__)), "..", "..",
                    ".git")
                try:
                    pwd.getpwnam('pi')
                    v_short = str(
                        subprocess.Popen([
                            "sudo", "-u", "pi", "git", "--git-dir", path,
                            "rev-list", "HEAD", "--count"
                        ],
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         stdin=subprocess.PIPE).communicate()
                        [0].decode()).replace("\n", "")
                    v_hash = str(
                        subprocess.Popen(
                            [
                                "sudo", "-u", "pi", "git", "--git-dir", path,
                                "log", "--pretty=format:%h", "-n", "1"
                            ],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE).communicate()[0].decode())
                except:
                    v_short = str(
                        subprocess.Popen([
                            "sudo", "git", "--git-dir", path, "rev-list",
                            "HEAD", "--count"
                        ],
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         stdin=subprocess.PIPE).communicate()
                        [0].decode()).replace("\n", "")
                    v_hash = str(
                        subprocess.Popen(
                            [
                                "sudo", "git", "--git-dir", path, "log",
                                "--pretty=format:%h", "-n", "1"
                            ],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE).communicate()[0].decode())

                p.rint(
                    "<-> version request received from server, returning " +
                    str(v_hash), "l")

                msg = {}
                msg["mid"] = m2m_mid
                msg["cmd"] = enc.get("cmd")
                msg["v_short"] = v_short
                msg["v_hash"] = v_hash
                con.msg_q.append(msg)

            ############## M2M CMD #############  run a git update
            elif (enc.get("cmd") == "git_update"):
                p.rint("<-- update request received from server", "l")
                # remount root rw
                rw()
                path = os.path.join(
                    os.path.dirname(os.path.realpath(__file__)), "..", "..",
                    ".git")
                # run the update
                try:
                    pwd.getpwnam('pi')
                    result = subprocess.Popen(
                        ["sudo", "-u", "pi", "git", "pull"],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                        stdin=subprocess.PIPE).communicate()
                except:
                    result = subprocess.Popen(
                        ["sudo", "git", "pull"],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                        stdin=subprocess.PIPE).communicate()
                ret_res = result[0].decode().replace("\n", "")
                # get new version
                try:
                    pwd.getpwnam('pi')
                    v_short = str(
                        subprocess.Popen([
                            "sudo", "-u", "pi", "git", "--git-dir", path,
                            "rev-list", "HEAD", "--count"
                        ],
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         stdin=subprocess.PIPE).communicate()
                        [0].decode()).replace("\n", "")
                    v_hash = str(
                        subprocess.Popen(
                            [
                                "sudo", "-u", "pi", "git", "--git-dir", path,
                                "log", "--pretty=format:%h", "-n", "1"
                            ],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE).communicate()[0].decode())
                except:
                    v_short = str(
                        subprocess.Popen([
                            "sudo"
                            "git", "--git-dir", path, "rev-list", "HEAD",
                            "--count"
                        ],
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         stdin=subprocess.PIPE).communicate()
                        [0].decode()).replace("\n", "")
                    v_hash = str(
                        subprocess.Popen(
                            [
                                "sudo", "git", "--git-dir", path, "log",
                                "--pretty=format:%h", "-n", "1"
                            ],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE).communicate()[0].decode())

                msg = {}
                msg["mid"] = m2m_mid
                msg["cmd"] = enc.get("cmd")
                msg["v_short"] = v_short
                msg["v_hash"] = v_hash
                msg["cmd_result"] = ret_res
                con.msg_q.append(msg)

            ############## M2M CMD ############## run a reboot
            elif (enc.get("cmd") == "reboot"):
                con.sock.shutdown()
                con.sock.close()
                print("<- ============================")
                print("<- ======== rebooting =========")
                print("<- ============================")
                result = str(
                    subprocess.Popen("reboot",
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE,
                                     stdin=subprocess.PIPE).communicate()
                    [0].decode()).replace("\n", "")

            ############## M2M CMD #############  set a pin
            elif (enc.get("cmd") == "toggle_external_pin"):
                state = 0
                if (str(enc.get("state", 0)) == "1"):
                    state = 1
                p.rint("<-- switching external pin to " + str(state), "l")
                gpio.set(gpio.PIN_USER, state)

                msg = {}
                msg["mid"] = m2m_mid
                msg["cmd"] = enc.get("cmd")
                msg["ok"] = "1"
                con.msg_q.append(msg)

            ############## M2M CMD ############## set alias
            elif (enc.get("cmd") == "set_alias"):
                alias = enc.get("alias", "-")
                p.rint("<-- Trying to set a new name: " + str(alias), "l")
                msg = {}
                msg["mid"] = m2m_mid
                msg["cmd"] = enc.get("cmd")
                msg["ok"] = "-1"

                try:
                    # remount root rw
                    rw()
                    # run update
                    path = os.path.join(
                        os.path.dirname(os.path.realpath(__file__)), "..",
                        "gpucam")
                    if (os.path.isfile(os.path.join(path,
                                                    "annotation.config"))):
                        file = open(os.path.join(path, "annotation.config"),
                                    "w")
                        file.write(
                            "annotation " + alias +
                            " %04d.%02d.%02d_%02d:%02d:%02d \nanno_background false"
                        )
                        file.close()
                        subprocess.Popen(os.path.join(path,
                                                      "generate_config.sh"),
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         stdin=subprocess.PIPE).communicate()
                        msg["ok"] = "1"
                        p.rint("--> Setting new alias, ok", "l")
                except:
                    import sys, traceback
                    print("sys:")
                    print(str(sys.exc_info()[0]))
                    print(str(sys.exc_info()[1]))
                    print(str(repr(traceback.format_tb(sys.exc_info()[2]))))
                    print("--> setting new name failed")
                con.msg_q.append(msg)

            ############## M2M CMD #############  this is the monitoring section, if the device is set as a monitor it will receive the state_change from all other m2ms in the same area
            elif (enc.get("cmd") == "state_change"):

                ### update the state that we've saved, or add client to list
                f = 0
                for m in w.clients:
                    if (m.mid == enc.get("mid")):
                        m.state = enc.get("state")
                        f = 1
                        break
                if (f == 0):
                    w.clients.append(
                        watcher_m2m(mid=enc.get("mid"),
                                    state=enc.get("state")))

                ### check all states
                all_state = 0  #0=idle, 1=alert, 2=detection disabled, idle, 3=detection disabled, movement
                for m in w.clients:
                    if (m.state % 2 == 1):
                        all_state = 1
                        break
                if (all_state == 0):
                    #we are convinced that there is no movement anymore
                    if (w.handle_movements_stopped != ""):
                        w.handle_movements_stopped.cancel()
                    if (w.handle_movements_started != ""):
                        w.handle_movements_started.cancel()
                    w.handle_movements_stopped = external.movements_stopped()
                    w.handle_movements_stopped.start()
                else:
                    # stop callback that would switch off stuff and call the switch on
                    if (w.handle_movements_stopped != ""):
                        w.handle_movements_stopped.cancel()
                    if (w.handle_movements_started != ""):
                        w.handle_movements_started.cancel()
                    w.handle_movements_started = external.movements_started()
                    w.handle_movements_started.start()

            ############## M2M CMD ############# backup
            else:
                p.rint("<-- unsupported command received:" + enc.get("cmd"),
                       "l")

        #end of "if"
    # end of "for"

    if (data_array[len(data_array) - 1] == ""):
        #if data contained a full message and ended with closing tag, we a$
        con.recv_buffer = ""
    else:
        # but if we grabbed something like 1.5 messages, we should buffer $
        con.recv_buffer = data_array[len(data_array) - 1]
        #rint("using buffer!")

    p.set_last_action("recv done")
    return 0
예제 #7
0
                    if (msg_i["cmd"] == "register"):
                        p.rint("r--> equesting registration", "d")
                        msg = msg_i
                        con.msg_q.remove(msg_i)
                    if (msg_i["cmd"] == "login"):
                        p.rint("--> sending encrypted login", "d")
                        msg = msg_i
                        con.msg_q.remove(msg_i)

            else:  # in this case we have a message waiting and we are logged in and the unacknowledged_msg_queue is short / empty
                msg = con.msg_q[0]
                con.msg_q.remove(msg)

            if (msg != ""):
                #rint("A message is ready to send")
                p.set_last_action("json / encode / sendall")

                send_msg = json.dumps(msg)
                send_msg_enc = send_msg.encode("UTF-8")

                if (msg.get("cmd", " ") == "wf"):
                    if (msg.get("eof", 0) == 1):
                        if (TIMING_DEBUG):
                            if (time.time() - d.last_pic_taken_ts > 15):
                                d.active_since_ts = 0
                                d.estimated_fps = 0
                                p.rint("reset fps", "d")

                            d.last_pic_taken_ts = time.time()
                            d.frames_uploaded_since_active = d.frames_uploaded_since_active + 1
예제 #8
0
def parse_incoming_msg(con):
	global register_mode, m2m_pw, m2m_mid
	p.set_last_action("start recv")
	try:
		data = con.sock.recv(con.max_msg_size)
		if(len(data) == 0):
			p.rint("disconnect","l")
			client_socket = ""
			p.set_last_action("disconnected")

			return -1

		p.rint("received "+str(len(data))+" byte", "v")
		p.set_last_action("decoding")
		data_dec = data.decode("UTF-8")
		#rint("Data received:"+str(data))
	except:
		p.rint('client_socket.recv detected error',"d")
		return -1

	p.set_last_action("start parse")

	data_dec = con.recv_buffer+data_dec
	data_array = data_dec.split('}')	# might have multiple JSON messages in the buffer or just "{blab}_"

	for a in range(0, len(data_array)-1):
		data_array[a] += '}'	# add } again, as it got lost during "split"

		try:
			enc = json.loads(data_array[a])
		except:
			p.rint("json decode failed on:"+data_array[a],"l")
			p.set_last_action("decoding bad")

			return -2 # bad message, reconnect

		if(type(enc) is dict):
			con.last_transfer = time.time()
			#rint("json decoded msg")
			#rint(enc)
			# ack ok packets are always send alone, they carry the cmd to acknowledge, but the reason will be a separate msg
			if(enc.get("ack_ok", 0) == 1):
				#rint("this is an ack ok package "+str(len(con.unacknowledged_msg)))
				if(len(con.unacknowledged_msg) > 0):
					for ele in con.unacknowledged_msg:
						if(ele[0] == enc.get("cmd", 0)): # find the right entry
							con.unacknowledged_msg.remove(ele)
							if(time.time()-d.last_pic_taken_ts<15):
								if(d.estimated_fps==0):
									d.estimated_fps = 1/(time.time()-d.last_pic_taken_ts)
								else:
									d.estimated_fps = 0.90 * d.estimated_fps + 0.10 / (time.time()-d.last_pic_taken_ts)
							break
					#rint("comm wait dec at "+str(time.time())+" --> "+str(len(con.unacknowledged_msg)))
				# recalc timestamp
				if(len(con.unacknowledged_msg) == 0):
					con.ack_request_ts = 0					# clear ts
				else:
					con.ack_request_ts = con.unacknowledged_msg[0][1]		# move to latest ts

			elif(enc.get("cmd") == "prelogin" and register_mode==0):
				p.rint("<-- encryption challange received","l")
				#### send login
				#rint("received challange "+enc.get("challange"))
				h = hashlib.md5()

				# hash the login with the challange
				h.update(str(m2m_pw+enc.get("challange")).encode("UTF-8"))
				#rint("total to code="+str(pw+enc.get("challange")))
				pw_c = h.hexdigest()
				#rint("result="+pw_c)
				path=os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","..",".git")
				v_sec=SEC_VERSION
				#check if there is a user pi
				try: 
					pwd.getpwnam('pi')
					v_hash=str(subprocess.Popen(["sudo","-u","pi", "git", "--git-dir", path, "log", "--pretty=format:%h", "-n", "1"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode())
				except:
					v_hash=str(subprocess.Popen(["sudo", "git", "--git-dir", path, "log", "--pretty=format:%h", "-n", "1"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode())
				p.rint("<-> hash "+str(v_hash),"l")

				msg = {}
				msg["mid"] = m2m_mid
				msg["client_pw"] = pw_c
				msg["cmd"] = "login"
				msg["state"] = trigger.r.s.state
				msg["detection"] = trigger.r.s.detection
				msg["ts"] = time.strftime("%d.%m.%Y || %H:%M:%S")
				msg["ack"] = 1
				msg["v_sec"] = v_sec
				msg["v_hash"] = v_hash
				con.msg_q.append(msg)

			elif(enc.get("cmd") == "prelogin" and register_mode==1):
				# try to get cam name from raspimjpeg config file
				alias="SecretCam"
				if(os.path.isfile(os.path.join(os.path.dirname(os.path.realpath(__file__)),"../gpucam/annotation.config"))):
					file=open(os.path.join(os.path.dirname(os.path.realpath(__file__)),"../gpucam/annotation.config"),"r")
					file_c=file.readlines()
					for line in file_c:
						if(line.find("annotation")==0 and line.find("%04d.%02d.%02d_%02d:%02d:%02d")>0):
							alias=line[len("annotation")+1:line.find("%04d.%02d.%02d_%02d:%02d:%02d")-1]
							break

				ws_login = input("Please enter your username: "******"Hi "+ws_login+", please enter your userpassword: "******"UTF-8"))
				ws_pw_enc = h.hexdigest()

				h = hashlib.md5()
				h.update(str(ws_pw_enc+enc.get("challange")).encode("UTF-8"))
				ws_pw_ch_enc = h.hexdigest()

				msg = {}
				msg["mid"] = m2m_mid
				msg["login"] = ws_login
				msg["password"] = ws_pw_ch_enc
				msg["m2m_pw"] = m2m_pw
				msg["cmd"] = "register"
				msg["alias"] = alias
				con.msg_q.append(msg)

				#rint(msg)

			elif(enc.get("cmd") == "login"):
				if(enc.get("ok") == 1):
					con.logged_in = 1

					r = enc.get("mRed",0)
					g = enc.get("mGreen",0)
					b = enc.get("mBlue",0)
	
					light.runner.l.d_r = r
					light.runner.l.d_g = g
					light.runner.l.d_b = b

					p.rint("<-- received log-in OK","l")				
					p.rint("<-- setting detection to "+str(enc.get("detection")),"l")
					trigger.set_detection(int(enc.get("detection")))
				else:
					con.logged_in = 0
					p.rint("<-- ERROR log-in failed","l")
			elif(enc.get("cmd") == "m2m_hb"):
				con.hb_out = 0
				p.rint("<-- connection checked OK","l")
			elif(enc.get("cmd") == "set_detection"):
				p.rint("<-- received request to change detection state to "+str(enc.get("state")),"l")
				trigger.set_detection(enc.get("state"))
			elif(enc.get("cmd") == "wf"):
				ignore = 1
			elif(enc.get("cmd") == "set_color"):
				# avoid light output message, like to many many commands
				r = enc.get("r", 0)
				g = enc.get("g", 0)
				b = enc.get("b", 0)
				light.set_color(r,g,b)
				light.add_q_entry(time.time(), r, g, b, 500) # 4 sec to dimm to warm orange - now

			elif(enc.get("cmd") == "set_interval"):
				if(enc.get("interval", 0) == 0):
					cam.webview_active = 0
					gpio.set(gpio.PIN_CAM,0)
					p.rint("<-- switching webcam off","l")
				else:
					cam.webview_active = 1
					gpio.set(gpio.PIN_CAM,1)
					p.rint("<-- switching webcam on","l")
				cam.interval = (enc.get("interval", 0))
				cam.quality = (enc.get("qual", "HD"))
				if(enc.get("alarm_while_streaming","no_alarm")=="alarm"):
					cam.alarm_while_streaming = 1
				else:
					cam.alarm_while_streaming = 0
######### SPY MODE #########
				if(enc.get("interval",0)>0):
					(r,g,b) = light.runner.get_color()
					light.set_old_color(r,g,b,time.time()+light.get_delay_off()) # set the color to which we return as soon as the webfeed is closed
					light.add_q_entry(time.time(),0,255,0,1000) # 4 sec to dimm to off - in 10 min from now
				else:
					light.add_q_entry(time.time(),-1,-1,-1,1000) # 4 sec to dimm to off - in 10 min from now
######### SPY MODE #########
			elif(enc.get("cmd") == "register"):
				if(enc.get("ok",0) == 1):
					p.rint("<-- successful registered, sending sign in","l")
					register_mode=0
				else:
					p.rint("<-- registration was not successful, status: "+str(enc.get("ok"))+". Starting over","l")

				msg = {}
				msg["mid"] = m2m_mid
				msg["cmd"] = "prelogin"
				con.msg_q.append(msg)
	
			elif(enc.get("cmd") == "update_parameter"):
				p.rint("<-- Received Parameter update from server","l")
				if(enc.get("alarm_while_streaming","no_alarm")=="alarm"):
					cam.alarm_while_streaming = 1
				else:
					cam.alarm_while_streaming = 0
				cam.interval = (enc.get("interval", 0))
				cam.quality = (enc.get("qual", "HD"))

				# save old parameter
				old_with_cam = config.with_cam
				old_with_lights = config.with_lights
				old_with_ext = config.with_ext
				old_with_pir = config.with_pir

				# save new parameter
				config.with_pir = int(enc.get("with_pir", "0"))
				config.with_lights = int(enc.get("with_lights", "0"))
				config.with_ext = int(enc.get("with_ext", "0"))
				config.with_cam = int(enc.get("with_cam", "0"))

				# re-starting the light and trigger with new parameter, if different
				if(config.with_lights != old_with_lights):
					p.rint("=== (re)start light, as configuration has changed","l")
					light.restart(config)
					time.sleep(1)
				
				if(config.with_pir != old_with_pir):
					p.rint("=== (re)start trigger, as configuration has changed","l")
					trigger.restart(config,gpio)


			# get the git version
			elif(enc.get("cmd") == "get_version"):
				path=os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","..",".git")
				try: 
					pwd.getpwnam('pi')
					v_short=str(subprocess.Popen(["sudo","-u","pi", "git","--git-dir", path, "rev-list", "HEAD", "--count"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode()).replace("\n","")
					v_hash=str(subprocess.Popen(["sudo","-u","pi", "git","--git-dir", path,"log", "--pretty=format:%h", "-n", "1"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode())
				except:
					v_short=str(subprocess.Popen(["sudo", "git","--git-dir", path, "rev-list", "HEAD", "--count"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode()).replace("\n","")
					v_hash=str(subprocess.Popen(["sudo", "git","--git-dir", path,"log", "--pretty=format:%h", "-n", "1"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode())
	
				p.rint("<-> version request received from server, returning "+str(v_hash),"l")

				msg = {}
				msg["mid"] = m2m_mid
				msg["cmd"] = enc.get("cmd")
				msg["v_short"] = v_short
				msg["v_hash"] = v_hash
				con.msg_q.append(msg)

			# run a git update
			elif(enc.get("cmd") == "git_update"):
				p.rint("<-- update request received from server","l")
				# remount root rw
				rw() 
				path=os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","..",".git")
				# run the update
				try: 
					pwd.getpwnam('pi')
					result=subprocess.Popen(["sudo","-u","pi", "git", "pull"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()
				except:
					result=subprocess.Popen(["sudo", "git", "pull"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()
				ret_res=result[0].decode().replace("\n","")
				# get new version
				try: 
					pwd.getpwnam('pi')
					v_short=str(subprocess.Popen(["sudo","-u","pi", "git","--git-dir", path, "rev-list", "HEAD", "--count"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode()).replace("\n","")
					v_hash=str(subprocess.Popen(["sudo","-u","pi", "git","--git-dir", path,"log", "--pretty=format:%h", "-n", "1"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode())
				except:
					v_short=str(subprocess.Popen(["sudo" "git","--git-dir", path, "rev-list", "HEAD", "--count"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode()).replace("\n","")
					v_hash=str(subprocess.Popen(["sudo", "git","--git-dir", path,"log", "--pretty=format:%h", "-n", "1"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode())


				msg = {}
				msg["mid"] = m2m_mid
				msg["cmd"] = enc.get("cmd")
				msg["v_short"] = v_short
				msg["v_hash"] = v_hash
				msg["cmd_result"] = ret_res
				con.msg_q.append(msg)

			# run a reboot
			elif(enc.get("cmd") == "reboot"):
				con.sock.shutdown()
				con.sock.close()
				print("<- ============================")
				print("<- ======== rebooting =========")
				print("<- ============================")
				result=str(subprocess.Popen("reboot",stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode()).replace("\n","")

				
			# set a pin 
			elif(enc.get("cmd") == "toggle_external_pin"):
				state = 0
				if(str(enc.get("state",0))=="1"):
					state = 1
				p.rint("<-- switching external pin to "+str(state),"l")
				gpio.set(gpio.PIN_USER,state)

				msg = {}
				msg["mid"] = m2m_mid
				msg["cmd"] = enc.get("cmd")
				msg["ok"] = "1"
				con.msg_q.append(msg)

			# set alias
			elif(enc.get("cmd") == "set_alias"):
				alias = enc.get("alias","-")
				p.rint("<-- Trying to set a new name: "+str(alias),"l")
				msg = {}
				msg["mid"] = m2m_mid
				msg["cmd"] = enc.get("cmd")
				msg["ok"] = "-1"
			
				try:
					# remount root rw
					rw() 
					# run update
					path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","gpucam")
					if(os.path.isfile(os.path.join(path,"annotation.config"))):
						file=open(os.path.join(path,"annotation.config"),"w")
						file.write("annotation "+alias+" %04d.%02d.%02d_%02d:%02d:%02d \nanno_background false")
						file.close()
						subprocess.Popen(os.path.join(path,"generate_config.sh"),stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()
						msg["ok"] = "1"
						p.rint("--> Setting new alias, ok","l")
				except:
					import sys, traceback
					print("sys:")
					print(str(sys.exc_info()[0]))
					print(str(sys.exc_info()[1]))
					print(str(repr(traceback.format_tb(sys.exc_info()[2]))))
					print("--> setting new name failed")
				con.msg_q.append(msg)

			else:
				p.rint("<-- unsopported command received:"+enc.get("cmd"),"l")


		#end of "if"
	# end of "for"

	if(data_array[len(data_array)-1] == ""):
		#if data contained a full message and ended with closing tag, we a$
		con.recv_buffer = ""
	else:
		# but if we grabbed something like 1.5 messages, we should buffer $
		con.recv_buffer = data_array[len(data_array)-1]
		#rint("using buffer!")

	p.set_last_action("recv done")
	return 0
예제 #9
0
					if(msg_i["cmd"] == "register"):
						p.rint("r--> equesting registration","d")
						msg = msg_i
						con.msg_q.remove(msg_i)
					if(msg_i["cmd"] == "login"):
						p.rint("--> sending encrypted login","d")
						msg = msg_i
						con.msg_q.remove(msg_i)

			else:	# in this case we have a message waiting and we are logged in and the unacknowledged_msg_queue is short / empty
				msg = con.msg_q[0]
				con.msg_q.remove(msg)

			if(msg != ""):
				#rint("A message is ready to send")
				p.set_last_action("json / encode / sendall")

				send_msg = json.dumps(msg)
				send_msg_enc = send_msg.encode("UTF-8")


				if(msg.get("cmd", " ") == "wf"):
					if(msg.get("eof", 0) == 1):
						if(TIMING_DEBUG):
							if(time.time()-d.last_pic_taken_ts > 15):
								d.active_since_ts = 0
								d.estimated_fps = 0
								p.rint("reset fps","d")

							d.last_pic_taken_ts = time.time()
							d.frames_uploaded_since_active = d.frames_uploaded_since_active+1