]> git.aero2k.de Git - sirius.git/commitdiff
Move next-command-id generation into Message model.
authorTom Hunger <tehunger@gmail.com>
Fri, 23 Jan 2015 12:53:21 +0000 (12:53 +0000)
committerTom Hunger <tehunger@gmail.com>
Fri, 23 Jan 2015 12:53:21 +0000 (12:53 +0000)
The next command id is somewhat subtle because we're using it
to ack messages. Having it in its own class method is easier.

sirius/models/messages.py
sirius/protocol/protocol_loop.py

index 21b70597b645ffc4deb80a4fbbf254b0390247ce..e23eb654111e61066508abb9ddc9e57daa7524b0 100644 (file)
@@ -1,6 +1,7 @@
 import base64
 import datetime
 import logging
+from sqlalchemy import desc
 
 from sirius.models.db import db
 from sirius.models import hardware
@@ -83,3 +84,19 @@ class Message(db.Model):
 
         db.session.add(message)
         db.session.commit()
+
+    @classmethod
+    def get_next_command_id(cls):
+        """Return the next command id to be used by the bridge. Command ids
+        are used to ack messages so we need to make sure we don't have
+        any collisions. The best way to do so is to pick the
+        next-highest number after the ones we already used up.
+        """
+        last = cls.query.order_by(desc('print_id')).first()
+        if last is None:
+            next_print_id = 1
+        else:
+            next_print_id = last.print_id + 1
+
+        db.session.commit()
+        return next_print_id
index b2766d92202c31735c8548516955786f37da230a..dc4f1f5040270d25d27ac87b14adac44fc32a235 100644 (file)
@@ -9,7 +9,6 @@ send_message(device_address, message)
 import messages
 import json
 import logging
-from sqlalchemy import desc
 
 from sirius.coding import encoders
 from sirius.coding import decoders
@@ -37,19 +36,10 @@ class BridgeState(object):
         self.websocket = websocket
         self.pending_commands = dict()
         self.connected_devices = set()
-        # NB 0 is an invalid command id (AKA file-id) so we start at
-        # 10. This took me an hour to debug, do not change!
-
-        last = model_messages.Message.query.order_by(desc('id')).first()
-        if last is None:
-            next_print_id = 0
-        else:
-            next_print_id = last.id + 1
-        db.session.commit()
 
-        print next_print_id
-
-        self.next_command_id = next_print_id
+        # NB 0 is an invalid command id (AKA file-id) so we start at
+        # whatever the latest message id is to avoid collisions.
+        self.next_command_id = model_messages.Message.get_next_command_id()
 
 
 def send_message(device_address, message):