Subversion Repositories HomeAutomation

Rev

Rev 1599 | Rev 1607 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | SVN | RSS feed

Rev Author Line No. Line
1595 runge 1
/*
2
 *
3
 *  Copyright (C) 2010  Mattias Runge
4
 *
5
 *  This program is free software; you can redistribute it and/or modify
6
 *  it under the terms of the GNU General Public License as published by
7
 *  the Free Software Foundation; either version 2 of the License, or
8
 *  (at your option) any later version.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License along
16
 *  with this program; if not, write to the Free Software Foundation, Inc.,
17
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
 *
19
 */
20
 
21
#include "Network.h"
22
 
23
#include <vector>
24
 
25
#include <boost/algorithm/string.hpp>
26
#include <boost/lexical_cast.hpp>
27
 
28
#include "net/Manager.h"
29
 
1596 runge 30
#include "broker/Manager.h"
31
 
32
#include "Protocol.h"
33
#include "Message.h"
34
 
35
#include "type/Bitset.h"
1597 runge 36
#include "type/common.h"
1596 runge 37
 
1595 runge 38
namespace atom {
39
namespace can {
40
 
1596 runge 41
enum
1595 runge 42
{
1596 runge 43
    PACKET_START = 253,
44
    PACKET_END   = 250,
45
    PACKET_PING  = 251
46
};
47
 
1598 runge 48
Network::Network(std::string address): broker::Subscriber(false), LOG("can::Network"), buffer_(2048)
1596 runge 49
{
1595 runge 50
    this->address_ = address;
51
    this->client_id_ = 0;
52
 
53
    // Examples of address
54
    // udp:192.168.1.250:1100
55
    // serial:/dev/ttyUSB0:38400
56
 
57
    std::vector<std::string> parts;
58
    boost::algorithm::split(parts, address, boost::is_any_of(":"), boost::algorithm::token_compress_off);
59
 
60
    if (parts.size() < 3)
61
    {
62
        LOG.Error("Malformed address string: " + address);
63
        return;
64
    }
65
 
66
    boost::algorithm::to_lower(parts[0]);
67
 
68
    if (parts[0] == "udp")
69
    {
70
        this->protocol_ = net::PROTOCOL_UDP;
71
    }
72
    else if (parts[0] == "serial")
73
    {
74
        this->protocol_ = net::PROTOCOL_SERIAL;
75
    }
76
    else
77
    {
78
        LOG.Error("Unknown protocol, only support udp and serial, got " + parts[0]);
79
        return;
80
    }
81
 
82
    this->address_ = parts[1];
83
    this->port_or_baud_ = boost::lexical_cast<unsigned int>(parts[2]);
84
 
85
    try
86
    {
87
        this->client_id_ = net::Manager::Instance()->Connect(this->protocol_, this->address_, this->port_or_baud_);
1596 runge 88
        LOG.Info("Connected to " + address);
1595 runge 89
 
1599 runge 90
        LOG.Info("Sending ping...");
91
 
1596 runge 92
        type::Byteset buffer(1);
93
        buffer[0] = PACKET_PING;
94
 
95
        net::Manager::Instance()->SendTo(this->client_id_, buffer);
1595 runge 96
    }
1606 runge 97
    catch (std::runtime_error& e)
1595 runge 98
    {
99
        LOG.Error(e.what());
100
    }
101
}
102
 
103
Network::~Network()
104
{
105
    net::Manager::Instance()->Disconnect(this->client_id_);
106
}
107
 
1596 runge 108
void Network::SlotOnTimeout(timer::TimerId timer_id)
109
{
110
    if (timer_id == this->timer_id_)
111
    {
112
        this->io_service_.post(boost::bind(&Network::SlotOnTimeoutHandler, this, timer_id));
113
    }
114
}
115
 
1595 runge 116
void Network::SlotOnMessageHandler(broker::Message::Pointer message)
117
{
1596 runge 118
    if (message->GetType() == broker::Message::CAN_MESSAGE)
119
    {
120
        Message* payload = static_cast<Message*>(message->GetPayload().get());
1598 runge 121
        type::Byteset data(17);
1596 runge 122
 
1598 runge 123
        data[0] = PACKET_START;
1596 runge 124
 
1598 runge 125
        unsigned int class_id = Protocol::Instance()->ResolveClassId(payload->GetClassName());
126
        data[4] = class_id << 1;
127
 
128
        if (payload->GetClassName() == "nmt")
129
        {
130
            unsigned int command_id = Protocol::Instance()->ResolveNMTCommandId(payload->GetCommandName());
131
            data[3] = command_id;
132
        }
133
        else
134
        {
135
            unsigned int direction_flag = Protocol::Instance()->ResolveDirectionFlag(payload->GetDirectionName());
136
            data[4] |= (direction_flag & 0x01);
137
 
138
            unsigned int module_id = Protocol::Instance()->ResolveModuleId(payload->GetModuleName());
139
            data[3] = module_id;
140
 
141
            data[2] = payload->GetId();
142
 
143
            unsigned int command_id = Protocol::Instance()->ResolveCommandId(payload->GetCommandName(), payload->GetModuleName());
144
            data[1] = command_id;
145
        }
1596 runge 146
 
1598 runge 147
        unsigned int highest_bit = 0;
148
        type::Bitset databits(64);
149
 
150
        xml::Node::NodeList variable_nodes;
151
        unsigned int start_bit;
152
        unsigned int bit_length;
153
        std::string type;
154
        std::string value;
155
 
156
        if (payload->GetClassName() == "nmt")
157
        {
158
            variable_nodes = Protocol::Instance()->GetNMTCommandVariables(payload->GetCommandName());
159
        }
160
        else
161
        {
162
            variable_nodes = Protocol::Instance()->GetCommandVariables(payload->GetCommandName(), payload->GetModuleName());
163
        }
164
 
165
        for (unsigned int n = 0; n < variable_nodes.size(); n++)
166
        {
167
            value = payload->GetVariable(variable_nodes[n].GetAttributeValue("name"));
168
 
169
            if (value == "")
170
            {
171
                continue;
172
            }
173
 
174
            start_bit = boost::lexical_cast<unsigned int>(variable_nodes[n].GetAttributeValue("start_bit"));
175
            bit_length = boost::lexical_cast<unsigned int>(variable_nodes[n].GetAttributeValue("bit_length"));
176
            type = variable_nodes[n].GetAttributeValue("type");
177
 
178
            if (highest_bit < start_bit + bit_length - 1)
179
            {
180
                highest_bit = start_bit + bit_length - 1;
181
            }
182
 
183
            if (type == "int")
184
            {
185
                Protocol::Instance()->EncodeInt(databits, start_bit, bit_length, value);
186
            }
187
            else if (type == "float")
188
            {
189
                Protocol::Instance()->EncodeFloat(databits, start_bit, bit_length, value);
190
            }
191
            else if (type == "ascii")
192
            {
193
                Protocol::Instance()->EncodeAscii(databits, start_bit, bit_length, value);
194
            }
195
            else if (type == "hexstring")
196
            {
197
                Protocol::Instance()->EncodeHexstring(databits, start_bit, bit_length, value);
198
            }
199
            else if (type == "enum")
200
            {
201
                value = variable_nodes[n].SelectChild("name", value).GetAttributeValue("id");
202
                Protocol::Instance()->EncodeUint(databits, start_bit, bit_length, value);
203
            }
204
            else// if (type == "uint")
205
            {
206
                Protocol::Instance()->EncodeUint(databits, start_bit, bit_length, value);
207
            }
208
        }
209
 
210
        //LOG.Debug(databits.ToDebugString());
211
 
212
        unsigned int length = ceil((float)highest_bit / 8.0f);
213
 
214
        data[5] = 1;
215
        data[6] = 0;
216
 
217
        data[7] = length;
218
 
219
        for (unsigned int n = 0; n < 8; n++)
220
        {
221
            data[8 + n] = databits.GetBytes()[n];
222
        }
223
 
224
        data[16] = PACKET_END;
225
 
226
        data.SetSize(17);
227
 
228
        //LOG.Debug("Bytes: " + data.ToDebugString());
229
        net::Manager::Instance()->SendTo(this->client_id_, data);
1596 runge 230
    }
1595 runge 231
}
232
 
1596 runge 233
void Network::SlotOnNewDataHandler(net::ClientId client_id, net::ServerId server_id, type::Byteset data)
1595 runge 234
{
1598 runge 235
    if (client_id != this->client_id_)
236
    {
237
            return;
238
    }
239
 
1596 runge 240
    static bool have_start = false;
241
 
242
    for (unsigned int n = 0; n < data.GetSize(); n++)
243
    {
244
        if (have_start)
245
        {
246
            if (data[n] == PACKET_END && this->buffer_.GetSize() == 15)
247
            {
248
                this->ProcessBuffer();
249
                have_start = false;
250
            }
251
            else
252
            {
253
                this->buffer_.Append(data[n]);
254
            }
255
        }
256
        else if (data[n] == PACKET_START)
257
        {
258
            this->buffer_.Clear();
259
            have_start = true;
260
        }
261
        else if (data[n] == PACKET_PING)
262
        {
263
            LOG.Info("Received pong.");
264
        }
265
    }
1595 runge 266
}
267
 
268
void Network::SlotOnNewStateHandler(net::ClientId client_id, net::ServerId server_id, net::ClientState client_state)
269
{
1598 runge 270
    if (client_id != this->client_id_)
271
    {
272
        return;
273
    }
274
 
1595 runge 275
    if (client_state == net::CLIENT_STATE_DISCONNECTED)
276
    {
1596 runge 277
        LOG.Warning("Got disconnected, setting reconnect timer...");
278
 
279
        this->timer_id_ = timer::Manager::Instance()->Set(10000, true);
1595 runge 280
        this->client_id_ = 0;
1596 runge 281
    }
282
    else
283
    {
284
        LOG.Debug("Got state: " + boost::lexical_cast<std::string>((int)client_state));
285
    }
286
}
287
 
288
void Network::SlotOnTimeoutHandler(timer::TimerId timer_id)
289
{
290
    try
291
    {
292
        this->client_id_ = net::Manager::Instance()->Connect(this->protocol_, this->address_, this->port_or_baud_);
293
        LOG.Info("Connected again.");
1595 runge 294
 
1596 runge 295
        timer::Manager::Instance()->Cancel(timer_id);
296
        this->timer_id_ = 0;
297
    }
1606 runge 298
    catch (std::runtime_error& e)
1596 runge 299
    {
300
        LOG.Error(e.what());
301
        LOG.Warning("Will try again soon...");
302
    }
303
}
304
 
305
void Network::ProcessBuffer()
306
{
307
    try
308
    {
309
        std::string class_name = "";
310
        std::string direction_name = "";
311
        std::string module_name = "";
312
        unsigned int id = 0;
313
        std::string command_name = "";
314
 
315
        unsigned int class_id = (this->buffer_[3] >> 1) & 0x0F;
316
        class_name = Protocol::Instance()->LookupClassName(class_id);
317
 
318
        if (class_name == "nmt")
1595 runge 319
        {
1596 runge 320
            unsigned int command_id = this->buffer_[2];
321
            command_name = Protocol::Instance()->LookupNMTCommandName(command_id);
1595 runge 322
        }
1596 runge 323
        else
1595 runge 324
        {
1596 runge 325
            unsigned int direction_flag = this->buffer_[3] & 0x01;
326
            direction_name = Protocol::Instance()->LookupDirectionFlag(direction_flag);
327
 
328
            unsigned int module_id = this->buffer_[2];
329
            module_name = Protocol::Instance()->LookupModuleName(module_id);
330
 
331
            id = this->buffer_[1];
332
 
333
            unsigned int command_id = this->buffer_[0];
334
            command_name = Protocol::Instance()->LookupCommandName(command_id, module_name);
1595 runge 335
        }
1596 runge 336
 
337
        Message* payload = new Message(class_name, direction_name, module_name, id, command_name);
338
 
339
        unsigned int length = this->buffer_[6];
340
 
341
        type::Byteset data_set(length);
342
 
343
        for (unsigned int n = 0; n < length; n++)
344
        {
345
            data_set.Append(this->buffer_[n + 7]);
346
        }
1598 runge 347
 
1596 runge 348
        type::Bitset databits(data_set);
349
        xml::Node::NodeList variable_nodes;
1598 runge 350
        unsigned int start_bit;
351
        unsigned int bit_length;
352
        std::string type;
353
        std::string value;
1596 runge 354
 
355
        if (class_name == "nmt")
356
        {
357
            variable_nodes = Protocol::Instance()->GetNMTCommandVariables(command_name);
358
        }
359
        else
360
        {
361
            variable_nodes = Protocol::Instance()->GetCommandVariables(command_name, module_name);
362
        }
363
 
364
        for (unsigned int n = 0; n < variable_nodes.size(); n++)
365
        {
1598 runge 366
            start_bit = boost::lexical_cast<unsigned int>(variable_nodes[n].GetAttributeValue("start_bit"));
367
            bit_length = boost::lexical_cast<unsigned int>(variable_nodes[n].GetAttributeValue("bit_length"));
368
            type = variable_nodes[n].GetAttributeValue("type");
1596 runge 369
 
1597 runge 370
            if (type == "int")
1596 runge 371
            {
1598 runge 372
                value = Protocol::Instance()->DecodeInt(databits, start_bit, bit_length);
1597 runge 373
            }
374
            else if (type == "float")
375
            {
1598 runge 376
                value = Protocol::Instance()->DecodeFloat(databits, start_bit, bit_length);
1597 runge 377
            }
378
            else if (type == "ascii")
379
            {
1598 runge 380
                value = Protocol::Instance()->DecodeAscii(databits, start_bit, bit_length);
1597 runge 381
            }
382
            else if (type == "hexstring")
383
            {
1598 runge 384
                value = Protocol::Instance()->DecodeHexstring(databits, start_bit, bit_length);
1597 runge 385
            }
386
            else if (type == "enum")
387
            {
1598 runge 388
                value = Protocol::Instance()->DecodeUint(databits, start_bit, bit_length);
1596 runge 389
                value = variable_nodes[n].SelectChild("id", value).GetAttributeValue("name");
390
            }
1597 runge 391
            else// if (type == "uint")
392
            {
1598 runge 393
                value = Protocol::Instance()->DecodeUint(databits, start_bit, bit_length);
1597 runge 394
            }
1596 runge 395
 
396
            payload->SetVariable(variable_nodes[n].GetAttributeValue("name"), value);
397
        }
398
 
399
        broker::Manager::Instance()->Post(broker::Message::Pointer(new broker::Message(broker::Message::CAN_MESSAGE, broker::Message::PayloadPointer(payload), this)));
1595 runge 400
    }
1596 runge 401
    catch (std::runtime_error& e)
1595 runge 402
    {
1596 runge 403
        LOG.Error("Malformed message received, " + std::string(e.what()));
1598 runge 404
        LOG.Debug("Bytes: " + this->buffer_.ToDebugString());
1595 runge 405
    }
1596 runge 406
 
407
    this->buffer_.Clear();
1595 runge 408
}
409
 
410
}; // namespace can
411
}; // namespace atom