Ejemplo n.º 1
0
	def _do_measure(self):
		log("monitor",TRACE,"Start run",self.name)
		try:
			self.running.clear()
			self.started_at = now()
			self._monitor()
			if self.send_check_event:
				simple_event(self.ectx, "monitor","checked",*self.name)
			if self.new_value is not None:
				self.last_value = self.value
				self.value = self.new_value
				if hasattr(self,"delta"):
					if self.last_value is not None:
						val = self.value-self.last_value
						self._ectx.value_delta = val
						if val >= 0 or self.delta == 0:
							simple_event(self.ectx,"monitor","update",*self.name)
				else:
					simple_event(self.ectx,"monitor","update",*self.name)
		except Exception as e:
			fix_exception(e)
			process_failure(e)
		finally:
			log("monitor",TRACE,"Stop run",self.name)
			self.running.set()
			self._schedule()
Ejemplo n.º 2
0
	def go_down(self, _=None):
		if not self.is_up:
			return
		self.is_up = False
		if _ is not None:
			process_failure(_)
		simple_event("onewire","down",typ=self.typ,id=self.id)
Ejemplo n.º 3
0
	def __init__(self, name, host,port, socket=None):
		self.socket = socket
		self.host = host
		self.port = port
		self.name = name
		storage2 = getattr(self,"storage2",{})
		assert (host,port) not in storage2, "already known host/port tuple"
		super(NetCommonConnector,self).__init__()
		storage2[(host,port)] = self
		external = (self.socket is not None)
		if self.socket is None:
			try:
				self._connect()
			except Exception as ex:
				fix_exception(ex)
				if isinstance(ex,EnvironmentError) and ex.errno in (errno.ECONNREFUSED,errno.EHOSTDOWN,errno.EHOSTUNREACH,errno.ENETDOWN,errno.ENETUNREACH,errno.ETIMEDOUT):
					ex.no_backtrace = True
				try:
					del storage2[(host,port)]
				except KeyError:
					pass
				else:
					super(NetCommonConnector,self).delete()
				try:
					self.not_up_event()
				except Exception as ex2:
					fix_exception(ex2)
					process_failure(ex2)
				reraise(ex)
			self.handshake(False)
		else:
			self.handshake(True)

		self.start_job("job",self._reader)
Ejemplo n.º 4
0
	def _do_measure(self):
		log("monitor",TRACE,"Start run",self.name)
		try:
			self.running.clear()
			self.started_at = now()
			self._monitor()
			if self.send_check_event:
				process_event(Event(self.ctx, "monitor","checked",*self.name))
			if self.new_value is not None:
				if hasattr(self,"delta"):
					if self.value is not None:
						val = self.new_value-self.value
						if val >= 0 or self.delta == 0:
							process_event(Event(Context(),"monitor","value",self.new_value-self.value,*self.name))
				else:
					process_event(Event(Context(),"monitor","value",self.new_value,*self.name))
			if self.new_value is not None:
				self.value = self.new_value
		except Exception as e:
			fix_exception(e)
			process_failure(e)
		finally:
			log("monitor",TRACE,"Stop run",self.name)
			self.running.set()
			self._schedule()
Ejemplo n.º 5
0
	def go_down(self, _=None):
		if not self.is_up:
			return
		self.is_up = False
		if _ is not None:
			process_failure(_)
		process_event(Event(self.ctx,"onewire","down",self.typ,self.id))
Ejemplo n.º 6
0
	def process(self, event=None, **k):
		super(EventCallback,self).process(**k)

		# This is an event monitor. Failures will not be tolerated.
		try:
			msg = getattr(event.ctx,'raw',None)
			if msg is None:
				d = dict((x,y) for x,y in event.ctx if isinstance(y,(int,str,unicode,long,bool,float)))
				try:
					msg = json.dumps(dict(event=list(event), **d))
				except (TypeError,UnicodeDecodeError):
					msg = json.dumps(dict(data=repr(event)+"|"+repr(d)))
			elif isinstance(msg,(int,long,float)):
				msg = str(msg)
			elif isinstance(msg,unicode):
				msg = msg.encode("utf-8")
			global _mseq
			_mseq += 1
			msg = amqp.Message(body=msg, content_type='application/json', message_id=base_mseq+str(_mseq))
			self.channel.basic_publish(msg=msg, exchange=self.exchange, routing_key=".".join(str(x) for x in self.prefix+tuple(event)[self.strip:]))
		except Exception as ex:
			fix_exception(ex)
			process_failure(ex)
			try:
				self.cancel()
			except Exception as ex:
				fix_exception(ex)
				process_failure(ex)
		raise TrySomethingElse
Ejemplo n.º 7
0
	def update_all(self):
		try:
			process_event(Event(Context(),"onewire","scanning",self.name))
			self._update_all()
		except Exception as e:
			fix_exception(e)
			process_failure(e)
Ejemplo n.º 8
0
	def update_all(self):
		try:
			simple_event("onewire","scanning",self.name)
			self._update_all()
		except Exception as e:
			fix_exception(e)
			process_failure(e)
Ejemplo n.º 9
0
	def error(self,err):
		"""An error occurred."""
		if self.result is not None and not self.result.successful:
			log("onewire",DEBUG,"done error: ",self,err)
			self.result.set_exception(err)
		else:
			process_failure(err)
Ejemplo n.º 10
0
	def _watcher(self):
		res = []
		while True:
			try:
				self.update_all()
			except Exception as ex:
				fix_exception(ex)
				process_failure(ex)
				resl = len(res)
				while res:
					q = res.pop()
					q.set_exception(ex)
			else:
				resl = len(res)
				while res:
					q = res.pop()
					q.set(None)

			if TESTING:
				if resl: d = 10
				else: d = 30
			else:
				if resl: d = 60
				else: d = 300

			while True:
				try:
					q = self.watch_q.get(timeout=(d if not res else 0))
				except Empty:
					break
				else:
					res.append(q)
Ejemplo n.º 11
0
	def dataReceived(self, data):
		self._stop_timer()
		data = self.dbuf+data
		while True:
			xi = len(data)+1
			try: pi = data.index('\r')
			except ValueError: pi = xi
			try: ei = data.index('\n')
			except ValueError: ei = xi
			if pi==xi and ei==xi:
				break
			if pi < ei:
				self.lbuf = data[:pi]
				data = data[pi+1:]
			else:
				msg = data[:ei]
				data = data[ei+1:]
				if msg == "" and self.lbuf is not None:
					msg = self.lbuf
					self.lbuf = None
				try:
					self.lineReceived(msg)
				except Exception as e:
					fix_exception(e)
					process_failure(e)

		self.dbuf = data
		self._start_timer()
Ejemplo n.º 12
0
	def do_timed_switch(self):
		self.timer = None
		try:
			self.do_switch()
		except Exception as e:
			fix_exception(e)
			process_failure(e)
Ejemplo n.º 13
0
		def err(e):
			try:
				e = e.get()
			except BaseException as e:
				pass
			from homevent.run import process_failure
			fix_exception(e)
			process_failure(e)
Ejemplo n.º 14
0
	def _run(self,a,k):
		try:
			super(Async,self).run(*a,**k)
		except HaltSequence:
			pass
		except Exception as err:
			fix_exception(err)
			process_failure(err)
Ejemplo n.º 15
0
def _readcf():
	c = Context()
	try:
		for f in args:
			parse(f,ctx=c)
	except Exception as e:
		fix_exception(e)
		process_failure(e)
		shut_down()
Ejemplo n.º 16
0
	def _run(self,ctx,**k):
		try:
			super(TryStatement,self).run(ctx,**k)
		except Exception as err:
			fix_exception(err)
			if self.catch_do:
				self.catch_do.run(ctx(error_=err), **k)
			else:
				process_failure(err)
Ejemplo n.º 17
0
Archivo: rpc.py Proyecto: pombreda/MoaT
	def exposed_monitor(self,callback,*args):
		try:
			w = EventCallback(self,callback,*args)
			self.workers.add(w)
			register_worker(w)
			return w
		except Exception as ex:
			fix_exception(ex)
			process_failure(ex)
Ejemplo n.º 18
0
Archivo: rpc.py Proyecto: pombreda/MoaT
	def exposed_cmd_list(self,*args):
		# don't call this 'exposed_list'!
		c = get_collect(args, allow_collection=True)
		try:
			if c is None:
				for m in all_collect(skip=False):
					yield m.name,
			elif isinstance(c,Collection):
				if args[-1] == "*":
					for n,m in c.iteritems():
						yield n,m
					return
				for n,m in c.iteritems():
					try:
						m = m.info
					except AttributeError:
						m = m.name
					else:
						if callable(m):
							m = m()
						if isinstance(m,basestring):
							m = m.split("\n")[0].strip()

					if m is not None:
						yield (n,m)
					else:
						yield n,
			else:
				q = Queue(3)
				job = spawn(flatten,q,(c,))
				job.link(lambda _:q.put(None))

				while True:
					res = q.get()
					if res is None:
						return
					p,t = res
					if isinstance(t,datetime):
						if TESTING:
							if t.year != 2003:
								t = "%s" % (humandelta(t-now(t.year != 2003)),)
							else: 
								t = "%s (%s)" % (humandelta(t-now(t.year != 2003)),t)
							ti = t.rfind('.')
							if ti>0 and len(t)-ti > 3 and len(t)-ti<9: # limit to msec
								t= t[:ti+3]+")"
						# otherwise transmit the datetime as-is
					elif not isinstance(t,(date,time,timedelta)):
						t = unicode(t)

					yield p,t

		except Exception as e:
				fix_exception(e)
				yield "* ERROR *",repr(e)
				process_failure(e)
Ejemplo n.º 19
0
def _shut_down():
	"""\
		Code to be called last. The main loop is running and will
		be stopped when all events have progressed.
		"""
	try:
		process_event(shutdown_event)
	except Exception as e:
		fix_exception(e)
		process_failure(e)
Ejemplo n.º 20
0
	def _get_typ(self):
		try:
			t = self.get("type")
			self._setattr(t,"typ")
		except Exception as ex:
			del self.typ
			del devices[self.id]
			fix_exception(ex)
			process_failure(ex)
		else:
			self.go_up()
Ejemplo n.º 21
0
	def delete(self,ctx=None):
		if self.timer:
			self.timer.cancel()
			self.timer = None
		try:
			if self.state:
				process_event(Event(self.ctx,"pcm","set",self.names[0],*self.name))
		except Exception as ex:
			fix_exception(ex)
			process_failure(ex)
		finally:
			super(CommonPM,self).delete()
Ejemplo n.º 22
0
def start_up():
	"""\
		Code to be called first. The main loop is NOT running.
		"""
	register_worker(Shutdown_Worker("shutdown handler"))

	global running
	if not running:
		running = True
		try:
			process_event(startup_event)
		except Exception as e:
			fix_exception(e)
			process_failure(e)
Ejemplo n.º 23
0
	def cont(self, _=None):
		while self.waiting:
			try:
				msg = self.waiting.pop(0)
				log("fs20",DEBUG,msg)
				d = self._dataReceived(msg)
			except Exception as e:
				fix_exception(e)
				process_failure(e)
			else:
				if d:
					d.addCallback(self.cont)
					return
		self.waiting = None
		self._start_timer()
Ejemplo n.º 24
0
Archivo: rpc.py Proyecto: pombreda/MoaT
	def process(self, **k):
		super(EventCallback,self).process(**k)

		# This is an event monitor. Failures will not be tolerated.
		try:
			self.run_callback(**k)
		except Exception as ex:
			fix_exception(ex)
			process_failure(ex)
			try:
				self.cancel()
			except Exception as ex:
				fix_exception(ex)
				process_failure(ex)
		raise TrySomethingElse
Ejemplo n.º 25
0
Archivo: rpc.py Proyecto: pombreda/MoaT
	def exposed_command(self,*args,**kwargs):
		try:
			sub = kwargs.get("sub",())
			if sub:
				cmd = CommandProcessor(parent=self,ctx=self.ctx)
				proc = cmd.complex_statement(args)
				for s in sub:
					proc.simple_statement(s)
				proc.done()
				cmd.run()
			else:
				return CommandProcessor(parent=self,ctx=self.ctx).simple_statement(args)
		except Exception as e:
			fix_exception(e)
			process_failure(e)
			reraise(e)
Ejemplo n.º 26
0
	def dataReceived(self,val):
		buffer = self.buffer + val
		data = []

		while True:
			i = buffer.find(self.delimiter)
			if i < 0:
				break
			data.append(buffer[:i])
			buffer = buffer[i+len(self.delimiter):]

		self.buffer = buffer
		for d in data:
			try:
				self.lineReceived(d)
			except Exception as e:
				fix_exception(e)
				process_failure(e)
Ejemplo n.º 27
0
	def _reader(self):
		try:
			while self.socket is not None:
				try:
					r = self.socket.recv(4096)
					if r is None or r == "":
						return
				except Exception as e:
					fix_exception(e)
					process_failure(e)
					return
				try:
					self.dataReceived(r)
				except Exception as e:
					fix_exception(e)
					process_failure(e)
		finally:
			if self.socket:
				self.socket.close()
				self.socket = None
				self.down_event(True)
Ejemplo n.º 28
0
	def do_switch(self):
		"""Click"""
		if self.state:
			self.state = 0
			tn = self.t_off
		else:
			self.state = 1
			tn = self.t_on

		process_event(Event(self.ctx,"pcm","set",self.names[self.state],*self.name))
		try:
			self.last = self.next
			if tn is not None:
				self.next = self.last + dt.timedelta(0,tn)
				self.timer = callLater(False,self.next,self.do_timed_switch)
			else:
				self.next = None
		except Exception as e:
			fix_exception(e)
			process_failure(e)
			simple_event(self.ctx,"pcm","error",*self.name)
Ejemplo n.º 29
0
		def died(e):
			fix_exception(e)
			process_failure(e)
Ejemplo n.º 30
0
	def _monitor(self):
		"""This implements a monitor sequence."""
		self.steps = 0
		self.data = []
		self.new_value = None

		def delay():
			if isinstance(self.delay,tuple):
				sleepUntil(False,time_delta(self.delay))
			else:
				sleepUntil(False,self.delay)

		try:
			while self.job and (self.maxpoints is None or self.steps < self.maxpoints):
				if self.steps and not self.passive:
					delay()

				self.steps += 1

				try:
					val = self.one_value(self.steps)

				except MonitorAgain:
					pass

				except Exception as e:
					fix_exception(e)
					process_failure(e)
					break

				else:
					log("monitor",TRACE,"raw",val,*self.name)
					if hasattr(self,"factor"):
						try:
							val = val * self.factor + self.offset
						except TypeError:
							log("monitor",ERROR,self.name,val,self.factor,self.offset)
					self.data.append(val)

					avg = self.filter_data()
					if avg is not None:
						if self.value is None or \
								self.diff is None or \
								abs(self.value-avg) > self.diff:

							try:
								if self.value is not None and \
										self.alarm is not None and \
										abs(self.value-avg) > self.alarm:
									process_event(Event(Context(),"monitor","alarm",avg,*self.name))
							except Exception as e:
								fix_exception(e)
								process_failure(e)
							else:
								self.new_value = avg
						return
					else:
						log("monitor",TRACE,"More data", self.data, "for", u"‹"+" ".join(unicode(x) for x in self.name)+u"›")
				
			try:
				process_event(Event(Context(),"monitor","error",*self.name))
			except Exception as e:
				fix_exception(e)
				process_failure(e)

		finally:
			log("monitor",TRACE,"End run", self.name)
			self.stopped_at = now()