public BumizObjectInfo(string name, string channelName, ObjectAddress address, int timeout) { Name = name; ChannelName = channelName; Address = address; Timeout = timeout; }
private void SetHostOjectField(ICSharpScriptObjectFieldAccesor scriptObject, string fieldName, object obj) { if (scriptObject == null) { return; } while (true) { try { if (!executeInSeparateAppDomain) { scriptObject.SetField(fieldName, obj); } else { scriptObject.SetField(fieldName, ObjectAddress.GetAddress(obj)); } break; } catch (NotSupportedException) { // capture the exception and try again. This happens because there was a GC call between // the time we obtained the raw address of obj and the call to SetField() } } }
public static void SendManyInteleconCommandsProgressive(this IMonoChannel channel, List <IInteleconCommand> commands, ObjectAddress objectAddress, int timeout, Action <ISendResultWithAddress> onEachComplete) { foreach (var command in commands) { channel.SendInteleconCommandAsync(command, objectAddress, timeout, onEachComplete); } }
public DateTime?GetLastBadTime(ObjectAddress obj) { if (_ot.ContainsKey(obj)) { return(_ot[obj]); } return(null); }
public void RemoveDNetId(ObjectAddress address) { if (_addressMap.ContainsKey(address.Way)) { if (_addressMap[address.Way].ContainsKey(address.Value)) { _addressMap[address.Way].Remove(address.Value); } } }
private void RetrieveDNetIdFromNetworkAndPutItIntoStorage(ObjectAddress address, int dnetIdRetreiveTimeout) { Log.Log("Запрос DNetId из сети для адреса " + address + ", таймаут операции = " + dnetIdRetreiveTimeout + " сек."); var dNetId = _channelSimple.ResolveDNetIdByBroadcastAtModemCommand(address, _channelSimple.SNetId, dnetIdRetreiveTimeout); // Can throw timeout exc _addressMap.SetDNetId(address, dNetId); Log.Log("Полученное значение DNetID = " + dNetId); }
public void SetLastBadTime(ObjectAddress obj, DateTime?time) { if (!_ot.ContainsKey(obj)) { _ot.Add(obj, time); } else { _ot[obj] = time; } }
/** * Returns the display register appropriate for object code at the current static level to access a data object at the static level of the given address. * @param address the address of the data object * @return the display register required for static addressing */ public Register DisplayRegister(ObjectAddress address) { if (address.Level == 0) { return(Register.SB); } if (Level - address.Level <= 6) { return((Register)(Level - address.Level)); // LBr|L1r|...|L6r } //errorReporter.ReportRestriction("can't access data more than 6 levels out"); return(Register.L6); // to allow code generation to continue }
private byte[] AskForData(ObjectAddress address, byte[] buffer, int attemptsCount, int waitTimeout) { try { Log.Log("Очередной запрос данных: " + buffer.ToText() + " для адреса " + address + ", количество попыток: " + attemptsCount + ", таймаут: " + waitTimeout + " сек."); return(GetDnetIdFromStorageAndDoSendReceiveData(address, buffer, attemptsCount, waitTimeout)); } catch (Exception ex) { Log.Log( "Либо DNetId отсутствует в базе данных, либо ошибка связи по существующему DNetId, будет произведена попытка получения адреса из сети и повторный запрос, ошибка: " + ex); RetrieveDNetIdFromNetworkAndPutItIntoStorage(address, waitTimeout); return(GetDnetIdFromStorageAndDoSendReceiveData(address, buffer, attemptsCount, waitTimeout)); } }
public Task <T> ConnectAsync(TimeSpan?timeout = null) { var actualConnectTimeout = timeout ?? TimeSpan.FromSeconds(1); var address = new ObjectAddress(TinyProtocol.CreatePrefix(_hostname, _port, _name), null).Encode(); var executor = DefaultClientEndpoint.GetExecutor(address, actualConnectTimeout); return(executor.Execute(TinyProtocol.MetadataPath).ContinueWith(meta => { // use result to correctly rethrow task exceptions, no actual checking yet CheckMeta(meta.Result); return TinyProtocol.Serializer <T> .Deserialize(DefaultClientEndpoint, address); }, TaskContinuationOptions.ExecuteSynchronously)); }
private byte[] GetDnetIdFromStorageAndDoSendReceiveData(ObjectAddress address, byte[] buffer, int attemptsCount, int waitTimeout) { var dNetId = _addressMap.GetDNetId(address); Log.Log("DNetId для адреса " + address + " найден в базе данных, значение = " + dNetId + ", будет произведен запрос"); //ushort? inteleconAddress = (_checkInteleconAddress ? (ushort?) address.Value : null); var replyBytes = RequestSomethingCycle(dNetId, (_checkInteleconAddress ? (ushort?)address.Value : null), buffer, attemptsCount, waitTimeout); Log.Log("Запрос успешно произведен для адреса " + address + " (DNetId=" + dNetId + "), байты ответа: " + replyBytes.ToText()); return(replyBytes); }
public static string GetObjAddrTypeName(this ObjectAddress address) { switch (address.Way) { case NetIdRetrieveType.InteleconAddress: return("ia"); case NetIdRetrieveType.SerialNumber: return("sn"); case NetIdRetrieveType.OldProtocolSerialNumber: return("oldsn"); default: return("unknown"); } }
public void SetDNetId(ObjectAddress address, ushort dNetId) { try { var storedDnetId = GetDNetId(address); if (storedDnetId != dNetId) { // на данный момент (т.к. не выскочило исключение) - элемент в карте для dnetId же имеется, то всё просто: GetTypedAddressMap(address.Way)[address.Value] = dNetId; WriteDNetIdToFile(address, dNetId); } // если элементы совпадают - ничего не нужно делать (иначе оверхёд на перезаписи содержимого файла) } catch { // на данный момент в карте address-dnetId нету элемента GetTypedAddressMap(address.Way).Add(address.Value, dNetId); WriteDNetIdToFile(address, dNetId); } }
/// <summary> /// Вставка строки в перечень лицевых счетов /// </summary> /// <param name="_objectAddress">Элемент перечня адресных объектов</param> /// <param name="_exportAccount">Элемент перечня лицевых счетов в ГИС ЖКХ</param> /// <returns>Результат вставки</returns> public static string InsertAccount(ObjectAddress _objectAddress, exportAccountResultType _exportAccount) { string _result; try { Program.db.spInsertAccount(Guid.Parse(_objectAddress.GUID.ToString()), _exportAccount.AccountNumber, true, int.Parse(_exportAccount.LivingPersonsNumber ?? "2"), Guid.Parse(_exportAccount.AccountGUID)); _result = "Account is synchronized"; } catch (Exception e) { _result = e.Message; } return(_result); }
public static void Connect(int port, Link link) { lock (_staticLock) { var address = new ObjectAddress(link); if (_usedLinks.Contains(address)) { throw new ApplicationException(); // todo2[ak] } var listener = GetRunningListener(port); if (listener == null) { throw new ApplicationException("Connection refused"); // todo2[ak] connection refused } _usedLinks.Add(new ObjectAddress(link)); listener.QueueLinkForAcceptance(link); } }
public ushort GetDNetId(ObjectAddress address) { var wayedAddressMap = GetTypedAddressMap(address.Way); if (wayedAddressMap.ContainsKey(address.Value)) { return(wayedAddressMap[address.Value]); } // если адреса нету в коллекции - попытаемся прочитать его из файла: var filename = GetStoredFilePath(address); if (File.Exists(filename)) { var fileText = File.ReadAllText(filename); var dNetId = ushort.Parse(fileText); wayedAddressMap.Add(address.Value, dNetId); return(dNetId); } throw new FileNotFoundException("Не удалось найти файл " + filename); }
private void WriteDNetIdToFile(ObjectAddress address, ushort dNetId) { var filename = GetStoredFilePath(address); File.WriteAllText(filename, dNetId.ToString(CultureInfo.InvariantCulture)); }
private string GetStoredFilePath(ObjectAddress address) { return(Path.Combine(_subDirectoryName, address.GetObjAddrTypeName() + "_" + address.Value.ToString("d10") + ".txt")); }
public static void SendInteleconCommandAsync(this IMonoChannel channel, IInteleconCommand command, ObjectAddress objectAddress, int timeout, Action <ISendResultWithAddress> onComplete) { SendInteleconCommandAsync(channel, command, objectAddress, timeout, onComplete, IoPriority.Normal); }
public static void SendInteleconCommandAsync(this IMonoChannel channel, IInteleconCommand command, ObjectAddress objectAddress, int timeout, Action <ISendResultWithAddress> onComplete, IoPriority priority) { var sendingItem = new AddressedSendingItem { Address = objectAddress, WaitTimeout = timeout, AttemptsCount = 1, // �� �����, ������� ��������� ������������� � �������, ������ ������� �� 8 ���� ������ ���� ��������� ������� // 2013.07.26 - ���� ������, ��� 0x00FF ������ ������ ����������� ��� ������ � ������ // 2013.08.15 - ������ ��� ������ � SerialNumber Buffer = command.Serialize() .GetNetBuffer( (ushort)(objectAddress.Way == NetIdRetrieveType.SerialNumber || objectAddress.Way == NetIdRetrieveType.OldProtocolSerialNumber ? 0x00FF : objectAddress.Value), command.Code) }; channel.AddCommandToQueueAndExecuteAsync( new QueueItem { SendingItems = new List <IAddressedSendingItem> { sendingItem }, OnComplete = results => { if (results == null) { onComplete(new SendingResultWithAddress(null, new Exception("������ ������� �� ���������� (is null)"), null, 0)); } else if (results.Count == 1) { var bytes = results[0].Bytes; var externalException = results[0].ChannelException; if (externalException == null) { Log.Log("��� �����: " + bytes.ToText()); Exception internalException = null; byte[] infoBytes = null; ushort addressInReply = 0; try { // ������������ ��� ��������� � ������� ����� ������ bytes.CheckInteleconNetBufCorrect((byte)(sendingItem.Buffer[2] + 10), null); addressInReply = (ushort)(bytes[3] * 0x100 + bytes[4]); Log.Log("����� ���������: " + addressInReply + " ��� 0x" + addressInReply.ToString("X4")); infoBytes = bytes.GetInteleconInfoReplyBytes(); Log.Log("����� ��������������� ����: " + infoBytes.ToText()); } catch (Exception ex) { Log.Log(ex.ToString()); internalException = ex; } finally { onComplete(new SendingResultWithAddress(infoBytes, internalException, results[0].Request, addressInReply)); } } else { onComplete(new SendingResultWithAddress(null, externalException, results[0].Request, 0)); } } else { onComplete(new SendingResultWithAddress(null, new Exception("�������� ���������� �������: " + results.Count + " (�������� ���� �����)"), null, 0)); // ��� ���� �� ����������, ����� ������ ������ ����������, �������, ������� �� �������� } } }, priority); }
public ushort ResolveDNetIdByBroadcastAtModemCommand(ObjectAddress address, ushort sNetId, int timeoutSeconds) { Log.Log("Попытка получить DNetID броадкастом"); byte[] netbuf; switch (address.Way) { case NetIdRetrieveType.SerialNumber: { var buf = new byte[6]; buf[0] = 0x03; // sn buf[1] = (byte)((address.Value & 0x000000FF)); buf[2] = (byte)((address.Value & 0x0000FF00) >> 8); buf[3] = (byte)((address.Value & 0x00FF0000) >> 16); buf[4] = (byte)(sNetId & 0x00FF); buf[5] = (byte)((sNetId & 0xFF00) >> 8); netbuf = buf.GetNetBuffer(0x00FF, 0x09); } break; case NetIdRetrieveType.InteleconAddress: { var buf = new byte[5]; buf[0] = 0x00; // ia buf[1] = (byte)((address.Value & 0x00FF)); buf[2] = (byte)((address.Value & 0xFF00) >> 8); buf[3] = (byte)(sNetId & 0x00FF); buf[4] = (byte)((sNetId & 0xFF00) >> 8); netbuf = buf.GetNetBuffer(0x00FF, 0x09); } break; case NetIdRetrieveType.OldProtocolSerialNumber: { var buf = new byte[5]; buf[0] = 0x03; // sn buf[1] = (byte)(address.Value & 0x00FF); buf[2] = (byte)((address.Value & 0xFF00) >> 8); buf[3] = (byte)(sNetId & 0x00FF); buf[4] = (byte)((sNetId & 0xFF00) >> 8); netbuf = buf.GetNetBuffer(0x00FF, 0x09); } break; default: throw new Exception("Не поддерживаемый тип адресации"); } // отсюда число байт, которые ожидает модем var bytes = Encoding.ASCII.GetBytes("AT+BCASTB:" + netbuf.Length.ToString("x2").ToUpper() + ",00\x0D"); Log.Log("Байты для отправки: " + bytes.ToText() + " = " + Encoding.ASCII.GetString(bytes)); _port.WriteBytes(bytes, 0, bytes.Length); //Thread.Sleep(100); Log.Log("В порту будет отправлено: " + netbuf.ToText()); _port.WriteBytes(netbuf, 0, netbuf.Length); var inBytes = _port.ReadBytes(10, /*ReadTimeoutSafe*/ timeoutSeconds); Log.Log("Из порта получены байты: " + inBytes.ToText()); var dNetId = (ushort)(inBytes[5] + (inBytes[6] << 8)); Log.Log("Получен DNetId = 0x" + dNetId.ToString("X4") + " = " + dNetId + " dec"); return(dNetId); }
/// <summary> /// Вставка строки в перечень приборов учета /// </summary> /// <param name="_exportMeteringDevice">Прибор учета в ГИС ЖКХ</param> /// <param name="_objectAddress">Адресный объект, к которому относится прибор учета</param> /// <returns>Результат вставки</returns> public static string InsertMeteringDevice(exportMeteringDeviceDataResultType _exportMeteringDevice, ObjectAddress _objectAddress) { string _result; try { Program.db.spInsertMeteringDevice(Guid.Parse(_objectAddress.GUID.ToString()), _exportMeteringDevice.BasicChatacteristicts.MeteringDeviceModel, _exportMeteringDevice.BasicChatacteristicts.MeteringDeviceStamp, _exportMeteringDevice.BasicChatacteristicts.MeteringDeviceNumber, 6, _exportMeteringDevice.BasicChatacteristicts.InstallationDate, _exportMeteringDevice.BasicChatacteristicts.FirstVerificationDate, Guid.Parse(_exportMeteringDevice.MeteringDeviceRootGUID), int.Parse(_exportMeteringDevice.VersionNumber)); _result = "Metering device element is synchronized"; } catch (Exception e) { _result = e.Message; } return(_result); }
public bool Equals(ObjectAddress other) { return(Equals(other.Way, Way) && other.Value == Value); }
protected ProxyBase(IEndpoint endpoint, string address) { Endpoint = endpoint; Address = ObjectAddress.Parse(address); _executor = Endpoint.GetExecutor(Address.Endpoint + "/"); }