From be1b0b8968fcb529b74d366974b75ca44e92fdde Mon Sep 17 00:00:00 2001 From: Tom Hunger Date: Fri, 23 Jan 2015 12:53:21 +0000 Subject: [PATCH] Move next-command-id generation into Message model. 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 | 17 +++++++++++++++++ sirius/protocol/protocol_loop.py | 16 +++------------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/sirius/models/messages.py b/sirius/models/messages.py index 21b7059..e23eb65 100644 --- a/sirius/models/messages.py +++ b/sirius/models/messages.py @@ -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 diff --git a/sirius/protocol/protocol_loop.py b/sirius/protocol/protocol_loop.py index b2766d9..dc4f1f5 100644 --- a/sirius/protocol/protocol_loop.py +++ b/sirius/protocol/protocol_loop.py @@ -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): -- 2.47.3