Example #1
0
 def launch_vlc_instance(self):
     while not self.thread.stopflag.is_set():
         try:
             nerve.log("Starting new instance of VLC")
             # TODO make this more robust
             cmdoptions = " --extraintf http --http-port 8081 --http-password test"
             if platform.system() == 'Windows':
                 cmdline = "C:\\Program Files\\VideoLAN\\VLC\\vlc.exe" + cmdoptions
                 # TODO the creationnflags is apparently a hax to get a detached process, but i'm not sure if it works or is needed
                 proc = subprocess.Popen(cmdline.split(' '),
                                         stdin=None,
                                         stdout=None,
                                         stderr=None,
                                         close_fds=True,
                                         creationflags=0x08)
             else:
                 cmdline = "/usr/bin/vlc" + cmdoptions
                 #cmdline = cmd + " --extraintf rc --rc-host localhost:4212"
                 #proc = subprocess.Popen(cmdline.split(' '), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                 #proc = subprocess.Popen(cmdline.split(' '), stdin=None, stdout=None, stderr=None, close_fds=True)
                 proc = subprocess.Popen(cmdline.split(' '),
                                         stdin=None,
                                         stdout=None,
                                         stderr=None,
                                         close_fds=True)
             return proc
         except:
             nerve.log(traceback.format_exc(), logtype='error')
         # if the process fails to launch, we sleep for a while and then try again
         time.sleep(7)
Example #2
0
 def run(self):
     while not self.stopflag.wait(60):
         try:
             for datalog in DatalogDevice.datalogs:
                 datalog._collect_data()
         except:
             nerve.log(traceback.format_exc(), logtype='error')
Example #3
0
 def run(self):
     while not self.stopflag.wait(60):
         try:
             for datalog in DatalogDevice.datalogs:
                 datalog._collect_data()
         except:
             nerve.log(traceback.format_exc(), logtype='error')
Example #4
0
    def run(self):
        self.xmms = xmmsclient.XMMS('PyXMMS')
        try:
            self.xmms.connect(os.getenv("XMMS_PATH"))
        except IOError as detail:
            print("Connection failed:" + str(detail))
            sys.exit(1)

        self.xmms.playback_current_id(self._get_info)
        self.xmms.broadcast_playback_current_id(self._get_info)

        while not self.thread.stopflag.is_set():
            fd = self.xmms.get_fd()

            if self.xmms.want_ioout():
                self.xmms.ioout()

            (i, o, e) = select.select([fd], [], [fd], 0.1)
            if i and i[0] == fd:
                self.xmms.ioin()
            if e and e[0] == fd:
                self.xmms.disconnect()
                self.thread.stopflag.set()

        nerve.log("exiting XMMS2 maintenance thread.")
Example #5
0
    def run(self):
        self.xmms = xmmsclient.XMMS('PyXMMS')
        try:
            self.xmms.connect(os.getenv("XMMS_PATH"))
        except IOError as detail:
            print ("Connection failed:" + str(detail))
            sys.exit(1)

        self.xmms.playback_current_id(self._get_info)
        self.xmms.broadcast_playback_current_id(self._get_info)

        while not self.thread.stopflag.is_set():
            fd = self.xmms.get_fd()

            if self.xmms.want_ioout():
                self.xmms.ioout()

            (i, o, e) = select.select([ fd ], [ ], [ fd ], 0.1)
            if i and i[0] == fd:
                self.xmms.ioin()
            if e and e[0] == fd:
                self.xmms.disconnect()
                self.thread.stopflag.set()

        nerve.log("exiting XMMS2 maintenance thread.")
Example #6
0
    def handle_connection(self, request):
        self.conn = request.source
        self.protocol = request.get_header('Sec-Websocket-Protocol', 'text')
        mimetype = protocols[self.protocol] if self.protocol in protocols else 'text/plain'
        self.on_connect()
        #while not self.conn.stopflag.is_set():
        #while not self.thread.stopflag.is_set():
        while True:
            try:
                msg = self.conn.read_message(mimetype=mimetype)
                if not msg:
                    break
                self.on_message(msg)

            except nerve.connect.QuitException:
                break

            except OSError as e:
                nerve.log("OSError: " + str(e), logtype='error')
                break

            except Exception as e:
                self.handle_connection_error(e, traceback.format_exc())

        self.on_disconnect()
Example #7
0
 def read_message(self):
     line = self.rfile.readline()
     if not line:
         return None
     line = line.rstrip('\r\n')
     nerve.log(" IN: " + line)
     return nerve.connect.Message(text=line + '\n')
Example #8
0
 def handle_error(self, error, traceback, request):
     accept = request.get_header('accept', default='text/html')
     if 'application/json' in accept and type(error) is not nerve.users.UserPermissionsRequired:
         nerve.log(traceback, logtype='error')
         self.load_json_view({ 'error' : repr(error) })
     else:
         super().handle_error(error, traceback, request)
Example #9
0
    def send(self, message, severity='info', label=''):
        # if a note with a matching label is found, update it and return
        for note in self.notifications:
            if label and note['label'] == label:
                note['occurances'] += 1
                note['acknowledged'] = False
                note['severity'] = severity
                note['message'] = message
                note['timestamp'] = time.time()
                return note['id']

        # create a new note with a new id
        nid = self.next_id
        self.next_id += 1

        self.notifications.insert(0, {
            'id': nid,
            'label': label,
            'timestamp': time.time(),
            'occurances': 1,
            'acknowledged': False,
            'severity': severity,
            'message': message
        })
        self.forward(self.notifications[0])
        nerve.log("[{0}] {1}".format(severity, message), logtype='notify')
        return nid
Example #10
0
    def run(self):
        nerve.log("Starting UDP Server")
        while True:
            self.open()

            while True:
                try:
                    data, addr = self.receive()
                    data = data.strip('\n')
                    (host, port) = addr
                    if data:
                        nerve.log("RECV <- " + str(host) + ":" + str(port) +
                                  ": " + data)
                        request = nerve.Request(self, None, 'QUERY', "/",
                                                {'requests[]': [data]})
                        controller = self.make_controller(request)
                        controller.handle_request(request)
                        self.send(controller.get_output() + '\n', addr)

                except socket.error as e:
                    nerve.log("Socket Error: " + str(e), logtype='error')
                    break

                except:
                    nerve.log(traceback.format_exc(), logtype='error')

            nerve.log("closing socket and retrying in 5 seconds")
            self.close()
            time.sleep(5)
Example #11
0
 def shutdown(self):
     self.stopflag.set()
     nerve.log("shutting down all threads")
     nerve.Thread.stop_all()
     nerve.Thread.join_all()
     os.system('stty sane')
     sys.exit(self.exitcode)
Example #12
0
def HTTPQueryHandler(_queryurl, *args, **kwargs):
    # TODO is this valid?  To have query options in the kwargs?  Might that cause problems for some things?  Should the key be deleted here if
    # present, so that it doesn't get encoded.
    #if 'query_method' in kwargs:
    #   method = kwargs['query_method']
    #   del kwargs['query_method']
    #else:
    #   method = 'POST'

    #method = kwargs['query_method'] if 'query_method' in kwargs else 'POST'

    args = nerve.Request.put_positional_args(args, kwargs)
    method = 'GET' if len(kwargs) <= 0 else 'POST'
    urlstring = urllib.parse.urlunparse((_queryurl.scheme, _queryurl.netloc, _queryurl.path, '', '', ''))

    nerve.log("executing query: " + method + " " + urlstring + " " + repr(args) + " " + repr(kwargs), logtype='query')

    r = requests.request(method, urlstring, json=None if method == 'GET' else kwargs)

    if r.status_code != 200:
        raise Exception("request to " + urlstring + " failed. " + str(r.status_code) + ": " + r.reason, r.text)

    (mimetype, pdict) = cgi.parse_header(r.headers['content-type'])
    if mimetype == 'application/json':
        result = r.json()
    elif mimetype == 'application/x-www-form-urlencoded':
        result = urllib.parse.parse_qs(r.text, keep_blank_values=True)
    else:
        result = r.text

    rstr = str(result)
    nerve.log("result: " + ( rstr[:75] + '...' if len(rstr) > 75 else rstr ), logtype='debug')
    return result
Example #13
0
 def readmsg(self):
     line = self.rfile.readline()
     if line == None:
         return None
     line = line.strip('\r\n')
     nerve.log(" IN: " + line)
     return Msg(line)
Example #14
0
    def send(self, message, severity='info', label=''):
        # if a note with a matching label is found, update it and return
        for note in self.notifications:
            if label and note['label'] == label:
                note['occurances'] += 1
                note['acknowledged'] = False
                note['severity'] = severity
                note['message'] = message
                note['timestamp'] = time.time()
                return note['id']

        # create a new note with a new id
        nid = self.next_id
        self.next_id += 1

        self.notifications.insert(0, {
            'id': nid,
            'label': label,
            'timestamp': time.time(),
            'occurances': 1,
            'acknowledged': False,
            'severity': severity,
            'message': message
        })
        self.forward(self.notifications[0])
        nerve.log("[{0}] {1}".format(severity, message), logtype='notify')
        return nid
Example #15
0
 def shutdown(self):
     self.stopflag.set()
     nerve.log("shutting down all threads")
     nerve.Task.stop_all()
     nerve.Task.join_all()
     os.system('stty sane')
     sys.exit(self.exitcode)
Example #16
0
 def read_message(self):
     line = self.rfile.readline()
     if not line:
         return None
     line = line.strip('\n')
     nerve.log("RECV <- " + str(self.hostname) + ":" + str(self.port) + ": " + line)
     return nerve.connect.Message(text=line)
Example #17
0
 def change_state(self, target_state):
     self.pipeline.set_state(target_state)
     (statechange, state, pending) = self.pipeline.get_state(timeout=5 * Gst.SECOND)
     if statechange != Gst.StateChangeReturn.SUCCESS:
         nerve.log("gstreamer failed waiting for state change to " + str(pending), logtype='error')
         return False
     return True
Example #18
0
 def readmsg(self):
     line = self.rfile.readline()
     if line == None:
         return None
     line = line.strip('\r\n')
     nerve.log(" IN: " + line)
     return Msg(line)
Example #19
0
    def run(self):
        nerve.log("Starting UDP Server")
        while True:
            self.open()

            while True:
                try:
                    data, addr = self.receive()
                    data = data.strip('\n')
                    (host, port) = addr
                    if data:
                        nerve.log("RECV <- " + str(host) + ":" + str(port) + ": " + data)
                        request = nerve.Request(self, None, 'QUERY', "/", { 'requests[]' : [ data ] })
                        controller = self.make_controller(request)
                        controller.handle_request(request)
                        self.send(controller.get_output() + '\n', addr)

                except socket.error as e:
                    nerve.log("Socket Error: " + str(e), logtype='error')
                    break

                except:
                    nerve.log(traceback.format_exc(), logtype='error')

            nerve.log("closing socket and retrying in 5 seconds")
            self.close()
            time.sleep(5)
Example #20
0
 def read_message(self, mimetype='text/plain'):
     line = self.rfile.readline()
     if not line:
         return None
     line = line.strip('\n')
     nerve.log("RECV <- " + str(self.hostname) + ":" + str(self.port) +
               ": " + line)
     return nerve.connect.Message(text=line, mimetype=mimetype)
Example #21
0
    def load_playlist(self, name):
        self.pipeline.stop()
        self.pipeline.queue = [ ]

        for media in nerve.medialib.Playlist(name).get_list():
            nerve.log("adding to playlist: " + media['artist'] + " - " + media['title'] + " (" + media['filename'] + ")")
            self.pipeline.queue.append(media['filename'])
        self.pipeline.play()
Example #22
0
 def handle_error(self, error, traceback, request):
     accept = request.get_header('accept', default='text/html')
     if 'application/json' in accept and type(
             error) is not nerve.users.UserPermissionsRequired:
         nerve.log(traceback, logtype='error')
         self.load_json_view({'error': repr(error)})
     else:
         super().handle_error(error, traceback, request)
Example #23
0
 def read_message(self, mimetype='text/plain'):
     # TODO should you check mimetype and die if not text?
     line = self.rfile.readline()
     if not line:
         return None
     line = line.rstrip('\r\n')
     nerve.log(" IN: " + line)
     return nerve.connect.Message(text=line + '\n', mimetype=mimetype)
Example #24
0
 def _on_event(event):
     nerve.log(event, logtype='warning')
     self.send_message(
         nerve.connect.Message('application/json',
                               data={
                                   'type': 'publish',
                                   'event': event
                               }))
Example #25
0
 def del_object(self, name):
     (path, _, leaf) = name.rpartition('/')
     root = self.get_object(path)
     if not root or not leaf:
         nerve.log("del_object(): invalid path given, " + name,
                   logtype='error')
         return None
     return root.del_child(leaf)
Example #26
0
 def websocket_wait_for_close(self):
     while True:
         (opcode, payload, headbyte1, headbyte2) = self.websocket_read_frame()
         if opcode == WS_OP_CLOSE:
             if payload:
                 nerve.log("websocket: received close message: " + str(struct.unpack("!H", payload[0:2])[0]) + " - " + payload[2:].decode('utf-8'))
             else:
                 nerve.log("websocket: received close message")
             return
Example #27
0
 def fetch_json(self, list_id):
     url = 'http://www.youtube.com/list_ajax?action_get_list=1&style=json&list=%s' % (list_id,)
     try:
         r = requests.get(url)
         if r.text:
             return json.loads(r.text)
     except:
         nerve.log("error fetching youtube list " + list_id, logtype='error')
     return None
Example #28
0
 def handle_connection_error(self, error, traceback):
     nerve.log(traceback, logtype='error')
     #self.send_message(nerve.connect.Message(text=traceback))
     self.send_message(
         nerve.connect.Message(mimetype='application/json',
                               data={
                                   'type': 'error',
                                   'text': traceback
                               }))
Example #29
0
def publish(topic, **event):
    if not allowed_publish.match(topic):
        raise Exception("invalid event topic in publish: " + topic)

    # TODO what about retaining the value?  This would require necessary branches to be filled out just so you can store the value somewhere, but it
    #      shouldn't be stored on the individual handlers; this kinda isn't the right datastructure to do it with
    event['topic'] = topic
    nerve.log("routing event " + repr(event), logtype='event')
    _route_event(event, topic, _event_listeners)
Example #30
0
    def load_playlist(self, name):
        self.pipeline.stop()
        self.pipeline.queue = []

        for media in nerve.medialib.Playlist(name).get_list():
            nerve.log("adding to playlist: " + media['artist'] + " - " +
                      media['title'] + " (" + media['filename'] + ")")
            self.pipeline.queue.append(media['filename'])
        self.pipeline.play()
Example #31
0
 def schedule(self, timeout, asynctask, *args, **kwargs):
     for (_, q_asynctask, _, _) in self.queue.queue:
         if asynctask == q_asynctask:
             nerve.log("asynctask already scheduled")
             # TODO maybe we should only reschedule the asynctask if the new time is less than the old time
             return
     self.queue.put((time.time() + timeout, asynctask, args, kwargs))
     with self.check:
         self.check.notify()
Example #32
0
 def schedule(self, timeout, asynctask, *args, **kwargs):
     for (_, q_asynctask, _, _) in self.queue.queue:
         if asynctask == q_asynctask:
             nerve.log("asynctask already scheduled")
             # TODO maybe we should only reschedule the asynctask if the new time is less than the old time
             return
     self.queue.put((time.time() + timeout, asynctask, args, kwargs))
     with self.check:
         self.check.notify()
Example #33
0
def publish(topic, **event):
    if not allowed_publish.match(topic):
        raise Exception("invalid event topic in publish: " + topic)

    # TODO what about retaining the value?  This would require necessary branches to be filled out just so you can store the value somewhere, but it
    #      shouldn't be stored on the individual handlers; this kinda isn't the right datastructure to do it with
    event['topic'] = topic
    nerve.log("routing event " + repr(event), logtype='event')
    _route_event(event, topic, _event_listeners)
Example #34
0
 def on_message(self, ws, msg):
     nerve.log(str(msg), logtype='debug')
     msg = json.loads(msg)
     if msg['type'] in ['reply', 'error']:
         self.resolve_pending(msg)
     elif msg['type'] == 'publish':
         msg['event']['topic'] = str(id(self)) + '/' + msg['event']['topic']
         #msg['event']['topic'] = self.url + '/' + msg['event']['topic']
         nerve.events.publish(**msg['event'])
Example #35
0
 def dispatch(self, msg):
     if msg.cmd == "PING":
         return self.sendmsg(msg.line.replace("PING", "PONG"))
     elif msg.cmd == "PRIVMSG":
         if msg.nargs < 1:
             return
         self.on_privmsg(msg)
     elif msg.cmd == "NOTICE":
         if msg.nargs < 1:
             return
         self.on_notice(msg)
     elif msg.cmd == "JOIN":
         if msg.nargs < 1:
             return
         channel = msg.args[0]
         if msg.nick == self.nick:
             if channel not in self.channels:
                 self.channels[channel] = Channel(channel)
         else:
             self.channels[channel].join(msg.nick)
             self.on_join(msg.nick)
     elif msg.cmd == "PART":
         if msg.nargs < 1:
             return
         channel = msg.args[0]
         if msg.nick == self.nick:
             # TODO rejoin??
             pass
         else:
             self.channels[channel].part(msg.nick)
             self.on_part(msg.nick)
     elif msg.cmd == "QUIT":
         for channel in self.channels:
             channel.part(msg.nick)
         self.on_quit(msg.nick)
     elif msg.cmd == "MODE":
         self.mode = msg.text
     elif msg.cmd == "NICK":
         self.on_nick(msg.nick, msg.args[0])
     elif msg.cmd == str(MsgType.RPL_NAMREPLY):
         if msg.nargs != 4:
             return
         channel = msg.args[2]
         for nick in msg.args[3].split():
             self.channels[channel].join(nick)
             self.on_name(nick)
     elif msg.cmd == str(MsgType.ERR_NICKNAMEINUSE):
         nerve.log("IRC: nick %s in use on server %s." %
                   (self.nick, self.hostname))
         # TODO add better altnick handling
         self.nick = self.nick + "_"
         self.sendmsg("NICK " + self.nick)
     elif msg.cmd == str(MsgType.RPL_ENDOFMOTD):
         self.connected = True
         nerve.log("IRC: Connection complete to server " + self.hostname)
         self.on_connect()
Example #36
0
    def evaluate(self):
        self._start_time = time.time()

        #self._output = io.StringIO()
        segments = self._parse_segments(self._contents)
        self._pycode = self._generate_python(segments)
        self._execute_python()

        self._run_time = time.time() - self._start_time
        nerve.log("pyhtml executed in %.4f seconds" % (self._run_time,))
Example #37
0
 def change_state(self, target_state):
     self.pipeline.set_state(target_state)
     (statechange, state,
      pending) = self.pipeline.get_state(timeout=5 * Gst.SECOND)
     if statechange != Gst.StateChangeReturn.SUCCESS:
         nerve.log("gstreamer failed waiting for state change to " +
                   str(pending),
                   logtype='error')
         return False
     return True
Example #38
0
 def handle_error(self, error, traceback, request):
     self.set_error(error)
     if not self._view:
         self.load_plaintext_view('')
     nerve.log(traceback, logtype='error')
     #if 'text/html' in request.headers['accept']:
     #   render some html
     #else:
     #   self.write(traceback)
     self._view.write(traceback)
Example #39
0
    def evaluate(self):
        self._start_time = time.time()

        #self._output = io.StringIO()
        segments = self._parse_segments(self._contents)
        self._pycode = self._generate_python(segments)
        self._execute_python()

        self._run_time = time.time() - self._start_time
        nerve.log("pyhtml executed in %.4f seconds" % (self._run_time,))
Example #40
0
 def handle_error(self, error, traceback, request):
     self.set_error(error)
     if not self._view:
         self.load_plaintext_view('')
     nerve.log(traceback, logtype='error')
     #if 'text/html' in request.headers['accept']:
     #   render some html
     #else:
     #   self.write(traceback)
     self._view.write(traceback)
Example #41
0
 def save_object_children(self):
     config = {}
     for objname in self._children.keys():
         if isinstance(self._children[objname], ObjectNode):
             config[objname] = self._children[objname].get_config_data()
         else:
             nerve.log("unable to save child object " + objname + ": " +
                       self._children[objname],
                       logtype='error')
     return config
Example #42
0
 def dispatch(self, msg):
     if msg.cmd == "PING":
         return self.sendmsg(msg.line.replace("PING", "PONG"))
     elif msg.cmd == "PRIVMSG":
         if msg.nargs < 1:
             return
         self.on_privmsg(msg)
     elif msg.cmd == "NOTICE":
         if msg.nargs < 1:
             return
         self.on_notice(msg)
     elif msg.cmd == "JOIN":
         if msg.nargs < 1:
             return
         channel = msg.args[0]
         if msg.nick == self.nick:
             if channel not in self.channels:
                 self.channels[channel] = Channel(channel)
         else:
             self.channels[channel].join(msg.nick)
             self.on_join(msg.nick)
     elif msg.cmd == "PART":
         if msg.nargs < 1:
             return
         channel = msg.args[0]
         if msg.nick == self.nick:
             # TODO rejoin??
             pass
         else:
             self.channels[channel].part(msg.nick)
             self.on_part(msg.nick)
     elif msg.cmd == "QUIT":
         for channel in self.channels:
             channel.part(msg.nick)
         self.on_quit(msg.nick)
     elif msg.cmd == "MODE":
         self.mode = msg.text
     elif msg.cmd == "NICK":
         self.on_nick(msg.nick, msg.args[0])
     elif msg.cmd == str(MsgType.RPL_NAMREPLY):
         if msg.nargs != 4:
             return
         channel = msg.args[2]
         for nick in msg.args[3].split():
             self.channels[channel].join(nick)
             self.on_name(nick)
     elif msg.cmd == str(MsgType.ERR_NICKNAMEINUSE):
         nerve.log("IRC: nick %s in use on server %s." % (self.nick, self.hostname))
         # TODO add better altnick handling
         self.nick = self.nick + "_"
         self.sendmsg("NICK " + self.nick)
     elif msg.cmd == str(MsgType.RPL_ENDOFMOTD):
         self.connected = True
         nerve.log("IRC: Connection complete to server " + self.hostname)
         self.on_connect()
Example #43
0
 def check_for_deleted(self):
     for libpath in self.path:
         if not os.path.exists(libpath):
             continue
         self.db.select('id,filename')
         self.db.where_like('filename', libpath + '%')
         for row in self.db.get('media'):
             if not os.path.exists(row[1]):
                 nerve.log("Removing " + row[1] + " (id: " + str(row[0]) + ")")
                 self.db.where('id', row[0])
                 self.db.delete('media')
Example #44
0
 def check_for_deleted(self):
     for libpath in self.path:
         if not os.path.exists(libpath):
             continue
         self.db.select('id,filename')
         self.db.where_like('filename', libpath + '%')
         for row in self.db.get('media'):
             if not os.path.exists(row[1]):
                 nerve.log("Removing " + row[1] + " (id: " + str(row[0]) + ")")
                 self.db.where('id', row[0])
                 self.db.delete('media')
Example #45
0
 def fetch_json(self, list_id):
     url = 'http://www.youtube.com/list_ajax?action_get_list=1&style=json&list=%s' % (
         list_id, )
     try:
         r = requests.get(url)
         if r.text:
             return json.loads(r.text)
     except:
         nerve.log("error fetching youtube list " + list_id,
                   logtype='error')
     return None
Example #46
0
 def websocket_wait_for_close(self):
     while True:
         (opcode, payload, headbyte1,
          headbyte2) = self.websocket_read_frame()
         if opcode == WS_OP_CLOSE:
             if payload:
                 nerve.log("websocket: received close message: " +
                           str(struct.unpack("!H", payload[0:2])[0]) +
                           " - " + payload[2:].decode('utf-8'))
             else:
                 nerve.log("websocket: received close message")
             return
Example #47
0
 def _collect_data(self):
     data = {}
     data['timestamp'] = time.time()
     for datapoint in self.get_setting('datapoints'):
         try:
             data[datapoint['name']] = nerve.query(datapoint['ref'])
         except Exception as exc:
             nerve.log("error collecting ref: " + str(datapoint['ref']) +
                       ": " + repr(exc),
                       logtype='error')
             data[datapoint['name']] = None
     self.db.insert(self.name, data)
Example #48
0
    def connect_any(self):
        while not self.stopflag.is_set():
            hostname = self.client.get_setting('hostname')
            port = self.client.get_setting('port')
            #url = urllib.parse.urlparse(address)
            try:
                nerve.log("connecting to " + hostname + ":" + str(port))
                self.client.connect(hostname, port)
                return

            except OSError as e:
                nerve.log("error connecting to " + hostname + ":" + port + ": " + str(e), logtype='error')
            self.stopflag.wait(10)
Example #49
0
    def connect_any(self):
        while not self.stopflag.is_set():
            hostname = self.client.get_setting('hostname')
            port = self.client.get_setting('port')
            #url = urllib.parse.urlparse(address)
            try:
                nerve.log("connecting to " + hostname + ":" + str(port))
                self.client.connect(hostname, port)
                return

            except OSError as e:
                nerve.log("error connecting to " + hostname + ":" + port + ": " + str(e), logtype='error')
            self.stopflag.wait(10)
Example #50
0
    def connect_any(self):
        while not self.stopflag.is_set():
            for address in self.client.servers:
                (hostname, port) = address.split(':', 1)
                #url = urllib.parse.urlparse(address)
                try:
                    nerve.log("connecting to " + hostname + ":" + port)
                    self.client.connect(hostname, port)
                    return

                except OSError as e:
                    nerve.log("error connecting to " + hostname + ":" + port + ": " + str(e), logtype='error')
            self.stopflag.wait(10)
Example #51
0
    def init_system(self):
        try:
            nerve.asyncs.init()
            nerve.users.init()

            if not self.load_config('settings.json'):
                return False
            if not self.run_init('init.py'):
                return False
            return True
        except:
            nerve.log(traceback.format_exc(), logtype='error')
            return False
Example #52
0
    def websocket_read_message(self):
        data = bytearray()
        msg_opcode = None
        while True:
            (opcode, payload, headbyte1,
             headbyte2) = self.websocket_read_frame()

            if headbyte1 & WS_B1_RSV:
                raise WebSocketError(
                    "websocket: received an invalid frame where first byte is "
                    + hex(headbyte1))
            if (headbyte2 & WS_B2_MASKBIT) == 0:
                raise WebSocketError(
                    "websocket: received an invalid frame where second byte is "
                    + hex(headbyte2))

            if opcode & WS_OP_CONTROL:
                if opcode == WS_OP_CLOSE:
                    self.websocket_write_close(1001, "")
                    self.closed = True
                    return (opcode, None)
                elif opcode == WS_OP_PING:
                    nerve.log("websocket: recieved ping from " +
                              ':'.join(self.client_address))
                    self.websocket_write_frame(WS_OP_PONG, payload)
                    continue
                elif opcode == WS_OP_PONG:
                    continue
                else:
                    raise WebSocketError(
                        "websocket: received invalid opcode " + hex(opcode))

            else:
                if msg_opcode == None:
                    msg_opcode = opcode
                else:
                    if opcode != WS_OP_CONT:
                        raise WebSocketError(
                            "websocket: expected CONT opcode, received " +
                            hex(opcode))

                data += payload
                if headbyte1 & WS_B1_FINBIT:
                    break

        if msg_opcode == WS_OP_TEXT:
            return (msg_opcode, data.decode('utf-8'))
        elif msg_opcode == WS_OP_BIN:
            return (msg_opcode, data)
        raise WebSocketError(
            "websocket: expected non-control opcode, received " + hex(opcode))
Example #53
0
    def on_receive(self, line):
        args = line.split(';')
        if len(args) != 6:
            nerve.log("mysensors: invalid message received: " + line, logtype='error')
            return
        nodeid = args[0]
        sensorid = args[1]
        msgtype = int(args[2])
        ack = int(args[3])
        subtype = int(args[4])
        payload = args[5]

        current_time = time.time()
        node = self.get_child(nodeid)
        if node:
            node.last_recv = current_time

        if msgtype == MsgType.PRESENTATION:
            nerve.log("mysensors: new sensor presented itself: " + str(nodeid) + ":" + str(sensorid))
            self._add_sensor(nodeid, sensorid, subtype, payload)

        elif msgtype == MsgType.SET:
            #sensor = self.get_sensor(nodeid, sensorid)
            sensor = node.get_child(sensorid)
            if not sensor:
                sensor = self._add_sensor(nodeid, sensorid)
            sensor.last_recv = current_time
            sensor.last_type = subtype
            sensor.last_value = payload
            # TODO publish event? maybe even have a per sensor or per node flag for whether to publish

        elif msgtype == MsgType.REQ:
            pass

        elif msgtype == MsgType.INTERNAL:
            if subtype == SubTypeInternal.I_LOG_MESSAGE:
                nerve.log("mysensors: " + payload)

            elif subtype == SubTypeInternal.I_BATTERY_LEVEL:
                node = self.get_node(nodeid)
                if node:
                    node.battery_level = float(payload)

            elif subtype == SubTypeInternal.I_SKETCH_NAME:
                node = self.get_node(nodeid)
                if node:
                    node.name = payload

            elif subtype == SubTypeInternal.I_SKETCH_VERSION:
                node = self.get_node(nodeid)
                if node:
                    node.version = payload

            elif subtype == SubTypeInternal.I_CONFIG:
                self.send("%s;%s;3;0;%d;M" % (nodeid, sensorid, subtype))

        elif msgtype == MsgType.STREAM:
            pass
        else:
            nerve.log("received an invalid message type: " + line, logtype='error')
Example #54
0
    def run_update(self):
        medialib = nerve.get_object('/modules/medialib')
        self.path = medialib.get_setting('medialib_dirs')
        self.ignore = medialib.get_setting('ignore_dirs')

        if not self.path:
            nerve.log("warning: medialib_dirs not set", logtype='warning')
            return

        nerve.log("Starting medialib update...")
        for libpath in self.path:
            for root, dirs, files in os.walk(libpath):
                if len(tuple(name for name in self.ignore if name in root)) > 0:
                    continue

                if self.stopflag.is_set():
                    return
                nerve.log("Searching " + root)
                for media in files:
                    #if media.endswith('.mp3'):
                    self.update_file(os.path.join(root, media), len(libpath.rstrip('/')) + 2)

        self.check_for_deleted()
        self.db.insert('info', { 'name' : 'last_updated', 'value' : str(time.time()) }, replace=True)
        nerve.log("Medialib update complete")
Example #55
0
    def run(self):
        while True:
            for name in self.updaters.keys():
                try:
                    self.updaters[name].check_update()
                except:
                    nerve.log(traceback.format_exc(), logtype='error')

            #nerve.query('/devices/notify/send', 'medialib update complete')

            if self.stopflag.is_set():
                break

            if self.interrupt.wait(60):
                self.interrupt.clear()
Example #56
0
    def do_request(self, request):
        result = None
        querystr = request.get_slug()

        if querystr != '':
            result = self.execute_query(querystr, **request.args)
        elif 'requests[]' in request.args:
            result = [ ]
            for querystr in request.args['requests[]']:
                try:
                    result.append(self.execute_query(querystr))
                except:
                    nerve.log(traceback.format_exc(), logtype='error')
                    result.append('error')
        self.load_json_view(result)
Example #57
0
    def __init__(self, **config):
        nerve.Server.__init__(self, **config)

        self.username = self.get_setting("username")
        self.password = self.get_setting("password")

        socketserver.TCPServer.__init__(self, ('', self.get_setting('port')), IRCRequestHandler)
        #if self.get_setting('ssl_enable'):
        #    self.socket = ssl.wrap_socket(self.socket, certfile=self.get_setting('ssl_cert'), server_side=True)

        sa = self.socket.getsockname()
        nerve.log('starting http(s) on port ' + str(sa[1]))

        self.thread = nerve.Task('HTTPServerTask', target=self.serve_forever)
        self.thread.daemon = True
        self.thread.start()
Example #58
0
    def run(self):
        while not self.stopflag.is_set():
            self.connect_any()

            while not self.stopflag.is_set():
                try:
                    msg = self.client.readmsg()
                    if not msg:
                        break
                    self.client.lastcontact = time.time()
                    self.client.dispatch(msg)
                except:
                    nerve.log("error on irc server connection to " + self.client.hostname + ":" + str(self.client.port), logtype='error')
                    nerve.log(traceback.format_exc(), logtype='error')
                    self.client.close()
                    break
            self.stopflag.wait(10)
Example #59
0
    def start(self):
        signal.signal(signal.SIGINT, self.signal_handler)

        if not self.init_system():
            self.shutdown()

        try:
            nerve.Task.start_all()

            #print (dir(nerve))
            while not self.stopflag.wait(0.5):
                pass
            nerve.log("exiting main loop")

        except:
            nerve.log(traceback.format_exc(), logtype='error')

        self.shutdown()
Example #60
0
    def handle_request(self, request):
        self.initialize(request)
        try:
            self.do_request(request)
            if self._view:
                self._view.finalize()

        except Exception as e:
            try:
                self.handle_error(e, traceback.format_exc(), request)
            except:
                nerve.log("error while handling exception:\n" + traceback.format_exc(), logtype='error')

        finally:
            self.finalize(request)

        if self._error is None:
            return True
        return False