summaryrefslogtreecommitdiffstats
path: root/__init__.py
blob: da0557a967ec4b5dd55e8d1996dbda16c8ecacc5 (plain)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# coding=utf-8
from __future__ import absolute_import
import re
import io
import requests
import sleekxmpp
import datetime

from octoprint.plugin import EventHandlerPlugin, SettingsPlugin

class xmpp_cmd():
    def __init__(self, usage, name=None, desc=None, hidden=False):
        self.name = name
        self.desc = desc
        self.hidden = hidden
    def __call__(self, fn):
        if (self.name):
            fn.xmpp_cmd = self.name
        else:
            fn.xmpp_cmd = fn.__name__[len('_cmd_'):]
        if (self.desc):
            fn.desc = self.desc
        else:
            fn.desc = fn.__doc__
        fn.hidden = self.hidden
        return fn

class OctoXMPP(EventHandlerPlugin, SettingsPlugin):

    def initialize(self):
        jid = self._settings.get(['xmpp', 'jid'])
        resource = self._settings.get(['xmpp', 'resource'])
        passwd = self._settings.get(['xmpp', 'password'])

        full_jid = sleekxmpp.JID(jid, resource=resource)
        self._xmpp = sleekxmpp.ClientXMPP(full_jid, passwd)

        def __session_start(event):
            self._xmpp.send_presence()
            self._xmpp.get_roster()
            self._join_groupchats()

        self._xmpp.add_event_handler('session_start', __session_start)
        self._xmpp.add_event_handler('message', self._process_message)

        self._xmpp.register_plugin('xep_0030') # disco
        self._xmpp.register_plugin('xep_0045') # muc
        self._xmpp.register_plugin('xep_0066') # oob
        self._xmpp.register_plugin('xep_0085') # chat state
        self._xmpp.register_plugin('xep_0184') # delivery receipts
        self._xmpp.register_plugin('xep_0363') # http upload

        self._xmpp.connect()
        self._xmpp.process(wait=True)


    def unload(self):
        self._xmpp.disconnect(wait=True)

    def get_settings_defaults(self):
        return {
                'xmpp': {
                    'jid': "rupert@m3k.cc",
                    'resource': "Rupert",
                    'password': "KosselMini",
                    'recipients': [("groupchat", "rupert@conference.m3k.cc")]
                }
        }

    def _take_snapshot(self):
        snapshot = self._settings.global_get(['webcam', 'snapshot'])
        if (snapshot):
            req = requests.get(snapshot)

            if (req.ok):
                return (req.content, req.headers.get('content-type', None))

        return (None, None)

    def _msg_recipients(self, msg, send_image=True):
        for (chat_type, recipient) in self._settings.get(['xmpp', 'recipients']):
            self._xmpp.send_message(mto=recipient, mbody=msg, mtype=chat_type)

        if (send_image):
            (snapshot, content_type) = self._take_snapshot()
            if (snapshot):
                i = self._xmpp['xep_0363'].start_upload(
                        'rupert.jpg', io.BytesIO(snapshot), len(snapshot), content_type)

                def __send_get_url(get_url):
                    for (chat_type, recipient) in self._settings.get(['xmpp', 'recipients']):
                        m = self._xmpp.make_message(mto=recipient, mbody=get_url, mtype=chat_type)
                        m['oob']['url'] = get_url
                        m.send()

                self._xmpp.add_event_handler("http_upload::{}::finished".format(i),
                        __send_get_url, disposable=True)

    def _join_groupchats(self):
        nick = self._settings.get(['xmpp', 'resource'])
        for (chat_type, recipient) in self._settings.get(['xmpp', 'recipients']):
            if (chat_type == "groupchat"):
                self._xmpp['xep_0045'].joinMUC(recipient, nick)

    def on_event(self, event, data):
        if (event == "PrintDone"):
            self._msg_recipients("Zack, Feditsch!")
        elif (event == "PrintFailed"):
            self._msg_recipients("Da ging was schief!")
        elif (event == "PrintPaused"):
            self._msg_recipients("Druck pausiert.")
        elif (event == "PrintResumed"):
            self._msg_recipients("Druck resümiert.", False)
        elif (event == "PrintCancelled"):
            self._msg_recipients("Druck abgebrochen!", False)
        elif (event == "PrintStarted"):
            self._msg_recipients("Druck begonnen.", False)

    def _process_message(self, msg):
        nick = self._settings.get(['xmpp', 'resource'])
        if (msg.get_type() == "groupchat"):
            pattern = r"({}[\s\W]+){{1}}(?P<cmd>.*)".format(nick)
        else:
            pattern = r"({}[\s\W]+){{0,1}}(?P<cmd>.*)".format(nick)

        m = re.match(pattern, msg['body'], re.I)
        if (m):
            cmd = m.group('cmd')
        else:
            return

        if (' ' in cmd):
            (cmd, cmd_args) = cmd.split(' ', 1)
        else:
            cmd_args = None

        if (cmd_args is not None):
            if (' ' in cmd_args):
                cmd_args = cmd_args.split(' ')
            else:
                cmd_args = [cmd_args]
        else:
            cmd_args = []

        fn = getattr(self, "_cmd_{}".format(cmd), self.__cmd_unknown(cmd))

        fn(msg, *cmd_args)

    @xmpp_cmd("", hidden=True)
    def __cmd_unknown(self, cmd):
        def __cmd_unknown_reply(msg, *args):
            reply = msg.reply(body="Unknown command '{}' ({})!".format(cmd, ", ".join(args)))
            reply.send()

        return __cmd_unknown_reply

    @xmpp_cmd("status <temp|job|machine|all>")
    def _cmd_status(self, msg, subsystem='all'):
        subsystems = ['temp', 'job', 'machine']

        if (subsystem == 'all'):
            reply = '\n\n'.join([getattr(self, "_status_{}".format(s))() for s in subsystems])
        elif (subsystem in subsystems + ['state']):
            reply = getattr(self, "_status_{}".format(subsystem))()
        else:
            reply = "Unknown subsystem ({}).\nAvailable: {}".format(subsystem, ", ".join(['all'] + subsystems))

        msg.reply(body=reply).send()

    def _status_temp(self):
        if (self._printer.is_closed_or_error()):
            return "Temperatures:\nNo temperatures available."
        else:
            return "Temperatures:\n{}".format("\n".join(
                ["{tool}: {actual}°C (target: {target}°C; offset: {offset}°K)".format(tool=tool, **temp)
                    for (tool, temp) in self._printer.get_current_temperatures().items()]))

    def __format_duration(self, dur):
        return "{:0>2}:{:0>2}:{:0>2}".format(int(dur / 3600), int((dur / 60) % 60), int(dur % 60))

    def _status_job(self):
        state = self._printer.get_current_data()
        lines = ["Job state:"]
        if (state['job']['file']['origin']):
            lines.append("File: {}".format(state['job']['file']['name']))
            flags = state['state']['flags']

            if (flags['paused']):
                lines.append("Paused. ({:.1f}%)".format(state['progress']['completion']))
            elif (flags['printing']):
                lines.append("Printing... ({:.1f}%)".format(state['progress']['completion']))

            if (state['progress']['printTime']):
                if (state['progress']['printTimeLeft']):
                    lines.append("Printing for {}, with {} still to go.".format(
                        self.__format_duration(state['progress']['printTime']),
                        self.__format_duration(state['progress']['printTimeLeft'])))
                else:
                    lines.append("Printing for {}.".format(
                        self.__format_duration(state['progress']['printTime'])))

            if (state['job']['filament']):
                for (k, v) in state['job']['filament'].items():
                    if (v['length'] > 1000.0):
                        lines.append("Filament ({}): {:.1f}cm³/{:.2f}m".format(
                            k, v['volume'], v['length']/1000.0))
                    else:
                        lines.append("Filament ({}): {:.1f}cm³/{:.0f}mm".format(
                            k, v['volume'], v['length']))

        else:
            lines.append("No job loaded.")

        return "\n".join(lines)

    def _status_machine(self):
        lines = ["Machine state:"]
        state = self._printer.get_current_data()
        (con, port, baud, profile) = self._printer.get_current_connection()
        if (port):
            lines.append("Connected to {} ({}) via {} at {}".format(
                profile['name'], profile['model'], port, baud))

            lines.append("State: {}".format(self._printer.get_state_string()))
        else:
            lines.append("Not connected.")

        if (state['currentZ']):
            lines.append("Current Z position: {}".format(state['currentZ']))

        return "\n".join(lines)

    def _status_state(self):
        return "{}".format(self._printer.get_current_data())

    @xmpp_cmd("snapshot")
    def _cmd_snapshot(self, msg):
        (snapshot, content_type) = self._take_snapshot()
        if (snapshot):
            i = self._xmpp['xep_0363'].start_upload(
                    'rupert.jpg', io.BytesIO(snapshot), len(snapshot), content_type)

            def __send_get_url(get_url):
                m = msg.reply(body=get_url)
                m['oob']['url'] = get_url
                m.send()

            self._xmpp.add_event_handler("http_upload::{}::finished".format(i),
                    __send_get_url, disposable=True)

    @xmpp_cmd("job <start|pause|resume|cancel>")
    def _cmd_job(self, msg, action=None):
        actions = ['start', 'pause', 'resume', 'cancel', 'abort']
        job = self._printer.get_current_job()
        if (action in actions):
            if (not job['file']['origin']):
                reply = "No job loaded."
            else:
                reply = getattr(self, "_job_{}".format(action))()
        else:
            reply = "Unknown action ({}).\nAvailable: {}".format(action, ", ".join(actions))

        msg.reply(body=reply).send()

    def _job_start(self):
        job = self._printer.get_current_job()
        if (self._printer.is_ready()):
            self._printer.start_print()
            return "Started new Print Job: {}".format(job['file']['name'])
        else:
            return "Could not start Print Job."

    def _job_pause(self):
        if (self._printer.is_printing()):
            self._printer.pause_print()
            return "Paused Print Job."
        else:
            return "Could not pause Print Job."

    def _job_resume(self):
        if (self._printer.is_paused()):
            self._printer.toggle_pause_print()
            return "Resumed Print Job."
        else:
            return "Could not resume Print Job."

    def _job_cancel(self):
        if (self._printer.is_printing() or self._printer.is_paused()):
            self._printer.cancel_print()
            return "Canceld Print Job."
        else:
            return "Could not cancel Print Job."

    def _job_abort(self):
        return self._job_cancel()

    @xmpp_cmd("home (<x|y|z|e>)*|<all>")
    def _cmd_home(self, msg, *axis):
        axes = list(filter(lambda a: a in ('all', ) + self._printer.valid_axes, axis))
        if (len(axes) == 0):
            reply = "Specify one or more axes (x y z e) or 'all' to home."
        elif (len(axes) > 0 and 'all' in axes):
            axes = ['x', 'y', 'z', 'e']
            reply = "Homing all axes..."
        else:
            reply = "Homing axes {}...".format(", ".join(axes))

        self._printer.home(axes)
        msg.reply(body=reply).send()

    @xmpp_cmd("temp <toolN|bed> <temperature>")
    def _cmd_temp(self, msg, dev, temp):
        if (not self._printer.valid_heater_regex.match(dev)):
            reply = "Invalid heater name! It must match '{}'!".format(
                    self._printer.valid_heater_regex.pattern)
        else:
            reply = "Setting temperature of {} to {}".format(dev, temp)
            self._printer.set_temperature(dev, float(temp))

        msg.reply(body=reply).send()

    @xmpp_cmd("move (<x|y|z|e|f><position>)*")
    def _cmd_move(self, msg, *coords):
        if (self._printer.is_operational()):
            if (self._printer.is_printing() and not self._printer.is_paused()):
                reply = "You can't move the Printer while it's printing! Pause it first."
            else:
                pattern = re.compile(r"[{}][+-]?\d+(\.\d+)?".format("".join(self._printer.valid_axes + ('f',)), re.I))
                valid_coords = True
                for coord in coords:
                    if (not (coord and pattern.match(coord))):
                        reply = "Did not move. '{}' doesn't seem like a valid position of an axis".format(coord)
                        valid_coords = False
                        break

                if (valid_coords):
                    gcode = "G1 {}".format(" ".join(coords))
                    reply = "Moving printer... ({})".format(gcode)
                    self._printer.commands(gcode)

        else:
            reply = "Printer not operational!"

        msg.reply(body=reply).send()

    @xmpp_cmd("help <command|all>")
    def _cmd_help(self, msg, *cmd):
        lines = []
        if (len(cmd) == 0 or cmd[0] == 'all'):
            lines.append("Available commands:")
            for (attr, fn) in self.__dict__.items():
                if (attr.startswith('_cmd_') and hasattr(fn, 'xmpp_cmd') and not fn.hidden):
                    lines.append("{} - {}".format(fn.xmpp_cmd, fn.desc))
        else:
            fn = getattr(self, "_cmd_{}".format(cmd[0]), None)
            if (fn and hasattr(fn, 'xmpp_cmd')):
                lines.append("{} - {}".format(fn.xmpp_cmd, fn.desc))
            else:
                lines.append("{} not an available command.".format(cmd[0]))

        msg.reply(body="\n".join(lines)).send()


__plugin_name__ = "OctoXMPP"
__plugin_version__ = "0.2.2"
__plugin_description__ = "Control OctoPrint via XMPP messages."
__plugin_implementation__ = OctoXMPP()

def __plugin_unload__():
    global __plugin_implementation__
    __plugin_implementation__.unload()