Exemple #1
0
 public void SendGw(byte[] addr, MsMessage msg)
 {
     msg.GetBytes();
     lock (_sendQueue) {
         _sendQueue.Enqueue(msg);
     }
 }
Exemple #2
0
 public MsForward(byte[] buf, int start, int end)
     : base(buf, start, end)
 {
     addr = new byte[_length - 3];
     Buffer.BlockCopy(buf, start + 3, addr, 0, _length - 3);
     msg = MsMessage.Parse(buf, start + _length, end);
 }
Exemple #3
0
 public void SendGw(MsDevice dev, MsMessage msg)
 {
     msg.GetBytes();
     lock (_sendQueue) {
         _sendQueue.Enqueue(msg);
     }
 }
Exemple #4
0
        public void Tick()
        {
            MsMessage msg = null;

            try {
                if (_port != null && _port.IsOpen)
                {
                    if (GetPacket(ref _inLen, _inBuffer, ref _inCnt, ref _inEscChar))
                    {
                        if (_inLen == 5 && _inBuffer[1] == (byte)MsMessageType.SUBSCRIBE)
                        {
                            _advTick = DateTime.Now.AddMilliseconds(100); // Send Advertise
                        }
                        if (!_pl.ProcessInPacket(this, _gateAddr, _inBuffer, 0, _inLen))
                        {
                            _port.DiscardInBuffer();
                        }
                        _inCnt = -1;
                    }
                    if (_busyTime <= DateTime.Now)
                    {
                        lock (_sendQueue) {
                            if (_sendQueue.Count > 0)
                            {
                                msg = _sendQueue.Dequeue();
                            }
                        }
                        if (msg != null)
                        {
                            SendRaw(msg, _sndBuf);
                            _busyTime = DateTime.Now.AddMilliseconds(msg.IsRequest ? 20 : 5);
                        }
                        else if (_advTick < DateTime.Now)
                        {
                            SendRaw(new MsAdvertise(gwIdx, 900), _sndBuf);
                            _advTick = DateTime.Now.AddMinutes(15);
                        }
                    }
                    return;
                }
            }
            catch (IOException ex) {
                if (_pl.verbose)
                {
                    Log.Error("MsGSerial({0}).CommThread() - {1}", gwIdx, ex.Message);
                }
            }
            catch (Exception ex) {
                Log.Error("MsGSerial({0}).CommThread() - {1}", gwIdx, ex.ToString());
            }
            if (_pl.verbose)
            {
                Log.Debug("MsGSerial({0}).CommThread - exit", gwIdx);
            }
            this.Dispose();
        }
Exemple #5
0
        public void SendGw(MsDevice dev, MsMessage msg)
        {
            if (_udp == null || msg == null)
            {
                return;
            }

            byte[]    buf = msg.GetBytes();
            IPAddress addr;

            if (dev == null)
            {
                addr = IPAddress.Broadcast;
                if (_bcIps == null)
                {
                    Log.Error("bcIps == null");
                    return;
                }
                foreach (var bc in _bcIps)
                {
                    try {
                        _udp.Send(buf, buf.Length, new IPEndPoint(bc, 1883));
                    }
                    catch (Exception ex) {
                        if (_pl.verbose)
                        {
                            Log.Warning("MsGUdp.SendGw({0}, {1}) - {2}", bc, msg, ex.Message);
                        }
                    }
                }
            }
            else if (dev.addr != null && dev.addr.Length == 4)
            {
                addr = new IPAddress(dev.addr);
                try {
                    _udp.Send(buf, buf.Length, new IPEndPoint(addr, 1883));
                }
                catch (Exception ex) {
                    if (_pl.verbose)
                    {
                        Log.Warning("MsGUdp.SendGw({0}, {1}) - {2}", addr, msg, ex.Message);
                    }
                }
            }
            else
            {
                return;
            }
            if (_pl.verbose)
            {
                Log.Debug("s {0}: {1}  {2}", addr, BitConverter.ToString(buf), msg.ToString());
            }
        }
Exemple #6
0
        private void SendRaw(MsMessage msg, byte[] tmp)
        {
            if (_port == null || !_port.IsOpen || msg == null)
            {
                return;
            }
            byte[] buf = msg.GetBytes();
            int    i, j = 0;
            byte   b;

            b = (byte)buf.Length;
            if (_useSlip)
            {
                tmp[j++] = 0xC0;
                if (b == 0xC0 || b == 0xDB)
                {
                    tmp[j++] = 0xDB;
                    tmp[j++] = (byte)(b ^ 0x20);
                }
                else
                {
                    tmp[j++] = b;
                }
                for (i = 0; i < buf.Length; i++)
                {
                    if (buf[i] == 0xC0 || buf[i] == 0xDB)
                    {
                        tmp[j++] = 0xDB;
                        tmp[j++] = (byte)(buf[i] ^ 0x20);
                    }
                    else
                    {
                        tmp[j++] = buf[i];
                    }
                }
                tmp[j++] = 0xC0;
            }
            else
            {
                tmp[j++] = b;
                for (i = 0; i < buf.Length; i++)
                {
                    tmp[j++] = buf[i];
                }
            }
            _port.Write(tmp, 0, j);

            if (_pl.verbose)
            {
                Log.Debug("s {0}: {1}  {2}", _port.PortName, BitConverter.ToString(buf), msg.ToString());
            }
        }
Exemple #7
0
        public void SendGw(byte[] arr, MsMessage msg)
        {
            if (_udp == null || arr == null || arr.Length != 4 || msg == null)
            {
                return;
            }
            byte[]    buf  = msg.GetBytes();
            IPAddress addr = new IPAddress(arr);

            _udp.Send(buf, buf.Length, new IPEndPoint(addr, 1883));
            if (_pl.verbose)
            {
                Log.Debug("s {0}: {1}  {2}", addr, BitConverter.ToString(buf), msg.ToString());
            }
        }
Exemple #8
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            if (_udp == null || _udp.Client == null)
            {
                return;
            }
            IPEndPoint re = new IPEndPoint(IPAddress.Any, 0);

            Byte[] buf = null;
            try {
                buf = _udp.EndReceive(ar, ref re);
                byte[] addr = re.Address.GetAddressBytes();
                if (!_myIps.Any(z => addr.SequenceEqual(z)))
                {
                    if (buf.Length > 1)
                    {
                        var mt = (MsMessageType)(buf[0] > 1 ? buf[1] : buf[3]);
                        if ((mt != MsMessageType.CONNECT && mt != MsMessageType.SEARCHGW) || _whiteList.Any(z => z.Check(addr)))
                        {
                            //_inBuf.Enqueue(new Tuple<byte[],byte[]>(addr, buf));
                            _pl.ProcessInPacket(this, addr, buf, 0, buf.Length);
                        }
                        else if (_pl.verbose)
                        {
                            var msg = MsMessage.Parse(buf, 0, buf.Length);
                            if (msg != null)
                            {
                                Log.Debug("restricted  {0}: {1}  {2}", this.Addr2If(addr), BitConverter.ToString(buf), msg.ToString());
                            }
                        }
                    }
                }
            }
            catch (ObjectDisposedException) {
                return;
            }
            catch (Exception ex) {
                Log.Error("ReceiveCallback({0}, {1}) - {2}", re, buf == null ? "null" : BitConverter.ToString(buf), ex.ToString());
            }
            if (_udp != null && _udp.Client != null)
            {
                _udp.BeginReceive(new AsyncCallback(ReceiveCallback), null);
            }
        }
Exemple #9
0
      public void SendGw(MsDevice dev, MsMessage msg) {
        if(_udp==null || msg==null) {
          return;
        }

        byte[] buf=msg.GetBytes();
        IPAddress addr;
        if(dev==null) {
          addr=IPAddress.Broadcast;
          foreach(var bc in _bcIps) {
            _udp.Send(buf, buf.Length, new IPEndPoint(bc, 1883));
          }
        } else if(dev.Addr!=null && dev.Addr.Length==4) {
          addr=new IPAddress(dev.Addr);
          _udp.Send(buf, buf.Length, new IPEndPoint(addr, 1883));
        } else {
          return;
        }
        if(_verbose.value) {
          Log.Debug("s  {0}: {1}  {2}", addr, BitConverter.ToString(buf), msg.ToString());
        }
      }
Exemple #10
0
      public void SendGw(byte[] arr, MsMessage msg) {
        if(_udp==null || arr==null || arr.Length!=4 || msg==null) {
          return;
        }
        byte[] buf=msg.GetBytes();
        IPAddress addr=new IPAddress(arr);
        _udp.Send(buf, buf.Length, new IPEndPoint(addr, 1883));
        if(_verbose.value) {
          Log.Debug("s  {0}: {1}  {2}", addr, BitConverter.ToString(buf), msg.ToString());
        }

      }
Exemple #11
0
    internal void ProcessInPacket(MsMessage msg) {
      if(_statistic.value && msg.MsgTyp!=MsMessageType.EncapsulatedMessage && msg.MsgTyp!=MsMessageType.PUBLISH) {
        Stat(false, msg.MsgTyp);
      }
      switch(msg.MsgTyp) {
      case MsMessageType.WILLTOPIC: {
          var tmp=msg as MsWillTopic;
          if(state==State.WillTopic) {
            _willPath=tmp.Path;
            _willRetain=tmp.Retain;
            state=State.WillMsg;
            ProccessAcknoledge(msg);
          }
        }
        break;
      case MsMessageType.WILLMSG: {
          var tmp=msg as MsWillMsg;
          if(state==State.WillMsg) {
            _wilMsg=tmp.Payload;
            Log.Info("{0}.state {1} => WILLTOPICREQ", Owner.path, state);
            state=State.PreConnect;
            ProccessAcknoledge(msg);
            Send(new MsConnack(MsReturnCode.Accepted));
          }
        }
        break;
      case MsMessageType.SUBSCRIBE: {
          var tmp=msg as MsSubscribe;

          SyncMsgId(msg.MessageId);
          Topic.Subscription s=null;
          ushort topicId=tmp.topicId;
          if(tmp.topicIdType!=TopicIdType.Normal || tmp.path.IndexOfAny(new[] { '+', '#' })<0) {
            TopicInfo ti=null;
            if(tmp.topicIdType==TopicIdType.Normal) {
              ti=GetTopicInfo(tmp.path, false);
            } else {
              ti=GetTopicInfo(tmp.topicId, tmp.topicIdType);
            }
            topicId=ti.TopicId;
          }
          Send(new MsSuback(tmp.qualityOfService, topicId, msg.MessageId, MsReturnCode.Accepted));
          if(state==State.PreConnect) {
            state=State.Connected;
          }
          s=Owner.Subscribe(tmp.path, PublishTopic, tmp.qualityOfService);
          _subsscriptions.Add(s);
        }
        break;
      case MsMessageType.REGISTER: {
          var  tmp=msg as MsRegister;
          ResetTimer();
          try {
            TopicInfo ti = GetTopicInfo(tmp.TopicPath, false);
            if(ti.topic!=null) {
              if(ti.topic.valueType==typeof(SmartTwi)) {
                if(ti.topic.GetValue()==null) {
                  ti.topic.SetValue(new SmartTwi(ti.topic), new TopicChanged(TopicChanged.ChangeArt.Value, Owner));
                } else {
                  (ti.topic as DVar<SmartTwi>).value.Reset();
                }
              } else if(ti.topic.valueType==typeof(TWIDriver)) {
                if(ti.topic.GetValue()==null) {
                  ti.topic.SetValue(new TWIDriver(ti.topic), new TopicChanged(TopicChanged.ChangeArt.Value, Owner));
                } else {
                  (ti.topic as DVar<TWIDriver>).value.Reset();
                }
              }
            }
            Send(new MsRegAck(ti.TopicId, tmp.MessageId, MsReturnCode.Accepted));
          }
          catch(Exception) {
            Send(new MsRegAck(0, tmp.MessageId, MsReturnCode.NotSupportes));
            Log.Warning("Unknown variable type by register {0}, {1}", Owner.path, tmp.TopicPath);
          }
        }
        break;
      case MsMessageType.REGACK: {
          var  tmp=msg as MsRegAck;
          ProccessAcknoledge(tmp);
          TopicInfo ti=_topics.FirstOrDefault(z => z.TopicId==tmp.TopicId);
          if(ti==null) {
            if(tmp.TopicId!=0xFFFF) { // 0xFFFF - remove variable
              Log.Warning("{0} RegAck({1:X4}) for unknown variable", Owner.path, tmp.TopicId);
            }
            return;
          }
          if(tmp.RetCode==MsReturnCode.Accepted) {
            ti.registred=true;
            if(ti.it!=TopicIdType.PreDefined) {
              Send(new MsPublish(ti.topic, ti.TopicId, QoS.AtLeastOnce));
            }
          } else {
            Log.Warning("{0} registred failed: {1}", ti.path, tmp.RetCode.ToString());
            _topics.Remove(ti);
            ti.topic.Remove();
          }
        }
        break;
      case MsMessageType.PUBLISH: {
          var tmp=msg as MsPublish;
          if(_statistic.value) {
            Stat(false, msg.MsgTyp, tmp.Dup);
          }
          TopicInfo ti=_topics.Find(z => z.TopicId==tmp.TopicId && z.it==tmp.topicIdType);
          if(ti==null && tmp.topicIdType!=TopicIdType.Normal) {
            ti=GetTopicInfo(tmp.TopicId, tmp.topicIdType, false);
          }
          if(tmp.qualityOfService==QoS.AtMostOnce || (tmp.qualityOfService==QoS.MinusOne && (tmp.topicIdType==TopicIdType.PreDefined || tmp.topicIdType==TopicIdType.ShortName))) {
            ResetTimer();
          } else if(tmp.qualityOfService==QoS.AtLeastOnce) {
            SyncMsgId(tmp.MessageId);
            Send(new MsPubAck(tmp.TopicId, tmp.MessageId, ti!=null?MsReturnCode.Accepted:MsReturnCode.InvalidTopicId));
          } else if(tmp.qualityOfService==QoS.ExactlyOnce) {
            SyncMsgId(tmp.MessageId);
            // QoS2 not supported, use QoS1
            Send(new MsPubAck(tmp.TopicId, tmp.MessageId, ti!=null?MsReturnCode.Accepted:MsReturnCode.InvalidTopicId));
          } else {
            throw new NotSupportedException("QoS -1 not supported "+Owner.path);
          }
          if(tmp.topicIdType==TopicIdType.PreDefined && tmp.TopicId>=LOG_D_ID && tmp.TopicId<=LOG_E_ID) {
            string str=string.Format("{0} msgId={2:X4}  msg={1}", this.Owner.name, tmp.Data==null?"null":(BitConverter.ToString(tmp.Data)+"["+ Encoding.ASCII.GetString(tmp.Data.Select(z => (z<0x20 || z>0x7E)?(byte)'.':z).ToArray())+"]"), tmp.MessageId);
            switch(tmp.TopicId) {
            case LOG_D_ID:
              Log.Debug("{0}", str);
              break;
            case LOG_I_ID:
              Log.Info("{0}", str);
              break;
            case LOG_W_ID:
              Log.Warning("{0}", str);
              break;
            case LOG_E_ID:
              Log.Error("{0}", str);
              break;
            }
          } else if(ti!=null) {
            if(tmp.Dup && _lastInPub!=null && tmp.MessageId==_lastInPub.MessageId) {  // arready recieved
            } else {
              SetValue(ti, tmp.Data, tmp.Retained);
            }
            _lastInPub=tmp;
          }
        }
        break;
      case MsMessageType.PUBACK: {
          ProccessAcknoledge(msg);
        }
        break;
      case MsMessageType.PINGREQ: {
          var tmp=msg as MsPingReq;
          if(state==State.ASleep) {
            if(string.IsNullOrEmpty(tmp.ClientId) || tmp.ClientId==Owner.name) {
              state=State.AWake;
              ProccessAcknoledge(msg);    // resume send proccess
            } else {
              SendGw(this, new MsDisconnect());
              state=State.Lost;
              Log.Warning("{0} PingReq from unknown device: {1}", Owner.path, tmp.ClientId);
            }
          } else {
            ResetTimer();
            if(_gate!=null) {
              _gate.SendGw(this, new MsMessage(MsMessageType.PINGRESP));
              if(_statistic.value) {
                Stat(true, MsMessageType.PINGRESP, false);
              }
            }
          }
        }
        break;
      case MsMessageType.DISCONNECT:
        Disconnect((msg as MsDisconnect).Duration);
        break;
      case MsMessageType.CONNECT:
        Connect(msg as MsConnect);
        break;
      case MsMessageType.EncapsulatedMessage: {
          Topic devR=Topic.root.Get("/dev");
          var fm=msg as MsForward;
          if(fm.msg==null) {
            if(_verbose.value) {
              Log.Warning("bad message {0}:{1}", _gate, fm.ToString());
            }
            return;
          }
          if(fm.msg.MsgTyp==MsMessageType.SEARCHGW) {
            _gate.SendGw(this, new MsGwInfo(gwIdx));
          } else if(fm.msg.MsgTyp==MsMessageType.DHCP_REQ) {
            var dr=fm.msg as MsDhcpReq;
            //******************************
            List<byte> ackAddr=new List<byte>();
            byte[] respPrev=null;

            foreach(byte hLen in dr.hLen) {
              if(hLen==0) {
                continue;
              } else if(hLen<=8) {
                byte[] resp;
                if(respPrev!=null && respPrev.Length==hLen) {
                  resp=respPrev;
                } else {
                  resp=new byte[hLen];

                  for(int i=0; i<5; i++) {
                    for(int j=0; j<resp.Length; j++) {
                      resp[j]=(byte)_rand.Next((i<3 && hLen==1)?32:1, (i<3 && hLen==1)?126:(j==0?254:255));
                    }
                    if(devR.children.Select(z => z as DVar<MsDevice>).Where(z => z!=null && z.value!=null).All(z => !z.value.CheckAddr(resp))) {
                      break;
                    } else if(i==4) {
                      for(int j=0; j<resp.Length; j++) {
                        resp[j]=0xFF;
                      }
                    }
                  }
                  respPrev=resp;
                }
                ackAddr.AddRange(resp);
              } else {
                if(_verbose.value) {
                  Log.Warning("{0}:{1} DhcpReq.hLen is too high", BitConverter.ToString(fm.addr), fm.msg.ToString());
                }
                ackAddr=null;
                break;
              }
            }
            if(ackAddr!=null) {
              _gate.SendGw(this, new MsForward(fm.addr, new MsDhcpAck(gwIdx, dr.xId, ackAddr.ToArray())));
            }
            //******************************
          } else {
            if(fm.msg.MsgTyp==MsMessageType.CONNECT) {
              var cm=fm.msg as MsConnect;
              if(fm.addr!=null && fm.addr.Length==2 && fm.addr[1]==0xFF) {    // DHCP V<0.3
                _gate.SendGw(this, new MsForward(fm.addr, new MsConnack(MsReturnCode.Accepted)));

                byte[] nAddr=new byte[1];
                do {
                  nAddr[0]=(byte)(_rand.Next(32, 254));
                } while(!devR.children.Select(z => z as DVar<MsDevice>).Where(z => z!=null && z.value!=null).All(z => !z.value.CheckAddr(nAddr)));
                Log.Info("{0} new addr={1:X2}", cm.ClientId, nAddr[0]);
                _gate.SendGw(this, new MsForward(fm.addr, new MsPublish(null, PredefinedTopics[".cfg/XD_DeviceAddr"], QoS.AtLeastOnce) { MessageId=1, Data=nAddr }));
              } else {
                DVar<MsDevice> dDev=devR.Get<MsDevice>(cm.ClientId);
                if(dDev.value==null) {
                  dDev.value=new MsDevice(this, fm.addr);
                  Thread.Sleep(0);
                  dDev.value.Owner=dDev;
                } else {
                  this.RemoveNode(dDev.value);
                  dDev.value._gate=this;
                  dDev.value.Addr=fm.addr;
                }
                this.AddNode(dDev.value);
                dDev.value.Connect(cm);
                foreach(var dub in devR.children.Select(z => z.GetValue() as MsDevice).Where(z => z!=null && z!=dDev.value && z.Addr!=null && z.Addr.SequenceEqual(fm.addr) && z._gate==this).ToArray()) {
                  dub.Addr=null;
                  dub._gate=null;
                  dub.state=State.Disconnected;
                }
              }
            } else {
              MsDevice dev=devR.children.Select(z => z.GetValue() as MsDevice).FirstOrDefault(z => z!=null && z.Addr!=null && z.Addr.SequenceEqual(fm.addr) && z._gate==this);
              if(dev!=null 
                && ((dev.state!=State.Disconnected && dev.state!=State.Lost) 
                  || fm.msg.MsgTyp==MsMessageType.CONNECT 
                  || (fm.msg.MsgTyp==MsMessageType.PUBLISH && (fm.msg as MsPublish).qualityOfService==QoS.MinusOne))) {
                dev.ProcessInPacket(fm.msg);
              } else if(fm.msg.MsgTyp==MsMessageType.PUBLISH && (fm.msg as MsPublish).qualityOfService==QoS.MinusOne) {
                var tmp=fm.msg as MsPublish;
                if(tmp.topicIdType==TopicIdType.PreDefined && tmp.TopicId>=LOG_D_ID && tmp.TopicId<=LOG_E_ID) {
                  string str=string.Format("{0}: msgId={2:X4} msg={1}", BitConverter.ToString(this.Addr), tmp.Data==null?"null":(BitConverter.ToString(tmp.Data)+"["+ Encoding.ASCII.GetString(tmp.Data.Select(z => (z<0x20 || z>0x7E)?(byte)'.':z).ToArray())+"]"), tmp.MessageId);
                  switch(tmp.TopicId) {
                  case LOG_D_ID:
                    Log.Debug(str);
                    break;
                  case LOG_I_ID:
                    Log.Info(str);
                    break;
                  case LOG_W_ID:
                    Log.Warning(str);
                    break;
                  case LOG_E_ID:
                    Log.Error(str);
                    break;
                  }
                }
              } else {
                if(dev==null || dev.Owner==null) {
                  if(_verbose.value) {
                    Log.Debug("{0} via {1} unknown device", BitConverter.ToString(fm.addr), this.name);
                  }
                } else {
                  if(_verbose.value) {
                    Log.Debug("{0} via {1} inactive", dev.Owner.name, this.name);
                  }
                }
                _gate.SendGw(this, new MsForward(fm.addr, new MsDisconnect()));
              }
            }
          }
        }
        break;
      }
    }
Exemple #12
0
 public void SendGw(MsDevice dev, MsMessage msg) {
   if(_gate!=null) {
     _gate.SendGw(this, new MsForward(dev.Addr, msg));
   }
 }
Exemple #13
0
        internal bool ProcessInPacket(IMsGate gate, byte[] addr, byte[] buf, int start, int end)
        {
            var msg = MsMessage.Parse(buf, start, end);

            if (msg == null)
            {
                if (verbose)
                {
                    Log.Warning("r {0}: {1}  bad message", gate.Addr2If(addr), BitConverter.ToString(buf, start, end - start));
                }
                return(false);
            }
            if (msg.MsgTyp == MsMessageType.ADVERTISE || msg.MsgTyp == MsMessageType.GWINFO)
            {
                return(true);
            }
            if (verbose)
            {
                Log.Debug("r {0}: {1}  {2}", gate.Addr2If(addr), BitConverter.ToString(buf, start, end - start), msg.ToString());
            }
            if (msg.MsgTyp == MsMessageType.SEARCHGW)
            {
                if ((msg as MsSearchGW).radius == 0 || (msg as MsSearchGW).radius == gate.gwRadius)
                {
                    gate.SendGw((MsDevice)null, new MsGwInfo(gate.gwIdx));
                }
                return(true);
            }
            if (msg.MsgTyp == MsMessageType.DHCP_REQ)
            {
                var dr = msg as MsDhcpReq;
                if ((dr.radius == 0 || dr.radius == 1))
                {
                    List <byte> ackAddr  = new List <byte>();
                    byte[]      respPrev = null;
                    foreach (byte hLen in dr.hLen)
                    {
                        if (hLen == 0)
                        {
                            continue;
                        }
                        else if (hLen <= 8)
                        {
                            byte[] resp;
                            if (respPrev != null && respPrev.Length == hLen)
                            {
                                resp = respPrev;
                            }
                            else
                            {
                                resp = new byte[hLen];
                                for (int i = 0; i < 5; i++)
                                {
                                    for (int j = 0; j < resp.Length; j++)
                                    {
                                        resp[j] = (byte)_rand.Next(j == 0 ? 4 : 0, (i < 3 && hLen == 1) ? 31 : (j == 0 ? 254 : 255));
                                    }
                                    if (!_devs.Any(z => z.gwIdx == gate.gwIdx && z.CheckAddr(resp)))
                                    {
                                        break;
                                    }
                                    else if (i == 4)
                                    {
                                        for (int j = 0; j < resp.Length; j++)
                                        {
                                            resp[j] = 0xFF;
                                        }
                                    }
                                }
                                respPrev = resp;
                            }
                            ackAddr.AddRange(resp);
                        }
                        else
                        {
                            if (verbose)
                            {
                                Log.Warning("r {0}: {1}  DhcpReq.hLen is too high", gate.Addr2If(addr), BitConverter.ToString(buf, start, end - start));
                            }
                            ackAddr = null;
                            break;
                        }
                    }
                    if (ackAddr != null)
                    {
                        gate.SendGw((MsDevice)null, new MsDhcpAck(gate.gwIdx, dr.xId, ackAddr.ToArray()));
                    }
                }
                return(true);
            }
            if (msg.MsgTyp == MsMessageType.CONNECT)
            {
                var      cm  = msg as MsConnect;
                MsDevice dev = _devs.FirstOrDefault(z => z.owner != null && z.owner.name == cm.ClientId);
                if (dev == null)
                {
                    var dt = Topic.root.Get("/dev/" + cm.ClientId, true, _owner);
                    dev = new MsDevice(this, dt);
                    _devs.Add(dev);
                    dt.SetAttribute(Topic.Attribute.Readonly);
                    dt.SetField("editor", "MsStatus", _owner);
                    dt.SetField("cctor.MqsDev", string.Empty, _owner);
                }
                dev._gate = gate;
                dev.addr  = addr;
                dev.Connect(cm);
                foreach (var dub in _devs.Where(z => z != dev && z.CheckAddr(addr) && z._gate == gate).ToArray())
                {
                    dub.addr  = null;
                    dub._gate = null;
                    dub.state = State.Disconnected;
                }
            }
            else
            {
                MsDevice dev = _devs.FirstOrDefault(z => z.addr != null && z.addr.SequenceEqual(addr) && z._gate == gate);
                if (dev != null && (dev.state != State.Disconnected && dev.state != State.Lost))
                {
                    dev.ProcessInPacket(msg);
                }
                else
                {
                    if (verbose)
                    {
                        if (dev == null || dev.owner == null)
                        {
                            Log.Debug("{0} unknown device", gate.Addr2If(addr));
                        }
                        else
                        {
                            Log.Debug("{0} inactive device: {1}", gate.Addr2If(addr), dev.owner.path);
                        }
                    }
                    gate.SendGw(addr, new MsDisconnect());
                }
            }
            return(true);
        }
Exemple #14
0
 public MsForward(byte[] addr, MsMessage msg)
   : base(MsMessageType.EncapsulatedMessage) {
   this.addr=addr;
   this.msg=msg;
 }
Exemple #15
0
 private void Send(MsMessage msg) {
   if(state!=State.Disconnected && state!=State.Lost) {
     msg.Addr=this.Addr;
     bool send=true;
     if(msg.MessageId==0 && msg.IsRequest) {
       msg.MessageId=NextMsgId();
       lock(_sendQueue) {
         if(_sendQueue.Count>0 || state==State.ASleep) {
           send=false;
         }
         _sendQueue.Enqueue(msg);
       }
     }
     if(send) {
       if(msg.IsRequest) {
         _tryCounter=2;
       }
       SendIntern(msg);
     }
   }
 }
      private static void SendRaw(MsGSerial g, MsMessage msg, byte[] tmp) {
        if(g==null || g._port==null || !g._port.IsOpen || msg==null) {
          return;
        }
        byte[] buf=msg.GetBytes();
        int i, j=0;
        byte b;
        b=(byte)buf.Length;
#if UART_RAW_MQTTSN
        tmp[j++]=b;
        for(i=0; i<buf.Length; i++) {
          tmp[j++]=buf[i];
        }
#else
        tmp[j++]=0xC0;
        if(b==0xC0 || b==0xDB) {
          tmp[j++]=0xDB;
          tmp[j++]=(byte)(b ^ 0x20);
        } else {
          tmp[j++]=b;
        }
        for(i=0; i<buf.Length; i++) {
          if(buf[i]==0xC0 || buf[i]==0xDB) {
            tmp[j++]=0xDB;
            tmp[j++]=(byte)(buf[i] ^ 0x20);
          } else {
            tmp[j++]=buf[i];
          }
        }
        tmp[j++]=0xC0;
#endif
        g._port.Write(tmp, 0, j);

        if(_verbose.value) {
          Log.Debug("s {0}: {1}  {2}", g._port.PortName, BitConverter.ToString(buf), msg.ToString());
        }
      }
 private static void SendRaw(MsGSerial g, MsMessage msg) {
   if(g==null || g._port==null || !g._port.IsOpen || msg==null || msg.Addr==null || msg.Addr.Length!=1) {
     return;
   }
   int i;
   byte[] b=new byte[1];
   b[0]=0xC0;
   g._port.Write(b, 0, 1);
   if(msg.Addr[0]==0xC0 || msg.Addr[0]==0xDB) {
     b[0]=0xDB;
     g._port.Write(b, 0, 1);
     b[0]=(byte)(msg.Addr[0] ^ 0x20);
   } else {
     b[0]=msg.Addr[0];
   }
   g._port.Write(b, 0, 1);
   byte[] buf=msg.GetBytes();
   for(i=0; i<buf.Length; i++) {
     if(buf[i]==0xC0 || buf[i]==0xDB) {
       b[0]=0xDB;
       g._port.Write(b, 0, 1);
       b[0]=(byte)(buf[i] ^ 0x20);
     } else {
       b[0]=buf[i];
     }
     g._port.Write(b, 0, 1);
   }
   b[0]=0xC0;
   g._port.Write(b, 0, 1);
   if(_verbose.value) {
     Log.Debug("s {0:X2}:{1:X2}:{2} \t{3}", g.gwIdx, msg.Addr[0], BitConverter.ToString(buf), msg.ToString());
   }
 }
 public void Send(MsMessage msg) {
   lock(_sendQueue) {
     _sendQueue.Enqueue(msg);
   }
 }
Exemple #19
0
 public MsForward(byte[] addr, MsMessage msg)
     : base(MsMessageType.EncapsulatedMessage)
 {
     this.addr = addr;
     this.msg  = msg;
 }
Exemple #20
0
 private void ProccessAcknoledge(MsMessage rMsg) {
   ResetTimer();
   MsMessage msg=null;
   lock(_sendQueue) {
     MsMessage reqMsg;
     if(_sendQueue.Count>0 && (reqMsg=_sendQueue.Peek()).MsgTyp==rMsg.ReqTyp && reqMsg.MessageId==rMsg.MessageId) {
       _sendQueue.Dequeue();
       _waitAck=false;
       if(_sendQueue.Count>0 && !(msg=_sendQueue.Peek()).IsRequest) {
         _sendQueue.Dequeue();
       }
     }
   }
   if(msg!=null || state==State.AWake) {
     if(msg!=null && msg.IsRequest) {
       _tryCounter=2;
     }
     SendIntern(msg);
   }
 }
Exemple #21
0
 private void SendIntern(MsMessage msg) {
   while((msg!=null || state==State.AWake) && state!=State.ASleep) {
     if(msg!=null) {
       if(_gate!=null) {
         Stat(true, msg.MsgTyp, ((msg is MsPublish && (msg as MsPublish).Dup) || (msg is MsSubscribe && (msg as MsSubscribe).dup)));
         try {
           _gate.SendGw(this, msg);
         }
         catch(ArgumentOutOfRangeException ex) {
           Log.Warning("{0} - {1}", this.name, ex.Message);
           if(msg.IsRequest) {
             lock(_sendQueue) {
               if(_sendQueue.Count>0 && _sendQueue.Peek()==msg) {
                 _sendQueue.Dequeue();
                 _waitAck=false;
               }
             }
           }
           msg=null;
         }
       }
       if(msg!=null && msg.IsRequest) {
         ResetTimer(_rand.Next(ACK_TIMEOUT, ACK_TIMEOUT*5/3)/(_tryCounter+1));  // 600, 1000
         _waitAck=true;
         break;
       }
       if(_waitAck) {
         break;
       }
     }
     msg=null;
     lock(_sendQueue) {
       if(_sendQueue.Count==0 && state==State.AWake) {
         if(_gate!=null) {
           _gate.SendGw(this, new MsMessage(MsMessageType.PINGRESP));
           Stat(true, MsMessageType.PINGRESP, false);
         }
         state=State.ASleep;
         break;
       }
       if(_sendQueue.Count>0 && !(msg=_sendQueue.Peek()).IsRequest) {
         _sendQueue.Dequeue();
       }
     }
   }
 }
Exemple #22
0
 private static void PrintPacket(MsDevice dev, MsMessage msg, byte[] buf) {
   if(_verbose.value) {
     Log.Debug("r {4:X2}:{0}:{1} \t{2}:{3}", BitConverter.ToString(msg.Addr??new byte[0]), BitConverter.ToString(buf??new byte[0]), (dev!=null && dev.Owner!=null)?dev.Owner.name:string.Empty, msg.ToString(), (dev!=null && dev._gate!=null)?dev._gate.gwIdx:0xFF);
   }
 }
Exemple #23
0
 private void SendIntern(MsMessage msg) {
   while(state==State.AWake || (msg!=null && (state!=State.ASleep || msg.MsgTyp==MsMessageType.DISCONNECT))) {
     if(msg!=null) {
       if(_gate!=null) {
         if(_statistic.value) {
           Stat(true, msg.MsgTyp, ((msg is MsPublish && (msg as MsPublish).Dup) || (msg is MsSubscribe && (msg as MsSubscribe).dup)));
         }
         try {
           _gate.SendGw(this, msg);
         }
         catch(ArgumentOutOfRangeException ex) {
           Log.Warning("{0} - {1}", this.name, ex.Message);
           if(msg.IsRequest) {
             lock(_sendQueue) {
               if(_sendQueue.Count>0 && _sendQueue.Peek()==msg) {
                 _sendQueue.Dequeue();
                 _waitAck=false;
               }
             }
           }
           msg=null;
         }
       }
       if(msg!=null && msg.IsRequest) {
         ResetTimer(_rand.Next(ACK_TIMEOUT, ACK_TIMEOUT*5/3)/(_tryCounter+1));  // 600, 1000
         _waitAck=true;
         break;
       }
       if(_waitAck) {
         break;
       }
     }
     msg=null;
     lock(_sendQueue) {
       if(_sendQueue.Count==0 && state==State.AWake) {
         if(_gate!=null) {
           _gate.SendGw(this, new MsMessage(MsMessageType.PINGRESP));
           if(_statistic.value) {
             Stat(true, MsMessageType.PINGRESP, false);
           }
         }
         var st=Owner.Get<long>(".cfg/XD_SleepTime", Owner);
         ResetTimer(st.value>0?(3100+(int)st.value*1550):_duration);  // t_wakeup
         state=State.ASleep;
         break;
       }
       if(_sendQueue.Count>0 && !(msg=_sendQueue.Peek()).IsRequest) {
         _sendQueue.Dequeue();
       }
     }
   }
 }
Exemple #24
0
 private void SendIntern(MsMessage msg) {
   while((msg!=null || state==State.AWake) && state!=State.ASleep) {
     if(msg!=null) {
       if(_gate!=null) {
         Stat(true, msg.MsgTyp, ((msg is MsPublish && (msg as MsPublish).Dup) || (msg is MsSubscribe && (msg as MsSubscribe).dup)));
         _gate.Send(msg);
       }
       if(msg.IsRequest) {
         ResetTimer(ACK_TIMEOUT);
         _waitAck=true;
         break;
       }
       if(_waitAck) {
         break;
       }
     }
     msg=null;
     lock(_sendQueue) {
       if(_sendQueue.Count==0 && state==State.AWake) {
         if(_gate!=null) {
           _gate.Send(new MsMessage(MsMessageType.PINGRESP) { Addr=this.Addr });
           Stat(true, MsMessageType.PINGRESP, false);
         }
         state=State.ASleep;
         break;
       }
       if(_sendQueue.Count>0 && !(msg=_sendQueue.Peek()).IsRequest) {
         _sendQueue.Dequeue();
       }
     }
   }
 }
Exemple #25
0
 public void SendGw(byte[] addr, MsMessage msg) {
   if(_gate!=null && addr!=null) {
     _gate.SendGw(this, new MsForward(addr, msg));
   }
 }
Exemple #26
0
 public MsForward(byte[] buf, int start, int end)
   : base(buf, start, end) {
   addr=new byte[_length-3];
   Buffer.BlockCopy(buf, start+3, addr, 0, _length-3);
   msg=MsMessage.Parse(buf, start+_length, end);
 }
Exemple #27
0
 public void SendGw(byte[] addr, MsMessage msg) {
   msg.GetBytes();
   lock(_sendQueue) {
     _sendQueue.Enqueue(msg);
   }
 }
 public void SendGw(MsDevice dev, MsMessage msg) {
   msg.GetBytes();
   lock(_sendQueue) {
     _sendQueue.Enqueue(msg);
   }
 }
Exemple #29
0
      public void Send(MsMessage msg) {
        if(_udp==null || msg==null || msg.Addr==null || msg.Addr.Length!=4) {
          return;
        }

        byte[] buf=msg.GetBytes();

        if(IPAddress.Broadcast.GetAddressBytes().SequenceEqual(msg.Addr)) {
          foreach(var bc in _bcIps) {
            _udp.Send(buf, buf.Length, new IPEndPoint(bc, 1883));
          }
        } else {
          _udp.Send(buf, buf.Length, new IPEndPoint(new IPAddress(msg.Addr), 1883));
        }
        if(_verbose.value) {
          Log.Debug("s {0:X2}:{1}:{2} \t{3}", gwIdx, BitConverter.ToString(msg.Addr), BitConverter.ToString(buf), msg.ToString());
        }
      }