예제 #1
0
	def get_state(self, area, account):
		if(area=="" or account==""):
			p.err("get_state was callen with area and or account empty")
			return -1
		try:
			self.connect()
			with self.connection.cursor() as cursor:
				# Create a new record
				req = "SELECT COUNT(*) FROM area_state WHERE `account` = %s AND `area`=%s"
				cursor.execute(req, (str(account), str(area)) )
				result = cursor.fetchone()
				#rint(result)
				if(result["COUNT(*)"] == 1):
					req = "SELECT `state` FROM  `area_state` WHERE  `account` = %s AND `area`=%s"
					cursor.execute(req, (str(account), str(area)) )
					result = cursor.fetchone()
				else: 
					p.rint("get state Count was "+str(result["COUNT(*)"])+"!=1", "d")
					p.rint(req%(str(account), str(area)), "d")
					result = -1
		except:
			self.he()
			result = -1
		self.close()
		return result
예제 #2
0
	def print_all(self):
		reactivate=0
		for p_rule in p.print_out:
			if(p_rule.shortcut=="r"):
				if(not(p_rule.state)):
					p_rule.state=1
					reactivate=1
				break
			
		now=time.localtime()[3]*3600+time.localtime()[4]*60+time.localtime()[5]
		p.rint("== I'm the rule manager, I have "+str(len(self.data))+" accounts registered at ts: "+str(now)+"==","r") 
		i=1
		for a in self.data:
			if(a.account!=""):
				p.rint("","r")
				p.rint("|+ Account "+str(i)+"/"+str(len(self.data)),"r")
				a.print_account()
				i+=1
		p.rint("","r")
		p.rint("== End of rule manager output ==","r")
		
		#### stop output again
		if(reactivate):
			for p_rule in p.print_out:
				if(p_rule.shortcut=="r"):
					p_rule.state=0
					break
예제 #3
0
	def get_ws_data(self, login):
		#rint("get data mid:"+mid)
		try:
			self.connect()
			#rint("try:")
			with self.connection.cursor() as cursor:
				# Read a single record
				#rint("get_data gen req:")
				req = "SELECT COUNT(*) FROM ws WHERE login=%s or email=%s"
				cursor.execute(req, (str(login), str(login)))
				result_c = cursor.fetchone()
				#rint(result)
				#rint(result)
				if(result_c["COUNT(*)"] == 1):
					req = "SELECT  pw, account, email, login FROM ws WHERE login=%s or email=%s"
					#rint(req)
					cursor.execute(req, (str(login), str(login)))
					#rint("setting result to ")
					result = cursor.fetchone()
				else:
					result = -1
					p.rint("count not 1, it is "+str(result_c["COUNT(*)"]), "d")
					p.rint(req, "d")
				#rint(result)
		except:
			self.he()
			result = -2
		self.close()
		return result
예제 #4
0
	def return_to_old(self,ms):
		if(self.l.o_lifetime>time.time()):
			p.rint("LIGHT return_to_old, goto backup color cause lifetime is "+str(self.l.o_lifetime-time.time()),"r")
			self.add_q_entry(time.time(),self.l.o_rd,self.l.o_gd,self.l.o_bd,ms)	# first move back to old color as it is still valid
			self.add_q_entry(self.l.o_lifetime,0,0,0,ms)				# remember to turn off at some point
		else:
			p.rint("LIGHT return_to_old, goto 0/0/0 lifetime is over","r")
			self.add_q_entry(time.time(),0,0,0,ms)					# return to nothing, as the old color is not valid, turn off
예제 #5
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
예제 #6
0
	def rm_override(self, override):
		del_list=[]
		if(override=="*"):
			self.has_override_detection_on=0
		elif(override=="/"):
			self.has_override_detection_off=0

		for r in self.rules:
			if(r.conn==override):
				del_list.append(r)

		for r in del_list:
			p.rint("[A_ws  "+time.strftime("%H:%M:%S")+"] Remove rule " + str(r.id) + "","r")
			self.rm_rule(r.id)
예제 #7
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
예제 #8
0
	def rm_rule(self, id):
		found=0
		for r in self.rules:
			if(r.id==id):
				self.rules.remove(r)
				found=1
				break;
			
		if(not(found)):
			for r in self.sub_rules:
				if(r.id==id):
					self.sub_rules.remove(r)
					break;
		# delete from db
		if(self.db!=""):
			self.db.rm_rule(id)		
			if(not(self.db.rm_rule(id)==0)):
				p.rint("Delete rule "+str(id)+" failed","r")
예제 #9
0
	def __init__(self):
		self.recv_buffer = ""
		self.sock = ""
		self.last_transfer = 0
		self.logged_in = 0			# avoiding that we send stuff without being logged in
		self.hb_out = 0
		self.hb_out_ts = 0
		self.msg_q = []
		self.unacknowledged_msg = []
		self.ack_request_ts = 0		# used to save the time when the last message, requesting a ACK was send

		self.max_msg_size = 10024000 # 10 MB?
		self.server_ip = "illuminum.de"
		self.server_port = 9875
		if(os.path.isfile(os.path.join(os.path.dirname(os.path.realpath(__file__)),"experimental"))):
			self.server_port = 9775
			p.rint("!!!!!!!!! RUNNING ON EXPERIMENTAL PORT !!!!!!!!!!!","l")
		self.server_timeout = 15
		self.max_outstanding_acks = 2
예제 #10
0
	def run(self,config,gpio):
		self.alive = True
		try:
			# basic config 
			busy=1
			p.rint("TRIGGER: thread started","l")
			if(not(config.with_pir)):
				p.rint("TRIGGER: configured without PIR","l")
				
			while self.alive:
		
				# cpu spacing
				if(busy==0):
					time.sleep(0.1)
				busy=0

				# try to get the pin state
				try:
					# sensor offline
					if(not(config.with_pir)):
						gpio_state=4
					else:
						gpio_state=gpio.get(gpio.PIN_PIR)
				except:
					p.rint("TRIGGER: Trouble reading GPIO, trying to reconfigure","d")
					break

				# set detection on / off
				if(self.s.state_change_event):
					self.s.state=-1 #to be refreshed by the part below	
					self.s.state_change_event=0
					self.s.last_triggered=0 # make sure the refresh happens fast

				# react on pin state change				
				if(gpio_state != self.s.state and self.s.last_triggered+self.s.timeout<time.time()):
					self.s.last_triggered=time.time()
					self.s.state=gpio_state
					busy=1

					p.rint("TRIGGER Switch to state '"+m2m_state[self.s.state]+"' with detection '"+det_state[self.s.detection]+"'","t")

					# call everyone who subscribed to our update list
					for callb in self.s.callback_action:
						if(not(type(callb) is str)):
							try:
								callb("state_change",(self.s.state,self.s.detection))
							except:
								print("TRIGGER callback crashed")

			# while
		except:
			print("TRIGGER CRASHED")
		self.is_stop = True
예제 #11
0
	def dimm_to(self,r,g,b,ms):
		p.rint("LIGHT, dimming to "+str(r)+"/"+str(g)+"/"+str(b),"r")
		# selection is 0-255 based, but it really means 0-100%
		######## calculate target value 0-255 (half-log) out of the input value 0-255 (linear) #######
		_r=r/2.55
		_g=g/2.55
		_b=b/2.55

		intens=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,27,28,29,30,31,32,33,34,35,36,38,39,40,41,43,44,45,47,48,50,51,53,55,57,58,60,62,64,66,68,70,73,75,77,80,82,85,88,91,93,96,99,103,106,109,113,116,120,124,128,132,136,140,145,150,154,159,164,170,175,181,186,192,198,205,211,218,225,232,239,247,255]

		_r=int(max(min(len(intens)-1,_r),0)) 			# just to make sure that we don't take an element outside the array 0-100
		_g=int(max(min(len(intens)-1,_g),0))
		_b=int(max(min(len(intens)-1,_b),0))

		self.l.t_r=intens[_r]							# convert percentage to half-logarithmical brightness
		self.l.t_g=intens[_g]
		self.l.t_b=intens[_b]
		######## calculate target value 0-255 (half-log) out of the input value 0-255 (linear) #######

		max_diff=max([abs(self.l.t_g-self.l.c_g),abs(self.l.t_r-self.l.c_r),abs(self.l.t_b-self.l.c_b)]) # find out what color has to do the most steps, this will determine the time between our single steps

		if(max_diff>0):							# just go on, if at least one has to change the color by at least one step
			self.l.o_rd=self.l.c_rd						# save current color as old
			self.l.o_gd=self.l.c_gd
			self.l.o_bd=self.l.c_bd

			self.l.c_rd=r						# current target linear 0-255 color in the structure
			self.l.c_gd=g
			self.l.c_bd=b


			self.l.s_t=time.time()					# copy the starttime
			self.l.t_t=self.l.s_t+ms/1000					# set start time as starttime + time to dimm

			self.l.state=1 							# state 1 means dimming
			self.l.ĺast_ts=0							# last_ts=0 will result in instant execution of the first dimming step in the loop above
			self.l.ms_step=ms/max_diff				# calc the time between the dimming steps as total time / max steps
			#print("ms:"+str(ms)+" ms_step:"+str(self.l.ms_step))
			self.l.s_r = self.l.c_r						# set start color as current color
			self.l.s_g = self.l.c_g
			self.l.s_b = self.l.c_b
			p.rint("LIGHT start at "+str(time.time())+" to "+str(self.l.c_r)+"/"+str(self.l.c_g)+"/"+str(self.l.c_b)+" -> "+str(self.l.t_r)+"/"+str(self.l.t_g)+"/"+str(self.l.t_b)+" within "+str(ms),"r")
예제 #12
0
	def print_account(self,m_dict=0):
		if(m_dict!=1):
			p.rint("|"+p.bcolors.FAIL+"+ This is account '"+self.account+"' I have "+str(len(self.areas))+" areas:"+p.bcolors.ENDC,"r")
		else:
			ret_dict={}
		i=1
		for a in self.areas:
			if(a.area!=""):
				if(m_dict!=1):
					p.rint("|","r")
					p.rint("||"+p.bcolors.WARNING+"+ Area "+str(i)+"/"+str(len(self.areas))+p.bcolors.ENDC,"r")  
					a.print_rules()
				else:
					ret_dict[i]=a.print_rules(dict=1)
				i+=1
		if(m_dict!=1):
			p.rint("|","r")
			p.rint("|+ my next timebased trigger event is at '"+str(self.next_ts)+"'","r")
		else:
			return ret_dict
예제 #13
0
파일: u_gpio.py 프로젝트: pdf7/illuminum
	def setup(self):
		if(rpi_support):
			p.rint("configuring raspberry pins","g")
			GPIO.setwarnings(False)
			GPIO.setmode(GPIO.BOARD)

			self.PIN_PIR 		= 7
			self.PIN_MOVEMENT 	= 11	
			self.PIN_DETECTION 	= 13
			self.PIN_USER 		= 15
			self.PIN_CAM 		= 16

			GPIO.setup(self.PIN_PIR, 		GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
			GPIO.setup(self.PIN_MOVEMENT, 		GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
			GPIO.setup(self.PIN_DETECTION, 		GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
			GPIO.setup(self.PIN_USER, 		GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
			GPIO.setup(self.PIN_CAM, 		GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

		elif(fsys_support):
			p.rint("configuring fsys pins","g")

			# XIO-P0   408    13
			# XIO-P1   409    14
			# XIO-P2   410    15
			# XIO-P3   411    16
			# XIO-P4   412    17
			# XIO-P5   413    18
			# XIO-P6   414    19
			# XIO-P7   415    20

			self.PIN_PIR 		= 408
			self.PIN_MOVEMENT 	= 409	
			self.PIN_DETECTION 	= 410
			self.PIN_USER 		= 411
			self.PIN_CAM 		= 412

			self.fsys_export(self.PIN_PIR)
			self.fsys_export(self.PIN_MOVEMENT)
			self.fsys_export(self.PIN_DETECTION)
			self.fsys_export(self.PIN_USER)
			self.fsys_export(self.PIN_CAM)
예제 #14
0
    def __init__(self):
        self.recv_buffer = ""
        self.sock = ""
        self.last_transfer = 0
        self.logged_in = 0  # avoiding that we send stuff without being logged in
        self.hb_out = 0
        self.hb_out_ts = 0
        self.msg_q = []
        self.unacknowledged_msg = []
        self.ack_request_ts = 0  # used to save the time when the last message, requesting a ACK was send

        self.max_msg_size = 10024000  # 10 MB?
        self.server_ip = "illuminum.de"
        self.server_port = 9875
        if (os.path.isfile(
                os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             "experimental"))):
            self.server_port = 9775
            p.rint("!!!!!!!!! RUNNING ON EXPERIMENTAL PORT !!!!!!!!!!!", "l")
        self.server_timeout = 15
        self.max_outstanding_acks = 2
예제 #15
0
def start_server ():
#	context = SSL.Context(SSL.TLSv1_2_METHOD)
#	context = SSL.Context(SSL.TLSv1_METHOD)
	
#	context.use_privatekey_file('startssl.key')
#	context.use_certificate_file('startssl.cert')
#	context.use_certificate_chain_file('startssl.cert')
	
	s_n = socket.socket()
	s_n.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s_n.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
#	s = SSL.Connection(context, s_n)
	s=s_n

	s.bind(('', PORT))
	s.listen(MAX_CLIENTS) # max clients

	p.rint("[S_wss "+time.strftime("%H:%M:%S")+"] Waiting on wss_clients on Port "+str(PORT),"l")
	while 1:
		conn, addr = s.accept()
		try:
			#connstream = ssl.wrap_socket(conn, server_side=True, certfile="cert", keyfile="key", ssl_version=ssl.PROTOCOL_TLSv1)
			# generate new client
			new_client=ws_clients(conn.getpeername()[1],conn.getpeername()[0]) # port, ip
			new_client.ws=WebSocket(conn) 
			# append it
			clients.append(new_client)
			p.rint("[S_wss "+time.strftime("%H:%M:%S")+"] -> Connection from: "+ str(addr[0])+". Serving "+str(len(clients))+" ws_clients now","l")
			threading.Thread(target = handle, args = (new_client,addr)).start()
			# send every subscr
			for callb in callback_con:
				callb("connect",new_client)
		except Exception as n:
			p.rint("[S_wss "+time.strftime("%H:%M:%S")+"] exception before starting connect thread","d")
			print(n)
예제 #16
0
def check_clients():
	p.rint("[S_m2m "+time.strftime("%H:%M:%S")+"] -> checking clients","r")
	for cli in clients:
		if(cli.last_comm>0 and cli.last_comm+cli.comm_timeout<time.time()):
			p.rint("[S_m2m "+time.strftime("%H:%M:%S")+"] disconnecting client as last comm is older than timeout","r")
			disconnect(cli)
	p.rint("[S_m2m "+time.strftime("%H:%M:%S")+"] -> checking clients done","r")
예제 #17
0
파일: u_gpio.py 프로젝트: pdf7/illuminum
	def set(self,pin,level):
		if(rpi_support):
			if(level==0):
				p.rint("setting pin "+str(pin)+" weak low","g")
				GPIO.setup(pin,	GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
			else:
				p.rint("setting pin "+str(pin)+" high","g")
				GPIO.setup(pin, GPIO.OUT)
				GPIO.output(pin,1)
		elif(fsys_support and pin>=408 and pin<=415):
			try:
				gpiopin = "gpio%s" % (str(pin))
				f = open("/sys/class/gpio/"+gpiopin+"/direction","w")
				f.write("out")
				f.close()
				f = open("/sys/class/gpio/"+gpiopin+"/value","w")
				if(level==0):
					f.write("0")
				else:
					f.write("1")
				f.close()
			except:
				p.warn("failed to write to pin "+str(pin))
예제 #18
0
파일: server_ws.py 프로젝트: pdf7/illuminum
    def _sendBuffer(self, buff):
        size = len(buff)
        tosend = size
        already_sent = 0

        while tosend > 0:
            try:
                # i should be able to send a bytearray
                sent = self.sock.send(buff[already_sent:])
                p.rint("send " + str(sent) + " bytes", "w")
                if sent == 0:
                    raise RuntimeError("socket connection broken")

                already_sent += sent
                tosend -= sent

            except socket.error as e:
                # if we have full buffers then wait for them to drain and try again
                if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]:
                    return buff[already_sent:]
                else:
                    raise e

        return None
예제 #19
0
	def _sendBuffer(self, buff):
		size = len(buff)
		tosend = size
		already_sent = 0

		while tosend > 0:
			try:
				# i should be able to send a bytearray
				sent = self.sock.send(buff[already_sent:])
				p.rint("send "+str(sent)+" bytes","w")
				if sent == 0:
					raise RuntimeError("socket connection broken")

				already_sent += sent
				tosend -= sent

			except socket.error as e:
				# if we have full buffers then wait for them to drain and try again
				if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]:
					return buff[already_sent:]
				else:
					raise e

		return None
예제 #20
0
def start_server ():
	context = SSL.Context(SSL.TLSv1_METHOD)
#	context = SSL.Context(SSL.TLSv1_2_METHOD)
	context.use_privatekey_file('startssl.key')
	context.use_certificate_file('startssl.cert')
	
	s_n = socket.socket()
	s_n.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s_n.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
	s = SSL.Connection(context, s_n)

	s.bind(('', SERVER_PORT))
	s.listen(MAX_CONN) # max clients
	p.rint("[S_m2m "+time.strftime("%H:%M:%S")+"] Waiting on m2m_clients on port "+str(SERVER_PORT),"l")
	while 1:
		conn, addr = s.accept()
		#rint(conn.recv(65535))
		new_client=m2m_clients(conn)
		clients.append(new_client)
		p.rint("[S_m2m "+time.strftime("%H:%M:%S")+"] -> Connection from: "+ str(addr[0])+". Serving "+str(len(clients))+" m2m_clients now","l")
		threading.Thread(target = handle, args = (new_client, addr)).start()
		# for what ever that might be good for
		for callb in callback_con:
			callb("connect",new_client)
예제 #21
0
def recv_ws_msg_dq_handle():
	ret=0
	if(len(recv_ws_msg_q)>0):
		ret=1
		recv_msg=recv_ws_msg_q[0]
		recv_ws_msg_q.remove(recv_msg)
		data = recv_msg[0]
		ws = recv_msg[1]
		try:
			try:
				enc=json.loads(data)
			except:
				enc=""
				p.rint("-d--> json decoding failed","d")

			if(type(enc) is dict):
				if(enc.get("cmd") == "ping"):
					msg={}
					msg["cmd"]="pong"
					msg_q_ws.append((msg,ws))
				elif(enc.get("cmd") == "img"):
					p.rint("upload pic","d")
					upload_picture()
				elif(enc.get("cmd") == "ctrl"):
					dl=enc.get("dl",0)
					dr=enc.get("dr",0)
					pl=enc.get("pl",0)
					pr=enc.get("pr",0)
					arduino.digitalWrite(14,dr) # in3, dir righ
					arduino.setPWM(0,pr) # en3, en right 

					arduino.digitalWrite(13,dl) # in1 dir left
					arduino.setPWM(9,pl) # en1, left

					print(str(dl)+"/"+str(dr)+"/"+str(pl)+"/"+str(pr))
				else:
					p.rint("<-- unsopported command received:"+enc.get("cmd"),"l")
		except:
			p.err("sys:")
			p.err(str(sys.exc_info()[0]))
			p.err(str(sys.exc_info()[1]))
			p.err(str(repr(traceback.format_tb(sys.exc_info()[2]))))
	return ret
예제 #22
0
파일: server_ws.py 프로젝트: pdf7/illuminum
def start_server():
    #	context = SSL.Context(SSL.TLSv1_2_METHOD)
    context = SSL.Context(SSL.TLSv1_METHOD)

    context.use_privatekey_file('startssl.key')
    context.use_certificate_file('startssl.cert')
    context.use_certificate_chain_file('startssl.cert')

    s_n = socket.socket()
    s_n.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s_n.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
    s = SSL.Connection(context, s_n)

    s.bind(('', PORT))
    s.listen(MAX_CLIENTS)  # max clients

    p.rint(
        "[S_wss " + time.strftime("%H:%M:%S") +
        "] Waiting on wss_clients on Port " + str(PORT), "l")
    while 1:
        conn, addr = s.accept()
        try:
            #connstream = ssl.wrap_socket(conn, server_side=True, certfile="cert", keyfile="key", ssl_version=ssl.PROTOCOL_TLSv1)
            # generate new client
            new_client = ws_clients(conn.getpeername()[1],
                                    conn.getpeername()[0])  # port, ip
            new_client.ws = WebSocket(conn)
            # append it
            clients.append(new_client)
            p.rint(
                "[S_wss " + time.strftime("%H:%M:%S") +
                "] -> Connection from: " + str(addr[0]) + ". Serving " +
                str(len(clients)) + " ws_clients now", "l")
            threading.Thread(target=handle, args=(new_client, addr)).start()
            # send every subscr
            for callb in callback_con:
                callb("connect", new_client)
        except Exception as n:
            p.rint(
                "[S_wss " + time.strftime("%H:%M:%S") +
                "] exception before starting connect thread", "d")
            print(n)
예제 #23
0
def stop_server():
	send_data_all_clients(bytes("shutdown","UTF-8"))
	p.rint("[S_m2m "+time.strftime("%H:%M:%S")+"] -> shutdown","d")
	os._exit(1)
예제 #24
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
예제 #25
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
예제 #26
0
def trigger_handle(event, data):
    global cam
    global con
    global register_mode

    if (event == "state_change"):
        _state = data[0]
        _detection = data[1]
        #rint("setting in client.py "+str(_state)+" /  "+str(_detection))

        if (register_mode == 0):
            p.rint(
                "Switch to state '" + trigger.m2m_state[_state] +
                "' with detection '" + trigger.det_state[_detection] + "'",
                "v")

        msg = {}
        msg["cmd"] = event
        msg["state"] = _state
        msg["detection"] = _detection

        ##### delete ALL old status msg, and place the current status in the queue #########
        for m in con.msg_q:
            if (msg["cmd"] == m["cmd"]):
                con.msg_q.remove(m)

        # avoid message on alarm if alarm_while_streaming=0 at various conditions
        send_msg = 1
        if (_state > 0 and _detection > 0 and cam.alarm_while_streaming == 0):
            if (cam.webview_active == 1):  # no alarm while streaming
                send_msg = 0
            elif (time.time() - cam.last_picture_taken_ts <
                  5):  # dead - time after streaming, 5 sec
                send_msg = 0
        if (send_msg):
            # if we have a new status, check the complete queue if we have old unsend stati and remove them first, they aren't valid anymore
            for msg_i in con.msg_q:
                if (msg_i["cmd"] == msg["cmd"]):
                    con.msg_q.remove(msg_i)
            con.msg_q.append(msg)
        ##### delete ALL old status msg, and place the current status in the queue #########

        ##### light dimming #########
        # if we change the state of the sensor, we should most likely change the light
        # clear all old dimming actions
        light.clear_q()
        # set new color
        if (_detection == 0 and _state == 1):  # deactive and motion
            if (
                    cam.webview_active == 0
            ):  # only change color if the webcam is no running to avoid that we switch the light during movement, while the videofeed is running
                light.add_q_entry(time.time(), light.runner.l.d_r,
                                  light.runner.l.d_g, light.runner.l.d_b,
                                  4000)  # 4 sec to dimm to default color - now
            else:
                (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
        elif (_detection == 0 and _state == 0):  # deactive and no motion
            if (
                    cam.webview_active == 0
            ):  # only change color if the webcam is no running to avoid that we switch the light during movement, while the videofeed is running
                light.add_q_entry(
                    time.time() + light.get_delay_off(), 0, 0, 0,
                    4000)  # 4 sec to dimm to off - in 10 min from now
            else:
                (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
            #rint("[A "+time.strftime("%H:%M:%S")+"] setting lights off to "+str((datetime.datetime.fromtimestamp(int((time.time()+light.get_delay_off())))).strftime('%y_%m_%d %H:%M:%S')))
        elif (_detection == 1 and _state == 1):  # alarm, go red, now
            if (
                    cam.webview_active == 0
            ):  # only change color if the webcam is no running to avoid that we switch the light during movement, while the videofeed is running
                light.add_q_entry(time.time(), 100, 0, 0, 4000)
            else:
                light.set_old_color(
                    100, 0, 0,
                    time.time() + light.get_delay_off()
                )  # set the color to which we return as soon as the webfeed is closed
        elif (_detection == 1 and _state == 0):  # off while nobody is there
            if (
                    cam.webview_active == 0
            ):  # only change color if the webcam is no running to avoid that we switch the light during movement, while the videofeed is running
                light.add_q_entry(time.time(), 0, 0, 0, 4000)
            else:
                (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 dimming #########

        ##### camera picture upload #########
        if (_state > 0 and _detection > 0):  # alarm state
            if (cam.alarm_in_alarm_state == 0):
                cam.alarm_in_alarm_state = 1
                cam.alarm_pictures_remaining = 5
        else:  # state==0 or detection==0, leave the picture remaining so we can finish uploading all 5 pictures per alarm
            cam.alarm_in_alarm_state = 0
        ##### camera picture upload #########

        ##### set the gpio pins #####
        g_state = 0
        if (_state > 0):
            g_state = 1
        gpio.set(gpio.PIN_MOVEMENT, g_state)

        g_detection = 0
        if (_detection > 0):
            g_detection = 1
        gpio.set(gpio.PIN_DETECTION, g_detection)
예제 #27
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
예제 #28
0
파일: server_ws.py 프로젝트: pdf7/illuminum
def handle(client, addr):
    t1 = 0
    t2 = 0

    busy = 1
    client.last_comm = time.time()
    #lock = threading.Lock()
    while client.alive:
        try:
            rList, wList, xList = select([client.ws.sock], [client.ws.sock],
                                         [client.ws.sock], 3)
        except:
            break

        if (busy == 0):
            time.sleep(0.03)
        busy = 0
        ######################## SEND ###########################
        if (len(wList) > 0):
            try:
                t1 = time.time()
                while client.ws.sendq:
                    busy = 1
                    opcode, payload = client.ws.sendq.popleft()
                    remaining = client.ws._sendBuffer(payload)
                    if remaining is not None:
                        client.ws.sendq.appendleft((opcode, remaining))
                        break
                    else:
                        if opcode == CLOSE:
                            for callb in callback_con:
                                callb("disconnect", client)
                t1 = time.time() - t1
            except Exception as n:
                disconnect(client)
        ######################## SEND ###########################
        ####################### RECEIVE ##########################
        if (len(rList) > 0):
            busy = 1
            lt = ""
            try:
                lt = "start _handleData()"
                t2 = time.time()
                if (client.ws._handleData() == -1):
                    disconnect(client)

                while (client.ws.data_ready == True):
                    lt = "Start getMessage()"
                    msg = client.ws.getMessage(
                    )  # getMessage will unset the data_ready flag if no data left
                    if (client.ws.data_ready == True):
                        #print(msg) # <-- prints the received data
                        lt = "Start callb"
                        for callb in callback_msg:
                            callb(msg, client)
                        #client.ws.data_ready=False
                        #client.ws.last_data=""
                t2 = time.time() - t2

            except (SSL.ZeroReturnError, SSL.SysCallError):
                # regular good SSL disconnect
                disconnect(client)
            except ValueError as err:
                # disconnct while handshake
                disconnect(client)
            except Exception as n:
                print("except while read in server_ws, our status ", end="")
                print(lt)
                print("sys:", end="")
                print(sys.exc_info()[0])
                print(sys.exc_info()[1])
                print(repr(traceback.format_tb(sys.exc_info()[2])))
                print("")

                disconnect(client)
        ####################### RECEIVE ##########################
        ######################## ERROR ##########################
        if (len(xList) > 0):
            busy = 1
            disconnect(client)
        ######################## ERROR ##########################
        ######################## MAINTAINANCE ##########################
        if (time.time() - client.debug_ts > 1):
            #if(time.time()-client.debug_ts>10):
            #	print("woohoo its me")
            #	print(t1)
            #	print(t2)
            client.debug_ts = time.time()
        ######################## MAINTAINANCE ##########################
    # end of while 1
    p.rint(
        "[S_wss " + time.strftime("%H:%M:%S") + "] -> Client " +
        str(client.login) + " closed: " + str(client.ip), "l")
예제 #29
0
파일: light.py 프로젝트: pdf7/illuminum
	def set_old_color(self,r,g,b,lifetime):
		p.rint("LIGHT setting old color "+str(r)+"/"+str(g)+"/"+str(b)+" in "+str(lifetime-time.time())+" sec","r")
		self.l.o_rd=r
		self.l.o_gd=g
		self.l.o_bd=b
		self.l.o_lifetime = lifetime
예제 #30
0
def add_q_entry(when,r,g,b,duration_ms):
	p.rint("LIGHT, add_q_entry: setting color "+str(r)+"/"+str(g)+"/"+str(b)+" in "+str(when-time.time())+" sec from now","r")
	runner.add_q_entry(when,r,g,b,duration_ms)
예제 #31
0
	f_content='class login:\r\n	def __init__(self):\r\n		self.pw="'+m2m_pw+'"\n		self.mid="'+m2m_mid+'"\n'
	
	rw()
	file=open(os.path.join(os.path.dirname(os.path.realpath(__file__)),"login.py"),"w")
	file.write(f_content)
	file.close()
		
	return (m2m_mid,m2m_pw)

###################### try import login #######################
register_mode=0
if(os.path.isfile(os.path.join(os.path.dirname(os.path.realpath(__file__)),"login.py"))):
	from login import *
	l = login()					# login
	m2m_pw=l.pw
	p.rint("STARTUP, login.py found, password loaded","l")

	try: 
		p.rint("STARTUP, login.py found, mid loaded","l")
		m2m_mid = l.mid
	except:
		p.rint("STARTUP, login.py without mid loaded, create new one","l")
		(m2m_mid,m2m_pw) = create_login("", m2m_pw)

else:
	register_mode=1
	# first time connection, create a password and send it to the server
	(m2m_mid,m2m_pw) = create_login("", "")
	p.rint("STARTUP, no login.py found, running in register mode","l")

예제 #32
0
	def set_detection(self,_detection):
		self.state_change_event=1
		self.detection=_detection
		p.rint("TRIGGER detection set to "+str(det_state[_detection]),"l")
예제 #33
0
	def print_rules(self,bars=1,account_info=1,print_out=1,formating=1,header=1,dict=0):
		if(dict):
			ret_dict={}
			ret_dict["name"]=self.area
			ret_dict["rules"]=[]
			ret_dict["subrules"]=[]
			header=0
			print_out=0
			account_info=0
			bars=0
			formating=0
		else:
			ret=""

		if(bars):
			ret+="|||+ "
		
		if(account_info):
			ret+="This is area '"+self.area+"' on account '"+self.account+"'. I have "
			ret+=str(len(self.rules))+" active rules and "+str(len(self.sub_rules))+" subrules\r\n"
		i=1
		if(bars):
			ret+="(r)|||+ "
		if(header):
			ret+="Rules: <br>(protection activ if at least one is true)\r\n"
		for r in self.rules:
			## marker
			g=0
			if(bars):
				ret+="(r)||||- "
			if(self.eval_rule(r.conn,r.arg1,r.arg2,10,1,r.id)>=1):
				if(formating):
					ret+="<g>"
				g=1
			else:
				if(formating):
					ret+="<r>"
			## marker
			txt=self.explain_rule(r,g,i)
			if(dict):
				ret_dict["rules"].append((r.id,r.conn,r.arg1,r.arg2,g))
			else:
				ret+=txt
			## marker
			if(g):
				if(formating):
					ret+="</g>\r\n"
			else:
				if(formating):
					ret+="</r>\r\n"
			## marker
			i+=1
			
		if(len(self.rules)==0):
			if(bars):
				ret+="(r)||||- "
			if(formating):		
				ret+="<g>none</g>\r\n"

		i=1
		if(bars):
			ret+="(r)|||\r\n"
			ret+="(r)|||+ "
		if(header):
			ret+="Sub-Rules:\r\n"
		
		for r in self.sub_rules:
		## marker
			g=0
			if(bars):
				ret+="(r)||||- "
			if(self.eval_rule(r.conn,r.arg1,r.arg2,10,1,r.id)>=1):
				if(formating):
					ret+="<g>"
				g=1
			else:
				if(formating):
					ret+="<r>"
			## marker
			txt=self.explain_rule(r,g,i)
			if(dict):
				ret_dict["subrules"].append((r.id,txt,g))
			else:
				ret+=txt
			## marker
			if(g):
				if(formating):
					ret+="</g>"
			else:
				if(formating):
					ret+="</r>"
			## marker
			i+=1
			if(dict!=1):
				if((i-1)<len(self.sub_rules)):
					ret+="\r\n"
			
		if(len(self.sub_rules)==0):
			if(bars):
				ret+="(r)||||- "
			if(formating):
				ret+="<g>none</g>"
			
		if(print_out):
			p.rint(ret,"r")
			return 0
		
		if(dict):
			return ret_dict
		return ret
예제 #34
0
def trigger_handle(event, data):
	global cam
	global con
	global register_mode

	if(event == "state_change"):
		_state = data[0]
		_detection = data[1]
		#rint("setting in client.py "+str(_state)+" /  "+str(_detection))

		if(register_mode==0):
			p.rint("Switch to state '"+trigger.m2m_state[_state]+"' with detection '"+trigger.det_state[_detection]+"'","v")

		msg = {}
		msg["cmd"] = event
		msg["state"] = _state
		msg["detection"] = _detection

		##### delete ALL old status msg, and place the current status in the queue #########
		for m in con.msg_q:
			if(msg["cmd"] == m["cmd"]):
				con.msg_q.remove(m)

		# avoid message on alarm if alarm_while_streaming=0 at various conditions
		send_msg=1
		if(_state>0 and _detection>0 and cam.alarm_while_streaming==0): 
			if(cam.webview_active==1):				# no alarm while streaming
				send_msg=0
			elif(time.time()-cam.last_picture_taken_ts<5):	# dead - time after streaming, 5 sec
				send_msg=0
		if(send_msg):
			# if we have a new status, check the complete queue if we have old unsend stati and remove them first, they aren't valid anymore
			for msg_i in con.msg_q:
				if(msg_i["cmd"]==msg["cmd"]):
					con.msg_q.remove(msg_i)
			con.msg_q.append(msg)
		##### delete ALL old status msg, and place the current status in the queue #########

		##### light dimming #########
		# if we change the state of the sensor, we should most likely change the light
		# clear all old dimming actions
		if (0): #illumino disabled :(
			light.clear_q()
			# set new color
			if(_detection == 0 and _state == 1): # deactive and motion
				if(cam.webview_active == 0): # only change color if the webcam is no running to avoid that we switch the light during movement, while the videofeed is running
					light.add_q_entry(time.time(), light.runner.l.d_r, light.runner.l.d_g, light.runner.l.d_b, 4000) # 4 sec to dimm to default color - now
				else:
					(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
			elif(_detection == 0 and _state == 0): # deactive and no motion
				if(cam.webview_active == 0): # only change color if the webcam is no running to avoid that we switch the light during movement, while the videofeed is running
					light.add_q_entry(time.time()+light.get_delay_off(), 0, 0, 0, 4000) # 4 sec to dimm to off - in 10 min from now
				else:
					(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
				#rint("[A "+time.strftime("%H:%M:%S")+"] setting lights off to "+str((datetime.datetime.fromtimestamp(int((time.time()+light.get_delay_off())))).strftime('%y_%m_%d %H:%M:%S')))
			elif(_detection == 1 and _state == 1): # alarm, go red, now
				if(cam.webview_active == 0): # only change color if the webcam is no running to avoid that we switch the light during movement, while the videofeed is running
					light.add_q_entry(time.time(), 100, 0, 0, 4000)
				else:
					light.set_old_color(100, 0, 0,time.time()+light.get_delay_off())# set the color to which we return as soon as the webfeed is closed
			elif(_detection == 1 and _state == 0): # off while nobody is there
				if(cam.webview_active == 0): # only change color if the webcam is no running to avoid that we switch the light during movement, while the videofeed is running
					light.add_q_entry(time.time(), 0, 0, 0, 4000)
				else:
					(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 dimming #########

		##### camera picture upload #########
		if(_state > 0 and _detection > 0): # alarm state
			if(cam.alarm_in_alarm_state == 0):
				cam.alarm_in_alarm_state = 1
				cam.alarm_pictures_remaining = 5
		else: # state==0 or detection==0, leave the picture remaining so we can finish uploading all 5 pictures per alarm
			cam.alarm_in_alarm_state = 0
		##### camera picture upload #########

		##### set the gpio pins #####
		g_state = 0
		if(_state > 0):
			g_state = 1
		gpio.set(gpio.PIN_MOVEMENT,g_state)

		g_detection = 0
		if(_detection > 0):
			g_detection = 1
		gpio.set(gpio.PIN_DETECTION,g_detection)
예제 #35
0
def handle (client, addr):
	lock = threading.Lock()
	busy=1
	while 1:
		try:
			rList, wList, xList = select([client.conn], [client.conn], [client.conn], 3)
		except Exception as n:
			p.warn("S_m2m Select() return an exception for connection "+str(addr)+":"+str(n))
			disconnect(client)
			break

		if(busy==0):
			time.sleep(0.03)
		busy=0
		######################## SEND ###########################
		if(len(wList)>0):
			try:
				if(len(client.sendq)>0):
					busy=1
					payload=client.sendq[0]
					client.sendq.remove(payload)
					
					msg= bytearray()
					# add payload
					for d in bytearray(payload):
				            msg.append(d)
					client.conn.send(msg)
					p.rint("m2m send "+str(len(msg))+" bytes","w")

			except Exception as n:
				print("exception!!!")
				print(n)
			
				disconnect(client)

		######################## SEND ###########################
		####################### RECEIVE ##########################
		if(len(rList)>0):
			busy=1
			lt=""
			try:
				#print(addr,end="")
				#print("server_m2m: rList has "+str(len(rList))+" Elements")
				lt="start _handleData()"
				res = recv_data(client, MAX_MSG_SIZE)
				if(res<0):
					disconnect(client)

			except Exception as n:
				print("exception!!!")
				print(n)

				print("")
				print("except, our status ",end="")
				print(lt,end="")
				print(" sys:",end="")
				print(sys.exc_info()[0])
				print("")

				disconnect(client)

		####################### RECEIVE ##########################
		######################## ERROR ##########################
		if(len(xList)>0):
			busy=1
			try:
				print("exception!!!")
				if client.conn:
					client.conn.close()
				try:
					for callb in callback_con:
						callb("disconnect",client)
				except:
					break;
					pass

				try:
					clients.remove(client)
				except:
					break;
					pass
			except:
				pass
			break;
		######################## ERROR ##########################
		######################## MAINTAINANCE ##########################                
		if(time.time()-client.debug_ts>1):
			client.debug_ts=time.time()
		######################## MAINTAINANCE ##########################
	p.rint("[S_m2m "+time.strftime("%H:%M:%S")+"] -> Client closed:"+str(addr),"l")
예제 #36
0
파일: light.py 프로젝트: pdf7/illuminum
	def run(self,config):		
		self.config = config

		while(1):
			p.rint("LIGHT, thread started","l")
			self.alive = True


			# Create NeoPixel object with appropriate configuration.
			if(str(self.config.with_lights) == "1"):
				p.rint("LIGHT, configured with NEO usage","l")
				if(self.neo_support and self.neo_loaded!=1):
					p.rint("LIGHT, neopixel supported, starting","l")
					strip = Adafruit_NeoPixel(self.neo_LED_COUNT, self.neo_LED_PIN, self.neo_LED_FREQ_HZ, self.neo_LED_DMA, self.neo_LED_INVERT, self.neo_LED_BRIGHTNESS)
					# Intialize the library (must be called once before other functions).
					strip.begin()
					strip.show()
					self.neo_loaded = 1 	# avoid loading it twice
				elif(self.neo_support):
					p.rint("LIGHT, neopixel already loaded","l")
				else:
					p.rint("LIGHT, ERROR neopixel not supported","l")
			elif(str(self.config.with_lights) == "2"):
				p.rint("LIGHT, configured with PWM usage","l")
				if(self.pwm_support):
					p.rint("LIGHT, PWM supported, starting","l")
					wiringpi.wiringPiSetupPhys()
					wiringpi.pinMode(12,2)
				else:
					p.rint("LIGHT, ERROR PWM not supported","l")
			elif(str(self.config.with_lights) == "3"):
				p.rint("LIGHT, configured with i2c usage","l")
				if(self.i2c_support and self.i2c_loaded!=1):
					p.rint("LIGHT, i2c supported, starting","l")
					salsa = arduino_bridge.connection()
					salsa.setup_pwm_output(0)
					salsa.setup_pwm_output(1)
					salsa.setup_pwm_output(2)
					salsa.setup_pwm_output(3)
					self.i2c_loaded = 1
				elif(self.i2c_loaded == 1):
					p.rint("LIGHT, i2c already loaded","l")
				else:
					p.rint("LIGHT, ERROR i2c not supported","l")
			else:
				p.rint("LIGHT, started without pwm and neo and i2c","l")
				p.rint("LIGHT, selection was "+str(self.config.with_lights),"l")

			while self.alive:
				### ------------ check if we have something to do ------------ ###
				if(len(self.light_dimming_q) > 0):
					for data in self.light_dimming_q:
						if(data[0]<=time.time()):
							light_action=data
							self.light_dimming_q.remove(data)
							if(light_action[1]==-1 and light_action[2]==-1 and light_action[3]==-1):
								self.return_to_old(light_action[4])
							else:
								self.dimm_to(light_action[1],light_action[2],light_action[3],light_action[4])
				### ------------ check if we have something to do ------------ ###

				if(self.l.state==1):						# state= 1 means dimming is active
					if(time.time()>=self.l.last_ts+self.l.ms_step/1000):	# last_ts holds time of last event, ms_step the time between two dimm steps, 
											# if that sum is smaller than NOW - we have work
						self.l.last_ts=time.time()			# refresh last_ts to now
						differ_r=self.l.s_r-self.l.t_r			# caluclate the difference of each color between the start and the end color
						differ_g=self.l.s_g-self.l.t_g
						differ_b=self.l.s_b-self.l.t_b
						differ_time=(self.l.t_t-self.l.s_t)		# calulate the total time between the start and end 
											#(this should be the same as the "dimm time" specified by the user)
						if(differ_time>0):			# if the user set instant switch, this time will be 0. avoid division by zero
							ratio=(time.time()-self.l.s_t)/(self.l.t_t-self.l.s_t)	# ratio of the time that has passed, should be 0..1
						else:
							ratio=1
						if(ratio<1):				# if ratio is below 1 we are still in the middle of the dimming
							if(LED_DEBUG):
								print(".", end="")
							self.l.c_r=int(self.l.s_r-ratio*differ_r)	# refresh the r,g,b parts to the current dimm ratio (minus since we did a "self.l.s_r - self.l.t_r")
							self.l.c_g=int(self.l.s_g-ratio*differ_g)
							self.l.c_b=int(self.l.s_b-ratio*differ_b)

						else:					# ratio is bigger than one, time has passed, set it to target color
							self.l.c_r=int(self.l.t_r)
							self.l.c_g=int(self.l.t_g)
							self.l.c_b=int(self.l.t_b)
							self.l.state=0 			# stop further dimming
							if(LED_DEBUG):
								print("LED stop at "+str(time.time())+" "+str(self.l.c_r)+"/"+str(self.l.c_g)+"/"+str(self.l.c_b))


						self.l.c_r=max(min(255,self.l.c_r),0)		# avoid that we set a value bigger then 255 or smaller then 0
						self.l.c_g=max(min(255,self.l.c_g),0)
						self.l.c_b=max(min(255,self.l.c_b),0)

						# neo pixel
						if(str(self.config.with_lights) == "1" and self.neo_support):
							for i in range(0,self.neo_LED_COUNT):
								strip.setPixelColor(i,Color(self.l.c_r,self.l.c_g,self.l.c_b))		# set value
							strip.show()
						# neo pixel
						# pwm controll on pin 12
						elif(str(self.config.with_lights) == "2" and self.pwm_support):
							wiringpi.pwmWrite(12, self.l.c_r*4)
						# pwm controll on pin 12
						# i2c controll
						elif(str(self.config.with_lights) == "3" and self.i2c_support):
							try:
								print(str(self.l.c_b))
								salsa.dimmTo(0,int(self.l.c_r/2.55),10) #  dimming is in % #R
								salsa.dimmTo(1,int(self.l.c_g/2.55),10) #  dimming is in % #G
								salsa.dimmTo(2,int(self.l.c_b/2.55),10) #  dimming is in % #B
								salsa.dimmTo(3,int(self.l.c_b/2.55),10) #  dimming is in % #B

							except:
								print("LIGHT i2c bus transaction crashed")
						# i2c controll

						# we can wait here a little while because we know that nothing will happen for us earlier than that anyway
						time.sleep(0.8*self.l.ms_step/1000) 		

				else:
					time.sleep(0.01) # sleep to avoid 100% cpu
				# while
		p.rint("LIGHT, thread stopped","l")
예제 #37
0
		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
	# end of while

#start pin config
p.rint("STARTUP, settings pins","l")
gpio = u_gpio()
gpio.setup()

arduino = arduino_bridge.connection()
arduino.setup_digital_output(13) #left
arduino.setup_digital_output(14) #right
arduino.setup_pwm_output(0) # right pwm
arduino.setup_pwm_output(9) # left pwm 


recv_ws_msg_q=[]	# incoming
recv_ws_con_q=[]	# incoming
msg_q_ws=[] 		# outgoing
server_ws.subscribe_callback(recv_ws_msg_q_handle,"msg")
server_ws.subscribe_callback(recv_ws_con_q_handle,"con")
예제 #38
0
def handle (client,addr):
	t1=0
	t2=0

	busy=1
	client.last_comm=time.time()
	#lock = threading.Lock()
	while client.alive:
		try:
			rList, wList, xList = select([client.ws.sock], [client.ws.sock], [client.ws.sock], 3)
		except:
			break;

		if(busy==0):
			time.sleep(0.03)
		busy=0
		######################## SEND ###########################
		if(len(wList)>0):
			try:
				t1=time.time()
				while client.ws.sendq:
					busy=1
					opcode, payload = client.ws.sendq.popleft()
					remaining = client.ws._sendBuffer(payload)
					if remaining is not None:
						client.ws.sendq.appendleft((opcode, remaining))
						break
					else:
						if opcode == CLOSE:
							for callb in callback_con:
								callb("disconnect",client)
				t1=time.time()-t1
			except Exception as n:
				disconnect(client)
		######################## SEND ###########################
		####################### RECEIVE ##########################
		if(len(rList)>0):
			busy=1
			lt=""
			try:
				lt="start _handleData()"
				t2=time.time()
				if(client.ws._handleData()==-1):
					disconnect(client)
					
				while(client.ws.data_ready==True):
					lt="Start getMessage()"
					msg=client.ws.getMessage() # getMessage will unset the data_ready flag if no data left
					if(client.ws.data_ready==True):
						#print(msg) # <-- prints the received data
						lt="Start callb"
						for callb in callback_msg:
							callb(msg,client)
						#client.ws.data_ready=False
						#client.ws.last_data=""
				t2=time.time()-t2

			except (SSL.ZeroReturnError, SSL.SysCallError):
				# regular good SSL disconnect
				disconnect(client)
			except ValueError as err:
				# disconnct while handshake
				disconnect(client)
			except Exception as n:
				print("except while read in server_ws, our status ",end="")
				print(lt)
				print("sys:",end="")
				print(sys.exc_info()[0])
				print(sys.exc_info()[1])
				print(repr(traceback.format_tb(sys.exc_info()[2])))
				print("")

				disconnect(client)
		####################### RECEIVE ##########################
		######################## ERROR ##########################
		if(len(xList)>0):
			busy=1
			disconnect(client)
		######################## ERROR ##########################
		######################## MAINTAINANCE ##########################
		if(time.time()-client.debug_ts>1):
			#if(time.time()-client.debug_ts>10):
			#	print("woohoo its me")
			#	print(t1)
			#	print(t2)
			client.debug_ts=time.time()
		######################## MAINTAINANCE ##########################
	# end of while 1
	p.rint("[S_wss "+time.strftime("%H:%M:%S")+"] -> Client "+str(client.login)+" closed: "+str(client.ip),"l")
예제 #39
0
        "w")
    file.write(f_content)
    file.close()

    return (m2m_mid, m2m_pw)


###################### try import login #######################
register_mode = 0
if (os.path.isfile(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     "login.py"))):
    from login import *
    l = login()  # login
    m2m_pw = l.pw
    p.rint("STARTUP, login.py found, password loaded", "l")

    try:
        p.rint("STARTUP, login.py found, mid loaded", "l")
        m2m_mid = l.mid
    except:
        p.rint("STARTUP, login.py without mid loaded, create new one", "l")
        (m2m_mid, m2m_pw) = create_login("", m2m_pw)

else:
    register_mode = 1
    # first time connection, create a password and send it to the server
    (m2m_mid, m2m_pw) = create_login("", "")
    p.rint("STARTUP, no login.py found, running in register mode", "l")

###################### try import login #######################
예제 #40
0
    def print_rules(self,
                    bars=1,
                    account_info=1,
                    print_out=1,
                    formating=1,
                    header=1,
                    dict=0):
        if (dict):
            ret_dict = {}
            ret_dict["name"] = self.area
            ret_dict["rules"] = []
            ret_dict["subrules"] = []
            header = 0
            print_out = 0
            account_info = 0
            bars = 0
            formating = 0
        else:
            ret = ""

        if (bars):
            ret += "|||+ "

        if (account_info):
            ret += "This is area '" + self.area + "' on account '" + self.account + "'. I have "
            ret += str(len(self.rules)) + " active rules and " + str(
                len(self.sub_rules)) + " subrules\r\n"
        i = 1
        if (bars):
            ret += "(r)|||+ "
        if (header):
            ret += "Rules: <br>(protection activ if at least one is true)\r\n"
        for r in self.rules:
            ## marker
            g = 0
            if (bars):
                ret += "(r)||||- "
            if (self.eval_rule(r.conn, r.arg1, r.arg2, 10, 1, r.id) >= 1):
                if (formating):
                    ret += "<g>"
                g = 1
            else:
                if (formating):
                    ret += "<r>"
            ## marker
            txt = self.explain_rule(r, g, i)
            if (dict):
                ret_dict["rules"].append((r.id, r.conn, r.arg1, r.arg2, g))
            else:
                ret += txt
            ## marker
            if (g):
                if (formating):
                    ret += "</g>\r\n"
            else:
                if (formating):
                    ret += "</r>\r\n"
            ## marker
            i += 1

        if (len(self.rules) == 0):
            if (bars):
                ret += "(r)||||- "
            if (formating):
                ret += "<g>none</g>\r\n"

        i = 1
        if (bars):
            ret += "(r)|||\r\n"
            ret += "(r)|||+ "
        if (header):
            ret += "Sub-Rules:\r\n"

        for r in self.sub_rules:
            ## marker
            g = 0
            if (bars):
                ret += "(r)||||- "
            if (self.eval_rule(r.conn, r.arg1, r.arg2, 10, 1, r.id) >= 1):
                if (formating):
                    ret += "<g>"
                g = 1
            else:
                if (formating):
                    ret += "<r>"
            ## marker
            txt = self.explain_rule(r, g, i)
            if (dict):
                ret_dict["subrules"].append((r.id, txt, g))
            else:
                ret += txt
            ## marker
            if (g):
                if (formating):
                    ret += "</g>"
            else:
                if (formating):
                    ret += "</r>"
            ## marker
            i += 1
            if (dict != 1):
                if ((i - 1) < len(self.sub_rules)):
                    ret += "\r\n"

        if (len(self.sub_rules) == 0):
            if (bars):
                ret += "(r)||||- "
            if (formating):
                ret += "<g>none</g>"

        if (print_out):
            p.rint(ret, "r")
            return 0

        if (dict):
            return ret_dict
        return ret
예제 #41
0
파일: light.py 프로젝트: pdf7/illuminum
def add_q_entry(when,r,g,b,duration_ms):
	p.rint("LIGHT, add_q_entry: setting color "+str(r)+"/"+str(g)+"/"+str(b)+" in "+str(when-time.time())+" sec from now","r")
	runner.add_q_entry(when,r,g,b,duration_ms)
예제 #42
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
예제 #43
0
	def set_old_color(self,r,g,b,lifetime):
		p.rint("LIGHT setting old color "+str(r)+"/"+str(g)+"/"+str(b)+" in "+str(lifetime-time.time())+" sec","r")
		self.l.o_rd=r
		self.l.o_gd=g
		self.l.o_bd=b
		self.l.o_lifetime = lifetime
예제 #44
0
파일: u_gpio.py 프로젝트: pdf7/illuminum
import time
import p
import subprocess

rpi_support  = 0
fsys_support = 0

cpu = str(subprocess.Popen(["cat", "/proc/cpuinfo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).communicate()[0].decode())
cpu = "".join(cpu)

# check platform to see what we can expect
if(cpu.find("Allwinner")>-1):
	# import fsys for CHIP if posible
	p.rint("Allwinner CPU found, running fsys mode","g")
	fsys_support = 1
elif(cpu.find("BCM27")>-1):
	# import rpi gpio if posible
	p.rint("Raspberry CPU found, try to import GPIO lib","g")
	try:
		import RPi.GPIO as GPIO
		p.rint("GPIO lib found and loaded","g")
		rpi_support = 1
	except:
		rpi_support = 0



class u_gpio:
	def __init__(self):
		self.PIN_PIR 		= 1
		self.PIN_MOVEMENT 	= 2
예제 #45
0
	def run(self,config):		
		self.config = config

		while(1):
			p.rint("LIGHT, thread started","l")
			self.alive = True

			self.config.with_neo=0
			self.config.with_pwm=0
			self.config.with_i2c=1

			# Create NeoPixel object with appropriate configuration.
			if(self.config.with_neo):
				p.rint("LIGHT, configured with NEO usage","l")
				if(self.neo_support and self.neo_loaded!=1):
					p.rint("LIGHT, neopixel supported, starting","l")
					strip = Adafruit_NeoPixel(self.neo_LED_COUNT, self.neo_LED_PIN, self.neo_LED_FREQ_HZ, self.neo_LED_DMA, self.neo_LED_INVERT, self.neo_LED_BRIGHTNESS)
					# Intialize the library (must be called once before other functions).
					strip.begin()
					strip.show()
					self.neo_loaded = 1 	# avoid loading it twice
				elif(self.neo_support):
					p.rint("LIGHT, neopixel already loaded","l")
				else:
					p.rint("LIGHT, ERROR neopixel not supported","l")
			elif(self.config.with_pwm):
				p.rint("LIGHT, configured with PWM usage","l")
				if(self.pwm_support):
					p.rint("LIGHT, PWM supported, starting","l")
					wiringpi.wiringPiSetupPhys()
					wiringpi.pinMode(12,2)
				else:
					p.rint("LIGHT, ERROR PWM not supported","l")
			elif(self.config.with_i2c and self.i2c_loaded!=1):
				p.rint("LIGHT, configured with i2c usage","l")
				if(self.i2c_support):
					p.rint("LIGHT, i2c supported, starting","l")
					bus = i2c.I2CMaster(1)
					self.i2c_loaded = 1
				else:
					p.rint("LIGHT, ERROR i2c not supported","l")
			else:
				p.rint("LIGHT, started without pwm and neo","l")

			while self.alive:
				### ------------ check if we have something to do ------------ ###
				if(len(self.light_dimming_q) > 0):
					for data in self.light_dimming_q:
						if(data[0]<=time.time()):
							light_action=data
							self.light_dimming_q.remove(data)
							if(light_action[1]==-1 and light_action[2]==-1 and light_action[3]==-1):
								self.return_to_old(light_action[4])
							else:
								self.dimm_to(light_action[1],light_action[2],light_action[3],light_action[4])
				### ------------ check if we have something to do ------------ ###

				if(self.l.state==1):						# state= 1 means dimming is active
					if(time.time()>=self.l.last_ts+self.l.ms_step/1000):	# last_ts holds time of last event, ms_step the time between two dimm steps, 
											# if that sum is smaller than NOW - we have work
						self.l.last_ts=time.time()			# refresh last_ts to now
						differ_r=self.l.s_r-self.l.t_r			# caluclate the difference of each color between the start and the end color
						differ_g=self.l.s_g-self.l.t_g
						differ_b=self.l.s_b-self.l.t_b
						differ_time=(self.l.t_t-self.l.s_t)		# calulate the total time between the start and end 
											#(this should be the same as the "dimm time" specified by the user)
						if(differ_time>0):			# if the user set instant switch, this time will be 0. avoid division by zero
							ratio=(time.time()-self.l.s_t)/(self.l.t_t-self.l.s_t)	# ratio of the time that has passed, should be 0..1
						else:
							ratio=1
						if(ratio<1):				# if ratio is below 1 we are still in the middle of the dimming
							if(LED_DEBUG):
								print(".", end="")
							self.l.c_r=int(self.l.s_r-ratio*differ_r)	# refresh the r,g,b parts to the current dimm ratio (minus since we did a "self.l.s_r - self.l.t_r")
							self.l.c_g=int(self.l.s_g-ratio*differ_g)
							self.l.c_b=int(self.l.s_b-ratio*differ_b)

						else:					# ratio is bigger than one, time has passed, set it to target color
							self.l.c_r=int(self.l.t_r)
							self.l.c_g=int(self.l.t_g)
							self.l.c_b=int(self.l.t_b)
							self.l.state=0 			# stop further dimming
							if(LED_DEBUG):
								print("LED stop at "+str(time.time())+" "+str(self.l.c_r)+"/"+str(self.l.c_g)+"/"+str(self.l.c_b))


						self.l.c_r=max(min(255,self.l.c_r),0)		# avoid that we set a value bigger then 255 or smaller then 0
						self.l.c_g=max(min(255,self.l.c_g),0)
						self.l.c_b=max(min(255,self.l.c_b),0)

						# neo pixel
						if(self.config.with_neo and self.neo_support):
							for i in range(0,self.neo_LED_COUNT):
								strip.setPixelColor(i,Color(self.l.c_r,self.l.c_g,self.l.c_b))		# set value
							strip.show()
						# neo pixel
						# pwm controll on pin 12
						elif(self.config.with_pwm and self.pwm_support):
							wiringpi.pwmWrite(12, self.l.c_r*4)
						# pwm controll on pin 12
						# i2c controll
						elif(self.config.with_i2c and self.i2c_support):
							if(1):#try:
								address = 4
								pin_r = 9
								pin_g = 6
								pin_b = 5
								

								bus.transaction(i2c.writing_bytes(address, 0xCE, pin_r,0x02, self.l.c_r, self.l.c_g, self.l.c_b))
								#bus.transaction(i2c.writing_bytes(address, 0xCE, pin_g,0x01, self.l.c_g))
								#bus.transaction(i2c.writing_bytes(address, 0xCE, pin_b,0x01, self.l.c_b))
							else:#xcept:
								print("LIGHT i2c bus transaction crashed")
						# i2c controll

						# we can wait here a little while because we know that nothing will happen for us earlier than that anyway
						time.sleep(0.8*self.l.ms_step/1000) 		

				else:
					time.sleep(0.01) # sleep to avoid 100% cpu
				# while
		p.rint("LIGHT, thread stopped","l")
예제 #46
0
def movements_stopped():
	p.rint("MOVEMENT, no motion, starting timer","l")
	return threading.Timer(1,dummy)