def start(serviceConfig): serviceId = serviceConfig['main'].get('id') log.info('Start service: %s' % serviceId) pid = isRunning(serviceId) if pid: log.error("Could not start service %s because already running on pid %s" % (serviceId, pid)) return if serviceConfig.get('command'): command = serviceConfig.get('command') else: command = '%s/service/runservice.py' % config.get('libdir') command = [command, json.dumps(serviceConfig)] log.info('Start service command: %s' % (command,)) # We need close_fds=True to avoid some crap being inherited from parent->child process, # which would cause manager process to not free all resources when killed, unless # all service subprocesses are also dead first, which we do not want to require. #proc = subprocess.Popen(command) processes[serviceId] = subprocess.Popen(command, close_fds=True) setPid(serviceId, processes[serviceId].pid) log.info("Started service %s on pid %s" % (serviceId, processes[serviceId].pid)) return processes[serviceId].pid
def onInit(self): log('IntegraService init.') self.model = self.config.get('model') self.ser_dev = self.config.get('serial') if self.ser_dev and self.model: self.topics, self.cmds = iscp.model_cmds(self.model) else: log.error('Service needs serial service and model to work.') sys.exit(1) self.act_desc = { 'info': 'Integra/Onkyo model %s' % self.model, 'actions': [] } for cmd in self.cmds: for subcmd in cmd: newcmd = { 'name': cmd + subcmd, 'info': self.cmds[cmd][subcmd]['description'], 'args': [ ] } if 'type' in self.cmds[cmd][subcmd]: param = self._type_desc(self.cmds[cmd][subcmd]['type']) if param: newcmd['args'].append(param) self.act_desc['actions'].append(newcmd) self.ser = serial.Serial(port=self.ser_dev, baudrate=9600, timeout=0.05, # 50ms reponse time according to spec bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, )
def onInit(self): log.info('IntegraService init.') self.model = self.config.get('model') self.ser_dev = self.config.get('serial') if self.ser_dev and self.model: self.topics, self.cmds = iscp.model_cmds(self.model) else: log.error('Service needs serial service and model to work.') sys.exit(1) self.act_desc = { 'info': 'Integra/Onkyo model %s' % self.model, 'actions': [] } for cmd in self.cmds: for subcmd in self.cmds[cmd]: newcmd = { 'name': cmd + subcmd, 'info': self.cmds[cmd][subcmd]['description'], 'args': [] } # matches non-empty type-dicts: if self.cmds[cmd][subcmd]['type']: param = self._type_desc(self.cmds[cmd][subcmd]['type']) if param: newcmd['args'].append(param) self.act_desc['actions'].append(newcmd) self.ser = serial.Serial( port=self.ser_dev, baudrate=9600, timeout=0.05, # 50ms reponse time according to spec bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, )
def start(serviceConfig): serviceId = serviceConfig['main'].get('id') log.info('Start service: %s' % serviceId) pid = isRunning(serviceId) if pid: log.error( "Could not start service %s because already running on pid %s" % (serviceId, pid)) return if serviceConfig.get('command'): command = serviceConfig.get('command') else: command = '%s/service/runservice.py' % config.get('libdir') command = [command, json.dumps(serviceConfig)] log.info('Start service command: %s' % (command, )) # We need close_fds=True to avoid some crap being inherited from parent->child process, # which would cause manager process to not free all resources when killed, unless # all service subprocesses are also dead first, which we do not want to require. #proc = subprocess.Popen(command) processes[serviceId] = subprocess.Popen(command, close_fds=True) setPid(serviceId, processes[serviceId].pid) log.info("Started service %s on pid %s" % (serviceId, processes[serviceId].pid)) return processes[serviceId].pid
def handleDaemonItem(self, type, id): # If item is already offline, do nothing - but (re)start if applicable item = self.orchestrator.data[type][id] if item['online'] == False: if type == 'service': if not item.has_key('offlineTimer'): item['offlineTimer'] = time.time() if item['main'].get('autostart'): if item.get('manuallyStopped'): log.debug('Do not auto-start service %s since manually stopped' % id) else: timeSinceOffline = time.time() - item['offlineTimer'] if timeSinceOffline > self.orchestrator.startInterval: self.orchestrator.data[type][id]['offlineTimer'] = time.time() try: #self.orchestrator.action_startService(id) serviceId, managerId = self.orchestrator.parseServiceParam(id) if self.orchestrator.isOnline('manager', managerId): log.info('Auto-start service %s @ %s after %s secs offline' % (serviceId, managerId, timeSinceOffline)) self.orchestrator.startService(managerId, serviceId) else: log.debug('Do not auto-start service %s since manager %s is offline' % (id,managerId)) except Exception, e: log.error('Error trying to autostart service %s: %s' % (id,e)) else: log.debug('Do not auto-start service %s since %s secs offline is less than startinterval %s' % (id,timeSinceOffline,self.orchestrator.startInterval)) else: log.debug('Do not auto-start service %s since autostart not set in config' % (id,))
def run(self): try: self.func() except Exception, e: log.error("Thread for %s in service %s died: %s" % ( self.name, self.serviceId, utils.e2str(e) ))
def listen(self): log.info('Start listening for messages, topics = %s' % self.getConsumeKeys()) actionPrefix = self.getActionPrefix() heartBeatRequestPrefix = self.getHeartBeatRequestPrefix() while not self._shutdown: log.notice('Waiting for messages') try: topic, data, correlationId = self.consumer.get() except socket.error as e: self.reconnect(e) continue except amqplib.client_0_8.exceptions.AMQPConnectionException as e: self.reconnect(e) continue except IOError as e: self.reconnect(e) continue except Exception as e: log.error('Caught during consumer.get() in listen: %s' % utils.e2str(e)) raise e try: self.consumer.ack() except Exception as e: log.error('Caught during consumer.ack() in listen: %s' % utils.e2str(e)) raise e if self._shutdown: log.info( 'Not handeling topic: %s because self._shutdown = True' % (topic, )) else: log.notice('Handeling topic: %s' % topic) tmp = topic.split('.') handle = False if tmp[0] == actionPrefix and len( tmp) > 1 and tmp[1] == self.id: pre, src, key = tmp if key == '_shutdown': continue if not data: data = [] try: result = self.runAction(key, data) except Exception as e: self.sendActionError(key, e, correlationId) else: if result is not None or correlationId: self.sendActionResponse(key, result, correlationId) elif tmp[0] == heartBeatRequestPrefix: self.sendHeartBeatResponse() else: self.onMessage(topic, data, correlationId) log.notice('Handeled topic: %s' % topic) log.info('Exited listen() loop - self._shutdown = %s' % self._shutdown)
def onMessage(self, topic, data, correlationId): self.aggregated['total_messages'] += 1 if topic.startswith('se.') and not topic.endswith('.online'): # aggregation: update the total number of events from this service and class cursrv = topic.split('.')[1] if cursrv in self.aggregated['service_events']: self.aggregated['service_events'][cursrv] += 1 else: self.aggregated['service_events'][cursrv] = 1 if 'class' in data: if data['class'] in self.aggregated['class_events']: self.aggregated['class_events'][data['class']] += 1 else: self.aggregated['class_events'][data['class']] = 1 # Ignore is in config ignoreclasses or ignore is set for the service if 'class' in data: if data['class'] in self.ignoreclasses: return if 'ignore' in data: if data['ignore'] in [True, 'True', 'true', 'Yes', 'yes', 'y']: return # start picking out data to report measures = [] tags = {} for tag in data: if tag in self.known_tags: if tag == 'key': tags.update({'event': data[tag]}) else: tagValue = data[tag] if type(tagValue) == types.UnicodeType: tagValue = tagValue.encode('utf-8') tags.update({tag: tagValue}) for measure in data['data']: if 'value' in data['data'][measure]: curval = data['data'][measure]['value'] if isinstance(curval, numbers.Number): measures.append(self.ix.data_template(measure, tags, {'value': curval})) # log.info('field: %s: %s' % (measure, str(curval))) # log.info('tags: %s' % str(tags)) elif curval in [True, 'True', 'true', 'On', 'on', 'Yes', 'yes']: measures.append(self.ix.data_template(measure, tags, {'value': True})) elif curval in [False, 'False', 'false', 'Off', 'off', 'No', 'no']: measures.append(self.ix.data_template(measure, tags, {'value': False})) else: # log.info('Skipping because value is not a number:') # log.info("topic: " + str(topic)) # log.info("data: " + str(data)) pass log.debug('insert measures: %s' % measures) try: self.ix.insert(measures) except Exception, e: log.error('Failed inserting measures in influxdb: %s\nAttempted insert was: %s' % (utils.e2str(e), measures))
def onInit(self): self.button_events = [ array('B', [1, 0, 0, 0, 0, 0, 0]), 'button_release', array('B', [1, 1, 0, 0, 0, 0, 0]), 'button_left', array('B', [1, 2, 0, 0, 0, 0, 0]), 'button_right', array('B', [1, 4, 0, 0, 0, 0, 0]), 'button_middle', array('B', [1, 8, 0, 0, 0, 0, 0]), 'button_3', array('B', [1, 16, 0, 0, 0, 0, 0]), 'button_4', array('B', [1, 32, 0, 0, 0, 0, 0]), 'button_5', array('B', [1, 64, 0, 0, 0, 0, 0]), 'button_6', array('B', [1, 128, 0, 0, 0, 0, 0]), 'button_7', array('B', [1, 255, 0, 0, 0, 0, 0]), 'button_8', array('B', [1, 0, 0, 0, 0, 0, 1]), 'wheel_up', array('B', [1, 0, 0, 0, 0, 0, 255]), 'wheel_down', # mouse button combinations # TODO: do this by using bitwise operator to generate all combinations array('B', [1, 3, 0, 0, 0, 0, 0]), 'button_left_right', array('B', [1, 5, 0, 0, 0, 0, 0]), 'button_left_middle', array('B', [1, 6, 0, 0, 0, 0, 0]), 'button_right_middle', array('B', [1, 7, 0, 0, 0, 0, 0]), 'button_left_right_middle', ] # "slow" mouse movements self.move_events = [ array('B', [1, 0, 0, 0, 1, 0, 0]), 'down', array('B', [1, 0, 255, 255, 1, 0, 0]), 'down-left', array('B', [1, 0, 1, 0, 1, 0, 0]), 'down-right', array('B', [1, 0, 0, 0, 255, 255, 0]), 'up', array('B', [1, 0, 255, 255, 255, 255, 0]), 'up-left', array('B', [1, 0, 1, 0, 255, 255, 0]), 'up-right', array('B', [1, 0, 255, 255, 0, 0, 0]), 'left', array('B', [1, 0, 1, 0, 0, 0, 0]), 'right', ] # ## Service config self.interval = int(self.config.get('interval')) or 600 # milliseconds self.vendorid = int(self.config.get('vendorid')) self.productid = int(self.config.get('productid')) self.search_params = {} if self.vendorid and self.productid: self.search_params.update({'idVendor': self.vendorid, 'idProduct': self.productid}) mousedevs = cusb.find_mouse(self.search_params) else: log.warn("No config, using first found mouse service") mousedevs = cusb.find_mouse() if not mousedevs: log.error("Can't find mouse service") sys.exit("Can't find mouse service") # Use first matching mouse mouse = mousedevs[0] # ## vendor and product ids self.dev = usb.core.find(address=mouse['address'], bus=mouse['bus']) self.interface = mouse['interface'] # use the first endpoint # dev[configuration][(interface, alt_config)][endpoint] self.endpoint = self.dev[mouse['configuration']][(mouse['interface'], 0)][0]
def updateTravelProposals(self): log.info('Updating travel props') headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36" } url = self.apiUri + '?fromplace=' + self.fromPlace + '&toplace=' + self.toPlace + '&isafter=true&transporttypes=' + self.transportTypes req = urllib2.Request(url, None, headers) try: response = urllib2.urlopen(req) self.parseReponse(response.read()) except urllib2.HTTPError as e: log.error('Error when updating TravelProposals %s: %s' % (e, e.read())) time.sleep(self.interval * 3)
def runWithSignalHandler(daemon): def signalHandler(signal, frame): daemon.shutdown() daemon.sendOfflineEvent() sys.exit(0) signal.signal(signal.SIGTERM, signalHandler) # $ kill <pid> signal.signal(signal.SIGINT, signalHandler) # Ctrl-C try: daemon.run() except Exception as e: log.error('Daemon crashed: %s' % utils.e2str(e)) raise e
def listen(self): log.info('Start listening for messages, topics = %s' % self.getConsumeKeys()) actionPrefix = self.getActionPrefix() heartBeatRequestPrefix = self.getHeartBeatRequestPrefix() while not self._shutdown: log.notice('Waiting for messages') try: topic, data, correlationId = self.consumer.get() except socket.error as e: self.reconnect(e) continue except amqplib.client_0_8.exceptions.AMQPConnectionException as e: self.reconnect(e) continue except IOError as e: self.reconnect(e) continue except Exception as e: log.error('Caught during consumer.get() in listen: %s' % utils.e2str(e)) raise e try: self.consumer.ack() except Exception as e: log.error('Caught during consumer.ack() in listen: %s' % utils.e2str(e)) raise e if self._shutdown: log.info('Not handeling topic: %s because self._shutdown = True' % (topic,)) else: log.notice('Handeling topic: %s' % topic) tmp = topic.split('.') handle = False if tmp[0] == actionPrefix and len(tmp) > 1 and tmp[1] == self.id: pre, src, key = tmp if key == '_shutdown': continue if not data: data = [] try: result = self.runAction(key, data) except Exception as e: self.sendActionError(key, e, correlationId) else: if result is not None or correlationId: self.sendActionResponse(key, result, correlationId) elif tmp[0] == heartBeatRequestPrefix: self.sendHeartBeatResponse() else: self.onMessage(topic, data, correlationId) log.notice('Handeled topic: %s' % topic) log.info('Exited listen() loop - self._shutdown = %s' % self._shutdown)
def updateTravelProposals(self): log.info('Updating travel props') headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36" } timestamp = datetime.strftime( datetime.now() + timedelta(minutes=self.walkTime), '%d%m%Y%H%M00') url = self.apiUri + '?time=' + timestamp + '&fromplace=' + self.fromPlace + '&toplace=' + self.toPlace + '&isafter=true&transporttypes=' + self.transportTypes req = urllib2.Request(url, None, headers) try: response = urllib2.urlopen(req) self.parseReponse(response.read()) except urllib2.HTTPError as e: log.error('Error when updating TravelProposals %s: %s' % (e, e.read())) time.sleep(self.interval * 3)
def getNext(self): try: # Iterate to next step in rule, running any actions in between if self.matchedEvent: self.event = self.rule.send(self.matchedEvent) else: self.event = self.rule.next() # Rule is done running actions, and we're waiting for an event again self.debug('Wait for event(s):', self.event) # No more events? Then we're done. except StopIteration: self.complete() # Hm, unsure if this works. # There are definitively at least some cases where thread can die # without us noticing. So make sure code in Action() is ok. except Exception, e: log.error("Rule crashed:", e) self.complete()
def Action(service, action, params=None): rpc = None connection = None try: log.info("Run Action: %s.%s( %s )" % (service, action, params)) if not params: params = [] topic = '%s%s.%s.%s' % (amqp.PREFIX_SERVICE, amqp.PREFIX_ACTION, service, action) connection = amqp.Connection() rpc = connection.rpc(queuePrefix='reactor-action') result = rpc.call(topic, data=params) except Exception, e: try: log.error("Exception in action %s.%s: %s" % (service,action,e)) except: pass
def action_sendmail(self, from_addr=None, to_addr=None, subject=None, message=None): ''' Send an email @param from_addr string Address to send from @param to_addr string Address to send to @param subject string Subject of the message @param message string Text message you want to send ''' msg = MIMEText(str(message)) msg['To'] = email.utils.formataddr(('Recipient', self.to_addr)) msg['From'] = email.utils.formataddr(('Chains', self.from_addr)) msg['Subject'] = self.subject log.info('Send msg: %s' % msg) server = smtplib.SMTP(self.smtpserver) # TODO: Implement authenticated smtp try: server.sendmail(from_addr, [to_addr], msg.as_string()) except: log.error("Sending mail failed")
def Action(service, action, params=None): rpc = None connection = None try: log.info("Run Action: %s.%s( %s )" % (service, action, params)) if not params: params = [] topic = '%s%s.%s.%s' % (amqp.PREFIX_SERVICE, amqp.PREFIX_ACTION, service, action) connection = amqp.Connection() rpc = connection.rpc(queuePrefix='reactor-action') result = rpc.call(topic, data=params) except Exception, e: try: log.error("Exception in action %s.%s: %s" % (service, action, e)) except: pass
def reconnect(self, e): if self.connection: self.connection.close() self.producer = None self.consumer = None self.connection = None delay = 2 retry = 0 while True: retry += 1 log.error('Attempting to reconnect #%s and continue in %s sec after socket error: %s' % (retry,delay,e)) time.sleep(delay) try: self._connect() log.error('Successfully reconnected (after %s retries) - back to work!' % (retry)) return except socket.error, e2: log.info('Ignoring expected exception on reconnect and will soon try again: %s' % e2) except amqplib.client_0_8.exceptions.AMQPConnectionException, e2: log.info('Ignoring expected exception on reconnect and will soon try again: %s' % e2)
def reconnect(self, e): if self.connection: self.connection.close() self.producer = None self.consumer = None self.connection = None delay = 2 retry = 0 while True: retry += 1 log.error( 'Attempting to reconnect #%s and continue in %s sec after socket error: %s' % (retry, delay, e)) time.sleep(delay) try: self._connect() log.error( 'Successfully reconnected (after %s retries) - back to work!' % (retry)) return except socket.error as e2: log.info( 'Ignoring expected exception on reconnect and will soon try again: %s' % repr(e2)) except amqplib.client_0_8.exceptions.AMQPConnectionException as e2: log.info( 'Ignoring expected exception on reconnect and will soon try again: %s' % repr(e2)) except ConnectionNotReadyException as e2: log.info( 'Ignoring expected exception on reconnect and will soon try again: %s' % repr(e2)) except Exception as e2: log.warn( 'Ignoring unexpected exception on reconnect and will soon try again: %s' % repr(e2))
def onError(self, e): log.error("Phidget Error %s: %s" % (e.eCode, e.description)) return 0
def onInit(self): self.keymaps = { 'en_US': [ '', '', '', '', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '\n', '^]', '^H', '^I', ' ', '-', '=', '[', ']', '\\', '>', ';', "'", '`', ',', '.', '/', 'CapsLock', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'PS', 'SL', 'Pause', 'Ins', 'Home', 'PU', '^D', 'End', 'PD', '->', '<-', '-v', '-^', 'NL', 'KP/', 'KP*', 'KP-', 'KP+', 'KPE', 'KP1', 'KP2', 'KP3', 'KP4', 'KP5', 'KP6', 'KP7', 'KP8', 'KP9', 'KP0', '\\', 'App', 'Pow', 'KP=', 'F13', 'F14' ] } self.shiftmaps = { 'en_US': [ '', '', '', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '\n', '^]', '^H', '^I', ' ', '_', '+', '{', '}', '|', '<', ':', '"', '~', '<', '>', '?', 'CapsLock', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'PS', 'SL', 'Pause', 'Ins', 'Home', 'PU', '^D', 'End', 'PD', '->', '<-', '-v', '-^', 'NL', 'KP/', 'KP*', 'KP-', 'KP+', 'KPE', 'KP1', 'KP2', 'KP3', 'KP4', 'KP5', 'KP6', 'KP7', 'KP8', 'KP9', 'KP0', '|', 'App', 'Pow', 'KP=', 'F13', 'F14' ] } self.mods = { 1: 'control_left', # Left control 2: 'shift_left', # Left shift 4: 'alt_left', # Left alt 8: 'super_left', # Left super 16: 'control_right', # Right control 32: 'shift_right', # Right shift 64: 'alt_right', # Right alt 128: 'super_right', # Right super } # ## Service config self.interval = int(self.config.get('interval')) or 10 self.max_word = int(self.config.get('max_word')) or 50 self.max_line = int(self.config.get('max_line')) or 250 self.vendorid = int(self.config.get('vendorid')) self.productid = int(self.config.get('productid')) self.search_params = {} if self.vendorid and self.productid: self.search_params.update({'idVendor': self.vendorid, 'idProduct': self.productid}) kbdevs = cusb.find_keyboard(self.search_params) else: log.warn("No config, using first found usb keyboard") kbdevs = cusb.find_keyboard() if not kbdevs: log.error("Can't find keyboard") sys.exit("Can't find keyboard") # Use first matching keyboard keyboard = kbdevs[0] # ## vendor and product ids self.dev = usb.core.find(address=keyboard['address'], bus=keyboard['bus']) self.interface = keyboard['interface'] # use the first endpoint # dev[configuration][(interface, alt_config)][endpoint] self.endpoint = self.dev[keyboard['configuration']][(keyboard['interface'], 0)][0]
def onInit(self): self.keymaps = { 'en_US': [ '', '', '', '', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '\n', '^]', '^H', '^I', ' ', '-', '=', '[', ']', '\\', '>', ';', "'", '`', ',', '.', '/', 'CapsLock', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'PS', 'SL', 'Pause', 'Ins', 'Home', 'PU', '^D', 'End', 'PD', '->', '<-', '-v', '-^', 'NL', 'KP/', 'KP*', 'KP-', 'KP+', 'KPE', 'KP1', 'KP2', 'KP3', 'KP4', 'KP5', 'KP6', 'KP7', 'KP8', 'KP9', 'KP0', '\\', 'App', 'Pow', 'KP=', 'F13', 'F14' ] } self.shiftmaps = { 'en_US': [ '', '', '', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '\n', '^]', '^H', '^I', ' ', '_', '+', '{', '}', '|', '<', ':', '"', '~', '<', '>', '?', 'CapsLock', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'PS', 'SL', 'Pause', 'Ins', 'Home', 'PU', '^D', 'End', 'PD', '->', '<-', '-v', '-^', 'NL', 'KP/', 'KP*', 'KP-', 'KP+', 'KPE', 'KP1', 'KP2', 'KP3', 'KP4', 'KP5', 'KP6', 'KP7', 'KP8', 'KP9', 'KP0', '|', 'App', 'Pow', 'KP=', 'F13', 'F14' ] } self.mods = { 1: 'control_left', # Left control 2: 'shift_left', # Left shift 4: 'alt_left', # Left alt 8: 'super_left', # Left super 16: 'control_right', # Right control 32: 'shift_right', # Right shift 64: 'alt_right', # Right alt 128: 'super_right', # Right super } # ## Service config self.interval = int(self.config.get('interval')) or 10 self.max_word = int(self.config.get('max_word')) or 50 self.max_line = int(self.config.get('max_line')) or 250 self.vendorid = int(self.config.get('vendorid')) self.productid = int(self.config.get('productid')) self.search_params = {} if self.vendorid and self.productid: self.search_params.update({ 'idVendor': self.vendorid, 'idProduct': self.productid }) kbdevs = cusb.find_keyboard(self.search_params) else: log.warn("No config, using first found usb keyboard") kbdevs = cusb.find_keyboard() if not kbdevs: log.error("Can't find keyboard") sys.exit("Can't find keyboard") # Use first matching keyboard keyboard = kbdevs[0] # ## vendor and product ids self.dev = usb.core.find(address=keyboard['address'], bus=keyboard['bus']) self.interface = keyboard['interface'] # use the first endpoint # dev[configuration][(interface, alt_config)][endpoint] self.endpoint = self.dev[keyboard['configuration']][( keyboard['interface'], 0)][0]
def _check_mail(self): # Add support for IMAP try: pop = poplib.POP3(self.mailserver) pop.user(self.username) pop.pass_(self.password) stat = pop.stat() # log.info('Hande %s mails' % stat[0]) # print stat for n in range(stat[0]): msgnum = n + 1 hresponse, hlines, bytes = pop.top(msgnum, self.maxheader) # print "response: " + hresponse # print "lines: " + str(hlines) # print lines[len(lines)-1] # print "bytes: " + str(bytes) mailto = mailfrom = subject = 'unknown' if bytes < self.maxsize: mresponse, mlines, bytes = pop.retr(msgnum) mailstring = '' for i in mlines: mailstring += i mailstring += '\n' msg = email.message_from_string(mailstring) # print msg if 'To' in msg: mailto = msg['To'] if 'From' in msg: mailfrom = msg['From'] if 'Subject' in msg: subject = msg['Subject'] log.info('Handle msg with proper size: %s | %s | %s' % (mailfrom, mailto, subject)) # heads = msg.keys() # for head in heads: # print head + '\n' parts = 0 multipart = '' for part in msg.walk(): # print "type", repr(part.get_content_type()) multipart += 'Part ' + str(parts + 1) + ":" + repr(part.get_content_type()) multipart += '\n' # print "body", repr(part.get_payload()) body = repr(part.get_payload()) parts += 1 if parts > 1: body = multipart self.sendEvent(mailfrom, {'to': mailto, 'subject': subject, 'message': body}) else: mailstring = '' for i in hlines: mailstring += i mailstring += '\n' msg = email.message_from_string(mailstring) # print msg if 'To' in msg: mailto = msg['To'] if 'From' in msg: mailfrom = msg['From'] if 'Subject' in msg: subject = msg['Subject'] log.info('Ignore body for mail with size above mailbase.maxsize: %s | %s | %s' % (mailfrom, mailto, subject)) self.sendEvent(mailfrom, {'to': mailto, 'subject': subject, 'message': 'LARGE_MAIL_BODY_IGNORED'}) if self.deletemail: pop.dele(msgnum) pop.quit() except poplib.error_proto, detail: log.error("POP3 Protocol Error:", detail)
from chains.service import process from chains.service import config # as serviceConfig from chains import service from chains.common import log, utils #from chains.common import config as globalConfig from .runservice import signalHandler, parseConfigParam, checkNotRunning serviceObject = None serviceConfig = parseConfigParam() serviceId = serviceConfig.get('id') log.setFileName('service-%s-%s' % (serviceConfig.get('name'), serviceId)) if serviceConfig.get('loglevel'): log.setLevel(serviceConfig.get('loglevel')) #checkNotRunning(serviceId) process.setPid(serviceId, os.getpid()) try: serviceObject = service.factory(serviceConfig) signal.signal(signal.SIGTERM, signalHandler) # $ kill <pid> signal.signal(signal.SIGINT, signalHandler) # Ctrl-C serviceObject.start(block=True) except Exception, e: log.error('Service crashed: %s' % serviceId) log.error(utils.e2str(e))
def getConfig(self, path): try: return config.BaseConfig(path) except Exception, e: log.error("Error loading config: %s, because: %s" % (path,utils.e2str(e))) return None
def onMessage(self, topic, data, correlationId): self.aggregated['total_messages'] += 1 if topic.startswith('se.') and not topic.endswith('.online'): # aggregation: update the total number of events from this service and class cursrv = topic.split('.')[1] if cursrv in self.aggregated['service_events']: self.aggregated['service_events'][cursrv] += 1 else: self.aggregated['service_events'][cursrv] = 1 if 'class' in data: if data['class'] in self.aggregated['class_events']: self.aggregated['class_events'][data['class']] += 1 else: self.aggregated['class_events'][data['class']] = 1 # Ignore is in config ignoreclasses or ignore is set for the service if 'class' in data: if data['class'] in self.ignoreclasses: return if 'ignore' in data: if data['ignore'] in [True, 'True', 'true', 'Yes', 'yes', 'y']: return # start picking out data to report measures = [] tags = {} for tag in data: if tag in self.known_tags: if tag == 'key': tags.update({'event': data[tag]}) else: tagValue = data[tag] if type(tagValue) == types.UnicodeType: tagValue = tagValue.encode('utf-8') tags.update({tag: tagValue}) for measure in data['data']: if 'value' in data['data'][measure]: curval = data['data'][measure]['value'] if isinstance(curval, numbers.Number): measures.append( self.ix.data_template(measure, tags, {'value': curval})) # log.info('field: %s: %s' % (measure, str(curval))) # log.info('tags: %s' % str(tags)) elif curval in [ True, 'True', 'true', 'On', 'on', 'Yes', 'yes' ]: measures.append( self.ix.data_template(measure, tags, {'value': True})) elif curval in [ False, 'False', 'false', 'Off', 'off', 'No', 'no' ]: measures.append( self.ix.data_template(measure, tags, {'value': False})) else: # log.info('Skipping because value is not a number:') # log.info("topic: " + str(topic)) # log.info("data: " + str(data)) pass log.debug('insert measures: %s' % measures) try: self.ix.insert(measures) except Exception, e: log.error( 'Failed inserting measures in influxdb: %s\nAttempted insert was: %s' % (utils.e2str(e), measures))
def onInit(self): self.button_events = [ array('B', [1, 0, 0, 0, 0, 0, 0]), 'button_release', array('B', [1, 1, 0, 0, 0, 0, 0]), 'button_left', array('B', [1, 2, 0, 0, 0, 0, 0]), 'button_right', array('B', [1, 4, 0, 0, 0, 0, 0]), 'button_middle', array('B', [1, 8, 0, 0, 0, 0, 0]), 'button_3', array('B', [1, 16, 0, 0, 0, 0, 0]), 'button_4', array('B', [1, 32, 0, 0, 0, 0, 0]), 'button_5', array('B', [1, 64, 0, 0, 0, 0, 0]), 'button_6', array('B', [1, 128, 0, 0, 0, 0, 0]), 'button_7', array('B', [1, 255, 0, 0, 0, 0, 0]), 'button_8', array('B', [1, 0, 0, 0, 0, 0, 1]), 'wheel_up', array('B', [1, 0, 0, 0, 0, 0, 255]), 'wheel_down', # mouse button combinations # TODO: do this by using bitwise operator to generate all combinations array('B', [1, 3, 0, 0, 0, 0, 0]), 'button_left_right', array('B', [1, 5, 0, 0, 0, 0, 0]), 'button_left_middle', array('B', [1, 6, 0, 0, 0, 0, 0]), 'button_right_middle', array('B', [1, 7, 0, 0, 0, 0, 0]), 'button_left_right_middle', ] # "slow" mouse movements self.move_events = [ array('B', [1, 0, 0, 0, 1, 0, 0]), 'down', array('B', [1, 0, 255, 255, 1, 0, 0]), 'down-left', array('B', [1, 0, 1, 0, 1, 0, 0]), 'down-right', array('B', [1, 0, 0, 0, 255, 255, 0]), 'up', array('B', [1, 0, 255, 255, 255, 255, 0]), 'up-left', array('B', [1, 0, 1, 0, 255, 255, 0]), 'up-right', array('B', [1, 0, 255, 255, 0, 0, 0]), 'left', array('B', [1, 0, 1, 0, 0, 0, 0]), 'right', ] # ## Service config self.interval = int(self.config.get('interval')) or 600 # milliseconds self.vendorid = int(self.config.get('vendorid')) self.productid = int(self.config.get('productid')) self.search_params = {} if self.vendorid and self.productid: self.search_params.update({ 'idVendor': self.vendorid, 'idProduct': self.productid }) mousedevs = cusb.find_mouse(self.search_params) else: log.warn("No config, using first found mouse service") mousedevs = cusb.find_mouse() if not mousedevs: log.error("Can't find mouse service") sys.exit("Can't find mouse service") # Use first matching mouse mouse = mousedevs[0] # ## vendor and product ids self.dev = usb.core.find(address=mouse['address'], bus=mouse['bus']) self.interface = mouse['interface'] # use the first endpoint # dev[configuration][(interface, alt_config)][endpoint] self.endpoint = self.dev[mouse['configuration']][(mouse['interface'], 0)][0]
heartBeatRequestPrefix = self.getHeartBeatRequestPrefix() while not self._shutdown: log.notice('Waiting for messages') try: topic, data, correlationId = self.consumer.get() except socket.error, e: self.reconnect(e) continue except amqplib.client_0_8.exceptions.AMQPConnectionException, e: self.reconnect(e) continue except IOError, e: self.reconnect(e) continue except Exception, e: log.error('Caught during consumer.get() in listen: %s' % utils.e2str(e)) raise e try: self.consumer.ack() except Exception, e: log.error('Caught during consumer.ack() in listen: %s' % utils.e2str(e)) raise e if self._shutdown: log.info('Not handeling topic: %s because self._shutdown = True' % (topic,)) else: log.notice('Handeling topic: %s' % topic) tmp = topic.split('.') handle = False if tmp[0] == actionPrefix and len(tmp) > 1: pre, src, key = tmp if key == '_shutdown':